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,1694 @@
1
+ """Cellular design of laser-architectured sheets: the phases of a grid of cells, and
2
+ their optimization by cellular automata and by densities (the loop of the SCOLASTIC
3
+ project: a generative module, the finite elements of the load case, a local rule).
4
+
5
+ **Cells.** The parallel part of a specimen is a grid of square cells
6
+ (:class:`CellGrid`, 1 mm by default: the width of a laser track, the increment of the
7
+ path, and a volume large enough for each cell to carry a homogenized behaviour). Each
8
+ cell holds a :class:`Phase`: a flow law, a critical plastic strain (the fracture of a
9
+ brittle phase: the specimen fails when a point of it reaches it) and a cost (its share
10
+ of the treatment budget: 0 for the untreated sheet, 1 for a full treatment, between for
11
+ the mild and strong levels of a multi-level treatment). The tracks are drawn on the
12
+ blank before the specimen is cut: the end columns of the grid continue along x to the
13
+ grips (``extend``).
14
+
15
+ **Load case.** The tensile test of the specimen (:func:`~morphogen.laser.mechanics.tensile_test`):
16
+ the engineering curve up to the failure, the first of the maximum force (diffuse
17
+ necking) and of the fracture of a brittle point. Measures (:func:`failure_measures`):
18
+ the tensile strength reached before the failure, the failure strain (``ductility``),
19
+ the work absorbed up to it per unit volume (``energy``, MJ/m³: the plastically
20
+ dissipated energy of Wang et al. 2023), and their product with the strength. The
21
+ objective is one of them, the constraints bound the others (exponential penalties).
22
+
23
+ **Sensitivities by replay.** A test records the deformation gradients of the Gauss
24
+ points at every step; replaying them with the law of another phase
25
+ (:func:`~morphogen.laser.mechanics.replay`) gives the work and the plastic strains each
26
+ element would have seen with it, the kinematics held: the first-order change of the
27
+ force at every step if one cell alone changed its phase, and whether a brittle phase
28
+ there would have broken first. :meth:`CellProblem.estimates` turns them into the value
29
+ of the objective each cell would give the design in each phase — the failure included,
30
+ which a derivative would miss (the fracture of the reinforcement that limits the
31
+ ductility, Wang et al. 2023, is a threshold). The replays of all the cells cost a few
32
+ tenths of a second; the next finite element test checks them.
33
+
34
+ **Cellular automata.**
35
+
36
+ * :func:`beso` — the bidirectional evolutionary rule (Huang & Xie 2007, 2010; Querin,
37
+ Steven & Xie 1998) on cells: the benefit of each phase over the untreated one,
38
+ filtered over a radius (the neighbourhood of the automaton) and averaged with the
39
+ previous iteration; the budget moves to its target by ``er`` per iteration, each cell
40
+ takes the phase that maximizes its benefit minus ``λ`` times its cost (``λ`` meets the
41
+ budget: with two phases, the cells of largest benefit are treated), at most one level
42
+ per iteration and a share ``max_change`` of the cells changing. Several levels of
43
+ treatment (mild, strong, very strong: SCOLASTIC) are phases of increasing cost.
44
+ ``multigrid``: the cells are first coarse (4 mm, then 2 mm), each solution starting
45
+ the finer grid (the multigrid automata of Abdalla, Kim & Gürdal 2004 and Zakhama et
46
+ al. 2009). ``exchange``: the phases of neighbouring cells exchanged, at a constant
47
+ budget (a Kawasaki rule), the best estimates tested by finite elements.
48
+ * :func:`hca` — the hybrid cellular automaton of Tovar et al. (2006): continuous
49
+ treatment densities (the flow stress mixes the phases by the weight ``x^q``, the
50
+ critical strain of the brittle phase grows as ``x^-2`` when the treatment is
51
+ partial), each cell driven by the estimated derivative of the objective (its
52
+ stimulus, averaged over the neighbourhood) towards the set point that meets the
53
+ budget, a proportional controller of gain ``kp``; the densities then rounded to the
54
+ levels.
55
+ * :func:`topology` — density-based topology optimization (Bendsøe 1989; SIMP): the
56
+ same densities filtered (Bruns & Tortorelli 2001) and projected (Wang, Lazarov &
57
+ Sigmund 2011), the derivatives from the replays, the method of moving asymptotes
58
+ (:class:`~morphogen.optimization.mma.MMA`) with the budget as constraint.
59
+
60
+ **Bands and tracks.** :func:`band_fractions` gives the share of a band of width ``t``
61
+ along polylines (straight or corrugated tracks of constant width: the ideal designs of
62
+ Wang et al. 2023) in the region of each Gauss point, for :meth:`CellProblem.evaluate`.
63
+ :meth:`CellGrid.stamp` draws polylines with a square spot of some cells,
64
+ :func:`treatable` tells whether such a spot draws a design (the minimum width of the
65
+ automata), :func:`design_tracks` gives the centre lines of the tracks that draw one (a
66
+ path for :class:`~morphogen.laser.design.SheetCase`, the process model).
67
+
68
+ What the replays miss: they hold the kinematics, so that the strain a change moves onto
69
+ its neighbours (a gap that necks, a corner that concentrates) escapes them — the
70
+ finite element tests of the automata keep only the true gains, and the derivatives of
71
+ :func:`hca` and :func:`topology` see the strength a cell adds, not the fracture it
72
+ causes next to it (``docs/laser.md``, §6 and §7).
73
+ """
74
+
75
+ from __future__ import annotations
76
+
77
+ import math
78
+ import time
79
+ from dataclasses import dataclass, field, replace
80
+
81
+ import numpy as np
82
+ from scipy import sparse
83
+
84
+ from morphogen.laser.materials import FlowLaw
85
+ from morphogen.laser.mechanics import Membrane, TensileResult, replay
86
+ from morphogen.laser.patterns import distance_to_polyline
87
+ from morphogen.laser.specimen import QuadMesh, Specimen
88
+ from morphogen.optimization.filters import heaviside, heaviside_derivative
89
+
90
+ #: Measures of a design (:func:`failure_measures`), the objectives among them.
91
+ OBJECTIVES = ("energy", "strength_ductility", "ductility", "tensile_strength")
92
+ MEASURES = (*OBJECTIVES, "yield_strength", "uniform_elongation", "failure_strain", "budget")
93
+ #: Symmetries of the designs: mirrors about the middle of the length (``x``), of the
94
+ #: width (``y``), and the half turn (``point``).
95
+ SYMMETRIES = ("x", "y", "point")
96
+ #: The critical plastic strain of the laser martensite of Wang et al. (2023), fitted to
97
+ #: the failure of their straight reinforcement (sample 1, at an engineering strain of
98
+ #: 0.083) with the laws of :func:`wang_phases`, averaged over :data:`FRACTURE_RADIUS`.
99
+ MARTENSITE_CRITICAL = 0.072
100
+ #: The radius (mm) over which the plastic strain of a brittle phase is averaged
101
+ #: (:class:`~morphogen.laser.mechanics.Fracture`): about the width of a track, the
102
+ #: crack crossing it whole; with it the failure strains of the corrugated samples of
103
+ #: Wang et al. (2023) follow their tests.
104
+ FRACTURE_RADIUS = 1.5
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class Phase:
109
+ """A material state of the cells (see the module): ``law``, ``critical`` plastic
110
+ strain (infinite: ductile) and ``cost`` in the treatment budget."""
111
+
112
+ name: str
113
+ law: FlowLaw
114
+ critical: float = math.inf
115
+ cost: float = 1.0
116
+
117
+ @classmethod
118
+ def from_config(cls, data) -> Phase:
119
+ if isinstance(data, Phase):
120
+ return data
121
+ d = dict(data)
122
+ law = d.pop("law")
123
+ if not isinstance(law, FlowLaw):
124
+ law = dict(law)
125
+ if "k" in law: # Hollomon from the yield stress
126
+ law = FlowLaw.hollomon(law["yield_strength"], law["k"], law["n"])
127
+ else:
128
+ law = FlowLaw(**law)
129
+ critical = d.pop("critical", math.inf)
130
+ return cls(law=law, critical=math.inf if critical is None else float(critical), **d)
131
+
132
+
133
+ def wang_phases(critical: float = MARTENSITE_CRITICAL) -> tuple[Phase, Phase]:
134
+ """The phases of Wang et al. (2023, Table 3): the annealed 0.23 C steel (ferrite and
135
+ pearlite, Hollomon σ0 280 MPa, K 986 MPa, n 0.24) and its laser martensite (1300,
136
+ 1966, 0.06), brittle beyond ``critical``."""
137
+ return (
138
+ Phase("ferrite", FlowLaw.hollomon(280.0, 986.0, 0.24), cost=0.0),
139
+ Phase("martensite", FlowLaw.hollomon(1300.0, 1966.0, 0.06), critical=critical),
140
+ )
141
+
142
+
143
+ #: Rules of the critical plastic strain of a reinforcement softer than the laser
144
+ #: martensite (:func:`contrast_phases`).
145
+ FRACTURE_RULES = ("graded", "brittle", "ductile")
146
+
147
+
148
+ def contrast_phases(
149
+ contrast: float, fracture: str = "graded", critical: float = MARTENSITE_CRITICAL
150
+ ) -> tuple[Phase, Phase]:
151
+ """The matrix of :func:`wang_phases` and a reinforcement whose yield stress is
152
+ ``contrast`` times the matrix's, from 1 to the contrast ``c_M = 1300/280`` of the
153
+ as-quenched laser martensite (the hardest state of the steel): the Hollomon
154
+ parameters ``σ0``, ``K`` and ``n`` interpolated linearly between those of the matrix
155
+ and of the martensite at the share ``a = (contrast − 1)/(c_M − 1)``, the states
156
+ between the annealed steel and its martensite (partly transformed by an intercritical
157
+ peak, or tempered), a harder state hardening less. The critical plastic strain of
158
+ the reinforcement (:data:`FRACTURE_RULES`): ``graded``, ``critical / a²`` (the rule
159
+ of a partial treatment, as in :func:`hca`: the martensite breaks at ``critical``, a
160
+ softer state later); ``brittle``, ``critical`` whatever the contrast; ``ductile``,
161
+ none (the necking alone). The last two bound the first."""
162
+ ferrite, martensite = wang_phases(critical)
163
+ lo, hi = ferrite.law, martensite.law
164
+ top = hi.sigma0 / lo.sigma0
165
+ c = float(contrast)
166
+ if not 1.0 <= c <= top:
167
+ raise ValueError(f"contrast: from 1 to {top:.4g} (the laser martensite)")
168
+ if fracture not in FRACTURE_RULES:
169
+ raise ValueError(f"fracture: one of {FRACTURE_RULES}")
170
+ a = (c - 1.0) / (top - 1.0)
171
+ law = FlowLaw.hollomon(
172
+ *((1.0 - a) * x + a * y for x, y in ((lo.sigma0, hi.sigma0), (lo.a, hi.a), (lo.b, hi.b)))
173
+ )
174
+ if fracture == "ductile":
175
+ crit = math.inf
176
+ elif fracture == "brittle":
177
+ crit = float(critical)
178
+ else:
179
+ crit = float(critical) / a**2 if a > 0 else math.inf
180
+ return ferrite, Phase("reinforcement", law, critical=crit)
181
+
182
+
183
+ # -- the cells -------------------------------------------------------------------------
184
+
185
+
186
+ @dataclass
187
+ class CellGrid:
188
+ """Square cells of about ``size`` mm over ``[x0, x0 + length] x [y0, y0 + width]``
189
+ (the parallel part of a specimen, the region of a structure): ``ny`` rows (along y)
190
+ and ``nx`` columns; a design is an array ``(ny, nx)``."""
191
+
192
+ length: float
193
+ width: float
194
+ size: float = 1.0
195
+ x0: float = 0.0
196
+ y0: float = 0.0
197
+
198
+ def __post_init__(self):
199
+ if not (self.length > 0 and self.width > 0 and self.size > 0):
200
+ raise ValueError("cell grid: positive length, width and size")
201
+ self.nx = max(1, round(self.length / self.size))
202
+ self.ny = max(1, round(self.width / self.size))
203
+ self.dx = self.length / self.nx
204
+ self.dy = self.width / self.ny
205
+
206
+ @classmethod
207
+ def of(cls, specimen: Specimen, size: float = 1.0) -> CellGrid:
208
+ return cls(specimen.length, specimen.width, size)
209
+
210
+ @property
211
+ def shape(self) -> tuple[int, int]:
212
+ return (self.ny, self.nx)
213
+
214
+ @property
215
+ def count(self) -> int:
216
+ return self.nx * self.ny
217
+
218
+ def centres(self) -> np.ndarray:
219
+ """The centres of the cells ``(ny, nx, 2)``."""
220
+ x = self.x0 + (np.arange(self.nx) + 0.5) * self.dx
221
+ y = self.y0 + (np.arange(self.ny) + 0.5) * self.dy
222
+ X, Y = np.meshgrid(x, y)
223
+ return np.stack([X, Y], axis=-1)
224
+
225
+ def locate(self, points, extend: bool = True) -> np.ndarray:
226
+ """The cell (flat index) of each point, -1 outside the grid; ``extend``: the end
227
+ columns continue along x beyond the parallel part."""
228
+ p = np.asarray(points, dtype=float)
229
+ x, y = p[..., 0] - self.x0, p[..., 1] - self.y0
230
+ xc = np.clip(x, 0.0, self.length * (1 - 1e-12)) if extend else x
231
+ j = np.floor(xc / self.dx).astype(int)
232
+ i = np.floor(y / self.dy).astype(int)
233
+ ok = (i >= 0) & (i < self.ny) & (j >= 0) & (j < self.nx)
234
+ return np.where(ok, i * self.nx + np.clip(j, 0, self.nx - 1), -1)
235
+
236
+ def filter_matrix(self, radius: float) -> sparse.csr_matrix:
237
+ """The neighbourhood of the automaton: weights ``max(0, radius - d)`` between
238
+ cell centres (mm), rows normalized; the identity for ``radius <= size``."""
239
+ if radius <= min(self.dx, self.dy):
240
+ return sparse.identity(self.count, format="csr")
241
+ reach_x = math.ceil(radius / self.dx)
242
+ reach_y = math.ceil(radius / self.dy)
243
+ rows, cols, vals = [], [], []
244
+ idx = np.arange(self.count).reshape(self.shape)
245
+ for di in range(-reach_y, reach_y + 1):
246
+ for dj in range(-reach_x, reach_x + 1):
247
+ d = math.hypot(di * self.dy, dj * self.dx)
248
+ if d >= radius:
249
+ continue
250
+ a = idx[max(0, -di) : self.ny - max(0, di), max(0, -dj) : self.nx - max(0, dj)]
251
+ b = idx[max(0, di) : self.ny + min(0, di), max(0, dj) : self.nx + min(0, dj)]
252
+ rows.append(a.ravel())
253
+ cols.append(b.ravel())
254
+ vals.append(np.full(a.size, radius - d))
255
+ m = sparse.csr_matrix(
256
+ (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))),
257
+ shape=(self.count, self.count),
258
+ )
259
+ s = np.asarray(m.sum(axis=1)).ravel()
260
+ return sparse.diags(1.0 / s) @ m
261
+
262
+ def orbits(self, symmetry=(), period: float | None = None) -> np.ndarray:
263
+ """The orbit of each cell under the ``symmetry`` (:data:`SYMMETRIES`) and the
264
+ translation by ``period`` (mm, a divisor of the length in cells): a design
265
+ constant on the orbits is symmetric and periodic."""
266
+ sym = set(symmetry or ())
267
+ bad = sym - set(SYMMETRIES)
268
+ if bad:
269
+ raise ValueError(f"symmetry: among {SYMMETRIES}")
270
+ if len(sym) >= 2:
271
+ sym = set(SYMMETRIES)
272
+ idx = np.arange(self.count).reshape(self.shape)
273
+ images = []
274
+ if "x" in sym:
275
+ images.append(idx[:, ::-1])
276
+ if "y" in sym:
277
+ images.append(idx[::-1, :])
278
+ if "point" in sym:
279
+ images.append(idx[::-1, ::-1])
280
+ if period:
281
+ m = round(period / self.dx)
282
+ if m < 1 or self.nx % m:
283
+ raise ValueError("period: a divisor of the length, in cells")
284
+ images.append(np.roll(idx, -m, axis=1))
285
+ rep = idx.ravel().copy()
286
+ while True: # the least index of each orbit
287
+ new = rep.copy()
288
+ for img in images:
289
+ new = np.minimum(new, new[img.ravel()])
290
+ if np.array_equal(new, rep):
291
+ break
292
+ rep = new
293
+ return np.unique(rep, return_inverse=True)[1]
294
+
295
+ def transfer(self, design, other: CellGrid) -> np.ndarray:
296
+ """A design of this grid sampled at the cell centres of ``other`` (multigrid)."""
297
+ d = np.asarray(design)
298
+ cells = self.locate(other.centres())
299
+ return d.ravel()[cells].reshape(other.shape)
300
+
301
+ def coverage(self, polylines, width: float, n: int = 6) -> np.ndarray:
302
+ """The share of each cell ``(ny, nx)`` within ``width / 2`` of the polylines."""
303
+ t = (np.arange(n) + 0.5) / n
304
+ x = self.x0 + (np.arange(self.nx)[:, None] + t[None, :]).ravel() * self.dx
305
+ y = self.y0 + (np.arange(self.ny)[:, None] + t[None, :]).ravel() * self.dy
306
+ X, Y = np.meshgrid(x, y)
307
+ pts = np.column_stack([X.ravel(), Y.ravel()])
308
+ inside = np.zeros(len(pts), dtype=bool)
309
+ for poly in polylines:
310
+ inside |= distance_to_polyline(pts, np.asarray(poly, dtype=float)) <= 0.5 * width
311
+ return inside.reshape(self.ny, n, self.nx, n).mean(axis=(1, 3))
312
+
313
+ def rasterize(self, polylines, width: float, budget: float | None = None) -> np.ndarray:
314
+ """The cells of a band of ``width`` along the polylines (phase 1): those most
315
+ covered, as many as the ``budget`` asks (default: those covered at least by
316
+ half)."""
317
+ cov = self.coverage(polylines, width).ravel()
318
+ n = int((cov >= 0.5).sum()) if budget is None else round(budget * self.count)
319
+ out = np.zeros(self.count, dtype=int)
320
+ out[np.argsort(-cov, kind="stable")[:n]] = 1
321
+ return out.reshape(self.shape)
322
+
323
+ def stamp(self, polylines, width: int = 2) -> np.ndarray:
324
+ """The cells a square spot of ``width`` cells covers along the polylines (phase
325
+ 1): a design :func:`treatable` by construction, the tracks of a laser spot."""
326
+ out = np.zeros(self.shape, dtype=int)
327
+ step = 0.25 * min(self.dx, self.dy)
328
+ for poly in polylines:
329
+ p = np.asarray(poly, dtype=float)
330
+ seg = np.diff(p, axis=0)
331
+ length = np.hypot(seg[:, 0], seg[:, 1])
332
+ s = np.concatenate([[0.0], np.cumsum(length)])
333
+ t = np.arange(0.0, s[-1] + step, step)
334
+ x = np.interp(t, s, p[:, 0])
335
+ y = np.interp(t, s, p[:, 1])
336
+ i0 = np.rint((y - self.y0) / self.dy - 0.5 * width).astype(int)
337
+ j0 = np.rint((x - self.x0) / self.dx - 0.5 * width).astype(int)
338
+ for a, b in set(zip(i0.tolist(), j0.tolist(), strict=True)):
339
+ out[max(a, 0) : max(a + width, 0), max(b, 0) : max(b + width, 0)] = 1
340
+ return out
341
+
342
+ def band(self, budget: float, rows: int | None = None) -> np.ndarray:
343
+ """The straight design: the central rows treated (phase 1), as many as the
344
+ ``budget`` (fraction of the cells) asks, rounded."""
345
+ n = round(budget * self.ny) if rows is None else int(rows)
346
+ d = np.zeros(self.shape, dtype=int)
347
+ lo = (self.ny - n) // 2
348
+ d[lo : lo + n] = 1
349
+ return d
350
+
351
+
352
+ def quarter_points(mesh: QuadMesh, n: int = 4) -> np.ndarray:
353
+ """Points of the quarter of each element around each of its Gauss points: ``(e, 4,
354
+ n², 2)``, regular sub-grids of the quarters of the reference square."""
355
+ xe = mesh.nodes[mesh.quads]
356
+ t = (np.arange(n) + 0.5) / n
357
+ out = np.empty((len(mesh.quads), 4, n * n, 2))
358
+ for g, (sr, ss) in enumerate(((-1, -1), (1, -1), (1, 1), (-1, 1))):
359
+ r, s = np.meshgrid(sr * t, ss * t)
360
+ r, s = r.ravel(), s.ravel()
361
+ shape = 0.25 * np.stack(
362
+ [(1 - r) * (1 - s), (1 + r) * (1 - s), (1 + r) * (1 + s), (1 - r) * (1 + s)], axis=1
363
+ )
364
+ out[:, g] = np.einsum("ka,eai->eki", shape, xe)
365
+ return out
366
+
367
+
368
+ def band_fractions(mesh: QuadMesh, polylines, width: float, n: int = 4) -> np.ndarray:
369
+ """The share ``(e, 4)`` of the region of each Gauss point within ``width / 2`` of
370
+ the polylines (tracks of constant width)."""
371
+ pts = quarter_points(mesh, n)
372
+ flat = pts.reshape(-1, 2)
373
+ inside = np.zeros(len(flat), dtype=bool)
374
+ for poly in polylines:
375
+ inside |= distance_to_polyline(flat, np.asarray(poly, dtype=float)) <= 0.5 * width
376
+ return inside.reshape(pts.shape[:3]).mean(axis=2)
377
+
378
+
379
+ def corrugation(
380
+ specimen: Specimen,
381
+ amplitude: float,
382
+ period: float | None,
383
+ *,
384
+ count: int = 1,
385
+ margin: float = 10.0,
386
+ resolution: int = 64,
387
+ ):
388
+ """The centre lines of ``count`` corrugated tracks ``y = yc + H sin(2π x / P)``
389
+ (``period`` None: straight), evenly spread over the width, through the grips."""
390
+ x0, x1 = specimen.extent()
391
+ x = np.linspace(x0 - margin, x1 + margin, resolution * 8 + 1)
392
+ w = specimen.width
393
+ lines = []
394
+ for k in range(count):
395
+ yc = (k + 0.5) * w / count
396
+ y = np.full_like(x, yc) if not period else yc + amplitude * np.sin(2 * math.pi * x / period)
397
+ lines.append(np.column_stack([x, y]))
398
+ return lines
399
+
400
+
401
+ def constant_area_width(width: float, amplitude: float, period: float | None) -> float:
402
+ """The width of a sinusoidal track of the same area as a straight one of ``width``
403
+ (Wang 2022: the spot shrunk by defocusing, ``t = t0 P / L``, ``L`` the arc length of
404
+ a period)."""
405
+ if not period or amplitude == 0:
406
+ return width
407
+ u = np.linspace(0.0, 2 * math.pi, 4001)
408
+ k = 2 * math.pi * amplitude / period
409
+ arc = np.trapezoid(np.sqrt(1.0 + (k * np.cos(u)) ** 2), u) / (2 * math.pi) * period
410
+ return width * period / arc
411
+
412
+
413
+ def design_tracks(
414
+ grid: CellGrid, design, width: int = 2, margin: float = 5.0, cross: bool = False
415
+ ) -> list:
416
+ """The centre lines (polylines, mm) of the tracks that draw a design: the runs of
417
+ treated cells of each column, linked to the runs they overlap in the next column (the
418
+ straightest continuation first where a track splits), crossed at their midpoint —
419
+ or, with ``cross``, from end to end when longer than a spot of ``width`` cells (a
420
+ square spot then covers every cell; a real track, wider than the spot, would treat
421
+ too much) —; the tracks that reach the ends of the grid continue along x by
422
+ ``margin`` (the blank is treated before the specimen is cut)."""
423
+ d = np.asarray(design) > 0
424
+ runs = [] # (column, first row, end row)
425
+ by_col = []
426
+ for j in range(grid.nx):
427
+ col = np.concatenate([[False], d[:, j], [False]])
428
+ starts = np.flatnonzero(~col[:-1] & col[1:])
429
+ ends = np.flatnonzero(col[:-1] & ~col[1:])
430
+ ids = []
431
+ for a, b in zip(starts, ends, strict=True):
432
+ ids.append(len(runs))
433
+ runs.append((j, int(a), int(b)))
434
+ by_col.append(ids)
435
+ adj = {i: set() for i in range(len(runs))}
436
+ for j in range(grid.nx - 1):
437
+ for u in by_col[j]:
438
+ for v in by_col[j + 1]:
439
+ _, a, b = runs[u]
440
+ _, c, e = runs[v]
441
+ if min(b, e) > max(a, c): # the runs share a row
442
+ adj[u].add(v)
443
+ adj[v].add(u)
444
+ xy = np.array(
445
+ [(grid.x0 + (j + 0.5) * grid.dx, grid.y0 + 0.5 * (a + b) * grid.dy) for j, a, b in runs]
446
+ )
447
+ used = set()
448
+
449
+ def edge(u, v):
450
+ return (min(u, v), max(u, v))
451
+
452
+ def walk(start):
453
+ path = [start]
454
+ cur, prev = start, None
455
+ while True:
456
+ options = [v for v in adj[cur] if edge(cur, v) not in used]
457
+ if not options:
458
+ return path
459
+ if prev is None:
460
+ nxt = min(
461
+ options, key=lambda v: (xy[v, 0] < xy[cur, 0], abs(xy[v, 1] - xy[cur, 1]))
462
+ )
463
+ else:
464
+ ahead = xy[cur] - xy[prev]
465
+
466
+ def turn(v, ahead=ahead, cur=cur):
467
+ dv = xy[v] - xy[cur]
468
+ return -float(ahead @ dv) / (np.linalg.norm(ahead) * np.linalg.norm(dv) + 1e-12)
469
+
470
+ nxt = min(options, key=turn)
471
+ used.add(edge(cur, nxt))
472
+ path.append(nxt)
473
+ prev, cur = cur, nxt
474
+
475
+ tracks = []
476
+ order = sorted(range(len(runs)), key=lambda i: (len(adj[i]) % 2 == 0, xy[i, 0], xy[i, 1]))
477
+ for i in order:
478
+ while any(edge(i, v) not in used for v in adj[i]):
479
+ tracks.append(walk(i))
480
+ if not adj[i]:
481
+ tracks.append([i])
482
+ out = []
483
+ half = 0.5 * width * grid.dy
484
+ for t in tracks:
485
+ pts = []
486
+ for n, i in enumerate(t):
487
+ j, a, b = runs[i]
488
+ x = grid.x0 + (j + 0.5) * grid.dx
489
+ lo, hi = grid.y0 + a * grid.dy + half, grid.y0 + b * grid.dy - half
490
+ if not cross or hi - lo <= 1e-9: # the midpoint of the run
491
+ pts.append((x, grid.y0 + 0.5 * (a + b) * grid.dy))
492
+ continue
493
+ # a longer run: the track crosses it, from the side of the previous run
494
+ ref = xy[t[n - 1], 1] if n > 0 else (xy[t[n + 1], 1] if len(t) > 1 else lo)
495
+ ends = [(x, lo), (x, hi)]
496
+ if abs(ref - hi) < abs(ref - lo):
497
+ ends.reverse()
498
+ if n == 0 and len(t) > 1:
499
+ ends.reverse()
500
+ pts += ends
501
+ p = np.array(pts, dtype=float)
502
+ if len(p) == 1:
503
+ p = np.vstack([p[0] - [0.25 * grid.dx, 0.0], p[0] + [0.25 * grid.dx, 0.0]])
504
+ if p[0, 0] > p[-1, 0]:
505
+ p = p[::-1]
506
+ x0, x1 = grid.x0, grid.x0 + grid.length
507
+ if margin and p[0, 0] <= x0 + 0.5 * grid.dx + 1e-9: # the ends continue to the grips
508
+ p = np.vstack([[x0 - margin, p[0, 1]], p])
509
+ if margin and p[-1, 0] >= x1 - 0.5 * grid.dx - 1e-9:
510
+ p = np.vstack([p, [x1 + margin, p[-1, 1]]])
511
+ out.append(p)
512
+ return out
513
+
514
+
515
+ # -- the measures ----------------------------------------------------------------------
516
+
517
+
518
+ def failure_measures(strain, stress, failure, *, young: float = 210000.0, cap=None) -> dict:
519
+ """Measures of engineering curves ``stress`` (steps x m, or steps) on the common
520
+ ``strain`` with the failure strains ``failure`` (m, infinite: none): the maximum
521
+ (diffuse necking: the uniform elongation, a parabola through the points around the
522
+ largest), the failure at the first of the necking and the fracture
523
+ (``failure_strain``, alias ``ductility``), the strength reached before it, the work
524
+ up to it (MJ/m³) and the 0.2 % proof stress. ``cap``: the strength of the weakest
525
+ cross-section (m): a curve that reaches it necks there. Arrays of length m (or
526
+ floats)."""
527
+ e = np.asarray(strain, dtype=float)
528
+ s = np.asarray(stress, dtype=float)
529
+ single = s.ndim == 1
530
+ if single:
531
+ s = s[:, None]
532
+ m = s.shape[1]
533
+ fail = np.broadcast_to(np.asarray(failure, dtype=float), (m,))
534
+ if cap is not None:
535
+ capv = np.broadcast_to(np.asarray(cap, dtype=float), (m,))
536
+ over = s >= capv[None, :]
537
+ over[0] = False
538
+ hit = over.any(axis=0)
539
+ if hit.any():
540
+ kc = np.argmax(over, axis=0)
541
+ cols_ = np.arange(m)
542
+ s0, s1 = s[kc - 1, cols_], s[kc, cols_]
543
+ f = np.clip((capv - s0) / np.where(s1 > s0, s1 - s0, 1.0), 0.0, 1.0)
544
+ ecap = np.where(hit, e[kc - 1] + f * (e[kc] - e[kc - 1]), np.inf)
545
+ fail = np.minimum(fail, ecap)
546
+ s = np.minimum(s, capv[None, :])
547
+ ns = len(e)
548
+ cols = np.arange(m)
549
+ k = np.argmax(s, axis=0)
550
+ eu, su = e[k].copy(), s[k, cols].copy()
551
+ inner = (k > 0) & (k < ns - 1)
552
+ if inner.any():
553
+ kk = k[inner]
554
+ x0, x1, x2 = e[kk - 1], e[kk], e[kk + 1]
555
+ y0, y1, y2 = s[kk - 1, cols[inner]], s[kk, cols[inner]], s[kk + 1, cols[inner]]
556
+ d0, d2 = x0 - x1, x2 - x1
557
+ den = d0 * d2 * (d0 - d2)
558
+ with np.errstate(divide="ignore", invalid="ignore"):
559
+ a = ((y0 - y1) * d2 - (y2 - y1) * d0) / den
560
+ b = ((y2 - y1) * d0 * d0 - (y0 - y1) * d2 * d2) / den
561
+ xm = -b / (2 * a)
562
+ ok = (a < 0) & (xm >= d0) & (xm <= d2) & np.isfinite(xm)
563
+ sel = np.flatnonzero(inner)[ok]
564
+ eu[sel] = x1[ok] + xm[ok]
565
+ su[sel] = y1[ok] + a[ok] * xm[ok] ** 2 + b[ok] * xm[ok]
566
+ ef = np.minimum(eu, fail)
567
+ ef = np.minimum(ef, e[-1])
568
+ # the curve at the failure strain, the work and the strength up to it
569
+ cum = np.vstack([np.zeros((1, m)), np.cumsum(0.5 * (s[1:] + s[:-1]) * np.diff(e)[:, None], 0)])
570
+ i = np.clip(np.searchsorted(e, ef, side="right") - 1, 0, ns - 2)
571
+ span = e[i + 1] - e[i]
572
+ t = np.where(span > 0, (ef - e[i]) / np.where(span > 0, span, 1.0), 0.0)
573
+ sf = s[i, cols] + t * (s[i + 1, cols] - s[i, cols])
574
+ energy = cum[i, cols] + 0.5 * (s[i, cols] + sf) * (ef - e[i])
575
+ before = np.where(e[:, None] <= ef[None, :], s, -np.inf)
576
+ strength = np.maximum(before.max(axis=0), sf)
577
+ strength = np.where(ef >= eu - 1e-15, np.maximum(strength, su), strength)
578
+ # the proof stress
579
+ line = s - young * (e[:, None] - 0.002)
580
+ below = line <= 0
581
+ below[0] = False
582
+ has = below.any(axis=0)
583
+ j = np.where(has, np.argmax(below, axis=0), 1)
584
+ l0, l1 = line[j - 1, cols], line[j, cols]
585
+ f = np.where(l0 != l1, l0 / np.where(l0 != l1, l0 - l1, 1.0), 0.0)
586
+ ys = np.where(has, s[j - 1, cols] + f * (s[j, cols] - s[j - 1, cols]), np.nan)
587
+ out = {
588
+ "energy": energy,
589
+ "ductility": ef,
590
+ "failure_strain": ef,
591
+ "tensile_strength": strength,
592
+ "strength_ductility": strength * ef,
593
+ "uniform_elongation": eu,
594
+ "yield_strength": ys,
595
+ }
596
+ if single:
597
+ return {k_: float(v[0]) for k_, v in out.items()}
598
+ return out
599
+
600
+
601
+ def _crossing(strain, ratio) -> np.ndarray:
602
+ """The strain at which each column of ``ratio`` (steps x n, non-decreasing) first
603
+ reaches 1 (infinite: never)."""
604
+ hit = ratio >= 1.0
605
+ has = hit.any(axis=0)
606
+ k = np.where(has, np.argmax(hit, axis=0), 1)
607
+ k = np.maximum(k, 1)
608
+ cols = np.arange(ratio.shape[1])
609
+ r0, r1 = ratio[k - 1, cols], ratio[k, cols]
610
+ f = np.clip((1.0 - r0) / np.maximum(r1 - r0, 1e-12), 0.0, 1.0)
611
+ e = strain[k - 1] + f * (strain[k] - strain[k - 1])
612
+ return np.where(has, e, np.inf)
613
+
614
+
615
+ def phase_strength(phase: Phase, young: float = 210000.0) -> float:
616
+ """The engineering tensile strength of a phase alone (MPa): the largest
617
+ ``σ(p) exp(−ε)`` (``ε = p + σ/E``) up to its necking or its critical strain."""
618
+ p = np.linspace(0.0, min(phase.critical, 1.5), 3001)
619
+ sig = phase.law.stress(p)
620
+ return float(np.max(sig * np.exp(-(p + sig / young))))
621
+
622
+
623
+ # -- the problem -----------------------------------------------------------------------
624
+
625
+
626
+ @dataclass
627
+ class CellEvaluation:
628
+ """A design and its tensile test: ``measures`` (:func:`failure_measures`, the
629
+ ``budget`` used), ``value`` (the objective with the penalties of the constraints)."""
630
+
631
+ design: np.ndarray
632
+ result: TensileResult
633
+ measures: dict
634
+ value: float
635
+ membrane: Membrane | None = field(default=None, repr=False)
636
+ fractions: np.ndarray | None = field(default=None, repr=False)
637
+
638
+
639
+ @dataclass
640
+ class CellProblem:
641
+ """The load case of a cellular design (see the module): a ``specimen`` (its parallel
642
+ part is the grid of cells of ``size`` mm), the ``phases`` (phase 0: the untreated
643
+ sheet), the mesh (``element`` mm, a divisor of the cell size), the ``objective``
644
+ (:data:`OBJECTIVES`, maximized) and the ``constraints`` ``{measure: [low, high]}``
645
+ (penalty ``exp(-penalty * relative violation)`` on the objective)."""
646
+
647
+ specimen: Specimen = field(default_factory=Specimen)
648
+ phases: tuple = field(default_factory=wang_phases)
649
+ size: float = 1.0
650
+ element: float = 0.5
651
+ objective: str = "energy"
652
+ constraints: dict = field(default_factory=dict)
653
+ penalty: float = 10.0
654
+ extend: bool = True
655
+ young: float = 210000.0
656
+ poisson: float = 0.3
657
+ max_strain: float = 0.35
658
+ failure_margin: float = 0.03
659
+ fracture_radius: float | None = FRACTURE_RADIUS
660
+ layers: int = 1
661
+ case: object = None
662
+
663
+ def __post_init__(self):
664
+ self.specimen = Specimen.from_config(self.specimen)
665
+ self.phases = tuple(Phase.from_config(p) for p in self.phases)
666
+ if len(self.phases) < 2:
667
+ raise ValueError("cell problem: at least two phases")
668
+ if self.objective not in OBJECTIVES:
669
+ raise ValueError(f"objective: one of {OBJECTIVES}")
670
+ for name in self.constraints:
671
+ if name not in MEASURES:
672
+ raise ValueError(f"constraint on {name!r}: one of {MEASURES}")
673
+ from morphogen.laser.structures import TensionCase, case_from_config
674
+
675
+ self.case = case_from_config(self.case) or TensionCase(self.specimen, self.element)
676
+ x0, x1, y0, y1 = self.case.region
677
+ self.grid = CellGrid(x1 - x0, y1 - y0, self.size, x0=x0, y0=y0)
678
+ self.mesh = self.case.mesh
679
+ centroid = self.mesh.nodes[self.mesh.quads].mean(axis=1)
680
+ self.element_cell = self.grid.locate(centroid, extend=self.extend and self.case.extend)
681
+ inside = self.element_cell >= 0
682
+ self.cell_matrix = sparse.csr_matrix(
683
+ (np.ones(int(inside.sum())), (self.element_cell[inside], np.flatnonzero(inside))),
684
+ shape=(self.grid.count, len(self.mesh.quads)),
685
+ )
686
+ #: the cells that hold elements: the others (a hole, the outside) never change
687
+ self.active = np.asarray(self.cell_matrix.sum(axis=1)).ravel() > 0
688
+ self.costs = np.array([p.cost for p in self.phases], dtype=float)
689
+ self._laws = np.array(
690
+ [[p.law.code, p.law.sigma0, p.law.a, p.law.b] for p in self.phases], dtype=float
691
+ )
692
+ self._critical = np.array([p.critical for p in self.phases], dtype=float)
693
+ self.strengths = np.array([phase_strength(p, self.young) for p in self.phases])
694
+ self._weights = self._same = None
695
+ if self.fracture_radius:
696
+ from scipy.spatial import cKDTree
697
+
698
+ pairs = cKDTree(centroid).query_pairs(self.fracture_radius, output_type="ndarray")
699
+ d = np.linalg.norm(centroid[pairs[:, 0]] - centroid[pairs[:, 1]], axis=1)
700
+ n = len(centroid)
701
+ rows = np.concatenate([pairs[:, 0], pairs[:, 1], np.arange(n)])
702
+ cols = np.concatenate([pairs[:, 1], pairs[:, 0], np.arange(n)])
703
+ r = self.fracture_radius
704
+ vals = np.concatenate([r - d, r - d, np.full(n, r)])
705
+ self._weights = sparse.csr_matrix((vals, (rows, cols)), shape=(n, n))
706
+ ec = self.element_cell
707
+ keep = (ec[rows] == ec[cols]) & (ec[rows] >= 0)
708
+ self._same = sparse.csr_matrix((vals[keep], (rows[keep], cols[keep])), shape=(n, n))
709
+
710
+ # -- designs to membranes ----------------------------------------------------------
711
+
712
+ def fractions(self, design) -> np.ndarray:
713
+ """The shares ``(e, 4, phases)`` of the phases at the Gauss points of a design
714
+ (phase indices per cell, or for two phases the densities of the second)."""
715
+ d = np.asarray(design)
716
+ ne = len(self.mesh.quads)
717
+ frac = np.zeros((ne, 4, len(self.phases)))
718
+ cell = self.element_cell
719
+ inside = cell >= 0
720
+ if np.issubdtype(d.dtype, np.integer):
721
+ ph = np.zeros(ne, dtype=int)
722
+ ph[inside] = d.ravel()[cell[inside]]
723
+ frac[np.arange(ne), :, ph] = 1.0
724
+ else:
725
+ if len(self.phases) != 2:
726
+ raise ValueError("densities: two phases")
727
+ x = np.zeros(ne)
728
+ x[inside] = d.ravel()[cell[inside]]
729
+ frac[:, :, 1] = x[:, None]
730
+ frac[:, :, 0] = 1.0 - x[:, None]
731
+ return frac
732
+
733
+ def _arrays(self, frac, q: float = 1.0, graded: bool = False):
734
+ """The flow laws ``(e, 4, layers, 9)`` and the critical strains of the shares
735
+ ``frac`` of the phases at the Gauss points: the two largest shares mix their flow
736
+ stresses (by the weight ``w^q`` of the second); the critical strain is that of
737
+ the largest share, or (``graded``: the densities of a partial treatment, two
738
+ phases) ``critical / w²`` of the brittle phase at the share ``w``."""
739
+ order = np.argsort(-frac, axis=2, kind="stable")
740
+ i = order[..., 0]
741
+ j = order[..., 1]
742
+ fi = np.take_along_axis(frac, i[..., None], 2)[..., 0]
743
+ fj = np.take_along_axis(frac, j[..., None], 2)[..., 0]
744
+ tot = fi + fj
745
+ w = np.where(tot > 0, fj / np.where(tot > 0, tot, 1.0), 0.0) ** q
746
+ law = np.concatenate([self._laws[i], self._laws[j], w[..., None]], axis=-1)
747
+ c = self._critical
748
+ if graded and len(c) == 2 and np.isfinite(c).sum() == 1:
749
+ b = int(np.argmin(c))
750
+ sb = frac[..., b]
751
+ crit = np.where(sb > 0, c[b] / np.maximum(sb, 1e-12) ** 2, np.inf)
752
+ else:
753
+ crit = c[i]
754
+ nl = self.layers
755
+ law = np.repeat(law[:, :, None, :], nl, axis=2)
756
+ crit = np.repeat(crit[:, :, None], nl, axis=2)
757
+ return np.ascontiguousarray(law), np.ascontiguousarray(crit)
758
+
759
+ def membrane(self, frac, q: float = 1.0, graded: bool = False) -> Membrane:
760
+ law, crit = self._arrays(frac, q, graded)
761
+ flow = [law[..., k] for k in range(9)]
762
+ return Membrane(
763
+ self.mesh,
764
+ flow,
765
+ young=self.young,
766
+ poisson=self.poisson,
767
+ thickness=self.case.thickness,
768
+ critical=crit,
769
+ fracture_radius=self.fracture_radius,
770
+ springs=self.case.springs,
771
+ )
772
+
773
+ def budget(self, design) -> float:
774
+ """The treatment budget a design uses: the mean cost of its active cells (those
775
+ that hold elements)."""
776
+ d = np.asarray(design).ravel()[self.active]
777
+ if np.issubdtype(d.dtype, np.integer):
778
+ return float(self.costs[d].mean())
779
+ return float(self.costs[0] + (self.costs[1] - self.costs[0]) * d.mean())
780
+
781
+ # -- evaluation --------------------------------------------------------------------
782
+
783
+ def _slope(self, res) -> float:
784
+ """The elastic slope of the nominal curve: Young's modulus in tension, the first
785
+ steps' secant for a structure."""
786
+ if self.case.kind == "tension":
787
+ return self.young
788
+ e, s = np.asarray(res.strain), np.asarray(res.stress)
789
+ j = max(1, min(2, len(e) - 1))
790
+ return float(s[j] / e[j]) if len(e) > 1 and e[j] > 0 else self.young
791
+
792
+ def value_of(self, measures) -> np.ndarray | float:
793
+ """The objective with the penalties of the constraints."""
794
+ v = np.asarray(measures[self.objective], dtype=float)
795
+ excess = np.zeros_like(v)
796
+ for name, (lo, hi) in self.constraints.items():
797
+ m = np.asarray(measures[name], dtype=float)
798
+ if lo is not None:
799
+ excess = excess + np.maximum(0.0, (lo - m) / abs(lo))
800
+ if hi is not None:
801
+ excess = excess + np.maximum(0.0, (m - hi) / abs(hi))
802
+ out = v * np.exp(-self.penalty * excess)
803
+ return float(out) if out.ndim == 0 else out
804
+
805
+ def evaluate(
806
+ self, design=None, *, fractions=None, record: bool = False, q: float = 1.0
807
+ ) -> CellEvaluation:
808
+ """The tensile test of a design (or of the ``fractions`` of the phases at the
809
+ Gauss points, :func:`band_fractions`); ``record``: keep the history for the
810
+ replays."""
811
+ frac = self.fractions(design) if fractions is None else np.asarray(fractions, float)
812
+ graded = design is not None and not np.issubdtype(np.asarray(design).dtype, np.integer)
813
+ mem = self.membrane(frac, q, graded)
814
+ res = self.case.run(
815
+ mem,
816
+ max_strain=self.max_strain if self.case.kind == "tension" else None,
817
+ failure_margin=self.failure_margin,
818
+ record_history=record,
819
+ keep_fields=True,
820
+ )
821
+ fail = res.failure_strain if math.isfinite(res.failure_strain) else math.inf
822
+ meas = failure_measures(res.strain, res.stress, fail, young=self._slope(res))
823
+ if design is not None:
824
+ meas["budget"] = self.budget(design)
825
+ else:
826
+ vol = self.mesh.gauss()[2]
827
+ gauge = self.element_cell >= 0
828
+ share = (frac[gauge] * vol[gauge][..., None]).sum(axis=(0, 1)) / vol[gauge].sum()
829
+ meas["budget"] = float(share @ self.costs)
830
+ value = self.value_of(meas)
831
+ return CellEvaluation(
832
+ None if design is None else np.asarray(design).copy(),
833
+ res,
834
+ meas,
835
+ float(value),
836
+ mem if record else None,
837
+ frac,
838
+ )
839
+
840
+ # -- sensitivities -----------------------------------------------------------------
841
+
842
+ def _columns(self, ev: CellEvaluation):
843
+ """The strength of each cell of a design (MPa, the mixture of its phases) and of
844
+ each cross-section of cells (N), for the weakest-section cap of the estimates."""
845
+ frac = ev.fractions
846
+ inside = self.element_cell >= 0
847
+ vol = self.mesh.gauss()[2]
848
+ cell_frac = np.zeros((self.grid.count, len(self.phases)))
849
+ np.add.at(
850
+ cell_frac, self.element_cell[inside], (frac[inside] * vol[inside][..., None]).sum(1)
851
+ )
852
+ tot = cell_frac.sum(axis=1, keepdims=True)
853
+ cell_frac = cell_frac / np.where(tot > 0, tot, 1.0)
854
+ cell_strength = cell_frac @ self.strengths
855
+ area = self.grid.dy * self.case.thickness
856
+ cols = (cell_strength.reshape(self.grid.shape) * area).sum(axis=0)
857
+ return cell_strength, cols
858
+
859
+ def _cap(self, columns, strength_alt) -> np.ndarray:
860
+ """The strength (MPa) of the weakest cross-section if each cell alone took the
861
+ strength ``strength_alt`` (cells)."""
862
+ cell_strength, cols = columns
863
+ area = self.grid.dy * self.case.thickness
864
+ col = np.arange(self.grid.count) % self.grid.nx
865
+ new_col = cols[col] + (strength_alt - cell_strength) * area
866
+ order = np.argsort(cols)
867
+ m1 = cols[order[0]]
868
+ m2 = cols[order[1]] if len(cols) > 1 else np.inf
869
+ others = np.where(col == order[0], m2, m1)
870
+ return np.minimum(new_col, others) / self.case.section
871
+
872
+ def _effects(self, ev: CellEvaluation, base, law_alt, crit_alt):
873
+ """The change of the work of each cell (steps x cells, mJ) and the strain at
874
+ which it would break (cells) had it alone taken the laws ``law_alt`` and the
875
+ critical strains ``crit_alt`` of its elements (the replays, see the module)."""
876
+ mem = ev.membrane
877
+ alt = replay(mem, ev.result.history, law=law_alt, critical=crit_alt)
878
+ dW = (self.cell_matrix @ (alt.work - base["work"]).T).T
879
+ if self.fracture_radius:
880
+ # the average over the neighbours: those of the same cell switched too
881
+ from morphogen.laser.mechanics import Fracture
882
+
883
+ fx = Fracture(mem.centroids, mem.w0, crit_alt, None)
884
+ bvol = fx.vol.sum(axis=(1, 2))
885
+ pe = fx.element_strain(alt.plastic) # steps x e
886
+ same = self._same
887
+ num = base["num"] - base["num_same"] + (same @ (pe * bvol).T).T
888
+ den = base["den"] - base["den_same"] + same @ bvol
889
+ avg = np.where(den > 0, num / np.where(den > 0, den, 1.0), 0.0)
890
+ brittle = bvol > 0
891
+ ratio = np.where(brittle, avg / np.where(brittle, fx.element_critical, 1.0), 0.0)
892
+ else:
893
+ ratio = alt.ratio
894
+ cross_alt = _crossing(base["strain"], ratio)
895
+ cell_alt = np.full(self.grid.count, np.inf)
896
+ inside = self.element_cell >= 0
897
+ np.minimum.at(cell_alt, self.element_cell[inside], cross_alt[inside])
898
+ return dW, cell_alt
899
+
900
+ def _combine(self, ev: CellEvaluation, base, dW, fail, cap) -> np.ndarray:
901
+ """The values of designs whose work differs from the current one by ``dW``
902
+ (steps x m), breaking at ``fail`` (m) and whose weakest section holds ``cap``
903
+ (MPa, m): the force changed by the derivative of the work with respect to the
904
+ grip displacement."""
905
+ strain, disp = base["strain"], base["displacement"]
906
+ dd = np.diff(disp)
907
+ mid = np.diff(dW, axis=0) / np.where(dd > 0, dd, np.inf)[:, None]
908
+ dF = np.zeros_like(dW)
909
+ dF[1:-1] = 0.5 * (mid[:-1] + mid[1:])
910
+ dF[-1] = mid[-1]
911
+ s_new = base["stress"][:, None] + dF / self.case.section
912
+ meas = failure_measures(strain, s_new, fail, young=base["young"], cap=cap)
913
+ meas["budget"] = np.full(dW.shape[1], ev.measures.get("budget", 0.0))
914
+ return np.asarray(self.value_of(meas), dtype=float)
915
+
916
+ def _switch(self, ev: CellEvaluation, base, law_alt, crit_alt, strength_alt) -> np.ndarray:
917
+ """The value of the design if each cell alone took the laws ``law_alt`` (and
918
+ critical strains ``crit_alt``) of its elements, estimated from the replays (see
919
+ the module): the force changed by the work of its elements, its elements broken
920
+ at the strain where their own (averaged) plastic strain reaches the critical
921
+ one, the others as in the design, the weakest cross-section of cells capping
922
+ the strength."""
923
+ dW, cell_alt = self._effects(ev, base, law_alt, crit_alt)
924
+ fail = np.minimum(base["others"], cell_alt)
925
+ cap = None if base["columns"] is None else self._cap(base["columns"], strength_alt)
926
+ return self._combine(ev, base, dW, fail, cap)
927
+
928
+ def exchanges(self, ev: CellEvaluation, reach: float = 1.5) -> tuple[np.ndarray, np.ndarray]:
929
+ """The estimated gain of exchanging the phases of two neighbouring cells of
930
+ different phases (centres within ``reach`` cells; two phases): the pairs
931
+ ``(c, c')`` (c treated, c' not) and their gains — the moves of a track that
932
+ bends or shifts without breaking, at a constant budget (a Kawasaki rule)."""
933
+ if len(self.phases) != 2:
934
+ raise ValueError("exchanges: two phases")
935
+ d = np.asarray(ev.design).ravel()
936
+ base = self._base(ev)
937
+ ne = len(self.mesh.quads)
938
+ effects = []
939
+ for k in range(2):
940
+ frac = np.zeros((ne, 4, 2))
941
+ frac[:, :, k] = 1.0
942
+ law, crit = self._arrays(frac)
943
+ effects.append(self._effects(ev, base, law, crit))
944
+ g = self.grid
945
+ idx = np.arange(g.count).reshape(g.shape)
946
+ pairs = []
947
+ r = math.floor(reach)
948
+ for di in range(-r, r + 1):
949
+ for dj in range(-r, r + 1):
950
+ if (di, dj) == (0, 0) or math.hypot(di, dj) > reach:
951
+ continue
952
+ a = idx[max(0, -di) : g.ny - max(0, di), max(0, -dj) : g.nx - max(0, dj)]
953
+ b = idx[max(0, di) : g.ny + min(0, di), max(0, dj) : g.nx + min(0, dj)]
954
+ a, b = a.ravel(), b.ravel()
955
+ keep = (d[a] == 1) & (d[b] == 0)
956
+ pairs.append(np.column_stack([a[keep], b[keep]]))
957
+ pairs = np.concatenate(pairs) if pairs else np.zeros((0, 2), dtype=int)
958
+ if not len(pairs):
959
+ return pairs, np.zeros(0)
960
+ c, cp = pairs[:, 0], pairs[:, 1]
961
+ dW = effects[0][0][:, c] + effects[1][0][:, cp]
962
+ # the failure: the cells but c as in the design, c' as the treated phase
963
+ cell_cur = base["cells"]
964
+ order = np.argsort(cell_cur)
965
+ m1, m2 = cell_cur[order[0]], cell_cur[order[1]]
966
+ others = np.where(c == order[0], m2, m1)
967
+ others = np.minimum(others, base["fixed"])
968
+ fail = np.minimum(others, effects[1][1][cp])
969
+ cap = None
970
+ if base["columns"] is not None: # the weakest section: the columns of c and c'
971
+ cols = base["columns"][1]
972
+ area = g.dy * self.case.thickness
973
+ col_c, col_p = c % g.nx, cp % g.nx
974
+ delta = (self.strengths[1] - self.strengths[0]) * area
975
+ new = np.repeat(cols[None, :], len(pairs), axis=0)
976
+ rows = np.arange(len(pairs))
977
+ new[rows, col_c] -= delta
978
+ new[rows, col_p] += delta
979
+ cap = new.min(axis=1) / self.case.section
980
+ values = self._combine(ev, base, dW, fail, cap)
981
+ return pairs, values - base["value"]
982
+
983
+ def _base(self, ev: CellEvaluation) -> dict:
984
+ res = ev.result
985
+ if ev.membrane is None or not res.history:
986
+ raise ValueError("estimates: evaluate the design with record=True")
987
+ cur = replay(ev.membrane, res.history)
988
+ strain = cur.strain
989
+ cross = _crossing(strain, cur.ratio)
990
+ inside = self.element_cell >= 0
991
+ cell_cur = np.full(self.grid.count, np.inf)
992
+ np.minimum.at(cell_cur, self.element_cell[inside], cross[inside])
993
+ fixed = float(cross[~inside].min(initial=np.inf))
994
+ order = np.argsort(cell_cur)
995
+ m1 = cell_cur[order[0]]
996
+ m2 = cell_cur[order[1]] if len(order) > 1 else np.inf
997
+ others = np.full(self.grid.count, m1)
998
+ others[order[0]] = m2
999
+ others = np.minimum(others, fixed)
1000
+ stress = np.interp(strain, res.strain, res.stress)
1001
+ base = {
1002
+ "strain": strain,
1003
+ "displacement": cur.displacement,
1004
+ "work": cur.work,
1005
+ "stress": stress,
1006
+ "others": others,
1007
+ "cells": cell_cur,
1008
+ "fixed": fixed,
1009
+ "columns": self._columns(ev) if self.case.columns else None,
1010
+ "young": self._slope(res),
1011
+ }
1012
+ if self.fracture_radius:
1013
+ fx = ev.membrane.fracture
1014
+ bvol = fx.vol.sum(axis=(1, 2))
1015
+ bp = (fx.element_strain(cur.plastic) * bvol).T # e x steps
1016
+ W, same = self._weights, self._same
1017
+ base["num"] = (W @ bp).T
1018
+ base["num_same"] = (same @ bp).T
1019
+ base["den"] = W @ bvol
1020
+ base["den_same"] = same @ bvol
1021
+ meas = failure_measures(
1022
+ strain, stress[:, None], np.array([min(m1, fixed)]), young=base["young"]
1023
+ )
1024
+ meas["budget"] = np.array([ev.measures.get("budget", 0.0)])
1025
+ base["value"] = float(np.asarray(self.value_of(meas))[0])
1026
+ return base
1027
+
1028
+ def estimates(self, ev: CellEvaluation) -> np.ndarray:
1029
+ """The value of the design if each cell alone took each phase ``(cells,
1030
+ phases)`` (its current phase: the design's value), from the replays."""
1031
+ base = self._base(ev)
1032
+ ne = len(self.mesh.quads)
1033
+ out = np.empty((self.grid.count, len(self.phases)))
1034
+ for k, _phase in enumerate(self.phases):
1035
+ frac = np.zeros((ne, 4, len(self.phases)))
1036
+ frac[:, :, k] = 1.0
1037
+ law, crit = self._arrays(frac)
1038
+ out[:, k] = self._switch(
1039
+ ev, base, law, crit, np.full(self.grid.count, self.strengths[k])
1040
+ )
1041
+ if ev.design is not None and np.issubdtype(np.asarray(ev.design).dtype, np.integer):
1042
+ d = np.asarray(ev.design).ravel()
1043
+ out[np.arange(self.grid.count), d] = base["value"]
1044
+ return out - base["value"]
1045
+
1046
+ def phase_effects(self, ev: CellEvaluation, base=None) -> list:
1047
+ """For each phase, the change of the work of each cell and the strain at which
1048
+ it would break had it alone taken that phase (:meth:`_effects`)."""
1049
+ base = self._base(ev) if base is None else base
1050
+ ne = len(self.mesh.quads)
1051
+ out = []
1052
+ for k in range(len(self.phases)):
1053
+ frac = np.zeros((ne, 4, len(self.phases)))
1054
+ frac[:, :, k] = 1.0
1055
+ law, crit = self._arrays(frac)
1056
+ out.append(self._effects(ev, base, law, crit))
1057
+ return out
1058
+
1059
+ def move_values(self, ev: CellEvaluation, base, effects, moves) -> np.ndarray:
1060
+ """The estimated gain of each move, a set of cells and their new phases
1061
+ ``(cells, phases)``, all changed together (first order: their works add up,
1062
+ the first of their fractures and of the others' counts, the cross-sections
1063
+ change)."""
1064
+ if not moves:
1065
+ return np.zeros(0)
1066
+ g = self.grid
1067
+ columns = base["columns"] is not None
1068
+ if columns:
1069
+ cell_strength, cols = base["columns"]
1070
+ area = g.dy * self.case.thickness
1071
+ order = np.argsort(base["cells"])
1072
+ ns = len(base["strain"])
1073
+ dW = np.zeros((ns, len(moves)))
1074
+ fail = np.empty(len(moves))
1075
+ cap = np.empty(len(moves))
1076
+ for m, (cells, phases) in enumerate(moves):
1077
+ cells = np.asarray(cells, dtype=int)
1078
+ phases = np.asarray(phases, dtype=int)
1079
+ inside = set(cells.tolist())
1080
+ other = next((base["cells"][c] for c in order if c not in inside), np.inf)
1081
+ f = min(other, base["fixed"])
1082
+ new_cols = cols.copy() if columns else None
1083
+ for c, k in zip(cells, phases, strict=True):
1084
+ dW[:, m] += effects[k][0][:, c]
1085
+ f = min(f, effects[k][1][c])
1086
+ if columns:
1087
+ new_cols[c % g.nx] += (self.strengths[k] - cell_strength[c]) * area
1088
+ fail[m] = f
1089
+ cap[m] = new_cols.min() / self.case.section if columns else np.inf
1090
+ return self._combine(ev, base, dW, fail, cap if columns else None) - base["value"]
1091
+
1092
+ def derivatives(self, ev: CellEvaluation, density, q: float = 1.0, step: float = 0.05):
1093
+ """The derivative of the value with respect to the density of each cell (two
1094
+ phases), by replays of the densities ``x ± step`` (one-sided at the bounds)."""
1095
+ base = self._base(ev)
1096
+ x = np.asarray(density, dtype=float).ravel()
1097
+ up = np.minimum(x + step, 1.0)
1098
+ lo = np.maximum(x - step, 0.0)
1099
+ vals = []
1100
+ for xx in (up, lo):
1101
+ law, crit = self._arrays(self.fractions(xx.reshape(self.grid.shape)), q, True)
1102
+ strength = self.strengths[0] + (self.strengths[1] - self.strengths[0]) * xx**q
1103
+ vals.append(self._switch(ev, base, law, crit, strength))
1104
+ span = np.maximum(up - lo, 1e-12)
1105
+ return (vals[0] - vals[1]) / span
1106
+
1107
+
1108
+ # -- cellular automata -----------------------------------------------------------------
1109
+
1110
+
1111
+ @dataclass
1112
+ class CellOptimization:
1113
+ """The result of an automaton: the best ``design`` and its ``evaluation``, the
1114
+ ``history`` of the iterations (value, measures, budget, time) and their designs."""
1115
+
1116
+ design: np.ndarray
1117
+ evaluation: CellEvaluation
1118
+ history: list = field(default_factory=list)
1119
+ designs: list = field(default_factory=list, repr=False)
1120
+ time_s: float = 0.0
1121
+ method: str = ""
1122
+ evaluations: int = 0
1123
+ density: np.ndarray | None = field(default=None, repr=False)
1124
+
1125
+ def summary(self) -> dict:
1126
+ return {"method": self.method, "value": self.evaluation.value, **self.evaluation.measures}
1127
+
1128
+
1129
+ def initial_design(grid: CellGrid, budget: float, kind: str = "band", seed: int = 0):
1130
+ """A starting design of two phases: the central ``band`` of rows, ``random`` cells,
1131
+ or (``uniform``) the densities equal to the budget."""
1132
+ if kind == "band":
1133
+ return grid.band(budget)
1134
+ if kind == "random":
1135
+ rng = np.random.default_rng(seed)
1136
+ d = np.zeros(grid.count, dtype=int)
1137
+ d[rng.permutation(grid.count)[: round(budget * grid.count)]] = 1
1138
+ return d.reshape(grid.shape)
1139
+ if kind == "uniform":
1140
+ return np.full(grid.shape, float(budget))
1141
+ raise ValueError("initial design: band, random or uniform")
1142
+
1143
+
1144
+ def _assign(values, costs, current, target, orbit_size, step, max_change):
1145
+ """The phases of the orbits that maximize ``Σ values − λ cost`` at the ``target``
1146
+ cost, within ``step`` levels of the current phases and a share ``max_change`` of
1147
+ changed cells (a hysteresis bonus to the current phases)."""
1148
+ n_orb, n_ph = values.shape
1149
+ levels = np.arange(n_ph)
1150
+ allowed = np.abs(levels[None, :] - current[:, None]) <= step
1151
+ cost = costs[None, :] * orbit_size[:, None]
1152
+ span = np.abs(values).max() + 1e-30
1153
+ keep_bonus = np.zeros_like(values)
1154
+ keep_bonus[np.arange(n_orb), current] = 1.0
1155
+
1156
+ def choose(lam, bonus):
1157
+ score = values + bonus * span * keep_bonus - lam * cost
1158
+ score = np.where(allowed, score, -np.inf)
1159
+ return np.argmax(score, axis=1)
1160
+
1161
+ def solve(bonus):
1162
+ steps = np.diff(np.unique(costs))
1163
+ reach = 100.0 * span / max(steps.min() if steps.size else 1.0, 1e-12)
1164
+ lo, hi = -reach - 1.0, reach + 1.0
1165
+ for _ in range(80):
1166
+ lam = 0.5 * (lo + hi)
1167
+ used = (costs[choose(lam, bonus)] * orbit_size).sum()
1168
+ if used > target:
1169
+ lo = lam
1170
+ else:
1171
+ hi = lam
1172
+ c_lo, c_hi = choose(lo, bonus), choose(hi, bonus)
1173
+ u_lo = (costs[c_lo] * orbit_size).sum()
1174
+ u_hi = (costs[c_hi] * orbit_size).sum()
1175
+ return c_lo if abs(u_lo - target) < abs(u_hi - target) else c_hi
1176
+
1177
+ total = orbit_size.sum()
1178
+ pick = solve(0.0)
1179
+ if max_change is None or (orbit_size * (pick != current)).sum() <= max_change * total:
1180
+ return pick
1181
+ lo, hi = 0.0, 2.0
1182
+ for _ in range(30):
1183
+ mid = 0.5 * (lo + hi)
1184
+ trial = solve(mid)
1185
+ if (orbit_size * (trial != current)).sum() > max_change * total:
1186
+ lo = mid
1187
+ else:
1188
+ hi = mid
1189
+ pick = trial
1190
+ return pick
1191
+
1192
+
1193
+ def _neighbour_pairs(grid: CellGrid, orbit, design, reach: float, active=None):
1194
+ """The pairs of orbits ``(a, b)`` of the same size, ``a`` treated and ``b`` not,
1195
+ with (active) cells within ``reach`` cells of each other."""
1196
+ d = np.asarray(design).ravel()
1197
+ act = np.ones(grid.count, dtype=bool) if active is None else np.asarray(active)
1198
+ idx = np.arange(grid.count).reshape(grid.shape)
1199
+ size = np.bincount(orbit)
1200
+ found = set()
1201
+ r = math.floor(reach)
1202
+ for di in range(-r, r + 1):
1203
+ for dj in range(-r, r + 1):
1204
+ if (di, dj) == (0, 0) or math.hypot(di, dj) > reach:
1205
+ continue
1206
+ a = idx[max(0, -di) : grid.ny - max(0, di), max(0, -dj) : grid.nx - max(0, dj)]
1207
+ b = idx[max(0, di) : grid.ny + min(0, di), max(0, dj) : grid.nx + min(0, dj)]
1208
+ a, b = a.ravel(), b.ravel()
1209
+ keep = (d[a] == 1) & (d[b] == 0) & act[a] & act[b]
1210
+ for oa, ob in zip(orbit[a[keep]], orbit[b[keep]], strict=True):
1211
+ if oa != ob and size[oa] == size[ob]:
1212
+ found.add((int(oa), int(ob)))
1213
+ return sorted(found)
1214
+
1215
+
1216
+ def symmetrize(design, orbit) -> np.ndarray:
1217
+ """A design made constant on the orbits (the phase most of their cells hold)."""
1218
+ d = np.asarray(design)
1219
+ flat = d.ravel()
1220
+ n = orbit.max() + 1
1221
+ out = np.empty_like(flat)
1222
+ for o in range(n):
1223
+ vals = flat[orbit == o]
1224
+ out[orbit == o] = np.bincount(vals).argmax()
1225
+ return out.reshape(d.shape)
1226
+
1227
+
1228
+ def treatable(design, width: int = 2) -> bool:
1229
+ """Whether a design (two phases) can be drawn by a spot of ``width`` cells: every
1230
+ treated cell lies in a treated square of ``width`` cells (the design equals its
1231
+ morphological opening), and the squares join by sides or corners wherever the
1232
+ treated cells do (no neck thinner than the spot)."""
1233
+ from scipy import ndimage
1234
+
1235
+ d = np.asarray(design) > 0
1236
+ if width <= 1 or not d.any():
1237
+ return True
1238
+ # a spot may overhang the edges: the specimen is cut after the treatment
1239
+ d = np.pad(d, width, mode="edge")
1240
+ st = np.ones((width, width), dtype=bool)
1241
+ if not np.array_equal(ndimage.binary_opening(d, structure=st), d):
1242
+ return False
1243
+ eroded = ndimage.binary_erosion(d, structure=st, origin=(-(width // 2),) * 2)
1244
+ n_d = ndimage.label(d)[1]
1245
+ n_e = ndimage.label(eroded, structure=np.ones((3, 3), dtype=bool))[1]
1246
+ return n_e == n_d
1247
+
1248
+
1249
+ def make_treatable(design, width: int = 2) -> np.ndarray:
1250
+ """The largest part of a design a spot of ``width`` cells draws (its opening)."""
1251
+ from scipy import ndimage
1252
+
1253
+ d = np.asarray(design) > 0
1254
+ if width <= 1:
1255
+ return d.astype(int)
1256
+ st = np.ones((width, width), dtype=bool)
1257
+ pad = np.pad(d, width, mode="edge")
1258
+ return ndimage.binary_opening(pad, structure=st)[width:-width, width:-width].astype(int)
1259
+
1260
+
1261
+ def beso(
1262
+ problem: CellProblem,
1263
+ design=None,
1264
+ *,
1265
+ budget: float | None = 0.2,
1266
+ er: float = 0.02,
1267
+ radius: float = 1.5,
1268
+ iterations: int = 40,
1269
+ step: int = 1,
1270
+ max_change: float | None = 0.1,
1271
+ averaging: bool = True,
1272
+ symmetry=(),
1273
+ period: float | None = None,
1274
+ tol: float = 1e-3,
1275
+ patience: int = 6,
1276
+ verify: bool = True,
1277
+ tries: int = 3,
1278
+ tabu_length: int = 3,
1279
+ moves: str = "swap",
1280
+ reach: float = 2.0,
1281
+ candidates: int = 4,
1282
+ min_width: int | None = None,
1283
+ multigrid=None,
1284
+ callback=None,
1285
+ ) -> CellOptimization:
1286
+ """The bidirectional evolutionary automaton on the cells (see the module), from a
1287
+ ``design`` (default: the central band of the ``budget``) towards the ``budget``
1288
+ (mean cost of the cells); the cells change by orbits of the ``symmetry`` and of
1289
+ the translation by ``period`` (the failure of a periodic pattern moves to the next
1290
+ period if one alone changes). ``moves``:
1291
+
1292
+ * ``swap`` — the BESO rule: the estimated benefit of each phase of each orbit over
1293
+ the untreated sheet, filtered over ``radius`` (mm) and averaged with the
1294
+ previous iteration; each orbit takes the phase of largest benefit minus ``λ``
1295
+ times its cost (``λ`` meets the budget, which moves by ``er`` per iteration), at
1296
+ most ``step`` levels and a share ``max_change`` of the cells changing.
1297
+ ``verify``: at the budget, the new design replaces the current one only if its
1298
+ finite element test does not lower the value (the replays hold the kinematics:
1299
+ a gap in a track that necks, a corner where the strain concentrates escape
1300
+ them); refused, the changes are halved, ``tries`` times, then their orbits keep
1301
+ their phase for ``tabu_length`` iterations.
1302
+ * ``exchange`` (two phases, at the budget) — the exchanges of the phases of two
1303
+ orbits with neighbouring cells (within ``reach`` cells), a track that bends or
1304
+ shifts without breaking (a Kawasaki rule): the ``candidates`` of largest
1305
+ estimated gains are tested by finite elements, the best taken if it raises the
1306
+ value, the others tabu.
1307
+
1308
+ ``min_width`` (cells, two phases): only designs a spot of this width draws are
1309
+ tried (:func:`treatable`): without it the automaton breaks the tracks into islands
1310
+ and corner contacts that carry no load and cannot be made.
1311
+
1312
+ Stops when the value stalls for ``patience`` iterations or nothing changes.
1313
+ ``multigrid``: the coarser cell sizes (mm) to solve first, e.g. ``(2, 1)``."""
1314
+ t0 = time.perf_counter()
1315
+ if multigrid:
1316
+ hist, designs, start, grid_prev, evals = [], [], design, None, 0
1317
+ for size in [*sorted((float(v) for v in multigrid), reverse=True), problem.size]:
1318
+ sub = problem if size == problem.size else replace(problem, size=size)
1319
+ if start is not None and grid_prev is not None:
1320
+ start = grid_prev.transfer(start, sub.grid)
1321
+ r = beso(
1322
+ sub,
1323
+ start,
1324
+ budget=budget,
1325
+ er=er,
1326
+ radius=max(radius, 1.5 * size),
1327
+ iterations=iterations,
1328
+ step=step,
1329
+ max_change=max_change,
1330
+ averaging=averaging,
1331
+ symmetry=symmetry,
1332
+ period=period,
1333
+ tol=tol,
1334
+ patience=patience,
1335
+ verify=verify,
1336
+ tries=tries,
1337
+ tabu_length=tabu_length,
1338
+ moves=moves,
1339
+ reach=reach,
1340
+ candidates=candidates,
1341
+ min_width=min_width,
1342
+ callback=callback,
1343
+ )
1344
+ hist += [{**h, "size": size} for h in r.history]
1345
+ designs += r.designs
1346
+ evals += r.evaluations
1347
+ start, grid_prev = r.design, sub.grid
1348
+ r.history, r.designs, r.evaluations = hist, designs, evals
1349
+ r.time_s = time.perf_counter() - t0
1350
+ r.method = f"beso-{moves}-multigrid"
1351
+ return r
1352
+ if moves not in ("swap", "exchange"):
1353
+ raise ValueError("moves: swap or exchange")
1354
+ grid = problem.grid
1355
+ orbit = grid.orbits(symmetry, period)
1356
+ n_orb = orbit.max() + 1
1357
+ # the sizes of the orbits in active cells: the budget counts them only
1358
+ size = np.bincount(orbit, weights=problem.active.astype(float), minlength=n_orb)
1359
+ n_cells = float(problem.active.sum())
1360
+ x = initial_design(grid, budget) if design is None else np.asarray(design).astype(int)
1361
+ if x.shape != grid.shape:
1362
+ raise ValueError(f"design of shape {grid.shape}")
1363
+ x = symmetrize(x, orbit)
1364
+ if budget is None:
1365
+ budget = problem.budget(x)
1366
+ H = grid.filter_matrix(radius)
1367
+ costs = problem.costs
1368
+ history, designs = [], []
1369
+ evaluations = 0
1370
+
1371
+ def at_budget(b):
1372
+ return abs(b - budget) <= 0.5 * size.max() / n_cells + 1e-12
1373
+
1374
+ def log(it, e, accepted):
1375
+ history.append(
1376
+ {
1377
+ "iteration": it,
1378
+ "evaluation": evaluations,
1379
+ "accepted": accepted,
1380
+ "value": e.value,
1381
+ **{k: e.measures[k] for k in MEASURES if k in e.measures},
1382
+ "time_s": time.perf_counter() - t0,
1383
+ }
1384
+ )
1385
+ designs.append(np.asarray(e.design).copy())
1386
+ if callback is not None:
1387
+ callback(it, e)
1388
+
1389
+ ev = problem.evaluate(x, record=True)
1390
+ evaluations += 1
1391
+ log(0, ev, True)
1392
+ best = ev if at_budget(problem.budget(x)) else None
1393
+ prev = None
1394
+ tabu = {}
1395
+ stall = 0
1396
+ for it in range(1, iterations + 1):
1397
+ cur_budget = problem.budget(x)
1398
+ base = problem._base(ev)
1399
+ effects = problem.phase_effects(ev, base)
1400
+ cur = np.zeros(n_orb, dtype=int)
1401
+ cur[orbit] = x.ravel()
1402
+ members = [np.flatnonzero(orbit == o) for o in range(n_orb)]
1403
+ tabu = {k: v - 1 for k, v in tabu.items() if v > 1}
1404
+ if moves == "exchange" and at_budget(cur_budget):
1405
+ if len(problem.phases) != 2:
1406
+ raise ValueError("exchange moves: two phases")
1407
+ pairs = [
1408
+ (a, b)
1409
+ for a, b in _neighbour_pairs(grid, orbit, x, reach, problem.active)
1410
+ if ("x", a, b) not in tabu
1411
+ ]
1412
+ mv = [
1413
+ (
1414
+ np.concatenate([members[a], members[b]]),
1415
+ np.concatenate([np.zeros(len(members[a]), int), np.ones(len(members[b]), int)]),
1416
+ )
1417
+ for a, b in pairs
1418
+ ]
1419
+ if min_width:
1420
+ keep = []
1421
+ for i, (cells, phases) in enumerate(mv):
1422
+ xn = x.ravel().copy()
1423
+ xn[cells] = phases
1424
+ if treatable(xn.reshape(grid.shape), min_width):
1425
+ keep.append(i)
1426
+ pairs = [pairs[i] for i in keep]
1427
+ mv = [mv[i] for i in keep]
1428
+ gains = problem.move_values(ev, base, effects, mv)
1429
+ order = np.argsort(-gains)[:candidates]
1430
+ trials = []
1431
+ for i in order:
1432
+ xn = x.ravel().copy()
1433
+ cells, phases = mv[i]
1434
+ xn[cells] = phases
1435
+ xn = xn.reshape(grid.shape)
1436
+ evn = problem.evaluate(xn, record=True)
1437
+ evaluations += 1
1438
+ log(it, evn, False)
1439
+ trials.append((evn.value, i, xn, evn))
1440
+ if not trials:
1441
+ break
1442
+ value, i, xn, evn = max(trials, key=lambda t: t[0])
1443
+ if value > ev.value * (1.0 + 1e-9):
1444
+ history[-len(trials) + [t[1] for t in trials].index(i)]["accepted"] = True
1445
+ gain = value - ev.value
1446
+ x, ev = xn, evn
1447
+ if best is None or ev.value > best.value:
1448
+ best = ev
1449
+ stall = stall + 1 if gain <= tol * abs(ev.value) else 0
1450
+ else:
1451
+ for _v, j, _x, _e in trials:
1452
+ tabu[("x", *pairs[j])] = tabu_length
1453
+ stall += 1
1454
+ if stall >= patience:
1455
+ break
1456
+ continue
1457
+ # the BESO rule on the orbits: the benefit of each phase over the untreated sheet
1458
+ mv = [
1459
+ (members[o], np.full(len(members[o]), k))
1460
+ for o in range(n_orb)
1461
+ for k in range(len(costs))
1462
+ ]
1463
+ gains = problem.move_values(ev, base, effects, mv).reshape(n_orb, len(costs))
1464
+ gains[np.arange(n_orb), cur] = 0.0
1465
+ rel = gains - gains[:, [0]]
1466
+ field_ = (rel / np.where(size > 0, size, 1.0)[:, None])[orbit] # per cell
1467
+ field_ = H @ (field_ * problem.active[:, None])
1468
+ vals = np.zeros((n_orb, len(costs)))
1469
+ np.add.at(vals, orbit, field_)
1470
+ if averaging and prev is not None:
1471
+ vals = 0.5 * (vals + prev)
1472
+ prev = vals
1473
+ frozen = np.array([("s", o) in tabu for o in range(n_orb)])
1474
+ frozen |= ~np.bincount(orbit, weights=problem.active, minlength=n_orb).astype(bool)
1475
+ vals_t = vals.copy()
1476
+ if frozen.any(): # recently refused changes: the orbits keep their phase
1477
+ vals_t[frozen] -= 1e6 * (np.abs(vals).max() + 1.0)
1478
+ vals_t[frozen, cur[frozen]] = vals[frozen, cur[frozen]]
1479
+ target = cur_budget + np.clip(budget - cur_budget, -er, er)
1480
+ limit = max_change
1481
+ accepted, proposed, changed = False, False, None
1482
+ for _attempt in range(tries if verify else 1):
1483
+ pick = _assign(vals_t, costs, cur, target * n_cells, size, step, limit)
1484
+ changed = pick != cur
1485
+ if not changed.any():
1486
+ break
1487
+ proposed = True
1488
+ xn = pick[orbit].reshape(grid.shape)
1489
+ if min_width and len(costs) == 2 and not treatable(xn, min_width):
1490
+ limit = 0.5 * (limit if limit is not None else (size * changed).sum() / n_cells)
1491
+ if limit * n_cells < size[size > 0].min():
1492
+ break
1493
+ continue
1494
+ evn = problem.evaluate(xn, record=True)
1495
+ evaluations += 1
1496
+ moving = not (at_budget(cur_budget) and at_budget(problem.budget(xn)))
1497
+ ok = not verify or moving or evn.value >= ev.value * (1.0 - 1e-9)
1498
+ log(it, evn, ok)
1499
+ if ok:
1500
+ accepted = True
1501
+ break
1502
+ limit = 0.5 * (limit if limit is not None else (size * changed).sum() / n_cells)
1503
+ if limit * n_cells < size[size > 0].min():
1504
+ break
1505
+ if accepted:
1506
+ gain = evn.value - ev.value
1507
+ x, ev = xn, evn
1508
+ if at_budget(problem.budget(x)) and (best is None or ev.value > best.value):
1509
+ best = ev
1510
+ stall = stall + 1 if abs(gain) <= tol * abs(ev.value) else 0
1511
+ else:
1512
+ if changed is not None:
1513
+ for o in np.flatnonzero(changed):
1514
+ tabu[("s", int(o))] = tabu_length
1515
+ stall += 1
1516
+ if not proposed and not frozen.any():
1517
+ break # no orbit wants to change
1518
+ if stall >= patience:
1519
+ break
1520
+ best = best or ev
1521
+ best.membrane = None
1522
+ out = CellOptimization(
1523
+ best.design, best, history, designs, time.perf_counter() - t0, f"beso-{moves}"
1524
+ )
1525
+ out.evaluations = evaluations
1526
+ return out
1527
+
1528
+
1529
+ def hca(
1530
+ problem: CellProblem,
1531
+ density=None,
1532
+ *,
1533
+ budget: float = 0.24,
1534
+ kp: float = 0.25,
1535
+ radius: float = 1.5,
1536
+ q: float = 2.0,
1537
+ iterations: int = 30,
1538
+ move: float = 0.2,
1539
+ levels: int | None = None,
1540
+ tol: float = 2e-3,
1541
+ callback=None,
1542
+ ) -> CellOptimization:
1543
+ """The hybrid cellular automaton (see the module) on the treatment densities of two
1544
+ phases: each cell's stimulus, the derivative of the value (from the replays)
1545
+ averaged over its neighbourhood, drives its density by ``kp`` (relative to the
1546
+ largest stimulus, at most ``move``) towards the set point that meets the
1547
+ ``budget``; finally rounded to ``levels`` (default: the two phases, at the
1548
+ budget)."""
1549
+ t0 = time.perf_counter()
1550
+ grid = problem.grid
1551
+ x = initial_design(grid, budget, "uniform") if density is None else np.asarray(density, float)
1552
+ H = grid.filter_matrix(radius)
1553
+ history, designs = [], []
1554
+ best = None
1555
+ for it in range(iterations):
1556
+ ev = problem.evaluate(x, record=True, q=q)
1557
+ history.append(
1558
+ {
1559
+ "iteration": it,
1560
+ "value": ev.value,
1561
+ "budget": problem.budget(x),
1562
+ **{k: ev.measures[k] for k in MEASURES if k in ev.measures},
1563
+ "time_s": time.perf_counter() - t0,
1564
+ }
1565
+ )
1566
+ designs.append(x.copy())
1567
+ if callback is not None:
1568
+ callback(it, ev)
1569
+ stim = H @ problem.derivatives(ev, x, q=q)
1570
+ scale = np.abs(stim).max() + 1e-30
1571
+ xr = x.ravel()
1572
+
1573
+ def update(setpoint, xr=xr, stim=stim, scale=scale):
1574
+ dx = np.clip(kp * (stim - setpoint) / scale, -move, move)
1575
+ return np.clip(xr + dx, 0.0, 1.0)
1576
+
1577
+ lo, hi = stim.min() - scale / kp, stim.max() + scale / kp
1578
+ for _ in range(80):
1579
+ mid = 0.5 * (lo + hi)
1580
+ if update(mid).mean() > budget:
1581
+ lo = mid
1582
+ else:
1583
+ hi = mid
1584
+ xn = update(0.5 * (lo + hi))
1585
+ change = np.abs(xn - xr).max()
1586
+ x = xn.reshape(grid.shape)
1587
+ if change < tol:
1588
+ break
1589
+ final = round_design(x, budget, levels)
1590
+ ev = problem.evaluate(final)
1591
+ history.append(
1592
+ {
1593
+ "iteration": len(history),
1594
+ "value": ev.value,
1595
+ "budget": problem.budget(final),
1596
+ **{k: ev.measures[k] for k in MEASURES if k in ev.measures},
1597
+ "time_s": time.perf_counter() - t0,
1598
+ }
1599
+ )
1600
+ best = ev
1601
+ out = CellOptimization(final, best, history, designs, time.perf_counter() - t0, "hca")
1602
+ out.density = x
1603
+ return out
1604
+
1605
+
1606
+ def round_design(density, budget: float | None = None, levels: int | None = None):
1607
+ """Densities rounded to two phases (the largest at the ``budget``: the share of
1608
+ cells treated) or to ``levels`` + 1 equally spaced levels (phase indices)."""
1609
+ x = np.asarray(density, dtype=float)
1610
+ if levels:
1611
+ return np.rint(x * levels).astype(int)
1612
+ n = round((x.mean() if budget is None else budget) * x.size)
1613
+ out = np.zeros(x.size, dtype=int)
1614
+ out[np.argsort(-x.ravel(), kind="stable")[:n]] = 1
1615
+ return out.reshape(x.shape)
1616
+
1617
+
1618
+ def topology(
1619
+ problem: CellProblem,
1620
+ density=None,
1621
+ *,
1622
+ budget: float = 0.24,
1623
+ radius: float = 1.5,
1624
+ q: float = 2.0,
1625
+ beta: float = 1.0,
1626
+ beta_max: float = 16.0,
1627
+ iterations: int = 40,
1628
+ move: float = 0.15,
1629
+ tol: float = 2e-3,
1630
+ callback=None,
1631
+ ) -> CellOptimization:
1632
+ """Density-based topology optimization (see the module): the densities filtered
1633
+ over ``radius`` and projected (``beta`` doubled every 10 iterations up to
1634
+ ``beta_max``), the mixture ``w^q``, the derivatives of the replays, MMA under the
1635
+ budget constraint; the result rounded to two phases at the budget."""
1636
+ from morphogen.optimization.mma import MMA
1637
+
1638
+ t0 = time.perf_counter()
1639
+ grid = problem.grid
1640
+ n = grid.count
1641
+ H = grid.filter_matrix(radius)
1642
+ x = np.full(n, float(budget)) if density is None else np.asarray(density, float).ravel()
1643
+ opt = MMA(n, 2, 0.0, 1.0, move=move)
1644
+ history, designs = [], []
1645
+ scale = None
1646
+ for it in range(iterations):
1647
+ xt = H @ x
1648
+ xp = heaviside(xt, beta) if beta > 0 else xt
1649
+ ev = problem.evaluate(xp.reshape(grid.shape), record=True, q=q)
1650
+ history.append(
1651
+ {
1652
+ "iteration": it,
1653
+ "value": ev.value,
1654
+ "budget": float(xp.mean()),
1655
+ "beta": beta,
1656
+ **{k: ev.measures[k] for k in MEASURES if k in ev.measures},
1657
+ "time_s": time.perf_counter() - t0,
1658
+ }
1659
+ )
1660
+ designs.append(xp.reshape(grid.shape).copy())
1661
+ if callback is not None:
1662
+ callback(it, ev)
1663
+ g = problem.derivatives(ev, xp, q=q)
1664
+ dxp = heaviside_derivative(xt, beta) if beta > 0 else np.ones_like(xt)
1665
+ dJ = H.T @ (g * dxp)
1666
+ if scale is None:
1667
+ scale = abs(ev.value) + 1e-30
1668
+ f0 = -ev.value / scale
1669
+ df0 = -dJ / scale
1670
+ vol = xp.mean() - budget # the budget as an equality: two inequalities
1671
+ dvol = H.T @ (dxp / n)
1672
+ xn = opt.update(x, f0, df0, np.array([vol, -vol]), np.vstack([dvol, -dvol]))
1673
+ change = np.abs(xn - x).max()
1674
+ x = xn
1675
+ if (it + 1) % 10 == 0 and beta < beta_max:
1676
+ beta = min(2 * beta, beta_max)
1677
+ opt.reset()
1678
+ elif change < tol and beta >= beta_max:
1679
+ break
1680
+ xp = heaviside(H @ x, beta) if beta > 0 else H @ x
1681
+ final = round_design(xp.reshape(grid.shape), budget)
1682
+ ev = problem.evaluate(final)
1683
+ history.append(
1684
+ {
1685
+ "iteration": len(history),
1686
+ "value": ev.value,
1687
+ "budget": problem.budget(final),
1688
+ **{k: ev.measures[k] for k in MEASURES if k in ev.measures},
1689
+ "time_s": time.perf_counter() - t0,
1690
+ }
1691
+ )
1692
+ out = CellOptimization(final, ev, history, designs, time.perf_counter() - t0, "topology")
1693
+ out.density = xp.reshape(grid.shape)
1694
+ return out