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,632 @@
1
+ """Topology optimization of periodic cells by inverse homogenization.
2
+
3
+ The cell is a grid of voxels of relative density ``rho`` (SIMP: stiffness
4
+ ``eps + (1 - eps) rho^p`` times the base material, Bendsøe 1989). Its homogenized tensor
5
+ (FFT solver, :mod:`morphogen.optimization.cell`) and the exact derivatives give the
6
+ objective and its gradient (Sigmund 1994). Objectives:
7
+
8
+ ``bulk_modulus``, ``shear_modulus``
9
+ maximize the mean of the normal block of the stiffness tensor (bulk modulus of a
10
+ cubic material) or of its shear moduli;
11
+ ``poisson_ratio``
12
+ minimize ``mean(C_ij, i != j) / mean(C_ii)`` over the normal block (``C_12 / C_11``
13
+ for square or cubic symmetry: the Poisson's ratio under uniaxial strain), with the
14
+ mean normal stiffness kept above ``min_stiffness`` times the Young's modulus of the
15
+ base material (a second constraint, mma only): negative Poisson's ratios (auxetics);
16
+ ``conductivity``
17
+ maximize the mean of the diagonal of the conductivity tensor;
18
+ ``target``
19
+ reach a target stiffness tensor (least squares, NaN entries ignored).
20
+
21
+ Planar cells (one voxel through the thickness, prismatic microstructures) use the
22
+ in-plane components. The design is constrained to a volume fraction, regularized by a
23
+ density filter, a Heaviside projection with continuation and a symmetry group.
24
+
25
+ Methods: ``oc`` (optimality criteria, monotone objectives), ``mma`` (method of moving
26
+ asymptotes, any objective), ``beso`` (bi-directional evolutionary structural
27
+ optimization: solid or void voxels, the volume decreasing to the target, Huang and Xie
28
+ 2010) and ``hca`` (hybrid cellular automaton, Tovar et al. 2006: every voxel adjusts its
29
+ density to bring the mean stimulus of its Moore neighbourhood to a common set point).
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import itertools
35
+ import math
36
+ import time
37
+ from dataclasses import dataclass, field
38
+
39
+ import numpy as np
40
+
41
+ from morphogen.automata.lattice import kernel_sum, offsets
42
+ from morphogen.homogenization.materials import Material
43
+ from morphogen.optimization.cell import PeriodicCell
44
+ from morphogen.optimization.filters import (
45
+ SYMMETRIES,
46
+ DensityFilter,
47
+ Symmetry,
48
+ heaviside,
49
+ heaviside_derivative,
50
+ )
51
+ from morphogen.optimization.mma import MMA
52
+
53
+ OBJECTIVES = ("bulk_modulus", "shear_modulus", "poisson_ratio", "conductivity", "target")
54
+ METHODS = ("oc", "mma", "beso", "hca")
55
+ INITIAL = ("centered_void", "random", "uniform")
56
+ #: Monotone objectives (negative sensitivities), as needed by oc, beso and hca.
57
+ MONOTONE = ("bulk_modulus", "shear_modulus", "conductivity")
58
+
59
+
60
+ @dataclass
61
+ class CellDesign:
62
+ """Result of a topology optimization."""
63
+
64
+ density: np.ndarray
65
+ design: np.ndarray
66
+ tensor: np.ndarray
67
+ binary_tensor: np.ndarray
68
+ objective: float
69
+ volume_fraction: float
70
+ binary_fraction: float
71
+ iterations: int
72
+ converged: bool
73
+ history: dict[str, list] = field(default_factory=dict)
74
+ settings: dict = field(default_factory=dict)
75
+ time_s: float = 0.0
76
+ #: Constants on a finer grid (``refinement``, ``properties``), when checked.
77
+ check: dict = field(default_factory=dict)
78
+
79
+ @property
80
+ def planar(self) -> bool:
81
+ return self.density.shape[2] == 1
82
+
83
+ @property
84
+ def binary(self) -> np.ndarray:
85
+ """Black-and-white design: voxels of density above 1/2."""
86
+ return (self.density > 0.5).astype(np.uint8)
87
+
88
+ @property
89
+ def hinges(self) -> int:
90
+ """Hinges of the black-and-white design (see :func:`count_hinges`)."""
91
+ return count_hinges(self.binary)
92
+
93
+ def properties(self, tensor: np.ndarray | None = None) -> dict[str, float]:
94
+ """Engineering constants of the thresholded design (or of ``tensor``)."""
95
+ c = self.binary_tensor if tensor is None else np.asarray(tensor)
96
+ return tensor_properties(c, planar=self.planar)
97
+
98
+ def refined_properties(self, factor: int = 2, *, tol: float = 1e-6) -> dict[str, float]:
99
+ """Engineering constants of the design voxelized ``factor`` times finer from the
100
+ level set of its densities, with true voids. Trilinear voxels overestimate thin
101
+ members and hinges: moduli that drop on refinement call for a finer grid, a
102
+ larger filter radius or a softer projection."""
103
+ f = int(factor)
104
+ if f < 1:
105
+ raise ValueError("factor: a positive integer")
106
+ shape = tuple(n * f if n > 1 else 1 for n in self.density.shape)
107
+ image = self.to_microstructure().voxelize(shape=shape).data
108
+ material = self.settings.get(
109
+ "material", {"young": 1.0, "poisson": 0.3, "conductivity": 1.0}
110
+ )
111
+ cell = PeriodicCell(
112
+ shape,
113
+ (float(self.settings.get("voxel_size", 1.0)) / f,) * 3,
114
+ physics="thermal" if self.settings.get("objective") == "conductivity" else "elastic",
115
+ material=Material.from_config(material),
116
+ tol=tol,
117
+ )
118
+ tensor, _ = cell.solve(image.astype(float))
119
+ return tensor_properties(tensor, planar=self.planar)
120
+
121
+ def to_microstructure(self, domain=None, *, smoothing: float = 0.0):
122
+ """The design as a lattice microstructure of the periodic cell: phase 1 where the
123
+ density exceeds 1/2, the density field giving smooth interfaces (level set),
124
+ optionally smoothed by a Gaussian of ``smoothing`` voxels (rounding the staircases
125
+ of nearly black-and-white designs, for conforming meshes and sections)."""
126
+ from morphogen.domain import Domain
127
+ from morphogen.models.lattice_field import LatticeField
128
+
129
+ if domain is None:
130
+ h = float(self.settings.get("voxel_size", 1.0))
131
+ domain = Domain(size=tuple(n * h for n in self.density.shape), periodic=True)
132
+ return LatticeField(
133
+ domain,
134
+ self.binary,
135
+ field=self.density.astype(np.float32),
136
+ threshold=0.5,
137
+ smoothing=smoothing,
138
+ attributes={"optimization": {k: v for k, v in self.settings.items()}},
139
+ )
140
+
141
+
142
+ def _hinge_table(dims: int) -> np.ndarray:
143
+ """For each pattern of a 2 x 2 (x 2) block (bit ``k``: voxel at the binary digits of
144
+ ``k``), whether its solid voxels form several face-connected groups."""
145
+ corners = list(itertools.product((0, 1), repeat=dims))
146
+ table = np.zeros(2 ** len(corners), dtype=bool)
147
+ for pattern in range(len(table)):
148
+ solid = {k for k in range(len(corners)) if pattern >> k & 1}
149
+ groups, seen = 0, set()
150
+ for start in solid:
151
+ if start in seen:
152
+ continue
153
+ groups += 1
154
+ stack = [start]
155
+ seen.add(start)
156
+ while stack:
157
+ a = corners[stack.pop()]
158
+ for k in solid - seen:
159
+ if sum(abs(u - v) for u, v in zip(a, corners[k], strict=True)) == 1:
160
+ seen.add(k)
161
+ stack.append(k)
162
+ table[pattern] = groups > 1
163
+ return table
164
+
165
+
166
+ _HINGES = {2: _hinge_table(2), 3: _hinge_table(3)}
167
+
168
+
169
+ def count_hinges(binary) -> int:
170
+ """Number of 2 x 2 blocks (2 x 2 x 2 in 3D) of a periodic black-and-white design
171
+ whose solid voxels touch only along an edge or at a corner. Trilinear voxels make
172
+ such contacts stiff hinges, which a continuum does not have (planar designs: one
173
+ voxel through the thickness)."""
174
+ b = np.asarray(binary) > 0
175
+ if b.ndim != 3:
176
+ raise ValueError("count_hinges: a 3D array ((nx, ny, 1) for planar designs)")
177
+ axes = (0, 1) if b.shape[2] == 1 else (0, 1, 2)
178
+ code = np.zeros(b.shape, dtype=np.int64)
179
+ for k, shift in enumerate(itertools.product((0, 1), repeat=len(axes))):
180
+ code |= np.roll(b, tuple(-s for s in shift), axis=axes).astype(np.int64) << k
181
+ return int(np.count_nonzero(_HINGES[len(axes)][code]))
182
+
183
+
184
+ def tensor_properties(c: np.ndarray, *, planar: bool = False) -> dict[str, float]:
185
+ """Moduli of a stiffness (6 x 6) or conductivity (3 x 3) tensor.
186
+
187
+ Elastic: bulk modulus (mean of the normal block), shear modulus (mean of the shear
188
+ diagonal), Young's moduli and Poisson's ratio ``nu_12`` from the compliance of the
189
+ normal block (the full compliance for orthotropic cells); planar cells use the
190
+ in-plane block (plane strain).
191
+ """
192
+ c = np.asarray(c, dtype=float)
193
+ if c.shape == (3, 3):
194
+ idx = [0, 1] if planar else [0, 1, 2]
195
+ return {"conductivity": float(np.mean(np.diag(c)[idx]))}
196
+ normal = [0, 1] if planar else [0, 1, 2]
197
+ shear = [5] if planar else [3, 4, 5]
198
+ out = {
199
+ "bulk_modulus": float(c[np.ix_(normal, normal)].mean()),
200
+ "shear_modulus": float(np.mean(np.diag(c)[shear])),
201
+ }
202
+ sub = c[np.ix_(normal, normal)]
203
+ if np.all(np.isfinite(sub)):
204
+ try:
205
+ s = np.linalg.inv(sub)
206
+ out["young_1"] = float(1.0 / s[0, 0])
207
+ out["young_2"] = float(1.0 / s[1, 1])
208
+ out["poisson_12"] = float(-s[0, 1] / s[0, 0])
209
+ except np.linalg.LinAlgError:
210
+ pass
211
+ return out
212
+
213
+
214
+ def initial_density(micro, shape, *, phase: int = 1, supersampling: int = 4) -> np.ndarray:
215
+ """The densities of a microstructure on the grid of a cell optimization (``shape``;
216
+ ``nz = 1``: its middle section, a slab one voxel thick): the fraction of ``phase`` in
217
+ each voxel (``supersampling**3`` samples), to start an optimization from it (the
218
+ ``initial`` of :class:`CellOptimization`)."""
219
+ from morphogen.domain import Domain, Grid
220
+
221
+ shape = tuple(int(n) for n in shape)
222
+ if len(shape) != 3 or min(shape) < 1:
223
+ raise ValueError("shape: three positive numbers of voxels")
224
+ domain = micro.domain
225
+ if shape[2] == 1:
226
+ lower, lengths = np.asarray(domain.lower, float), np.asarray(domain.lengths, float)
227
+ thickness = float(min(lengths[0] / shape[0], lengths[1] / shape[1]))
228
+ middle = lower[2] + 0.5 * lengths[2] - 0.5 * thickness
229
+ domain = Domain(
230
+ size=(lengths[0], lengths[1], thickness),
231
+ origin=(lower[0], lower[1], middle),
232
+ periodic=domain.periodic,
233
+ )
234
+ image = micro.voxelize(grid=Grid(domain, shape), supersampling=int(supersampling))
235
+ data = np.asarray(image.data)
236
+ if data.dtype.kind == "f": # the fraction of phase 1 in each voxel
237
+ density = data.astype(float) if phase == 1 else 1.0 - data.astype(float)
238
+ else:
239
+ density = (data == phase).astype(float)
240
+ return np.clip(density, 0.0, 1.0)
241
+
242
+
243
+ class CellOptimization:
244
+ """Settings of the optimization of a periodic cell of ``shape`` voxels (``nz = 1``
245
+ for planar cells), and :meth:`run`."""
246
+
247
+ def __init__(
248
+ self,
249
+ shape,
250
+ volume_fraction: float,
251
+ *,
252
+ objective: str = "bulk_modulus",
253
+ material: Material | None = None,
254
+ voxel_size: float = 1.0,
255
+ method: str = "mma",
256
+ penalty: float = 3.0,
257
+ filter_radius: float = 1.5,
258
+ projection: float = 0.0,
259
+ symmetry: str = "cubic",
260
+ stiffness_floor: float = 1e-3,
261
+ iterations: int = 200,
262
+ tolerance: float = 0.01,
263
+ move: float = 0.2,
264
+ target=None,
265
+ min_stiffness: float = 0.05,
266
+ evolution_rate: float = 0.02,
267
+ initial="centered_void",
268
+ solver_tol: float = 1e-4,
269
+ ):
270
+ self.shape = tuple(int(n) for n in shape)
271
+ if len(self.shape) != 3 or min(self.shape) < 1:
272
+ raise ValueError("shape: three positive numbers of voxels")
273
+ self.planar = self.shape[2] == 1
274
+ if not 0.0 < volume_fraction < 1.0:
275
+ raise ValueError("volume_fraction: in (0, 1)")
276
+ if objective not in OBJECTIVES:
277
+ raise ValueError(f"objective: one of {OBJECTIVES}")
278
+ if method not in METHODS:
279
+ raise ValueError(f"method: one of {METHODS}")
280
+ if method != "mma" and objective not in MONOTONE:
281
+ raise ValueError(f"method {method} needs a monotone objective {MONOTONE}; use mma")
282
+ if symmetry not in SYMMETRIES:
283
+ raise ValueError(f"symmetry: one of {SYMMETRIES}")
284
+ if isinstance(initial, str):
285
+ if initial not in INITIAL:
286
+ raise ValueError(f"initial: one of {INITIAL}, or densities of the cell")
287
+ else: # the densities of a microstructure (initial_density)
288
+ initial = np.asarray(initial, dtype=float)
289
+ if initial.shape != self.shape:
290
+ raise ValueError(f"initial: densities of the shape of the cell {self.shape}")
291
+ if not np.all(np.isfinite(initial)) or initial.min() < 0.0 or initial.max() > 1.0:
292
+ raise ValueError("initial: densities in [0, 1]")
293
+ if penalty < 1:
294
+ raise ValueError("penalty: at least 1")
295
+ if not 0 < stiffness_floor < 0.1:
296
+ raise ValueError("stiffness_floor: in (0, 0.1)")
297
+ if projection < 0:
298
+ raise ValueError("projection: a non-negative final sharpness (0: no projection)")
299
+ self.volume_fraction = float(volume_fraction)
300
+ self.objective = objective
301
+ self.material = material or Material(young=1.0, poisson=0.3, conductivity=1.0)
302
+ self.voxel_size = float(voxel_size)
303
+ self.method = method
304
+ self.penalty = float(penalty)
305
+ self.filter_radius = float(filter_radius)
306
+ self.projection = float(projection)
307
+ self.symmetry = symmetry
308
+ self.eps = float(stiffness_floor)
309
+ self.iterations = int(iterations)
310
+ self.tolerance = float(tolerance)
311
+ self.move = float(move)
312
+ if not 0.0 <= min_stiffness < 1.0:
313
+ raise ValueError("min_stiffness: in [0, 1) times the Young's modulus")
314
+ self.min_stiffness = float(min_stiffness)
315
+ self.evolution_rate = float(evolution_rate)
316
+ self.initial = initial
317
+ self.solver_tol = float(solver_tol)
318
+ self.physics = "thermal" if objective == "conductivity" else "elastic"
319
+ if objective == "target":
320
+ if target is None:
321
+ raise ValueError("the target objective needs a target tensor (6 x 6)")
322
+ self.target = np.asarray(target, dtype=float).reshape(6, 6)
323
+ else:
324
+ self.target = None
325
+ self.normal = [0, 1] if self.planar else [0, 1, 2]
326
+ self.shear = [5] if self.planar else [3, 4, 5]
327
+ if self.physics == "thermal":
328
+ self.cases = self.normal
329
+ elif objective == "shear_modulus":
330
+ self.cases = self.shear
331
+ elif objective == "target":
332
+ self.cases = [i for i in range(6) if np.any(np.isfinite(self.target[i]))]
333
+ else:
334
+ self.cases = self.normal
335
+ self._scale = self._reference_scale()
336
+
337
+ def settings(self) -> dict:
338
+ return {
339
+ "shape": list(self.shape),
340
+ "volume_fraction": self.volume_fraction,
341
+ "objective": self.objective,
342
+ "method": self.method,
343
+ "penalty": self.penalty,
344
+ "filter_radius": self.filter_radius,
345
+ "projection": self.projection,
346
+ "symmetry": self.symmetry,
347
+ "stiffness_floor": self.eps,
348
+ "min_stiffness": self.min_stiffness,
349
+ "voxel_size": self.voxel_size,
350
+ "material": self.material.to_config(),
351
+ "initial": self.initial if isinstance(self.initial, str) else "given",
352
+ }
353
+
354
+ def _reference_scale(self) -> float:
355
+ """Modulus of the base material used to normalize the objective."""
356
+ m = self.material
357
+ if self.physics == "thermal":
358
+ return float(m.conductivity)
359
+ if self.objective == "shear_modulus":
360
+ return float(m.shear)
361
+ return float(m.young)
362
+
363
+ # -- objective -----------------------------------------------------------------------
364
+
365
+ def objective_value(self, tensor, cell: PeriodicCell, energies, iteration: int):
366
+ """Objective (to minimize), its derivatives with respect to the voxel scales, and
367
+ the extra constraints ``g <= 0`` as (value, derivatives) pairs."""
368
+ ref = self._scale
369
+ n_idx = self.normal
370
+ if self.objective in ("bulk_modulus", "conductivity"):
371
+ if self.physics == "thermal":
372
+ pairs = [(i, i) for i in n_idx]
373
+ else:
374
+ pairs = [(i, j) for i in n_idx for j in n_idx]
375
+ value = -np.mean([tensor[i, j] for i, j in pairs]) / ref
376
+ grad = -sum(cell.derivative(energies, i, j) for i, j in pairs) / (len(pairs) * ref)
377
+ return value, grad, []
378
+ if self.objective == "shear_modulus":
379
+ value = -np.mean([tensor[i, i] for i in self.shear]) / ref
380
+ grad = -sum(cell.derivative(energies, i, i) for i in self.shear) / (
381
+ len(self.shear) * ref
382
+ )
383
+ return value, grad, []
384
+ if self.objective == "poisson_ratio":
385
+ off = [(i, j) for i in n_idx for j in n_idx if i != j]
386
+ num = float(np.mean([tensor[i, j] for i, j in off]))
387
+ den = float(np.mean([tensor[i, i] for i in n_idx]))
388
+ d_num = sum(cell.derivative(energies, i, j) for i, j in off) / len(off)
389
+ d_den = sum(cell.derivative(energies, i, i) for i in n_idx) / len(n_idx)
390
+ value = num / den
391
+ grad = (d_num * den - num * d_den) / den**2
392
+ c_min = self.min_stiffness * ref
393
+ constraints = []
394
+ if c_min > 0:
395
+ constraints.append((1.0 - den / c_min, -d_den / c_min))
396
+ return value, grad, constraints
397
+ # target tensor
398
+ t = self.target
399
+ mask = np.isfinite(t)
400
+ norm = float(np.sum(t[mask] ** 2)) or 1.0
401
+ value = 0.0
402
+ grad = np.zeros(cell.n_voxels)
403
+ for i in self.cases:
404
+ for j in self.cases:
405
+ if not mask[i, j]:
406
+ continue
407
+ diff = tensor[i, j] - t[i, j]
408
+ value += diff * diff / norm
409
+ grad += 2.0 * diff * cell.derivative(energies, i, j) / norm
410
+ return value, grad, []
411
+
412
+ # -- design --------------------------------------------------------------------------
413
+
414
+ def initial_design(self, rng: np.random.Generator) -> np.ndarray:
415
+ """``centered_void``: a void ball (disc) of radius 0.3 cell edges in a uniform
416
+ matrix of the target volume; ``random``: noise around the volume fraction;
417
+ ``uniform``: the volume fraction everywhere (a stationary point: only useful with
418
+ asymmetric objectives); or the densities given (e.g. :func:`initial_density` of a
419
+ microstructure), which the symmetry of the design then averages."""
420
+ if not isinstance(self.initial, str):
421
+ return np.array(self.initial, dtype=float)
422
+ v = self.volume_fraction
423
+ x = np.full(self.shape, v)
424
+ if self.initial == "centered_void":
425
+ c = [(np.arange(n) + 0.5) / n - 0.5 for n in self.shape]
426
+ r2 = c[0][:, None, None] ** 2 + c[1][None, :, None] ** 2
427
+ if not self.planar:
428
+ r2 = r2 + c[2][None, None, :] ** 2
429
+ hole = r2 < 0.3**2
430
+ x[hole] = 0.0
431
+ x[~hole] = min(1.0, v / max(1e-12, 1.0 - hole.mean()))
432
+ elif self.initial == "random":
433
+ x = np.clip(v + 0.25 * min(v, 1 - v) * (2 * rng.random(self.shape) - 1), 0, 1)
434
+ return x
435
+
436
+ def run(self, rng: np.random.Generator | None = None, callback=None) -> CellDesign:
437
+ """Optimize; ``callback(iteration, density, objective)`` is called every iteration,
438
+ and stops the optimization there when it returns True (the design so far, not
439
+ converged)."""
440
+ rng = np.random.default_rng() if rng is None else rng
441
+ t0 = time.perf_counter()
442
+ n = int(np.prod(self.shape))
443
+ cell = PeriodicCell(
444
+ self.shape,
445
+ (self.voxel_size,) * 3,
446
+ physics=self.physics,
447
+ material=self.material,
448
+ cases=self.cases,
449
+ tol=self.solver_tol,
450
+ )
451
+ filt = DensityFilter(self.shape, self.filter_radius)
452
+ sym = Symmetry(self.shape, self.symmetry)
453
+ p, eps = self.penalty, self.eps
454
+ beso = self.method == "beso"
455
+ hca = self.method == "hca"
456
+ use_filter = not (beso or hca)
457
+ beta = 1.0 if (self.projection > 0 and not (beso or hca)) else 0.0
458
+ x = sym(self.initial_design(rng))
459
+ if beso:
460
+ x = np.where(self.initial_design(rng) < self.volume_fraction, 1e-3, 1.0)
461
+ x = sym(x)
462
+ current_volume = float(x.mean())
463
+ n_cons = 2 if (self.objective == "poisson_ratio" and self.min_stiffness > 0) else 1
464
+ mma = MMA(n, n_cons, 0.0, 1.0, move=self.move) if self.method == "mma" else None
465
+ hood = offsets("moore", 1, dims=2 if self.planar else 3, include_center=True)
466
+
467
+ def to_design(g, factor):
468
+ """Derivatives with respect to the design variables (chain rule through the
469
+ interpolation, projection, filter and symmetry)."""
470
+ g = g.reshape(self.shape) * factor
471
+ return sym(filt.transpose(g) if use_filter else g)
472
+
473
+ hist = {
474
+ "iteration": [],
475
+ "objective": [],
476
+ "volume": [],
477
+ "change": [],
478
+ "beta": [],
479
+ "solver_iterations": [],
480
+ }
481
+ scale0 = None
482
+ alpha_old = None
483
+ converged = False
484
+ it = 0
485
+ density = x
486
+ tensor = np.full((6, 6), np.nan)
487
+ value = np.nan
488
+ for it in range(1, self.iterations + 1):
489
+ xt = filt(x) if use_filter else x
490
+ density = heaviside(xt, beta) if beta > 0 else xt
491
+ s = eps + (1.0 - eps) * density**p
492
+ ds = (1.0 - eps) * p * np.maximum(density, 1e-12) ** (p - 1)
493
+ before = cell.iterations
494
+ tensor, energies = cell.solve(s)
495
+ value, grad_s, extra = self.objective_value(tensor, cell, energies, it)
496
+ dproj = heaviside_derivative(xt, beta) if beta > 0 else np.ones(self.shape)
497
+ g_x = to_design(grad_s, ds * dproj)
498
+ g_v = to_design(np.full(self.shape, 1.0 / n), dproj)
499
+ volume = float(density.mean())
500
+ if self.method == "oc":
501
+ x_new = self._oc(x, g_x, g_v, filt, beta, sym)
502
+ elif self.method == "mma":
503
+ if scale0 is None:
504
+ scale0 = 10.0 / max(abs(value), 1e-12)
505
+ cons = [volume / self.volume_fraction - 1.0] + [c for c, _ in extra]
506
+ grads = [g_v.ravel() / self.volume_fraction]
507
+ grads += [to_design(g, ds * dproj).ravel() for _, g in extra]
508
+ x_new = mma.update(
509
+ x.ravel(), scale0 * value, scale0 * g_x.ravel(), cons, np.array(grads)
510
+ )
511
+ x_new = sym(np.clip(x_new.reshape(self.shape), 0.0, 1.0))
512
+ elif beso:
513
+ current_volume = max(
514
+ self.volume_fraction, current_volume * (1.0 - self.evolution_rate)
515
+ )
516
+ alpha = filt(-g_x)
517
+ if alpha_old is not None:
518
+ alpha = 0.5 * (alpha + alpha_old)
519
+ alpha_old = alpha
520
+ x_new = sym(self._beso_threshold(sym(alpha), current_volume))
521
+ x_new = np.where(x_new >= 0.5, 1.0, 1e-3)
522
+ else:
523
+ x_new = self._hca(x, -g_x, hood, sym)
524
+ change = float(np.max(np.abs(x_new - x)))
525
+ x = x_new
526
+ hist["iteration"].append(it)
527
+ hist["objective"].append(float(value))
528
+ hist["volume"].append(volume)
529
+ hist["change"].append(change)
530
+ hist["beta"].append(beta)
531
+ hist["solver_iterations"].append(cell.iterations - before)
532
+ if callback is not None and callback(it, density, value) is True:
533
+ break # stopped by the caller: the design so far
534
+ if beso:
535
+ done = (
536
+ current_volume <= self.volume_fraction + 1e-12
537
+ and len(hist["objective"]) > 10
538
+ and np.ptp(hist["objective"][-10:]) <= self.tolerance * abs(value)
539
+ )
540
+ else:
541
+ done = change < self.tolerance
542
+ sharp = beta == 0.0 or beta >= self.projection
543
+ if done and sharp:
544
+ converged = True
545
+ break
546
+ if beta > 0 and not sharp and (done or it % 40 == 0):
547
+ beta = min(2.0 * beta, self.projection)
548
+ if mma is not None:
549
+ mma.reset()
550
+ xt = filt(x) if use_filter else x
551
+ density = heaviside(xt, beta) if beta > 0 else xt
552
+ binary = density > 0.5
553
+ # the black-and-white design, with true voids and a tight tolerance
554
+ bcell = PeriodicCell(
555
+ self.shape,
556
+ (self.voxel_size,) * 3,
557
+ physics=self.physics,
558
+ material=self.material,
559
+ tol=1e-6,
560
+ )
561
+ binary_tensor, _ = bcell.solve(binary.astype(float))
562
+ return CellDesign(
563
+ density=density,
564
+ design=x,
565
+ tensor=tensor,
566
+ binary_tensor=binary_tensor,
567
+ objective=float(value),
568
+ volume_fraction=float(density.mean()),
569
+ binary_fraction=float(binary.mean()),
570
+ iterations=it,
571
+ converged=converged,
572
+ history=hist,
573
+ settings=self.settings(),
574
+ time_s=time.perf_counter() - t0,
575
+ )
576
+
577
+ # -- updates -------------------------------------------------------------------------
578
+
579
+ def _volume_of(self, x, filt, beta) -> float:
580
+ xt = filt(x)
581
+ return float((heaviside(xt, beta) if beta > 0 else xt).mean())
582
+
583
+ def _oc(self, x, g_x, g_v, filt, beta, sym):
584
+ """Optimality criteria with a bisection on the Lagrange multiplier."""
585
+ b0 = np.maximum(-g_x, 1e-30) / np.maximum(g_v, 1e-30)
586
+ lo, hi = 0.0, float(b0.max()) * 1e3 + 1e-30
587
+ x_new = x
588
+ for _ in range(200):
589
+ mid = 0.5 * (lo + hi)
590
+ x_new = np.clip(
591
+ x * np.sqrt(b0 / mid),
592
+ np.maximum(0.0, x - self.move),
593
+ np.minimum(1.0, x + self.move),
594
+ )
595
+ if self._volume_of(x_new, filt, beta) > self.volume_fraction:
596
+ lo = mid
597
+ else:
598
+ hi = mid
599
+ if hi - lo <= 1e-9 * (hi + lo):
600
+ break
601
+ return sym(x_new)
602
+
603
+ def _beso_threshold(self, alpha, volume) -> np.ndarray:
604
+ """Solid voxels: the ``volume`` fraction of highest sensitivity numbers."""
605
+ n_solid = round(volume * alpha.size)
606
+ out = np.zeros(alpha.size)
607
+ if n_solid > 0:
608
+ order = np.argsort(-alpha.ravel(), kind="stable")
609
+ out[order[:n_solid]] = 1.0
610
+ return out.reshape(alpha.shape)
611
+
612
+ def _hca(self, x, stimulus, hood, sym):
613
+ """Hybrid cellular automaton: proportional control of each voxel's density by the
614
+ mean stimulus of its Moore neighbourhood, around a set point fixed by the volume."""
615
+ local = kernel_sum(np.maximum(stimulus, 0.0), hood) / len(hood)
616
+ local = sym(local)
617
+ lo, hi = 1e-30, float(local.max()) * 1e3 + 1e-30
618
+ x_new = x
619
+ for _ in range(200):
620
+ mid = math.sqrt(lo * hi)
621
+ x_new = np.clip(
622
+ x + self.move * (local / mid - 1.0),
623
+ np.maximum(1e-3, x - self.move),
624
+ np.minimum(1.0, x + self.move),
625
+ )
626
+ if x_new.mean() > self.volume_fraction:
627
+ lo = mid
628
+ else:
629
+ hi = mid
630
+ if hi / lo < 1.0 + 1e-9:
631
+ break
632
+ return sym(x_new)