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,1125 @@
1
+ """Periodic frames of Euler–Bernoulli beams in the plane (:class:`Frame`: the honeycomb,
2
+ triangular, square and kagome lattices of architectured materials) and in space
3
+ (:class:`SpaceFrame`: the cubic, body-centred cubic, octet and Kelvin lattices of struts),
4
+ their linear stiffness, the axial forces of a macroscopic strain and the linear buckling
5
+ of a cell of several primitive cells (Azulay 2023).
6
+
7
+ In space, a node carries ``(u, v, w, θx, θy, θz)``; a strut of circular section has the
8
+ axial (``EA/L``), torsional (``GJ/L``) and bending (``EI``, the same about both axes of
9
+ the section) stiffness of a 3D Euler–Bernoulli beam and the consistent geometric
10
+ stiffness of its transverse motions in both planes, with the torsional term
11
+ ``N I_p / (A L)``; rotations (pseudo-vectors) turn by ``det(R) R`` under a symmetry.
12
+
13
+ A node carries ``(u, v, θ)``. A beam of axis ``e`` and length ``L`` has the stiffness of
14
+ Euler–Bernoulli beams (axial ``EA/L``; cubic Hermite bending ``EI/L^3 [12, 6L, 4L^2,
15
+ ...]``) and, under the axial force ``N`` (positive in tension), the consistent geometric
16
+ stiffness ``N/30L [36, 3L, 4L^2, -L^2, ...]`` of its transverse motion. The cell is
17
+ periodic: the displacement of a node is ``E X + w``, ``E`` the macroscopic strain and
18
+ ``w`` (and ``θ``) periodic, so that a beam from node ``i`` to node ``j`` shifted by the
19
+ periods ``s`` of the cell (``x_j + A s - x_i`` its vector ``d``) stretches by
20
+ ``e · (E d + w_j - w_i)``. The axial forces of a macroscopic strain come from the linear
21
+ periodic problem; the linear buckling loads ``λ`` of that strain are those of
22
+ ``(K_e + λ K_g) φ = 0`` on the periodic fluctuations, translations excluded.
23
+
24
+ Both frames take, as an option, Timoshenko beams: a transverse shear stiffness ``κGA`` per
25
+ beam (the attribute ``shear``; ``shear_coefficient`` κ in ``from_framework`` and
26
+ ``lattice_of``, Cowper's for solid sections by :func:`cowper_coefficient`) gives the exact
27
+ two-node Timoshenko stiffness, ``EI / L³(1 + Φ) [12, 6L, (4 + Φ)L², (2 − Φ)L², ...]`` with
28
+ ``Φ = 12 EI / (κGA L²)`` in each bending plane (``θ`` the rotation of the section), and the
29
+ consistent geometric stiffness of its interpolation, ``N / 30L(1 + Φ)² [36 + 60Φ + 30Φ²,
30
+ 3L, (4 + 5Φ + 2.5Φ²)L², −(1 + 5Φ + 2.5Φ²)L², ...]``; without it (``shear`` None) the beams
31
+ are those of Euler–Bernoulli, ``Φ = 0``.
32
+
33
+ The frames of random periodic frameworks (fibre networks, open foams, lattices with
34
+ defects) are built by ``from_framework``, beams of circular sections along their bars, and
35
+ their effective stiffness is solved on sparse matrices by
36
+ :mod:`morphogen.homogenization.networks` (``effective_stiffness``). As an option
37
+ (``rigid_joints``, the attribute ``rigid``), the beams of a framework have rigid ends at
38
+ their joints, the struts merged in the nodes of a continuum: a beam flexible over ``l - a₁
39
+ - a₂`` whose ends move with the rigid arms ``a₁ e`` and ``-a₂ e`` of its nodes, ``u + θ ×
40
+ a e``; only the effective stiffness of the sparse problem takes them.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ from dataclasses import dataclass
46
+ from itertools import product
47
+
48
+ import numpy as np
49
+ from scipy.linalg import block_diag, eigh
50
+
51
+ #: Primitive cells (wall length 1): lattice vectors (columns), nodes, walls ``(i, j, s)``
52
+ #: from node ``i`` to node ``j`` shifted by the primitive periods ``s``, and the centre
53
+ #: and generators of the point group of the lattice.
54
+ _S3 = np.sqrt(3.0)
55
+
56
+
57
+ def _rotation(angle: float) -> np.ndarray:
58
+ c, s = np.cos(angle), np.sin(angle)
59
+ return np.array([[c, -s], [s, c]])
60
+
61
+
62
+ LATTICES = {
63
+ "honeycomb": {
64
+ "lattice": np.array([[_S3, _S3 / 2], [0.0, 1.5]]),
65
+ "nodes": np.array([[0.0, 1.0], [-_S3 / 2, 0.5]]),
66
+ "walls": [(0, 1, (0, 0)), (0, 1, (1, 0)), (0, 1, (0, 1))],
67
+ "centre": np.zeros(2),
68
+ "rotation": np.pi / 3,
69
+ },
70
+ "triangular": {
71
+ "lattice": np.array([[1.0, 0.5], [0.0, _S3 / 2]]),
72
+ "nodes": np.zeros((1, 2)),
73
+ "walls": [(0, 0, (1, 0)), (0, 0, (0, 1)), (0, 0, (-1, 1))],
74
+ "centre": np.zeros(2),
75
+ "rotation": np.pi / 3,
76
+ },
77
+ "square": {
78
+ "lattice": np.eye(2),
79
+ "nodes": np.zeros((1, 2)),
80
+ "walls": [(0, 0, (1, 0)), (0, 0, (0, 1))],
81
+ "centre": np.zeros(2),
82
+ "rotation": np.pi / 2,
83
+ },
84
+ "kagome": {
85
+ "lattice": np.array([[2.0, 1.0], [0.0, _S3]]),
86
+ "nodes": np.array([[0.0, 0.0], [1.0, 0.0], [0.5, _S3 / 2]]),
87
+ "walls": [
88
+ (0, 1, (0, 0)),
89
+ (1, 2, (0, 0)),
90
+ (2, 0, (0, 0)),
91
+ (1, 0, (1, 0)),
92
+ (2, 0, (0, 1)),
93
+ (2, 1, (-1, 1)),
94
+ ],
95
+ "centre": np.array([1.5, _S3 / 2]), # a hexagon
96
+ "rotation": np.pi / 3,
97
+ },
98
+ }
99
+
100
+
101
+ def _framework_arrays(framework, dimension: int):
102
+ """Nodes, bars, shifts and lattice of a periodic framework (an object with the
103
+ attributes of :class:`morphogen.design.frames.Framework`, or its dictionary) in the
104
+ plane (its first two axes; no bar may cross the box along the third) or in space."""
105
+ if isinstance(framework, dict):
106
+ from morphogen.design.frames import Framework
107
+
108
+ framework = Framework.from_dict(framework)
109
+ nodes = np.asarray(framework.nodes, dtype=float)
110
+ bars = np.asarray(framework.bars, dtype=np.int64).reshape(-1, 2)
111
+ shifts = np.asarray(framework.shifts, dtype=np.int64).reshape(len(bars), -1)
112
+ box = np.asarray(framework.box, dtype=float).ravel()
113
+ if len(bars) == 0:
114
+ raise ValueError("from_framework: a framework without bars")
115
+ if np.any(np.bincount(bars.ravel(), minlength=len(nodes)) == 0):
116
+ raise ValueError("from_framework: isolated nodes (without_isolated_nodes() first)")
117
+ if dimension == 2:
118
+ if shifts.shape[1] > 2 and np.any(shifts[:, 2:] != 0):
119
+ raise ValueError("from_framework: a bar crosses the box along z (not a plane frame)")
120
+ if nodes.shape[1] > 2 and np.ptp(nodes[:, 2]) > 1e-9 * float(np.max(box)):
121
+ raise ValueError(
122
+ "from_framework: the nodes lie at several heights (not a plane frame: "
123
+ "SpaceFrame.from_framework, or network_stiffness with dimension 3)"
124
+ )
125
+ return nodes[:, :2], bars, shifts[:, :2], np.diag(box[:2])
126
+ return nodes, bars, shifts, np.diag(box)
127
+
128
+
129
+ def _per_bar(value, count: int, name: str) -> np.ndarray:
130
+ """One positive value per bar (a single value repeated)."""
131
+ out = np.broadcast_to(np.asarray(value, dtype=float), (count,)).copy()
132
+ if not np.all(np.isfinite(out)) or np.any(out <= 0):
133
+ raise ValueError(f"from_framework: {name} positive, one value or one per bar")
134
+ return out
135
+
136
+
137
+ #: The least flexible part of a beam with rigid ends, relative to its length: the rigid
138
+ #: ends of the shortest beams (edges shorter than two rigid lengths, inside their nodes)
139
+ #: are scaled down to leave it
140
+ FLEXIBLE_LIMIT = 0.1
141
+
142
+
143
+ def _rigid_ends(rigid_joints, radius: np.ndarray, lengths: np.ndarray):
144
+ """The lengths of the rigid ends of each beam at its two nodes (m x 2), ``rigid_joints``
145
+ radii of the beam (one value or one per bar; None or 0: no rigid ends), scaled down on
146
+ the beams shorter than them so that :data:`FLEXIBLE_LIMIT` of each stays flexible."""
147
+ if rigid_joints is None:
148
+ return None
149
+ c = np.broadcast_to(np.asarray(rigid_joints, dtype=float), radius.shape)
150
+ if not np.all(np.isfinite(c)) or np.any(c < 0):
151
+ raise ValueError("from_framework: rigid_joints non-negative, one value or one per bar")
152
+ if not np.any(c > 0): # ends of no length: the frame without rigid ends, every path open
153
+ return None
154
+ a = c * radius
155
+ scale = np.minimum(1.0, 0.5 * (1.0 - FLEXIBLE_LIMIT) * lengths / np.maximum(a, 1e-300))
156
+ return np.repeat((a * scale)[:, None], 2, axis=1)
157
+
158
+
159
+ def _check_rigid(frame) -> None:
160
+ """The dense paths (stiffness, axial forces, buckling) take beams without rigid ends."""
161
+ if frame.rigid is not None:
162
+ raise ValueError(
163
+ "rigid joints: the effective stiffness of the sparse periodic problem only "
164
+ "(effective_stiffness, networks.frame_stiffness)"
165
+ )
166
+
167
+
168
+ #: The solid sections of Cowper's shear coefficients
169
+ SECTIONS = ("circular", "rectangular")
170
+
171
+
172
+ def cowper_coefficient(poisson, section: str = "circular"):
173
+ """Cowper's (1966) shear coefficient ``κ`` of a solid section of Poisson's ratio
174
+ ``poisson``: ``6(1 + ν)/(7 + 6ν)`` for a circle, ``10(1 + ν)/(12 + 11ν)`` for a
175
+ rectangle (the transverse shear stiffness of a Timoshenko beam is ``κGA``)."""
176
+ nu = np.asarray(poisson, dtype=float)
177
+ if np.any(nu <= -1.0) or np.any(nu >= 0.5):
178
+ raise ValueError("cowper_coefficient: poisson in (-1, 0.5)")
179
+ if section == "circular":
180
+ return 6.0 * (1.0 + nu) / (7.0 + 6.0 * nu)
181
+ if section == "rectangular":
182
+ return 10.0 * (1.0 + nu) / (12.0 + 11.0 * nu)
183
+ raise ValueError(f"cowper_coefficient: section one of {SECTIONS}")
184
+
185
+
186
+ def _shear_stiffness(coefficient, young, poisson, area, section: str):
187
+ """The transverse shear stiffness ``κGA`` of each beam, ``G = E / 2(1 + ν)``, for a
188
+ shear ``coefficient`` κ (one value, one per beam, or ``"cowper"``: Cowper's for the
189
+ section); None (Euler–Bernoulli beams) without coefficient."""
190
+ if coefficient is None:
191
+ return None
192
+ count = len(area)
193
+ nu = np.broadcast_to(np.asarray(poisson, dtype=float), (count,))
194
+ if isinstance(coefficient, str):
195
+ if coefficient != "cowper":
196
+ raise ValueError("shear_coefficient: 'cowper', a value or one per beam")
197
+ kappa = cowper_coefficient(nu, section)
198
+ else:
199
+ kappa = _per_bar(coefficient, count, "shear_coefficient")
200
+ if np.any(nu <= -1.0) or np.any(nu >= 0.5):
201
+ raise ValueError("from_framework: poisson in (-1, 0.5)")
202
+ return kappa * young / (2.0 * (1.0 + nu)) * area
203
+
204
+
205
+ def _shear_parameter(bending, shear, length):
206
+ """The shear parameter ``Φ = 12 EI / (κGA L²)`` of a Timoshenko beam: 0 for an
207
+ Euler–Bernoulli beam (``shear`` None or infinite)."""
208
+ if shear is None:
209
+ return 0.0
210
+ return 12.0 * bending / (shear * length**2)
211
+
212
+
213
+ def beam_matrices(d, axial: float, bending: float, force: float = 0.0, shear=None):
214
+ """Elastic and geometric stiffness (6 x 6, global axes, dofs ``u1 v1 θ1 u2 v2 θ2``) of
215
+ a beam of vector ``d``, ``EA``, ``EI`` and axial force ``force``: an Euler–Bernoulli
216
+ beam, or with the transverse shear stiffness ``shear`` (``κGA``) the exact two-node
217
+ Timoshenko beam of shear parameter ``Φ = 12 EI / (κGA L²)`` (``θ`` the rotation of
218
+ the section; Przemieniecki 1968) and the consistent geometric stiffness ``N ∫ v'² dx``
219
+ of its interpolation (Friedman & Kosmatka 1993), the Euler–Bernoulli ones at ``Φ =
220
+ 0``."""
221
+ length = float(np.hypot(*d))
222
+ c, s = d[0] / length, d[1] / length
223
+ L = length
224
+ phi = _shear_parameter(bending, shear, L)
225
+ a, b = axial / length, bending / length**3 / (1.0 + phi)
226
+ ke = np.array(
227
+ [
228
+ [a, 0, 0, -a, 0, 0],
229
+ [0, 12 * b, 6 * b * L, 0, -12 * b, 6 * b * L],
230
+ [0, 6 * b * L, (4 + phi) * b * L**2, 0, -6 * b * L, (2 - phi) * b * L**2],
231
+ [-a, 0, 0, a, 0, 0],
232
+ [0, -12 * b, -6 * b * L, 0, 12 * b, -6 * b * L],
233
+ [0, 6 * b * L, (2 - phi) * b * L**2, 0, -6 * b * L, (4 + phi) * b * L**2],
234
+ ]
235
+ )
236
+ g = force / (30.0 * L * (1.0 + phi) ** 2)
237
+ p, q, r = _geometric_terms(phi, L)
238
+ kg = g * np.array(
239
+ [
240
+ [0, 0, 0, 0, 0, 0],
241
+ [0, p, 3 * L, 0, -p, 3 * L],
242
+ [0, 3 * L, q, 0, -3 * L, r],
243
+ [0, 0, 0, 0, 0, 0],
244
+ [0, -p, -3 * L, 0, p, -3 * L],
245
+ [0, 3 * L, r, 0, -3 * L, q],
246
+ ]
247
+ )
248
+ rot = np.array([[c, s, 0], [-s, c, 0], [0, 0, 1]])
249
+ t = np.kron(np.eye(2), rot)
250
+ return t.T @ ke @ t, t.T @ kg @ t
251
+
252
+
253
+ def _geometric_terms(phi: float, length: float) -> tuple[float, float, float]:
254
+ """The entries ``(v v, θ θ, θ1 θ2)`` of the geometric stiffness of a Timoshenko beam
255
+ times ``30 L (1 + Φ)² / N``: ``36``, ``4L²`` and ``-L²`` at ``Φ = 0``."""
256
+ return (
257
+ 36 + 60 * phi + 30 * phi**2,
258
+ (4 + 5 * phi + 2.5 * phi**2) * length**2,
259
+ -(1 + 5 * phi + 2.5 * phi**2) * length**2,
260
+ )
261
+
262
+
263
+ @dataclass
264
+ class Frame:
265
+ """A periodic frame: ``nodes`` (positions in the cell), ``beams`` (node pairs),
266
+ ``shifts`` (periods between the ends: beam ``k`` ends at ``nodes[j] + lattice @
267
+ shifts[k]``), the ``lattice`` of the cell (vectors in the columns), ``EA`` and ``EI`` of
268
+ each beam, the centre and generators ``(R, t)`` of its symmetry group, the area of
269
+ the section of each beam (for the fibre volume per unit area), the transverse shear
270
+ stiffness ``κGA`` of each beam: Timoshenko beams (None, the default: Euler–Bernoulli
271
+ beams, rigid in shear) and the lengths of the rigid ends of each beam at its first and
272
+ second node (m x 2; None, the default: none), which the effective stiffness alone
273
+ takes."""
274
+
275
+ nodes: np.ndarray
276
+ beams: np.ndarray
277
+ shifts: np.ndarray
278
+ lattice: np.ndarray
279
+ axial: np.ndarray
280
+ bending: np.ndarray
281
+ centre: np.ndarray
282
+ generators: list
283
+ area: np.ndarray | None = None
284
+ shear: np.ndarray | None = None
285
+ rigid: np.ndarray | None = None
286
+
287
+ @classmethod
288
+ def from_framework(
289
+ cls, framework, radius, *, young=1.0, poisson=0.3, shear_coefficient=None,
290
+ rigid_joints=None,
291
+ ) -> Frame: # fmt: skip
292
+ """The plane frame of a periodic framework of the plane (the first two axes of a
293
+ :class:`morphogen.design.frames.Framework`, or of its dictionary as the metadata
294
+ of the planar network models keep it): a beam per bar, of circular section of
295
+ ``radius`` and Young's modulus ``young`` (one value, or one per bar), ``EA = E π
296
+ r²`` and ``EI = E π r⁴ / 4`` (bending in the plane). The box is the cell; its
297
+ symmetry, the translations alone. With a ``shear_coefficient`` κ (one value, one
298
+ per bar, or ``"cowper"``: Cowper's ``6(1 + ν)/(7 + 6ν)``), Timoshenko beams of
299
+ shear stiffness ``κGA``, ``G = E / 2(1 + ν)`` (``poisson`` one value or one per
300
+ bar); Euler–Bernoulli beams without. With ``rigid_joints`` (one value or one per
301
+ bar), the beams are rigid over that many of their radii from each node (the
302
+ struts merged in the joints; :data:`FLEXIBLE_LIMIT` of the shortest left
303
+ flexible)."""
304
+ nodes, bars, shifts, lattice = _framework_arrays(framework, 2)
305
+ r = _per_bar(radius, len(bars), "radius")
306
+ e = _per_bar(young, len(bars), "young")
307
+ area = np.pi * r**2
308
+ frame = cls(
309
+ nodes,
310
+ bars,
311
+ shifts,
312
+ lattice,
313
+ e * area,
314
+ e * np.pi * r**4 / 4.0,
315
+ np.zeros(2),
316
+ [(np.eye(2), np.zeros(2))],
317
+ area,
318
+ _shear_stiffness(shear_coefficient, e, poisson, area, "circular"),
319
+ )
320
+ frame.rigid = _rigid_ends(rigid_joints, r, np.linalg.norm(frame.vectors(), axis=1))
321
+ return frame
322
+
323
+ @classmethod
324
+ def lattice_of(
325
+ cls,
326
+ kind: str = "honeycomb",
327
+ cells=(2, 2),
328
+ *,
329
+ length: float = 1.0,
330
+ elements: int = 4,
331
+ young: float = 1.0,
332
+ thickness: float = 0.1,
333
+ depth: float = 1.0,
334
+ poisson: float = 0.3,
335
+ shear_coefficient=None,
336
+ ) -> Frame:
337
+ """A cell of ``cells`` primitive cells of a lattice (``honeycomb``, ``triangular``,
338
+ ``square`` or ``kagome``) of walls of ``length``, each cut in ``elements`` beams of
339
+ Young's modulus ``young`` and rectangular section ``thickness x depth``:
340
+ Euler–Bernoulli beams, or with a ``shear_coefficient`` κ (a value, or
341
+ ``"cowper"``: Cowper's ``10(1 + ν)/(12 + 11ν)`` of rectangles) Timoshenko beams of
342
+ shear stiffness ``κGA``, ``G = E / 2(1 + ν)``."""
343
+ if kind not in LATTICES:
344
+ raise ValueError(f"lattice_of: one of {sorted(LATTICES)}")
345
+ spec = LATTICES[kind]
346
+ n1, n2 = (int(c) for c in cells)
347
+ a = spec["lattice"] * length
348
+ lattice = a @ np.diag([n1, n2])
349
+ inv = np.linalg.inv(lattice)
350
+ base = spec["nodes"] * length
351
+ npc = len(base)
352
+ nodes = [base[p] + a @ (i, j) for i in range(n1) for j in range(n2) for p in range(npc)]
353
+
354
+ def index(p, i, j):
355
+ return (i % n1) * n2 * npc + (j % n2) * npc + p
356
+
357
+ def wrap(x):
358
+ return lattice @ ((inv @ x) % 1.0)
359
+
360
+ nodes = [wrap(x) for x in nodes]
361
+ beams, shifts = [], []
362
+ for i in range(n1):
363
+ for j in range(n2):
364
+ for p, q, (s1, s2) in spec["walls"]:
365
+ start = index(p, i, j)
366
+ end = index(q, i + s1, j + s2)
367
+ x0 = nodes[start]
368
+ x1 = base[q] + a @ (i + s1, j + s2)
369
+ x1 = x0 + (x1 - (base[p] + a @ (i, j))) # unwrapped from the start node
370
+ chain = [start]
371
+ for k in range(1, int(elements)):
372
+ nodes.append(wrap(x0 + (k / elements) * (x1 - x0)))
373
+ chain.append(len(nodes) - 1)
374
+ chain.append(end)
375
+ for k in range(int(elements)):
376
+ u, v = chain[k], chain[k + 1]
377
+ step = (x1 - x0) / elements
378
+ shift = np.rint(inv @ (nodes[u] + step - nodes[v])).astype(int)
379
+ beams.append((u, v))
380
+ shifts.append(shift)
381
+ area, inertia = thickness * depth, depth * thickness**3 / 12.0
382
+ m = len(beams)
383
+ rot = _rotation(spec["rotation"])
384
+ mirror = np.array([[-1.0, 0.0], [0.0, 1.0]])
385
+ generators = [
386
+ (rot, np.zeros(2)),
387
+ (mirror, np.zeros(2)),
388
+ (np.eye(2), a[:, 0]),
389
+ (np.eye(2), a[:, 1]),
390
+ ]
391
+ return cls(
392
+ np.array(nodes),
393
+ np.array(beams, dtype=np.int64),
394
+ np.array(shifts, dtype=np.int64),
395
+ lattice,
396
+ np.full(m, young * area),
397
+ np.full(m, young * inertia),
398
+ spec["centre"] * length,
399
+ generators,
400
+ np.full(m, area),
401
+ _shear_stiffness(shear_coefficient, young, poisson, np.full(m, area), "rectangular"),
402
+ )
403
+
404
+ @property
405
+ def n_dofs(self) -> int:
406
+ return 3 * len(self.nodes)
407
+
408
+ def _shears(self) -> list:
409
+ """The transverse shear stiffness ``κGA`` of each beam (None: Euler–Bernoulli)."""
410
+ return [None] * len(self.beams) if self.shear is None else list(self.shear)
411
+
412
+ @staticmethod
413
+ def block(rotation) -> np.ndarray:
414
+ """The action of a point operation on the dofs ``(u, v, θ)`` of a node."""
415
+ r = np.asarray(rotation, dtype=float)
416
+ return block_diag(r, np.linalg.det(r))
417
+
418
+ def vectors(self) -> np.ndarray:
419
+ """The vector of each beam, from its first end to its second."""
420
+ return (
421
+ self.nodes[self.beams[:, 1]]
422
+ + self.shifts @ self.lattice.T
423
+ - self.nodes[self.beams[:, 0]]
424
+ )
425
+
426
+ def _dofs(self) -> np.ndarray:
427
+ e = self.beams
428
+ return np.column_stack(
429
+ [
430
+ 3 * e[:, 0],
431
+ 3 * e[:, 0] + 1,
432
+ 3 * e[:, 0] + 2,
433
+ 3 * e[:, 1],
434
+ 3 * e[:, 1] + 1,
435
+ 3 * e[:, 1] + 2,
436
+ ]
437
+ )
438
+
439
+ def _assemble(self, forces=None) -> tuple[np.ndarray, np.ndarray]:
440
+ _check_rigid(self)
441
+ n = self.n_dofs
442
+ ke, kg = np.zeros((n, n)), np.zeros((n, n))
443
+ forces = np.zeros(len(self.beams)) if forces is None else np.asarray(forces, dtype=float)
444
+ for d, a, b, f, q, dofs in zip(
445
+ self.vectors(), self.axial, self.bending, forces, self._shears(), self._dofs(),
446
+ strict=True,
447
+ ): # fmt: skip
448
+ e, g = beam_matrices(d, a, b, f, q)
449
+ ke[np.ix_(dofs, dofs)] += e
450
+ kg[np.ix_(dofs, dofs)] += g
451
+ return ke, kg
452
+
453
+ def stiffness(self) -> np.ndarray:
454
+ """The elastic stiffness of the periodic fluctuations (dense)."""
455
+ return self._assemble()[0]
456
+
457
+ def translations(self) -> np.ndarray:
458
+ """The two rigid translations of the cell (dofs x 2, orthonormal)."""
459
+ t = np.zeros((self.n_dofs, 2))
460
+ t[0::3, 0] = t[1::3, 1] = 1.0 / np.sqrt(len(self.nodes))
461
+ return t
462
+
463
+ def complement(self) -> np.ndarray:
464
+ """An orthonormal basis of the fluctuations orthogonal to the translations."""
465
+ t = self.translations()
466
+ q, _ = np.linalg.qr(np.hstack([t, np.eye(self.n_dofs)]))
467
+ return q[:, 2:]
468
+
469
+ def axial_forces(self, strain) -> tuple[np.ndarray, np.ndarray]:
470
+ """The axial forces of the beams under the macroscopic ``strain`` (2 x 2) and the
471
+ periodic fluctuations (dofs) of the linear periodic problem."""
472
+ e = np.asarray(strain, dtype=float)
473
+ ke = self.stiffness()
474
+ dofs = self._dofs()
475
+ force = np.zeros(self.n_dofs)
476
+ affine = []
477
+ for d, a, b, q, idx in zip(
478
+ self.vectors(), self.axial, self.bending, self._shears(), dofs, strict=True
479
+ ):
480
+ k, _ = beam_matrices(d, a, b, shear=q)
481
+ u = np.zeros(6)
482
+ u[3:5] = e @ d # the affine motion of the second end relative to the first
483
+ affine.append(u)
484
+ force[idx] += k @ u
485
+ z = self.complement()
486
+ w = z @ np.linalg.solve(z.T @ ke @ z, -z.T @ force)
487
+ forces = np.empty(len(self.beams))
488
+ for k, (d, a, idx, u) in enumerate(
489
+ zip(self.vectors(), self.axial, dofs, affine, strict=True)
490
+ ):
491
+ length = float(np.hypot(*d))
492
+ relative = u[3:5] + w[idx[3:5]] - w[idx[0:2]]
493
+ forces[k] = a / length * float(d @ relative) / length
494
+ return forces, w
495
+
496
+ def buckling(self, strain, modes: int = 6) -> tuple[np.ndarray, np.ndarray]:
497
+ """The lowest ``modes`` positive load factors ``λ`` of the linear buckling of the
498
+ cell under ``λ strain`` and their modes (dofs x modes)."""
499
+ forces, _ = self.axial_forces(strain)
500
+ ke, kg = self._assemble(forces)
501
+ z = self.complement()
502
+ return _buckling(z.T @ ke @ z, z.T @ kg @ z, z, modes)
503
+
504
+ def effective_stiffness(self):
505
+ """The effective stiffness of the periodic frame (3 x 3, Voigt order 11, 22, 12
506
+ with the engineering shear, per unit area of the plane), its split into stretching
507
+ and bending and the non-affinity of the fluctuations, by the sparse periodic
508
+ problem (:func:`morphogen.homogenization.networks.frame_stiffness`)."""
509
+ from morphogen.homogenization.networks import frame_stiffness
510
+
511
+ return frame_stiffness(self)
512
+
513
+ def reciprocal(self) -> np.ndarray:
514
+ """The reciprocal vectors of the cell (columns): ``b_i · a_j = 2π δ_ij``."""
515
+ return 2.0 * np.pi * np.linalg.inv(self.lattice).T
516
+
517
+ def bloch_buckling(self, strain, wavevectors, modes: int = 1) -> np.ndarray:
518
+ """The lowest ``modes`` load factors of the linear buckling of the infinite frame
519
+ under ``λ strain`` for the Bloch modes ``u(x + A s) = u(x) exp(i k · A s)`` of each
520
+ wave vector (rows: wave vectors): the smallest over the Brillouin zone gives the
521
+ critical wavelength, hence the cell of the patterns (Geymonat, Müller &
522
+ Triantafyllidis 1993); the cell at ``k`` of ``(m1 b1 + m2 b2) / n`` is that of
523
+ ``n x n`` cells."""
524
+ _check_rigid(self)
525
+ forces, _ = self.axial_forces(strain)
526
+ n = self.n_dofs
527
+ mats = [
528
+ beam_matrices(d, a, b, f, q)
529
+ for d, a, b, f, q in zip(
530
+ self.vectors(), self.axial, self.bending, forces, self._shears(), strict=True
531
+ )
532
+ ]
533
+ periods = self.shifts @ self.lattice.T
534
+ out = []
535
+ for k in np.atleast_2d(np.asarray(wavevectors, dtype=float)):
536
+ ke, kg = np.zeros((n, n), complex), np.zeros((n, n), complex)
537
+ for (e, g), dofs, period in zip(mats, self._dofs(), periods, strict=True):
538
+ p = np.ones(6, complex)
539
+ p[3:] = np.exp(1j * (k @ period))
540
+ ke[np.ix_(dofs, dofs)] += np.conj(p)[:, None] * e * p[None, :]
541
+ kg[np.ix_(dofs, dofs)] += np.conj(p)[:, None] * g * p[None, :]
542
+ frac = self.lattice.T @ k / (2.0 * np.pi) # Γ or its images: translations
543
+ basis = self.complement() if np.allclose(frac, np.round(frac), atol=1e-9) else np.eye(n)
544
+ ke, kg = basis.T @ ke @ basis, basis.T @ kg @ basis
545
+
546
+ def real(h):
547
+ h = 0.5 * (h + h.conj().T)
548
+ return np.block([[h.real, -h.imag], [h.imag, h.real]])
549
+
550
+ lam, _ = _buckling(real(ke), real(kg), np.eye(2 * basis.shape[1]), 2 * int(modes))
551
+ out.append(np.pad(lam[0::2], (0, int(modes) - len(lam[0::2])), constant_values=np.nan))
552
+ return np.array(out)
553
+
554
+ def plot(self, ax=None, displacement=None, *, scale: float = 0.0, tiles=(1, 1), **style):
555
+ """Draw the beams, displaced by ``displacement`` (its largest drawn as ``scale``
556
+ times the median length of the beams; 0.3 by default), the cell repeated ``tiles``
557
+ times; returns the axes."""
558
+ if ax is None:
559
+ from morphogen.viz.figures import _figure
560
+
561
+ ax = _figure(5.0, 5.0).subplots()
562
+ x = self.nodes.copy()
563
+ if displacement is not None:
564
+ u = np.asarray(displacement, dtype=float).reshape(-1, 3)[:, :2]
565
+ peak = max(float(np.abs(u).max()), 1e-300)
566
+ size = float(np.median(np.hypot(*self.vectors().T)))
567
+ x = x + u * (scale or 0.3) * size / peak
568
+ d = x[self.beams[:, 1]] + self.shifts @ self.lattice.T - x[self.beams[:, 0]]
569
+ segments = []
570
+ for i in range(int(tiles[0])):
571
+ for j in range(int(tiles[1])):
572
+ offset = self.lattice @ (i, j)
573
+ start = x[self.beams[:, 0]] + offset
574
+ segments.extend(zip(start, start + d, strict=True))
575
+ from matplotlib.collections import LineCollection
576
+
577
+ ax.add_collection(
578
+ LineCollection(
579
+ segments, colors=style.get("color", "k"), linewidths=style.get("lw", 1.0)
580
+ )
581
+ )
582
+ ax.set_aspect("equal")
583
+ ax.autoscale()
584
+ ax.set_axis_off()
585
+ return ax
586
+
587
+
588
+ def positive_subspace(k: np.ndarray, tol: float = 1e-10) -> np.ndarray:
589
+ """Orthonormal basis of the subspace where a symmetric stiffness is positive: its
590
+ mechanisms (eigenvalues below ``tol`` times the largest) left out."""
591
+ w, v = eigh(0.5 * (k + k.T))
592
+ return v[:, w > tol * max(float(np.abs(w).max()), 1e-300)]
593
+
594
+
595
+ def _buckling(ke: np.ndarray, kg: np.ndarray, basis: np.ndarray, modes: int, floor=None):
596
+ """Lowest positive ``λ`` of ``(K_e + λ K_g) φ = 0`` (``K_e`` positive definite): the
597
+ eigenvalues ``μ = 1/λ`` of ``-K_g φ = μ K_e φ`` above ``floor`` (by default 1e-10
598
+ times the largest ``|μ|``; a subspace where ``K_g`` vanishes has none)."""
599
+ if ke.shape[0] == 0:
600
+ return np.zeros(0), np.zeros((basis.shape[0], 0))
601
+ ke, kg = 0.5 * (ke + ke.T), 0.5 * (kg + kg.T)
602
+ try:
603
+ mu, phi = eigh(-kg, ke)
604
+ except np.linalg.LinAlgError: # mechanisms (zero-energy modes): left out
605
+ v = positive_subspace(ke)
606
+ mu, phi = eigh(-(v.T @ kg @ v), v.T @ ke @ v)
607
+ phi = v @ phi
608
+ if floor is None:
609
+ floor = 1e-10 * max(float(np.abs(mu).max()), 1e-300)
610
+ keep = mu > floor
611
+ loads, phi = 1.0 / mu[keep], phi[:, keep]
612
+ order = np.argsort(loads)[: int(modes)]
613
+ return loads[order], basis @ phi[:, order]
614
+
615
+
616
+ # -- frames in space ---------------------------------------------------------------------
617
+
618
+ _C4Z = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
619
+ _C3 = np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) # about [111]
620
+ #: The point group of the cubic lattices (O_h, about a node): generators
621
+ CUBIC_GENERATORS = (_C4Z, _C3, -np.eye(3))
622
+
623
+
624
+ def _kelvin_nodes() -> np.ndarray:
625
+ """The vertices of the truncated octahedra of the body-centred cubic packing (the
626
+ Kelvin cell), modulo the conventional cell of edge 1: permutations of ``(0, ±1/4,
627
+ ±1/2)``."""
628
+ out = []
629
+ for perm in {(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)}:
630
+ for s1, s2 in product((-1, 1), repeat=2):
631
+ x = np.array([0.0, 0.25 * s1, 0.5 * s2])[list(perm)] % 1.0
632
+ if not any(np.allclose(x, y) for y in out):
633
+ out.append(x)
634
+ return np.array(sorted(out, key=tuple))
635
+
636
+
637
+ _FCC = [np.array(c) for c in ((0.5, 0.5, 0.0), (0.5, 0.0, 0.5), (0.0, 0.5, 0.5))]
638
+
639
+
640
+ def _face_centred(basis) -> np.ndarray:
641
+ """The nodes of a face-centred cubic lattice with a ``basis``, in its cubic cell."""
642
+ sites = [np.zeros(3), *_FCC]
643
+ return np.array([(site + np.asarray(b, dtype=float)) % 1.0 for site in sites for b in basis])
644
+
645
+
646
+ #: Lattices of struts (conventional cubic cell of edge 1): nodes, length of the struts
647
+ #: (between nearest neighbours) and the centring translations of the lattice; point group
648
+ #: O_h about the origin, or the ``generators`` of the space group (a point operation and a
649
+ #: translation each) where some of its operations move the origin: the diamond lattice
650
+ #: (a node of one of its two face-centred lattices at the origin: its tetrahedral group,
651
+ #: and the inversion about the middle of a strut) and the pyrochlore lattice of
652
+ #: tetrahedra joined by their corners (a node at the origin: its inversion and its
653
+ #: threefold axis, and the fourfold rotation-reflection about a node of the diamond
654
+ #: lattice whose struts it bisects).
655
+ SPACE_LATTICES = {
656
+ "cubic": {"nodes": np.zeros((1, 3)), "strut": 1.0, "centring": []},
657
+ "bcc": {
658
+ "nodes": np.array([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]),
659
+ "strut": np.sqrt(3.0) / 2,
660
+ "centring": [np.array([0.5, 0.5, 0.5])],
661
+ },
662
+ "octet": {
663
+ "nodes": np.array([[0.0, 0.0, 0.0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5]]),
664
+ "strut": np.sqrt(2.0) / 2,
665
+ "centring": [np.array(c) for c in ((0.5, 0.5, 0.0), (0.5, 0.0, 0.5), (0.0, 0.5, 0.5))],
666
+ },
667
+ "kelvin": {
668
+ "nodes": _kelvin_nodes(),
669
+ "strut": np.sqrt(2.0) / 4,
670
+ "centring": [np.array([0.5, 0.5, 0.5])],
671
+ },
672
+ "diamond": {
673
+ "nodes": _face_centred([(0.0, 0.0, 0.0), (0.25, 0.25, 0.25)]),
674
+ "strut": np.sqrt(3.0) / 4,
675
+ "centring": _FCC,
676
+ "generators": [
677
+ (-_C4Z, np.zeros(3)),
678
+ (_C3, np.zeros(3)),
679
+ (-np.eye(3), np.array([0.25, 0.25, 0.25])),
680
+ ],
681
+ },
682
+ "pyrochlore": {
683
+ "nodes": _face_centred(
684
+ [(0.0, 0.0, 0.0), (0.0, 0.75, 0.75), (0.75, 0.0, 0.75), (0.75, 0.75, 0.0)]
685
+ ),
686
+ "strut": np.sqrt(2.0) / 4,
687
+ "centring": _FCC,
688
+ "generators": [
689
+ (-_C4Z, np.array([0.0, -0.25, -0.25])),
690
+ (_C3, np.zeros(3)),
691
+ (-np.eye(3), np.zeros(3)),
692
+ ],
693
+ },
694
+ }
695
+
696
+
697
+ def _struts(nodes: np.ndarray, length: float, tol: float = 1e-6) -> list:
698
+ """The struts ``(i, j, s)`` of length ``length`` between nodes of a periodic cell of
699
+ edge 1 (node ``j`` shifted by the periods ``s``), each once."""
700
+ out = []
701
+ for i, xi in enumerate(nodes):
702
+ for j, xj in enumerate(nodes):
703
+ if j < i:
704
+ continue
705
+ for shift in product((-1, 0, 1), repeat=3):
706
+ if j == i and shift <= (0, 0, 0):
707
+ continue
708
+ if abs(np.linalg.norm(xj + np.array(shift) - xi) - length) < tol:
709
+ out.append((i, j, shift))
710
+ return out
711
+
712
+
713
+ def space_beam_matrices(
714
+ d, axial: float, bending: float, torsion: float, force=0.0, polar=0.0, shear=None
715
+ ):
716
+ """Elastic and geometric stiffness (12 x 12, global axes, dofs ``u v w θx θy θz`` of
717
+ each end) of a 3D Euler–Bernoulli beam of vector ``d``: ``EA``, ``EI`` about both axes
718
+ of its section (circular or square), ``GJ``, the axial force ``force`` (positive in
719
+ tension) and ``polar`` = ``I_p / A`` of the section (the torsional term of the
720
+ geometric stiffness). With the transverse shear stiffness ``shear`` (``κGA``, the same
721
+ in both planes), the exact Timoshenko beam and its geometric stiffness in each bending
722
+ plane, of shear parameter ``Φ = 12 EI / (κGA L²)`` (as :func:`beam_matrices`)."""
723
+ d = np.asarray(d, dtype=float)
724
+ length = float(np.linalg.norm(d))
725
+ ex = d / length
726
+ helper = np.array([0.0, 0.0, 1.0]) if abs(ex[2]) < 0.9 else np.array([1.0, 0.0, 0.0])
727
+ ey = np.cross(helper, ex)
728
+ ey /= np.linalg.norm(ey)
729
+ ez = np.cross(ex, ey)
730
+ L = length
731
+ ke, kg = np.zeros((12, 12)), np.zeros((12, 12))
732
+ for i, j, v in ((0, 6, axial / L), (3, 9, torsion / L)):
733
+ ke[i, i] = ke[j, j] = v
734
+ ke[i, j] = ke[j, i] = -v
735
+ phi = _shear_parameter(bending, shear, L)
736
+ b, g = bending / L**3 / (1.0 + phi), force / (30.0 * L * (1.0 + phi) ** 2)
737
+ plane_y = np.array( # (v, θz) of both ends
738
+ [
739
+ [12, 6 * L, -12, 6 * L],
740
+ [6 * L, (4 + phi) * L**2, -6 * L, (2 - phi) * L**2],
741
+ [-12, -6 * L, 12, -6 * L],
742
+ [6 * L, (2 - phi) * L**2, -6 * L, (4 + phi) * L**2],
743
+ ]
744
+ )
745
+ p, q, r = _geometric_terms(phi, L)
746
+ geo_y = np.array(
747
+ [
748
+ [p, 3 * L, -p, 3 * L],
749
+ [3 * L, q, -3 * L, r],
750
+ [-p, -3 * L, p, -3 * L],
751
+ [3 * L, r, -3 * L, q],
752
+ ]
753
+ )
754
+ flip = np.diag([1.0, -1.0, 1.0, -1.0]) # (w, θy): θy = -dw/dx
755
+ for dofs, sign in (([1, 5, 7, 11], np.eye(4)), ([2, 4, 8, 10], flip)):
756
+ idx = np.ix_(dofs, dofs)
757
+ ke[idx] += b * sign @ plane_y @ sign
758
+ kg[idx] += g * sign @ geo_y @ sign
759
+ t = force * polar / L
760
+ kg[3, 3] = kg[9, 9] = t
761
+ kg[3, 9] = kg[9, 3] = -t
762
+ rot = np.kron(np.eye(4), np.array([ex, ey, ez]))
763
+ return rot.T @ ke @ rot, rot.T @ kg @ rot
764
+
765
+
766
+ @dataclass
767
+ class SpaceFrame:
768
+ """A periodic frame of struts in space: ``nodes`` (positions in the cell), ``beams``
769
+ (node pairs), ``shifts`` (periods between the ends), the ``lattice`` of the cell
770
+ (vectors in the columns), ``EA``, ``EI``, ``GJ`` and ``I_p / A`` of each strut, and the
771
+ centre and generators ``(R, t)`` of its symmetry group, the area of the section of
772
+ each strut (for the relative density), its transverse shear stiffness ``κGA``:
773
+ Timoshenko beams (None, the default: Euler–Bernoulli beams) and the lengths of its
774
+ rigid ends at its first and second node (m x 2; None, the default: none), which the
775
+ effective stiffness alone takes."""
776
+
777
+ nodes: np.ndarray
778
+ beams: np.ndarray
779
+ shifts: np.ndarray
780
+ lattice: np.ndarray
781
+ axial: np.ndarray
782
+ bending: np.ndarray
783
+ torsion: np.ndarray
784
+ polar: np.ndarray
785
+ centre: np.ndarray
786
+ generators: list
787
+ area: np.ndarray | None = None
788
+ shear: np.ndarray | None = None
789
+ rigid: np.ndarray | None = None
790
+
791
+ @classmethod
792
+ def lattice_of(
793
+ cls,
794
+ kind: str = "octet",
795
+ cells=(1, 1, 1),
796
+ *,
797
+ size: float = 1.0,
798
+ elements: int = 2,
799
+ young: float = 1.0,
800
+ poisson: float = 0.3,
801
+ radius: float = 0.05,
802
+ shear_coefficient=None,
803
+ ) -> SpaceFrame:
804
+ """A cell of ``cells`` conventional cubic cells of edge ``size`` of a lattice of
805
+ struts (``cubic``, ``bcc``, ``octet``, ``kelvin``, ``diamond`` or ``pyrochlore``:
806
+ :data:`SPACE_LATTICES`), each strut cut in
807
+ ``elements`` beams of Young's modulus ``young``, Poisson's ratio ``poisson`` and
808
+ circular section of ``radius`` (relative to ``size``): Euler–Bernoulli beams, or
809
+ with a ``shear_coefficient`` κ (a value, or ``"cowper"``: Cowper's ``6(1 + ν)/(7 +
810
+ 6ν)``) Timoshenko beams of shear stiffness ``κGA``."""
811
+ if kind not in SPACE_LATTICES:
812
+ raise ValueError(f"lattice_of: one of {sorted(SPACE_LATTICES)}")
813
+ spec = SPACE_LATTICES[kind]
814
+ counts = tuple(int(c) for c in cells)
815
+ a = np.eye(3) * size
816
+ lattice = a @ np.diag(counts)
817
+ inv = np.linalg.inv(lattice)
818
+ base = spec["nodes"] * size
819
+ npc = len(base)
820
+ cell_ids = list(product(*(range(c) for c in counts)))
821
+ position = {c: k for k, c in enumerate(cell_ids)}
822
+
823
+ def index(p, c):
824
+ return position[tuple(int(x) % n for x, n in zip(c, counts, strict=True))] * npc + p
825
+
826
+ def wrap(x):
827
+ return lattice @ ((inv @ x) % 1.0)
828
+
829
+ nodes = [wrap(base[p] + a @ c) for c in cell_ids for p in range(npc)]
830
+ beams, shifts = [], []
831
+ for c in cell_ids:
832
+ for p, q, s in _struts(spec["nodes"], spec["strut"]):
833
+ start, end = index(p, c), index(q, np.add(c, s))
834
+ x0 = nodes[start]
835
+ x1 = x0 + a @ (np.asarray(s) + spec["nodes"][q] - spec["nodes"][p])
836
+ chain = [start]
837
+ for k in range(1, int(elements)):
838
+ nodes.append(wrap(x0 + (k / elements) * (x1 - x0)))
839
+ chain.append(len(nodes) - 1)
840
+ chain.append(end)
841
+ step = (x1 - x0) / elements
842
+ for k in range(int(elements)):
843
+ u, v = chain[k], chain[k + 1]
844
+ beams.append((u, v))
845
+ shifts.append(np.rint(inv @ (nodes[u] + step - nodes[v])).astype(int))
846
+ r = radius * size
847
+ area, inertia = np.pi * r**2, np.pi * r**4 / 4.0
848
+ shear = young / (2.0 * (1.0 + poisson))
849
+ m = len(beams)
850
+ point = spec.get("generators") or [(g, np.zeros(3)) for g in CUBIC_GENERATORS]
851
+ generators = [(g, a @ t) for g, t in point]
852
+ generators += [(np.eye(3), a[:, k]) for k in range(3)]
853
+ generators += [(np.eye(3), a @ t) for t in spec["centring"]]
854
+ return cls(
855
+ np.array(nodes),
856
+ np.array(beams, dtype=np.int64),
857
+ np.array(shifts, dtype=np.int64),
858
+ lattice,
859
+ np.full(m, young * area),
860
+ np.full(m, young * inertia),
861
+ np.full(m, shear * 2.0 * inertia),
862
+ np.full(m, 2.0 * inertia / area),
863
+ np.zeros(3),
864
+ generators,
865
+ np.full(m, area),
866
+ _shear_stiffness(shear_coefficient, young, poisson, np.full(m, area), "circular"),
867
+ )
868
+
869
+ @classmethod
870
+ def from_framework(
871
+ cls, framework, radius, *, young=1.0, poisson=0.3, shear_coefficient=None,
872
+ rigid_joints=None,
873
+ ) -> SpaceFrame: # fmt: skip
874
+ """The frame of the bars of a periodic framework in space
875
+ (:class:`morphogen.design.frames.Framework`, or its dictionary as the metadata of
876
+ ``delaunay_network``, ``open_foam`` and ``random_lattice`` keep it): a strut per
877
+ bar, of circular section of ``radius``, Young's modulus ``young`` and Poisson's
878
+ ratio ``poisson`` (each one value, or one per bar): ``EA = E π r²``, ``EI = E π r⁴ /
879
+ 4`` about both axes of the section, ``GJ = G π r⁴ / 2``. The box of the framework
880
+ is the cell; its symmetry, the translations alone. With a ``shear_coefficient`` κ
881
+ (one value, one per bar, or ``"cowper"``: Cowper's ``6(1 + ν)/(7 + 6ν)``),
882
+ Timoshenko beams of shear stiffness ``κGA``; Euler–Bernoulli beams without. With
883
+ ``rigid_joints`` (one value or one per bar), the struts are rigid over that many of
884
+ their radii from each node (merged in the joints; :data:`FLEXIBLE_LIMIT` of the
885
+ shortest left flexible)."""
886
+ nodes, bars, shifts, lattice = _framework_arrays(framework, 3)
887
+ m = len(bars)
888
+ r = _per_bar(radius, m, "radius")
889
+ e = _per_bar(young, m, "young")
890
+ nu = np.broadcast_to(np.asarray(poisson, dtype=float), (m,))
891
+ if np.any(nu <= -1.0) or np.any(nu >= 0.5):
892
+ raise ValueError("from_framework: poisson in (-1, 0.5)")
893
+ area, inertia = np.pi * r**2, np.pi * r**4 / 4.0
894
+ frame = cls(
895
+ nodes,
896
+ bars,
897
+ shifts,
898
+ lattice,
899
+ e * area,
900
+ e * inertia,
901
+ e / (2.0 * (1.0 + nu)) * 2.0 * inertia,
902
+ 2.0 * inertia / area,
903
+ np.zeros(3),
904
+ [(np.eye(3), np.zeros(3))],
905
+ area,
906
+ _shear_stiffness(shear_coefficient, e, nu, area, "circular"),
907
+ )
908
+ frame.rigid = _rigid_ends(rigid_joints, r, np.linalg.norm(frame.vectors(), axis=1))
909
+ return frame
910
+
911
+ @property
912
+ def n_dofs(self) -> int:
913
+ return 6 * len(self.nodes)
914
+
915
+ def _shears(self) -> list:
916
+ """The transverse shear stiffness ``κGA`` of each strut (None: Euler–Bernoulli)."""
917
+ return [None] * len(self.beams) if self.shear is None else list(self.shear)
918
+
919
+ @staticmethod
920
+ def block(rotation) -> np.ndarray:
921
+ """The action of a point operation on the dofs of a node: displacements turned by
922
+ ``R``, rotations (pseudo-vectors) by ``det(R) R``."""
923
+ r = np.asarray(rotation, dtype=float)
924
+ return block_diag(r, np.linalg.det(r) * r)
925
+
926
+ def vectors(self) -> np.ndarray:
927
+ """The vector of each beam, from its first end to its second."""
928
+ return (
929
+ self.nodes[self.beams[:, 1]]
930
+ + self.shifts @ self.lattice.T
931
+ - self.nodes[self.beams[:, 0]]
932
+ )
933
+
934
+ def _dofs(self) -> np.ndarray:
935
+ e = self.beams
936
+ return np.hstack([6 * e[:, :1] + np.arange(6), 6 * e[:, 1:] + np.arange(6)])
937
+
938
+ def _matrices(self, forces=None) -> list:
939
+ _check_rigid(self)
940
+ forces = np.zeros(len(self.beams)) if forces is None else np.asarray(forces, dtype=float)
941
+ return [
942
+ space_beam_matrices(d, a, b, t, f, p, q)
943
+ for d, a, b, t, f, p, q in zip(
944
+ self.vectors(),
945
+ self.axial,
946
+ self.bending,
947
+ self.torsion,
948
+ forces,
949
+ self.polar,
950
+ self._shears(),
951
+ strict=True,
952
+ )
953
+ ]
954
+
955
+ def _assemble(self, forces=None) -> tuple[np.ndarray, np.ndarray]:
956
+ n = self.n_dofs
957
+ ke, kg = np.zeros((n, n)), np.zeros((n, n))
958
+ for (e, g), dofs in zip(self._matrices(forces), self._dofs(), strict=True):
959
+ ke[np.ix_(dofs, dofs)] += e
960
+ kg[np.ix_(dofs, dofs)] += g
961
+ return ke, kg
962
+
963
+ def stiffness(self) -> np.ndarray:
964
+ """The elastic stiffness of the periodic fluctuations (dense)."""
965
+ return self._assemble()[0]
966
+
967
+ def translations(self) -> np.ndarray:
968
+ """The three rigid translations of the cell (dofs x 3, orthonormal)."""
969
+ t = np.zeros((self.n_dofs, 3))
970
+ for c in range(3):
971
+ t[c::6, c] = 1.0 / np.sqrt(len(self.nodes))
972
+ return t
973
+
974
+ def complement(self) -> np.ndarray:
975
+ """An orthonormal basis of the fluctuations orthogonal to the translations."""
976
+ t = self.translations()
977
+ q, _ = np.linalg.qr(np.hstack([t, np.eye(self.n_dofs)]))
978
+ return q[:, 3:]
979
+
980
+ def axial_forces(self, strain) -> tuple[np.ndarray, np.ndarray]:
981
+ """The axial forces of the struts under the macroscopic ``strain`` (3 x 3) and the
982
+ periodic fluctuations (dofs) of the linear periodic problem."""
983
+ e = np.asarray(strain, dtype=float)
984
+ mats = self._matrices()
985
+ dofs = self._dofs()
986
+ n = self.n_dofs
987
+ ke = np.zeros((n, n))
988
+ force = np.zeros(n)
989
+ affine = []
990
+ for (k, _), d, idx in zip(mats, self.vectors(), dofs, strict=True):
991
+ ke[np.ix_(idx, idx)] += k
992
+ u = np.zeros(12)
993
+ u[6:9] = e @ d # the affine motion of the second end relative to the first
994
+ affine.append(u)
995
+ force[idx] += k @ u
996
+ z = self.complement()
997
+ w = z @ np.linalg.solve(z.T @ ke @ z, -z.T @ force)
998
+ forces = np.empty(len(self.beams))
999
+ for k, (d, a, idx, u) in enumerate(
1000
+ zip(self.vectors(), self.axial, dofs, affine, strict=True)
1001
+ ):
1002
+ length = float(np.linalg.norm(d))
1003
+ relative = u[6:9] + w[idx[6:9]] - w[idx[0:3]]
1004
+ forces[k] = a / length * float(d @ relative) / length
1005
+ return forces, w
1006
+
1007
+ def buckling(self, strain, modes: int = 6) -> tuple[np.ndarray, np.ndarray]:
1008
+ """The lowest ``modes`` positive load factors ``λ`` of the linear buckling of the
1009
+ cell under ``λ strain`` and their modes (dofs x modes)."""
1010
+ forces, _ = self.axial_forces(strain)
1011
+ ke, kg = self._assemble(forces)
1012
+ z = self.complement()
1013
+ return _buckling(z.T @ ke @ z, z.T @ kg @ z, z, modes)
1014
+
1015
+ def relative_density(self) -> float:
1016
+ """The volume of the struts over that of the cell (overlaps at the nodes counted)."""
1017
+ lengths = np.linalg.norm(self.vectors(), axis=1)
1018
+ return float(np.sum(self.area * lengths) / abs(np.linalg.det(self.lattice)))
1019
+
1020
+ def macroscopic_stiffness(self) -> np.ndarray:
1021
+ """The apparent stiffness (6 x 6, Voigt order 11, 22, 33, 23, 31, 12 with
1022
+ engineering shear strains) of the periodic frame: the energy of the periodic
1023
+ solutions of the unit strains per unit volume."""
1024
+ from morphogen.homogenization.elements import VOIGT
1025
+
1026
+ mats = self._matrices()
1027
+ dofs = self._dofs()
1028
+ z = self.complement()
1029
+ n = self.n_dofs
1030
+ ke = np.zeros((n, n))
1031
+ for (k, _), idx in zip(mats, dofs, strict=True):
1032
+ ke[np.ix_(idx, idx)] += k
1033
+ factor = np.linalg.cholesky(z.T @ ke @ z)
1034
+ states = []
1035
+ for a, b in VOIGT:
1036
+ e = np.zeros((3, 3))
1037
+ e[a, b] = e[b, a] = 1.0 if a == b else 0.5
1038
+ local = np.zeros((len(self.beams), 12))
1039
+ local[:, 6:9] = self.vectors() @ e.T
1040
+ force = np.zeros(n)
1041
+ for (k, _), idx, u in zip(mats, dofs, local, strict=True):
1042
+ force[idx] += k @ u
1043
+ y = np.linalg.solve(factor, -z.T @ force)
1044
+ w = z @ np.linalg.solve(factor.T, y)
1045
+ states.append(local + w[dofs])
1046
+ volume = abs(np.linalg.det(self.lattice))
1047
+ out = np.zeros((6, 6))
1048
+ for (k, _), b in zip(mats, range(len(self.beams)), strict=True):
1049
+ u = np.array([s[b] for s in states]) # 6 x 12
1050
+ out += u @ k @ u.T
1051
+ return 0.5 * (out + out.T) / volume
1052
+
1053
+ def effective_stiffness(self):
1054
+ """:meth:`macroscopic_stiffness` by the sparse periodic problem, for large random
1055
+ frames, with its split into stretching, bending and torsion and the non-affinity
1056
+ of the fluctuations (:func:`morphogen.homogenization.networks.frame_stiffness`)."""
1057
+ from morphogen.homogenization.networks import frame_stiffness
1058
+
1059
+ return frame_stiffness(self)
1060
+
1061
+ def reciprocal(self) -> np.ndarray:
1062
+ """The reciprocal vectors of the cell (columns): ``b_i · a_j = 2π δ_ij``."""
1063
+ return 2.0 * np.pi * np.linalg.inv(self.lattice).T
1064
+
1065
+ def bloch_buckling(self, strain, wavevectors, modes: int = 1) -> np.ndarray:
1066
+ """The lowest ``modes`` load factors of the linear buckling of the infinite frame
1067
+ under ``λ strain`` for the Bloch modes of each wave vector (rows), as
1068
+ :meth:`Frame.bloch_buckling`."""
1069
+ forces, _ = self.axial_forces(strain)
1070
+ n = self.n_dofs
1071
+ mats = self._matrices(forces)
1072
+ periods = self.shifts @ self.lattice.T
1073
+ out = []
1074
+ for k in np.atleast_2d(np.asarray(wavevectors, dtype=float)):
1075
+ ke, kg = np.zeros((n, n), complex), np.zeros((n, n), complex)
1076
+ for (e, g), dofs, period in zip(mats, self._dofs(), periods, strict=True):
1077
+ p = np.ones(12, complex)
1078
+ p[6:] = np.exp(1j * (k @ period))
1079
+ ke[np.ix_(dofs, dofs)] += np.conj(p)[:, None] * e * p[None, :]
1080
+ kg[np.ix_(dofs, dofs)] += np.conj(p)[:, None] * g * p[None, :]
1081
+ frac = self.lattice.T @ k / (2.0 * np.pi)
1082
+ basis = self.complement() if np.allclose(frac, np.round(frac), atol=1e-9) else np.eye(n)
1083
+ ke, kg = basis.T @ ke @ basis, basis.T @ kg @ basis
1084
+
1085
+ def real(h):
1086
+ h = 0.5 * (h + h.conj().T)
1087
+ return np.block([[h.real, -h.imag], [h.imag, h.real]])
1088
+
1089
+ lam, _ = _buckling(real(ke), real(kg), np.eye(2 * basis.shape[1]), 2 * int(modes))
1090
+ out.append(np.pad(lam[0::2], (0, int(modes) - len(lam[0::2])), constant_values=np.nan))
1091
+ return np.array(out)
1092
+
1093
+ def plot(self, ax=None, displacement=None, *, scale: float = 0.0, tiles=(1, 1, 1), **style):
1094
+ """Draw the struts in 3D axes, displaced by ``displacement`` (its largest drawn as
1095
+ ``scale`` times the median length of the beams; 0.3 by default), the cell repeated
1096
+ ``tiles`` times; returns the axes."""
1097
+ from mpl_toolkits.mplot3d.art3d import Line3DCollection
1098
+
1099
+ if ax is None:
1100
+ from morphogen.viz.figures import _figure
1101
+
1102
+ ax = _figure(5.0, 5.0).add_subplot(projection="3d")
1103
+ x = self.nodes.copy()
1104
+ if displacement is not None:
1105
+ u = np.asarray(displacement, dtype=float).reshape(-1, 6)[:, :3]
1106
+ peak = max(float(np.abs(u).max()), 1e-300)
1107
+ size = float(np.median(np.linalg.norm(self.vectors(), axis=1)))
1108
+ x = x + u * (scale or 0.3) * size / peak
1109
+ d = x[self.beams[:, 1]] + self.shifts @ self.lattice.T - x[self.beams[:, 0]]
1110
+ segments = []
1111
+ for offset in product(*(range(int(t)) for t in tiles)):
1112
+ start = x[self.beams[:, 0]] + self.lattice @ np.asarray(offset, dtype=float)
1113
+ segments.extend(zip(start, start + d, strict=True))
1114
+ segments = np.array(segments)
1115
+ ax.add_collection3d(
1116
+ Line3DCollection(
1117
+ segments, colors=style.get("color", "k"), linewidths=style.get("lw", 0.8)
1118
+ )
1119
+ )
1120
+ lo, hi = segments.reshape(-1, 3).min(axis=0), segments.reshape(-1, 3).max(axis=0)
1121
+ for setter, a, b in zip((ax.set_xlim, ax.set_ylim, ax.set_zlim), lo, hi, strict=True):
1122
+ setter(a, b)
1123
+ ax.set_box_aspect(tuple(np.maximum(hi - lo, 1e-9)))
1124
+ ax.set_axis_off()
1125
+ return ax