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,700 @@
1
+ """Isogeometric shape optimization: the control points of the geometry as the design.
2
+
3
+ In an isogeometric analysis the geometry is its control points, and moving them moves
4
+ the boundary exactly and smoothly: they are the natural variables of a shape
5
+ optimization (Wall, Frenzel & Cyron 2008; Qian 2010), without the remeshing and the
6
+ jagged boundaries of the methods that move the nodes of a mesh. Three levels:
7
+
8
+ * the *variables* ``x``: each moves some control points of the design along given
9
+ directions (:meth:`ShapeDesign.variable`; :meth:`ShapeDesign.radial` scales the control
10
+ points of a hole about its centre, with the symmetries of the cell). With the
11
+ ``symmetry`` of the pattern — mirrors, rotations (:func:`mirror`, :func:`rotation`),
12
+ and the periods of the cell — a variable moves the images of its control points as
13
+ well: the design keeps its symmetry, and the control points of the boundary of a
14
+ cell that are a period apart move together;
15
+ * the *design*, a coarse assembly whose control points are ``P(x) = P_0 + M x``;
16
+ * the *analysis*, a refinement of the design (elements cut, degree raised): for given
17
+ weights its control points are linear in those of the design, ``Q = T P``
18
+ (:meth:`~morphogen.iga.geometry.Multipatch.refinement`). The geometry is the same at
19
+ both levels; the design keeps few variables, the analysis its accuracy.
20
+
21
+ Sensitivities. Let ``A(u, v) = int (E_u + eps(u)) : D : (E_v + eps(v)) dOmega`` for two
22
+ fields of given unknowns and uniform strains. Moving the control point ``a`` by ``dQ``
23
+ moves the points by ``V = R_a dQ``; then ``d(dOmega) = div V dOmega`` and ``d(grad u) =
24
+ -grad u grad V``, so that::
25
+
26
+ dA / dQ_a = int Sigma grad R_a dOmega,
27
+ Sigma = (eps_u : D : eps_v) 1 - grad u^T sigma_v - grad v^T sigma_u,
28
+
29
+ the energy-momentum tensor of Eshelby for the pair: the gradients are *analytical*, one
30
+ integral per pair of fields and no further solution. For a structure under given loads
31
+ (``K u = f``) the compliance ``c = f . u`` has ``dc/dQ = -dA(u, u)/dQ``; for a periodic
32
+ cell the effective tensor is ``C_IJ = A(chi_I, chi_J) / |Y|`` with the fluctuations of
33
+ :mod:`morphogen.iga.homogenization`, and ``dC_IJ/dQ = (dA/dQ) / |Y|`` since each
34
+ fluctuation makes its energy stationary. The area of the material has ``dA/dQ_a = int
35
+ grad R_a dOmega``. The chain ``d/dx = M^T T^T d/dQ`` brings them to the variables.
36
+
37
+ Optimization (:func:`optimize`, :func:`optimize_cell`, :func:`optimize_structure`):
38
+ sequential quadratic programming (SLSQP of SciPy) or the method of moving asymptotes
39
+ (:mod:`morphogen.optimization.mma`), with bounds on the variables that keep the patches
40
+ from folding. The objectives and constraints of a cell are functions of its effective
41
+ tensor and of its fraction of material — a modulus, Poisson's ratio, the distance to a
42
+ target tensor —, differentiated numerically with respect to these few numbers; linear
43
+ constraints on the variables (``linear``) keep sizes of the geometry — the width of a
44
+ ligament, the thickness of a member — since the control points are linear in them.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import itertools
50
+ import math
51
+ import time
52
+ from collections.abc import Callable
53
+ from dataclasses import dataclass, field
54
+
55
+ import numpy as np
56
+ import scipy.optimize
57
+ from scipy.spatial import cKDTree
58
+
59
+ from morphogen.iga.analysis import Analysis
60
+ from morphogen.iga.geometry import Multipatch, Patch
61
+ from morphogen.iga.homogenization import Cell, CellSolution
62
+
63
+ METHODS = ("slsqp", "mma")
64
+ SYMMETRIES = (None, "d2", "d4")
65
+
66
+
67
+ #: The largest group of symmetries of a design (those of a cubic cell are 48)
68
+ _GROUP = 192
69
+
70
+
71
+ class FoldedDesign(ValueError):
72
+ """The variables of a design fold one of its patches (a Jacobian that is not
73
+ positive): no analysis there."""
74
+
75
+
76
+ def mirror(axis: int, at: float = 0.0, dim: int = 2) -> tuple[np.ndarray, np.ndarray]:
77
+ """The mirror in the line (plane) where the coordinate ``axis`` is ``at``, as an
78
+ operation ``x -> matrix x + shift`` (for the ``symmetry`` of a variable)."""
79
+ matrix, shift = np.eye(dim), np.zeros(dim)
80
+ matrix[axis, axis] = -1.0
81
+ shift[axis] = 2.0 * float(at)
82
+ return matrix, shift
83
+
84
+
85
+ def rotation(angle: float, centre=(0.0, 0.0)) -> tuple[np.ndarray, np.ndarray]:
86
+ """The rotation of the plane by ``angle`` (degrees, anticlockwise) about ``centre``,
87
+ as an operation ``x -> matrix x + shift`` (for the ``symmetry`` of a variable)."""
88
+ turn = round(float(angle) / 90.0)
89
+ if abs(float(angle) - 90.0 * turn) < 1e-12: # exact quarter-turns
90
+ c, s = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)][turn % 4]
91
+ else:
92
+ c, s = math.cos(math.radians(angle)), math.sin(math.radians(angle))
93
+ matrix = np.array([[c, -s], [s, c]])
94
+ centre = np.asarray(centre, dtype=float)
95
+ return matrix, centre - matrix @ centre
96
+
97
+
98
+ def _group(operations, lattice, dim: int) -> list[tuple[np.ndarray, np.ndarray]]:
99
+ """The operations ``x -> matrix x + shift`` that given ones generate, the shifts
100
+ counted up to the periods of ``lattice`` (when there is one)."""
101
+ inverse = None if lattice is None else np.linalg.inv(lattice)
102
+
103
+ def reduced(matrix, shift):
104
+ if inverse is not None:
105
+ share = (shift @ inverse) % 1.0
106
+ share[share > 1.0 - 1e-7] = 0.0
107
+ shift = share @ lattice
108
+ key = (tuple(np.round(matrix, 6).ravel() + 0.0), tuple(np.round(shift, 6) + 0.0))
109
+ return key, (matrix, shift)
110
+
111
+ generators = [(np.eye(dim), np.zeros(dim))]
112
+ for matrix, shift in operations:
113
+ matrix, shift = np.asarray(matrix, dtype=float), np.asarray(shift, dtype=float)
114
+ if matrix.shape != (dim, dim) or shift.shape != (dim,):
115
+ raise ValueError(f"symmetry: operations (matrix, shift) of {dim} dimensions")
116
+ if np.abs(matrix @ matrix.T - np.eye(dim)).max() > 1e-9:
117
+ raise ValueError("symmetry: mirrors and rotations (orthogonal matrices)")
118
+ generators.append((matrix, shift))
119
+ group = dict(reduced(m, t) for m, t in generators)
120
+ frontier = list(group.values())
121
+ while frontier:
122
+ found = []
123
+ for m1, t1 in frontier:
124
+ for m2, t2 in generators[1:]:
125
+ key, operation = reduced(m1 @ m2, m1 @ t2 + t1)
126
+ if key not in group:
127
+ group[key] = operation
128
+ found.append(operation)
129
+ if len(group) > _GROUP:
130
+ raise ValueError(
131
+ "symmetry: these operations do not make a finite group (up to the periods "
132
+ "of the lattice of the design)"
133
+ )
134
+ frontier = found
135
+ return list(group.values())
136
+
137
+
138
+ def stress_tensors(flux: np.ndarray, dim: int, nd: int) -> np.ndarray:
139
+ """The fluxes of the points as tensors (... x unknowns x dim): the stress tensors of
140
+ Voigt's components (elasticity), or the flux vectors as one row (conduction)."""
141
+ if nd == 1:
142
+ return flux[..., None, :]
143
+ out = np.empty((*flux.shape[:-1], dim, dim))
144
+ if dim == 2:
145
+ out[..., 0, 0], out[..., 1, 1] = flux[..., 0], flux[..., 1]
146
+ out[..., 0, 1] = out[..., 1, 0] = flux[..., 2]
147
+ else:
148
+ for k in range(3):
149
+ out[..., k, k] = flux[..., k]
150
+ out[..., 1, 2] = out[..., 2, 1] = flux[..., 3]
151
+ out[..., 0, 2] = out[..., 2, 0] = flux[..., 4]
152
+ out[..., 0, 1] = out[..., 1, 0] = flux[..., 5]
153
+ return out
154
+
155
+
156
+ def energy_gradients(analysis: Analysis, fields, uniform=None) -> np.ndarray:
157
+ """The derivatives of ``A(u_i, u_j)`` (see the module) with respect to the control
158
+ points of the analysis, for the fields ``fields`` (unknowns x m) and their uniform
159
+ strains ``uniform`` (components x m; none by default): m x m x control points x
160
+ dim."""
161
+ fields = np.asarray(fields, dtype=float)
162
+ fields = fields[:, None] if fields.ndim == 1 else fields
163
+ m = fields.shape[1]
164
+ model, dim, nd = analysis.model, analysis.dim, analysis.nd
165
+ out = np.zeros((m, m, model.n_nodes, dim))
166
+ eye = np.eye(dim)
167
+ for pts, b, d, dofs in analysis.points():
168
+ ue = fields[dofs] # elements x unknowns of the element x m
169
+ measure = np.einsum("eqsi,eim->eqsm", b, ue)
170
+ if uniform is not None:
171
+ measure = measure + np.asarray(uniform, dtype=float)[None, None]
172
+ flux = np.einsum("st,eqtm->eqsm", d, measure)
173
+ ua = ue.reshape(len(dofs), -1, nd, m)
174
+ grad = np.einsum("eqak,eacm->eqmck", pts.gradients, ua) # of the unknowns
175
+ sigma = stress_tensors(np.moveaxis(flux, -1, 2), dim, nd) # elements x points x m x ...
176
+ for i in range(m):
177
+ for j in range(i, m):
178
+ energy = np.einsum("eqs,eqs->eq", measure[..., i], flux[..., j])
179
+ tensor = energy[..., None, None] * eye
180
+ tensor = tensor - np.einsum("eqck,eqcj->eqkj", grad[:, :, i], sigma[:, :, j])
181
+ tensor = tensor - np.einsum("eqck,eqcj->eqkj", grad[:, :, j], sigma[:, :, i])
182
+ g = np.einsum("eq,eqkj,eqaj->eak", pts.weights, tensor, pts.gradients)
183
+ np.add.at(out[i, j], pts.nodes, g)
184
+ for i in range(m):
185
+ for j in range(i):
186
+ out[i, j] = out[j, i]
187
+ return out
188
+
189
+
190
+ def measure_gradient(analysis: Analysis) -> np.ndarray:
191
+ """The derivative of the area (volume) of the assembly with respect to its control
192
+ points: ``int grad R_a`` (control points x dim)."""
193
+ out = np.zeros((analysis.model.n_nodes, analysis.dim))
194
+ for pts, _, _, _ in analysis.points():
195
+ np.add.at(out, pts.nodes, np.einsum("eq,eqak->eak", pts.weights, pts.gradients))
196
+ return out
197
+
198
+
199
+ class ShapeDesign:
200
+ """A design (see the module): the coarse assembly ``model`` and the refinement of
201
+ its analysis (``subdivisions`` of every element and degrees raised by ``elevate``,
202
+ one value or one per direction). Variables are added by :meth:`variable` and
203
+ :meth:`radial`."""
204
+
205
+ def __init__(self, model, *, subdivisions=4, elevate=1):
206
+ if isinstance(model, Patch):
207
+ model = Multipatch(model)
208
+ self.model = model
209
+ self.fine, self.matrix = model.refinement(subdivisions, elevate)
210
+ self._moves: list[tuple[np.ndarray, np.ndarray]] = []
211
+ self.lower: list[float] = []
212
+ self.upper: list[float] = []
213
+ self.names: list[str] = []
214
+
215
+ @property
216
+ def n(self) -> int:
217
+ """The number of variables."""
218
+ return len(self._moves)
219
+
220
+ @property
221
+ def moves(self) -> list[tuple[np.ndarray, np.ndarray]]:
222
+ """For each variable, the control points of the design that it moves and their
223
+ directions (the moves of a unit of the variable)."""
224
+ return [(nodes.copy(), directions.copy()) for nodes, directions in self._moves]
225
+
226
+ def variable(self, nodes, directions, lower: float = -np.inf, upper: float = np.inf,
227
+ name: str | None = None, symmetry=None) -> int: # fmt: skip
228
+ """A variable that moves the control points ``nodes`` of the design by its value
229
+ times their ``directions`` (one vector each, or one for all); returns its index.
230
+
231
+ ``symmetry``: operations ``(matrix, shift)`` that map the design onto itself,
232
+ ``x -> matrix x + shift`` (:func:`mirror`, :func:`rotation`), up to the periods
233
+ of its ``lattice``. The variable then moves the images of its control points by
234
+ all the operations that these generate, along the images of their directions —
235
+ ``nodes`` are those of one copy; a control point that an operation leaves in
236
+ place keeps the part of its direction that the operation keeps. With an empty
237
+ list, only the control points a period apart move together."""
238
+ nodes = np.atleast_1d(np.asarray(nodes, dtype=np.int64))
239
+ directions = np.broadcast_to(
240
+ np.asarray(directions, dtype=float), (len(nodes), self.model.dim)
241
+ ).copy()
242
+ if nodes.size == 0 or nodes.min() < 0 or nodes.max() >= self.model.n_nodes:
243
+ raise ValueError("variable: control points of the design")
244
+ if not lower < upper:
245
+ raise ValueError("variable: lower < upper")
246
+ if symmetry is not None:
247
+ nodes, directions = self._images(nodes, directions, symmetry)
248
+ self._moves.append((nodes, directions))
249
+ self.lower.append(float(lower))
250
+ self.upper.append(float(upper))
251
+ self.names.append(name or f"x{len(self._moves)}")
252
+ return len(self._moves) - 1
253
+
254
+ def _images(self, nodes, directions, symmetry) -> tuple[np.ndarray, np.ndarray]:
255
+ """The control points that the symmetry maps those of a variable onto, and their
256
+ directions."""
257
+ model = self.model
258
+ group = _group(symmetry, model.lattice, model.dim)
259
+ periods = np.zeros((1, model.dim))
260
+ if model.lattice is not None:
261
+ combos = itertools.product(range(-3, 4), repeat=model.dim)
262
+ periods = np.array(list(combos), dtype=float) @ model.lattice
263
+ tree = cKDTree(model.nodes)
264
+ tolerance = 1e-6 * float(np.ptp(model.nodes, axis=0).max())
265
+ moves: dict[int, np.ndarray] = {}
266
+ for node, direction in zip(nodes, directions, strict=True):
267
+ images: dict[int, list] = {}
268
+ for matrix, shift in group:
269
+ distance, found = tree.query(matrix @ model.nodes[node] + shift + periods)
270
+ found = found[distance <= tolerance]
271
+ if not len(found):
272
+ raise ValueError(
273
+ f"symmetry: no control point at an image of the control point {node}; "
274
+ "the operations must map the design onto itself"
275
+ )
276
+ for other in found:
277
+ images.setdefault(int(other), []).append(matrix @ direction)
278
+ for other, parts in images.items(): # as many operations for each image
279
+ moves[other] = moves.get(other, 0.0) + np.sum(parts, axis=0) / len(images[node])
280
+ ids = np.array(sorted(moves), dtype=np.int64)
281
+ out = np.array([moves[k] for k in ids])
282
+ if np.abs(out).max() < 1e-12 * max(float(np.abs(directions).max()), 1e-300):
283
+ raise ValueError("symmetry: it leaves nothing of the move of this variable")
284
+ return ids, out
285
+
286
+ def radial(self, nodes, centre, lower: float = -0.3, upper: float = 0.3,
287
+ symmetry: str | None = None) -> list[int]: # fmt: skip
288
+ """Variables that scale the positions of control points about ``centre``: ``P =
289
+ centre + (1 + x) (P_0 - centre)``, ``x`` between ``lower`` and ``upper``. One
290
+ variable per control point, or per set of control points that the ``symmetry``
291
+ of the cell maps onto each other: ``"d2"`` (the two mirrors of a rectangle
292
+ through the centre) or ``"d4"`` (those of a square, diagonals included)."""
293
+ if symmetry not in SYMMETRIES:
294
+ raise ValueError(f"symmetry: one of {SYMMETRIES}")
295
+ nodes = np.unique(np.asarray(nodes, dtype=np.int64))
296
+ offsets = self.model.nodes[nodes] - np.asarray(centre, dtype=float)
297
+ if symmetry is None:
298
+ groups = [[k] for k in range(len(nodes))]
299
+ else:
300
+ folded = np.abs(offsets[:, :2])
301
+ if symmetry == "d4":
302
+ folded = np.sort(folded, axis=1)
303
+ scale = float(np.abs(offsets).max()) or 1.0
304
+ keys = np.round(folded / (1e-7 * scale)).astype(np.int64)
305
+ _, inverse = np.unique(keys, axis=0, return_inverse=True)
306
+ inverse = inverse.ravel()
307
+ groups = [np.flatnonzero(inverse == g).tolist() for g in range(inverse.max() + 1)]
308
+ return [self.variable(nodes[g], offsets[g], lower, upper) for g in groups]
309
+
310
+ # -- geometries ------------------------------------------------------------------------
311
+
312
+ def bounds(self) -> tuple[np.ndarray, np.ndarray]:
313
+ return np.array(self.lower), np.array(self.upper)
314
+
315
+ def control(self, x) -> np.ndarray:
316
+ """The control points of the design for the variables ``x``."""
317
+ x = np.asarray(x, dtype=float)
318
+ if x.shape != (self.n,):
319
+ raise ValueError(f"x: {self.n} variables")
320
+ nodes = self.model.nodes.copy()
321
+ for value, (ids, directions) in zip(x, self._moves, strict=True):
322
+ np.add.at(nodes, ids, value * directions)
323
+ return nodes
324
+
325
+ def design_model(self, x) -> Multipatch:
326
+ """The design moved by the variables ``x``."""
327
+ return self.model.with_nodes(self.control(x))
328
+
329
+ def analysis_model(self, x) -> Multipatch:
330
+ """The refined assembly of the analysis for the variables ``x``; a
331
+ :class:`FoldedDesign` if a patch of the design folds there (a negative Jacobian,
332
+ its boundary included: :meth:`~morphogen.iga.geometry.Multipatch.jacobians`)."""
333
+ control = self.control(x)
334
+ low, high = self.model.with_nodes(control).jacobians()
335
+ if low < -1e-9 * high:
336
+ raise FoldedDesign(
337
+ "a patch of the design folds for these variables (a negative Jacobian); "
338
+ "tighten their bounds"
339
+ )
340
+ return self.fine.with_nodes(self.matrix @ control)
341
+
342
+ def pull(self, gradient) -> np.ndarray:
343
+ """The derivative with respect to the variables of a quantity whose derivative
344
+ with respect to the control points of the analysis is ``gradient`` (control
345
+ points x dim)."""
346
+ coarse = self.matrix.T @ np.asarray(gradient, dtype=float)
347
+ return np.array(
348
+ [float(np.sum(coarse[ids] * directions)) for ids, directions in self._moves]
349
+ )
350
+
351
+
352
+ @dataclass
353
+ class CellResponse:
354
+ """The effective ``tensor`` of a cell and its ``fraction`` of material for some
355
+ variables, with their derivatives (``d_tensor``: n x n x variables; ``d_fraction``:
356
+ variables) and the solution."""
357
+
358
+ tensor: np.ndarray
359
+ fraction: float
360
+ d_tensor: np.ndarray
361
+ d_fraction: np.ndarray
362
+ solution: CellSolution = field(repr=False)
363
+
364
+
365
+ def cell_response(design: ShapeDesign, x, materials, *, physics: str = "elastic",
366
+ plane: str = "strain") -> CellResponse: # fmt: skip
367
+ """The effective tensor and the fraction of material of the periodic cell of a
368
+ design for the variables ``x``, and their derivatives with respect to ``x``."""
369
+ cell = Cell(design.analysis_model(x), materials, physics=physics, plane=plane)
370
+ solution = cell.solve()
371
+ n = len(solution.tensor)
372
+ gradients = energy_gradients(cell.analysis, solution.fluctuations, np.eye(n))
373
+ d_tensor = np.empty((n, n, design.n))
374
+ for i in range(n):
375
+ for j in range(n):
376
+ d_tensor[i, j] = design.pull(gradients[i, j]) / cell.measure
377
+ d_fraction = design.pull(measure_gradient(cell.analysis)) / cell.measure
378
+ return CellResponse(solution.tensor, solution.fraction, d_tensor, d_fraction, solution)
379
+
380
+
381
+ @dataclass
382
+ class StructureResponse:
383
+ """The ``compliance`` ``f . u`` of a structure and the ``measure`` (area, volume) of
384
+ its material, with their derivatives with respect to the variables, the unknowns
385
+ and the analysis."""
386
+
387
+ compliance: float
388
+ measure: float
389
+ d_compliance: np.ndarray
390
+ d_measure: np.ndarray
391
+ u: np.ndarray = field(repr=False)
392
+ analysis: Analysis = field(repr=False)
393
+
394
+
395
+ def structure_response(design: ShapeDesign, x, materials, loads: Callable, supports: Callable,
396
+ *, plane: str = "strain") -> StructureResponse: # fmt: skip
397
+ """The compliance of the structure of a design under the nodal forces
398
+ ``loads(analysis)`` with the unknowns ``supports(analysis)`` fixed (functions of the
399
+ :class:`~morphogen.iga.analysis.Analysis`: the loads must not depend on the
400
+ variables — tractions on sides that the design does not move)."""
401
+ analysis = Analysis(design.analysis_model(x), materials, plane=plane)
402
+ forces = np.asarray(loads(analysis), dtype=float)
403
+ u = analysis.solve(forces, supports(analysis))
404
+ gradient = -energy_gradients(analysis, u)[0, 0]
405
+ return StructureResponse(
406
+ float(forces @ u),
407
+ analysis.measure(),
408
+ design.pull(gradient),
409
+ design.pull(measure_gradient(analysis)),
410
+ u,
411
+ analysis,
412
+ )
413
+
414
+
415
+ @dataclass
416
+ class ShapeResult:
417
+ """An optimized shape: the variables ``x``, the ``design`` and the ``analysis``
418
+ assemblies, the ``objective`` and the ``constraints`` there, the ``history`` of the
419
+ iterations (objective, largest constraint, variables) and, for a cell, its effective
420
+ ``tensor`` and ``fraction`` of material."""
421
+
422
+ x: np.ndarray
423
+ design: Multipatch
424
+ analysis: Multipatch
425
+ objective: float
426
+ constraints: np.ndarray
427
+ iterations: int
428
+ converged: bool
429
+ history: list = field(default_factory=list, repr=False)
430
+ tensor: np.ndarray | None = None
431
+ fraction: float | None = None
432
+ time_s: float = 0.0
433
+ message: str = ""
434
+
435
+
436
+ def optimize(
437
+ evaluate: Callable,
438
+ x0,
439
+ lower,
440
+ upper,
441
+ *,
442
+ method: str = "slsqp",
443
+ maxiter: int = 100,
444
+ tolerance: float = 1e-7,
445
+ move: float = 0.2,
446
+ callback: Callable | None = None,
447
+ ):
448
+ """Minimize ``f(x)`` subject to ``g_i(x) <= 0`` and ``lower <= x <= upper``, with
449
+ ``evaluate(x) -> (f, df, g, dg)`` (``g``: m values, ``dg``: m x n). ``method``:
450
+ ``"slsqp"`` (sequential quadratic programming, SciPy) or ``"mma"`` (moving asymptotes).
451
+ ``move`` bounds the steps as a share of the bounds: each step of MMA, and the first
452
+ of SLSQP (whose objective is scaled for it; the later ones follow its estimate of the
453
+ curvature). Returns ``(x, history, converged, message)``: the history holds the
454
+ points that the iterations kept, and ``callback(iteration, x, f, g)`` is called for
455
+ each. A trial point where ``evaluate`` raises :class:`FoldedDesign` is turned down:
456
+ the line search of SLSQP shortens its step, the step of MMA is halved."""
457
+ if method not in METHODS:
458
+ raise ValueError(f"method: one of {METHODS}")
459
+ x0 = np.clip(np.asarray(x0, dtype=float), lower, upper)
460
+ lower, upper = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
461
+ trail: list[dict] = [] # the points evaluated, in order
462
+ history: list = []
463
+
464
+ def at(x) -> dict:
465
+ x = np.asarray(x, dtype=float)
466
+ if trail and np.array_equal(trail[-1]["x"], x):
467
+ return trail[-1]
468
+ try:
469
+ f, df, g, dg = evaluate(x)
470
+ except FoldedDesign:
471
+ valid = next((entry for entry in reversed(trail) if entry["valid"]), None)
472
+ if valid is None:
473
+ raise
474
+ # a trial step too far: a value that the line search turns down
475
+ entry = dict(valid, x=x.copy(), f=valid["f"] + 10.0 * (abs(valid["f"]) + 1.0))
476
+ entry["valid"] = False
477
+ else:
478
+ g = np.atleast_1d(np.asarray(g, dtype=float))
479
+ entry = {"x": x.copy(), "f": float(f), "df": np.asarray(df, dtype=float), "g": g,
480
+ "dg": np.asarray(dg, dtype=float).reshape(len(g), len(x)),
481
+ "valid": True} # fmt: skip
482
+ trail.append(entry)
483
+ return entry
484
+
485
+ def record(entry) -> None:
486
+ history.append({"objective": entry["f"], "x": entry["x"].copy(),
487
+ "constraint": float(entry["g"].max(initial=-np.inf))}) # fmt: skip
488
+ if callback is not None:
489
+ callback(len(history) - 1, entry["x"].copy(), entry["f"], entry["g"])
490
+
491
+ first = at(x0)
492
+ record(first)
493
+ if method == "slsqp":
494
+ # a first step of the size of ``move``: SLSQP starts from the steepest descent
495
+ spans = (upper - lower)[np.isfinite(upper - lower)]
496
+ typical = float(np.median(spans)) if spans.size else 1.0
497
+ scale = max(1.0, float(np.abs(first["df"]).max(initial=0.0)) / (move * typical))
498
+
499
+ def kept(_) -> None:
500
+ # SciPy calls this at the first trial point of an iteration: the point
501
+ # evaluated before it is the one that the previous iteration kept
502
+ if len(trail) > 1 and not np.array_equal(trail[-2]["x"], history[-1]["x"]):
503
+ record(trail[-2])
504
+
505
+ constraints = [
506
+ {
507
+ "type": "ineq",
508
+ "fun": lambda x, i=i: -at(x)["g"][i],
509
+ "jac": lambda x, i=i: -at(x)["dg"][i],
510
+ }
511
+ for i in range(len(first["g"]))
512
+ ]
513
+ result = scipy.optimize.minimize(
514
+ lambda x: (at(x)["f"] / scale, at(x)["df"] / scale),
515
+ x0,
516
+ jac=True,
517
+ method="SLSQP",
518
+ bounds=list(zip(lower, upper, strict=True)),
519
+ constraints=constraints,
520
+ callback=kept,
521
+ options={"maxiter": int(maxiter), "ftol": float(tolerance) / scale},
522
+ )
523
+ last = at(np.asarray(result.x, dtype=float))
524
+ if not np.array_equal(last["x"], history[-1]["x"]):
525
+ record(last)
526
+ return last["x"], history, bool(result.success), str(result.message)
527
+ from morphogen.optimization.mma import MMA
528
+
529
+ x = x0.copy()
530
+ m = max(len(first["g"]), 1)
531
+ if m >= len(x):
532
+ raise ValueError("mma: fewer constraints than variables")
533
+ scale = abs(first["f"]) or 1.0
534
+ optimizer = MMA(len(x), m, lower, upper, move=move)
535
+ for _ in range(int(maxiter)):
536
+ entry = at(x)
537
+ g, dg = entry["g"], entry["dg"]
538
+ if len(g) == 0: # MMA needs a constraint: one that never binds
539
+ g, dg = np.array([-1.0]), np.zeros((1, len(x)))
540
+ new = optimizer.update(x, entry["f"] / scale, entry["df"] / scale, g, dg)
541
+ for _ in range(30): # a step that folds the design is halved
542
+ if at(new)["valid"]:
543
+ break
544
+ new = x + 0.5 * (new - x)
545
+ else:
546
+ raise FoldedDesign("mma: every step from these variables folds the design")
547
+ change = float(np.abs(new - x).max() / max(float((upper - lower).max()), 1e-30))
548
+ x = new
549
+ record(at(x))
550
+ if change < tolerance:
551
+ return x, history, True, "the variables no longer change"
552
+ return x, history, False, f"{maxiter} iterations"
553
+
554
+
555
+ def _partials(function: Callable, tensor: np.ndarray, fraction: float):
556
+ """The value of ``function(tensor, fraction)`` and its derivatives with respect to
557
+ the entries of the tensor and to the fraction (central differences)."""
558
+ value = float(function(tensor, fraction))
559
+ step = 1e-6 * float(np.abs(tensor).max())
560
+ d_tensor = np.zeros_like(tensor)
561
+ for i in range(tensor.shape[0]):
562
+ for j in range(tensor.shape[1]):
563
+ plus, minus = tensor.copy(), tensor.copy()
564
+ plus[i, j] += step
565
+ minus[i, j] -= step
566
+ d_tensor[i, j] = (function(plus, fraction) - function(minus, fraction)) / (2 * step)
567
+ d_fraction = (function(tensor, fraction + 1e-6) - function(tensor, fraction - 1e-6)) / 2e-6
568
+ return value, d_tensor, float(d_fraction)
569
+
570
+
571
+ def optimize_cell(design: ShapeDesign, materials, objective: Callable, constraints=(), *,
572
+ linear=None, x0=None, physics: str = "elastic", plane: str = "strain",
573
+ method: str = "slsqp", maxiter: int = 100, tolerance: float = 1e-7,
574
+ move: float = 0.2, callback: Callable | None = None) -> ShapeResult: # fmt: skip
575
+ """The shape of a periodic cell that minimizes ``objective(tensor, fraction)`` under
576
+ ``constraint(tensor, fraction) <= 0`` for each of the ``constraints``: functions of
577
+ the effective tensor of the cell (Voigt's notation) and of its fraction of
578
+ material — for instance ``lambda c, f: -plane_constants(c)["bulk_modulus"]`` with
579
+ ``lambda c, f: f - 0.6``. ``linear = (A, b)`` adds the constraints ``A x <= b`` on
580
+ the variables (sizes of the geometry: the control points are linear in them); they
581
+ follow the others in the ``constraints`` of the result, as ``A x - b``. The
582
+ variables start from ``x0`` (zeros by default: the design as it is)."""
583
+ t0 = time.perf_counter()
584
+ functions = [objective, *constraints]
585
+ rows = np.zeros((0, design.n)), np.zeros(0)
586
+ if linear is not None:
587
+ rows = np.atleast_2d(np.asarray(linear[0], dtype=float)), np.atleast_1d(linear[1])
588
+ if rows[0].shape != (len(rows[1]), design.n):
589
+ raise ValueError(f"linear: (A, b) with one row of {design.n} coefficients per bound")
590
+
591
+ def evaluate(x):
592
+ try:
593
+ response = cell_response(design, x, materials, physics=physics, plane=plane)
594
+ except FoldedDesign:
595
+ raise
596
+ except ValueError as exc:
597
+ raise FoldedDesign(
598
+ f"{exc}: the design folds for these variables; tighten their bounds"
599
+ ) from None
600
+ values, gradients = [], []
601
+ for function in functions:
602
+ value, d_tensor, d_fraction = _partials(function, response.tensor, response.fraction)
603
+ values.append(value)
604
+ gradients.append(
605
+ np.einsum("ij,ijx->x", d_tensor, response.d_tensor)
606
+ + d_fraction * response.d_fraction
607
+ )
608
+ return (
609
+ values[0],
610
+ gradients[0],
611
+ np.concatenate([values[1:], rows[0] @ x - rows[1]]),
612
+ np.concatenate([np.array(gradients[1:]).reshape(-1, design.n), rows[0]]),
613
+ )
614
+
615
+ lower, upper = design.bounds()
616
+ x0 = np.zeros(design.n) if x0 is None else np.asarray(x0, dtype=float)
617
+ x, history, converged, message = optimize(
618
+ evaluate, x0, lower, upper, method=method, maxiter=maxiter, tolerance=tolerance,
619
+ move=move, callback=callback,
620
+ ) # fmt: skip
621
+ response = cell_response(design, x, materials, physics=physics, plane=plane)
622
+ values = [float(f(response.tensor, response.fraction)) for f in functions]
623
+ return ShapeResult(
624
+ x, design.design_model(x), design.analysis_model(x), values[0],
625
+ np.concatenate([values[1:], rows[0] @ x - rows[1]]),
626
+ len(history) - 1, converged, history, response.tensor, response.fraction,
627
+ time.perf_counter() - t0, message,
628
+ ) # fmt: skip
629
+
630
+
631
+ def optimize_structure(
632
+ design: ShapeDesign,
633
+ materials,
634
+ loads: Callable,
635
+ supports: Callable,
636
+ *,
637
+ measure: float | None = None,
638
+ x0=None,
639
+ plane: str = "strain",
640
+ method: str = "slsqp",
641
+ maxiter: int = 100,
642
+ tolerance: float = 1e-7,
643
+ move: float = 0.2,
644
+ callback: Callable | None = None,
645
+ ) -> ShapeResult:
646
+ """The shape of a structure of smallest compliance under given loads
647
+ (:func:`structure_response`) whose material has at most the area (volume)
648
+ ``measure`` (by default that of the design as it is)."""
649
+ t0 = time.perf_counter()
650
+ x0 = np.zeros(design.n) if x0 is None else np.asarray(x0, dtype=float)
651
+ if measure is None:
652
+ measure = Analysis(design.analysis_model(np.zeros(design.n)), materials).measure()
653
+ start = structure_response(design, x0, materials, loads, supports, plane=plane)
654
+
655
+ def evaluate(x):
656
+ try:
657
+ r = structure_response(design, x, materials, loads, supports, plane=plane)
658
+ except FoldedDesign:
659
+ raise
660
+ except ValueError as exc:
661
+ raise FoldedDesign(
662
+ f"{exc}: the design folds for these variables; tighten their bounds"
663
+ ) from None
664
+ return (
665
+ r.compliance / start.compliance,
666
+ r.d_compliance / start.compliance,
667
+ np.array([r.measure / measure - 1.0]),
668
+ r.d_measure[None, :] / measure,
669
+ )
670
+
671
+ lower, upper = design.bounds()
672
+ x, history, converged, message = optimize(
673
+ evaluate, x0, lower, upper, method=method, maxiter=maxiter, tolerance=tolerance,
674
+ move=move, callback=callback,
675
+ ) # fmt: skip
676
+ final = structure_response(design, x, materials, loads, supports, plane=plane)
677
+ return ShapeResult(
678
+ x, design.design_model(x), design.analysis_model(x), final.compliance,
679
+ np.array([final.measure / measure - 1.0]), len(history) - 1, converged, history,
680
+ None, None, time.perf_counter() - t0, message,
681
+ ) # fmt: skip
682
+
683
+
684
+ __all__ = [
685
+ "METHODS",
686
+ "CellResponse",
687
+ "FoldedDesign",
688
+ "ShapeDesign",
689
+ "ShapeResult",
690
+ "StructureResponse",
691
+ "cell_response",
692
+ "energy_gradients",
693
+ "measure_gradient",
694
+ "mirror",
695
+ "optimize",
696
+ "optimize_cell",
697
+ "optimize_structure",
698
+ "rotation",
699
+ "structure_response",
700
+ ]