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,764 @@
1
+ """Inputs and outputs of OpenRadioss, the explicit finite element solver (Radioss Block
2
+ Format of the input version 2022, which OpenRadioss reads; Radioss Reference Guide).
3
+
4
+ * :func:`write_radioss` writes the Starter input ``<name>_0000.rad`` of a mesh: its unit
5
+ system (``/BEGIN``), its nodes, its elements by part (``/BRICK`` for the voxels,
6
+ ``/TETRA4`` or ``/TETRA10`` for conforming tetrahedra; a part per phase), the solid
7
+ property (``/PROP/SOLID``: the stabilized 8-node brick, Isolid 24; the linear
8
+ tetrahedra with nodal pressures against locking), the materials of the phases
9
+ (``/MAT/LAW1`` elastic, ``/MAT/LAW36`` von Mises with tabulated yield curves,
10
+ ``/MAT/LAW2`` Johnson–Cook), the node groups of the loaded faces, the loading
11
+ (``/BCS``, ``/IMPVEL`` and its ``/FUNCT``; ``/INIVEL`` and a fixed ``/RWALL`` for an
12
+ impact), the self contact of the outer surface (``/INTER/TYPE24``) and the time
13
+ histories (``/TH/NODE`` of the reactions of the loaded faces, ``/TH/PART`` of the
14
+ energies and momenta); and the Engine input ``<name>_0001.rad`` (``/RUN``,
15
+ ``/TFILE``, ``/ANIM``: displacements, velocities, reaction and contact forces, von
16
+ Mises stresses, plastic strains, energy densities, pressures and the status of the
17
+ elements; ``/DT/NODA/CST`` for a mass scaling). It writes too the mesh and the
18
+ manifest that morphoGen reads the results back with (:mod:`morphogen.dynamics`).
19
+ * :func:`read_radioss_listing` reads the listing of a run (``<name>_0000.out``,
20
+ ``<name>_0001.out``): its cycles and times (the progress of a run), its errors and
21
+ whether it ended normally.
22
+ * :func:`read_radioss_th` reads a time history converted to CSV by OpenRadioss's
23
+ ``th_to_csv``; the animations converted by ``anim_to_vtk`` are legacy VTK files
24
+ (:func:`morphogen.io.vtk.read_vtk_grid`).
25
+
26
+ The fields of the cards are those of the reference guide: integers of 10 characters,
27
+ reals of 20, comments after ``#``. The 4-node tetrahedra are written with their natural
28
+ coordinates r, s, t running from node 4 toward nodes 1, 2, 3 (positive Jacobian,
29
+ ``det[x1 - x4, x2 - x4, x3 - x4] > 0``), the 10-node ones with their mid-side nodes 5 to
30
+ 10 on the edges 1-2, 2-3, 3-1, 1-4, 2-4 and 3-4 (morphoGen's and VTK's order), the bricks
31
+ with their nodes 1-4 on a face whose normal (right-hand rule) points toward nodes 5-8."""
32
+
33
+ from __future__ import annotations
34
+
35
+ import csv
36
+ import json
37
+ import re
38
+ import unicodedata
39
+ from dataclasses import dataclass, field
40
+ from pathlib import Path
41
+
42
+ import numpy as np
43
+
44
+ from morphogen._version import __version__
45
+
46
+ #: The input version of the cards (``/BEGIN``)
47
+ INPUT_VERSION = 2022
48
+ #: The solid property: the 8-node brick with physical stabilization (Isolid 24), the
49
+ #: small strains and the constant pressure chosen by Radioss for the law (-1), the
50
+ #: linear tetrahedra with nodal pressures against volumetric locking (Itetra4 3), the
51
+ #: quadratic ones by default
52
+ SOLID_PROPERTY = {
53
+ "Isolid": 24,
54
+ "Ismstr": -1,
55
+ "Icpre": -1,
56
+ "Itetra10": 0,
57
+ "Itetra4": 3,
58
+ "Iframe": -1,
59
+ }
60
+ #: The animated results of the Engine input
61
+ ANIM_VECTORS = ("DISP", "VEL", "FREAC", "CONT")
62
+ ANIM_ELEMENTS = ("VONM", "EPSP", "ENER", "P", "OFF")
63
+ #: The kinds of elements: the keyword of their block and their nodes
64
+ ELEMENTS = {"brick": ("BRICK", 8), "tetra4": ("TETRA4", 4), "tetra10": ("TETRA10", 10)}
65
+ #: The order of the nodes of a 10-node tetrahedron whose corners 1 and 2 are swapped
66
+ _SWAP10 = np.array([1, 0, 2, 3, 4, 6, 5, 8, 7, 9])
67
+ #: The values (nodes times variables times samples) of the time histories, at most: a
68
+ #: mesh with large loaded faces is sampled less often (its forces are also drawn from
69
+ #: the reaction forces of the animations)
70
+ MAX_HISTORY_VALUES = 20_000_000
71
+ #: The ruler of the columns of the cards (a comment)
72
+ RULER = "#---1----|" + "".join(f"----{k}----|" for k in range(2, 10)) + "---10----|"
73
+ MANIFEST = "morphogen_radioss.json"
74
+
75
+
76
+ def _i(value) -> str:
77
+ """An integer field (10 characters)."""
78
+ text = f"{int(value):10d}"
79
+ if len(text) > 10:
80
+ raise ValueError(f"{value}: more than 10 digits")
81
+ return text
82
+
83
+
84
+ def _f(value) -> str:
85
+ """A real field (20 characters, 12 significant digits)."""
86
+ return f"{float(value):20.12g}"
87
+
88
+
89
+ def _ascii(text: str) -> str:
90
+ """A text in ASCII, as the cards are read (accents dropped, ³ as 3, µ as u)."""
91
+ text = unicodedata.normalize("NFKD", str(text)).replace("μ", "u").replace("µ", "u")
92
+ return text.encode("ascii", "ignore").decode("ascii")
93
+
94
+
95
+ def _title(text: str) -> str:
96
+ return re.sub(r"\s+", " ", _ascii(text)).strip()[:100] or "morphoGen"
97
+
98
+
99
+ def run_name(text: str) -> str:
100
+ """A name for the files of a run: letters, digits, '_' and '-', 4 characters at least
101
+ (the Engine's ``/RUN`` asks for 4 to 80)."""
102
+ name = re.sub(r"[^A-Za-z0-9_-]+", "_", str(text or "")).strip("_") or "morphogen"
103
+ if len(name) < 4:
104
+ name = f"{name}_run"
105
+ return name[:60]
106
+
107
+
108
+ def _ids(values, per_line: int = 10) -> list[str]:
109
+ values = [int(v) for v in values]
110
+ return [
111
+ "".join(_i(v) for v in values[k : k + per_line]) for k in range(0, len(values), per_line)
112
+ ]
113
+
114
+
115
+ def element_kind(mesh) -> str:
116
+ """``brick``, ``tetra4`` or ``tetra10``: the elements of a voxel or tetrahedral mesh."""
117
+ n = np.asarray(mesh.elements).shape[1]
118
+ kinds = {8: "brick", 4: "tetra4", 10: "tetra10"}
119
+ if n not in kinds:
120
+ raise ValueError(f"meshes of 8-node hexahedra or 4- or 10-node tetrahedra, got {n} nodes")
121
+ return kinds[n]
122
+
123
+
124
+ def oriented(mesh) -> np.ndarray:
125
+ """The elements of a mesh (0-based nodes) in the orientation of Radioss: the
126
+ tetrahedra whose ``det[x1 - x4, x2 - x4, x3 - x4]`` is negative get their corners 1
127
+ and 2 swapped (and their mid-side nodes with them); the hexahedra of voxel meshes
128
+ are kept (morphoGen's order is Radioss's)."""
129
+ elements = np.array(mesh.elements, dtype=np.int64, copy=True)
130
+ if elements.shape[1] == 8:
131
+ return elements
132
+ x = np.asarray(mesh.nodes, dtype=float)[elements[:, :4]]
133
+ det = np.einsum("ij,ij->i", x[:, 0] - x[:, 3], np.cross(x[:, 1] - x[:, 3], x[:, 2] - x[:, 3]))
134
+ flip = det < 0
135
+ if elements.shape[1] == 4:
136
+ elements[flip, :2] = elements[flip, 1::-1]
137
+ else:
138
+ elements[flip] = elements[flip][:, _SWAP10]
139
+ return elements
140
+
141
+
142
+ def box_of(mesh) -> tuple[np.ndarray, np.ndarray]:
143
+ """The box of a mesh: that of a tetrahedral mesh, the extent of the nodes of a voxel
144
+ mesh."""
145
+ if hasattr(mesh, "lower") and hasattr(mesh, "upper"):
146
+ return np.asarray(mesh.lower, dtype=float), np.asarray(mesh.upper, dtype=float)
147
+ nodes = np.asarray(mesh.nodes, dtype=float)
148
+ return nodes.min(axis=0), nodes.max(axis=0)
149
+
150
+
151
+ def face_nodes(mesh, axis: int, side: int) -> np.ndarray:
152
+ """The nodes (0-based) on the face of the box of a mesh normal to ``axis``, lower
153
+ (``side`` 0) or upper (1)."""
154
+ if getattr(mesh, "whole", False):
155
+ raise ValueError(
156
+ "a mesh of whole periodic cells has no faces of the box to load: mesh the box"
157
+ )
158
+ sets = getattr(mesh, "node_sets", None)
159
+ name = f"{'xyz'[axis]}{side}"
160
+ if sets is not None and name in sets:
161
+ return np.asarray(sets[name], dtype=np.int64)
162
+ lower, upper = box_of(mesh)
163
+ target = lower[axis] if side == 0 else upper[axis]
164
+ tol = 1e-9 * float(np.max(upper - lower))
165
+ return np.flatnonzero(np.abs(np.asarray(mesh.nodes)[:, axis] - target) <= tol)
166
+
167
+
168
+ def element_volumes(mesh) -> np.ndarray:
169
+ """The volume of each element: the voxels', or that of the corners of the
170
+ tetrahedra (the straight ones)."""
171
+ elements = np.asarray(mesh.elements)
172
+ if elements.shape[1] == 8:
173
+ return np.full(len(elements), float(np.prod(mesh.spacing)))
174
+ x = np.asarray(mesh.nodes, dtype=float)[elements[:, :4]]
175
+ return (
176
+ np.abs(
177
+ np.einsum("ij,ij->i", np.cross(x[:, 1] - x[:, 0], x[:, 2] - x[:, 0]), x[:, 3] - x[:, 0])
178
+ )
179
+ / 6.0
180
+ )
181
+
182
+
183
+ @dataclass
184
+ class RadiossInputs:
185
+ """The inputs of a run of OpenRadioss written by :func:`write_radioss`: their
186
+ ``directory``, the run ``name``, the Starter and Engine inputs, the manifest that
187
+ the results are read back with (its contents in ``manifest``)."""
188
+
189
+ directory: Path
190
+ name: str
191
+ starter: Path
192
+ engine: Path
193
+ manifest: dict = field(default_factory=dict)
194
+
195
+ @property
196
+ def end_time(self) -> float:
197
+ return float(self.manifest["end_time"])
198
+
199
+
200
+ def _material_cards(
201
+ mat_id: int, title: str, material, funct_start: int
202
+ ) -> tuple[list[str], list[str], int]:
203
+ """The cards of a material (and of the functions of its yield curves, numbered from
204
+ ``funct_start``): the lines of the material, those of its functions, the next
205
+ number of function."""
206
+ e, nu, rho = material.young, material.poisson, material.density
207
+ eps_max = material.failure_strain or 0.0 # 0: Radioss's default, no failure
208
+ law = material.law
209
+ head = [f"/MAT/{law}/{mat_id}", _title(title), "# RHO_I", _f(rho)]
210
+ functs: list[str] = []
211
+ if law == "LAW1":
212
+ return (
213
+ [*head, "# E nu", _f(e) + _f(nu)],
214
+ functs,
215
+ funct_start,
216
+ )
217
+ if law == "LAW2":
218
+ jc = material.johnson_cook
219
+ lines = [
220
+ *head,
221
+ "# E Nu Iflag",
222
+ _f(e) + _f(nu) + _i(0),
223
+ "# a b "
224
+ " n EPS_max SIG_max0",
225
+ _f(jc.a) + _f(jc.b) + _f(jc.n) + _f(eps_max) + _f(jc.max_stress or 0.0),
226
+ "# c EPS_DOT_0 "
227
+ " ICC Fsmooth F_cut Chard",
228
+ _f(jc.c) + _f(jc.rate if jc.c > 0 else 0.0) + _i(0) + _i(0) + _f(0.0) + _f(0.0),
229
+ "# m T_melt rhoC_p T_r",
230
+ _f(0.0) * 4,
231
+ ]
232
+ return lines, functs, funct_start
233
+ rates = material.rates()
234
+ ids = list(range(funct_start, funct_start + len(rates)))
235
+ strains = np.asarray(material_curve_strains(), dtype=float)
236
+ for fid, rate in zip(ids, rates, strict=True):
237
+ stress = material.yield_curve(strains, rate)
238
+ functs += [
239
+ f"/FUNCT/{fid}",
240
+ _title(f"{title}: yield stress at the plastic strain rate {rate:g}"),
241
+ "# X Y",
242
+ ]
243
+ functs += [_f(p) + _f(s) for p, s in zip(strains, stress, strict=True)]
244
+ viscous = len(rates) > 1
245
+ lines = [
246
+ *head,
247
+ "# E Nu "
248
+ " Eps_p_max Eps_t Eps_m",
249
+ _f(e) + _f(nu) + _f(eps_max) + _f(0.0) + _f(0.0),
250
+ "# N_funct F_smooth C_hard "
251
+ " F_cut Eps_f VP",
252
+ _i(len(rates)) + _i(0) + _f(0.0) + _f(0.0) + _f(0.0) + " " * 10 + _i(1 if viscous else 0),
253
+ "# fct_IDp Fscale Fct_IDE EInf CE",
254
+ _i(0) + _f(0.0) + _i(0) + _f(0.0) + _f(0.0),
255
+ "# func_ID1 func_ID2 func_ID3 func_ID4 func_ID5",
256
+ *_ids(ids, 5),
257
+ "# Fscale_1 Fscale_2 "
258
+ " Fscale_3 Fscale_4 Fscale_5",
259
+ *["".join(_f(1.0) for _ in ids[k : k + 5]) for k in range(0, len(ids), 5)],
260
+ "# Eps_dot_1 Eps_dot_2 "
261
+ " Eps_dot_3 Eps_dot_4 Eps_dot_5",
262
+ *["".join(_f(r) for r in rates[k : k + 5]) for k in range(0, len(rates), 5)],
263
+ ]
264
+ return lines, functs, funct_start + len(rates)
265
+
266
+
267
+ def material_curve_strains() -> tuple[float, ...]:
268
+ """The plastic strains of the tabulated yield curves (:data:`morphogen.dynamics.
269
+ model.CURVE_STRAINS`)."""
270
+ from morphogen.dynamics.model import CURVE_STRAINS
271
+
272
+ return CURVE_STRAINS
273
+
274
+
275
+ def write_radioss(
276
+ directory,
277
+ mesh,
278
+ materials: dict,
279
+ loading,
280
+ *,
281
+ name: str = "morphogen",
282
+ units=None,
283
+ frames: int = 50,
284
+ history: int = 1000,
285
+ time_step: float | None = None,
286
+ length_scale: float = 1.0,
287
+ phase_names: dict | None = None,
288
+ title: str = "",
289
+ ) -> RadiossInputs:
290
+ """Write the inputs of a run of OpenRadioss for a mesh in ``directory``.
291
+
292
+ ``mesh``: a :class:`~morphogen.mesh.voxel.VoxelMesh` (bricks) or a
293
+ :class:`~morphogen.mesh.tetra.TetMesh` (4- or 10-node tetrahedra) of the box of a
294
+ morphology; ``materials``: phase -> :class:`~morphogen.dynamics.ExplicitMaterial`
295
+ of each phase of the mesh; ``loading``: an :class:`~morphogen.dynamics.
296
+ ExplicitLoading`; ``units``: the :class:`~morphogen.dynamics.UnitSystem` of every
297
+ value (Mg, mm, s by default). ``frames``: the animations written over the run (and
298
+ the initial one), ``history``: the samples of the time histories; ``time_step``: a
299
+ minimum time step kept by adding mass to the nodes (``/DT/NODA/CST``; none by
300
+ default, the run then going at the stable time step of its smallest element).
301
+ ``length_scale``: the length unit of the system per length unit of the mesh (1000 for
302
+ a mesh in metres written in mm). ``phase_names``: the names of the phases, for the
303
+ titles of the parts.
304
+
305
+ Returns the :class:`RadiossInputs`; besides the two inputs, the directory holds
306
+ ``<name>_mesh.npz`` (the mesh and the nodes of its loaded faces) and the manifest
307
+ ``morphogen_radioss.json`` that :func:`morphogen.dynamics.read_explicit_run` reads
308
+ the results back with.
309
+
310
+ The loaded faces: ``lateral`` ``fixed`` holds the lower face and the upper one
311
+ across the drive (a compression between bonded platens), ``free`` holds the lower
312
+ face along the axis only and one of its nodes, the nearest to its centre, across it
313
+ too (no rigid drift); a shear holds the lower face and the upper one but along the
314
+ drive. The reactions of the nodes of the loaded faces along the axis and the drive
315
+ are written to the time history, sampled less often when the faces are large
316
+ (:data:`MAX_HISTORY_VALUES`).
317
+ """
318
+ from morphogen.dynamics.model import AXES, ExplicitLoading, UnitSystem, critical_time_step
319
+
320
+ units = UnitSystem.parse(units)
321
+ loading = ExplicitLoading.from_config(loading)
322
+ directory = Path(directory)
323
+ directory.mkdir(parents=True, exist_ok=True)
324
+ name = run_name(name)
325
+ kind = element_kind(mesh)
326
+ keyword, per = ELEMENTS[kind]
327
+ scale = float(length_scale)
328
+ if not (np.isfinite(scale) and scale > 0):
329
+ raise ValueError(f"length_scale: > 0, got {length_scale!r}")
330
+ nodes = np.asarray(mesh.nodes, dtype=float) * scale
331
+ elements = oriented(mesh)
332
+ phase = np.asarray(mesh.phase, dtype=np.int64)
333
+ present = [int(q) for q in np.unique(phase)]
334
+ missing = [q for q in present if materials.get(q) is None]
335
+ if missing:
336
+ raise ValueError(f"phases {missing} of the mesh: no material (voids are not meshed)")
337
+ if int(frames) < 1 or int(history) < 2:
338
+ raise ValueError("frames >= 1 and history >= 2")
339
+ names = {int(k): str(v) for k, v in (phase_names or {}).items()}
340
+ lower, upper = box_of(mesh)
341
+ lower, upper = lower * scale, upper * scale
342
+ lengths = upper - lower
343
+ axis = loading.axis
344
+ end = loading.end_time(lengths)
345
+ speed = loading.speed(lengths)
346
+ volumes = element_volumes(mesh) * scale**3
347
+ density = np.array([materials[int(q)].density for q in phase])
348
+ mass = float(np.sum(volumes * density))
349
+ dt = critical_time_step(mesh, materials) * scale
350
+ n_nodes = len(nodes)
351
+ lines = [
352
+ "#RADIOSS STARTER",
353
+ f"# morphoGen {__version__}: {_title(title or name)}",
354
+ _ascii(
355
+ f"# units {' '.join(units.names)}: stresses in {units.unit('stress')}, densities in "
356
+ f"{units.unit('density')}, velocities in {units.unit('velocity')}"
357
+ ),
358
+ _ascii(f"# forces in {units.unit('force')}, energies in {units.unit('energy')}"),
359
+ RULER,
360
+ "/BEGIN",
361
+ name,
362
+ _i(INPUT_VERSION) + _i(0),
363
+ "".join(f"{u:>20s}" for u in units.names),
364
+ "".join(f"{u:>20s}" for u in units.names),
365
+ RULER,
366
+ "/NODE",
367
+ "# node_ID Xc Yc Zc",
368
+ ]
369
+ ids = np.arange(1, n_nodes + 1)
370
+ lines += [
371
+ f"{i:10d}{x:20.12g}{y:20.12g}{z:20.12g}" for i, (x, y, z) in zip(ids, nodes, strict=True)
372
+ ]
373
+ # parts: one per phase (an element type per mesh), numbered like the materials
374
+ parts: dict[int, int] = {}
375
+ order = np.argsort(phase, kind="stable")
376
+ numbers = np.empty(len(phase), dtype=np.int64)
377
+ numbers[order] = np.arange(1, len(phase) + 1)
378
+ funct = 1
379
+ material_lines: list[str] = []
380
+ function_lines: list[str] = []
381
+ for k, q in enumerate(present, start=1):
382
+ parts[q] = k
383
+ label = f"phase {q}" + (f" ({names[q]})" if q in names else "")
384
+ lines += [
385
+ RULER,
386
+ f"/PART/{k}",
387
+ _title(label),
388
+ "# prop_ID mat_ID subset_ID",
389
+ _i(1) + _i(k) + _i(0),
390
+ ]
391
+ own = np.flatnonzero(phase == q)
392
+ lines.append(f"/{keyword}/{k}")
393
+ if kind == "tetra10":
394
+ lines.append("#tetra_ID")
395
+ for e in own:
396
+ lines.append(_i(numbers[e]))
397
+ lines.append("".join(_i(n + 1) for n in elements[e]))
398
+ else:
399
+ lines.append(
400
+ f"#{'elem_ID':>9s}" + "".join(f"{'node_ID' + str(j + 1):>10s}" for j in range(per))
401
+ )
402
+ for e in own:
403
+ lines.append(_i(numbers[e]) + "".join(_i(n + 1) for n in elements[e]))
404
+ cards, functs, funct = _material_cards(k, label, materials[q], funct)
405
+ material_lines += [RULER, *cards]
406
+ function_lines += functs
407
+ prop = SOLID_PROPERTY
408
+ lines += [
409
+ RULER,
410
+ "/PROP/SOLID/1",
411
+ "solid",
412
+ "# Isolid Ismstr Iale Icpre "
413
+ " Itetra10 Inpts Itetra4 Iframe dn",
414
+ _i(prop["Isolid"])
415
+ + _i(prop["Ismstr"])
416
+ + " " * 10
417
+ + _i(prop["Icpre"])
418
+ + _i(prop["Itetra10"])
419
+ + _i(0)
420
+ + _i(prop["Itetra4"])
421
+ + _i(prop["Iframe"])
422
+ + _f(0.0),
423
+ "# qa qb "
424
+ " h LAMBDA_V MU_V",
425
+ _f(0.0) * 5,
426
+ "# deltaT_min",
427
+ _f(0.0),
428
+ "# Ndir sphpartID",
429
+ _i(0) + _i(0),
430
+ ]
431
+ lines += material_lines
432
+ if function_lines:
433
+ lines += [RULER, *function_lines]
434
+ # node groups, the loading, the contact and the time histories
435
+ lower_nodes = face_nodes(mesh, axis, 0)
436
+ upper_nodes = face_nodes(mesh, axis, 1)
437
+ if loading.kind != "impact" and (not len(lower_nodes) or not len(upper_nodes)):
438
+ raise ValueError(
439
+ f"no solid on the {'lower' if not len(lower_nodes) else 'upper'} face normal to "
440
+ f"{AXES[axis]}: nothing to hold or drive (another axis, or a morphology that "
441
+ "spans the box)"
442
+ )
443
+ groups: dict[str, int] = {}
444
+
445
+ def group(title_: str, node_ids) -> int:
446
+ gid = len(groups) + 1
447
+ groups[title_] = gid
448
+ lines.extend([RULER, f"/GRNOD/NODE/{gid}", _title(title_), *_ids(np.asarray(node_ids) + 1)])
449
+ return gid
450
+
451
+ histories: list[str] = []
452
+ th = 0
453
+
454
+ def node_history(title_: str, node_ids, variables, prefix: str) -> None:
455
+ nonlocal th
456
+ th += 1
457
+ histories.extend(
458
+ [RULER, f"/TH/NODE/{th}", _title(title_), "".join(f"{v:>10s}" for v in variables)]
459
+ )
460
+ histories.extend(_i(n + 1) + _i(0) + f"{prefix}{n + 1}" for n in node_ids)
461
+
462
+ drive = loading.driven
463
+ sign = loading.sign()
464
+ wall = None
465
+ if loading.kind == "impact":
466
+ gid = len(groups) + 1
467
+ groups["all nodes"] = gid
468
+ lines += [RULER, f"/GRNOD/PART/{gid}", "all nodes", *_ids(parts.values())]
469
+ velocity = np.zeros(3)
470
+ velocity[axis] = sign * speed
471
+ lines += [
472
+ RULER,
473
+ "/INIVEL/TRA/1",
474
+ "impact velocity",
475
+ "# Vx Vy Vz grnod_ID skew_ID",
476
+ _f(velocity[0]) + _f(velocity[1]) + _f(velocity[2]) + _i(gid) + _i(0),
477
+ ]
478
+ center = 0.5 * (lower + upper)
479
+ point = center.copy()
480
+ point[axis] = lower[axis]
481
+ normal = np.zeros(3)
482
+ normal[axis] = 1.0
483
+ slide = 2 if loading.friction > 0 else 0
484
+ wall = {"point": point.tolist(), "normal": normal.tolist()}
485
+ lines += [
486
+ RULER,
487
+ "/RWALL/PLANE/1",
488
+ "fixed wall at the lower face",
489
+ "# node_ID Slide grnod_ID1 grnod_ID2",
490
+ _i(0) + _i(slide) + _i(0) + _i(0),
491
+ "# Dsearch fric "
492
+ " Diameter ffac ifq",
493
+ _f(1.5 * float(np.max(lengths))) + _f(loading.friction) + _f(0.0) + _f(0.0) + _i(0),
494
+ "# XM YM ZM",
495
+ _f(point[0]) + _f(point[1]) + _f(point[2]),
496
+ "# X_M1 Y_M1 Z_M1",
497
+ _f(point[0] + normal[0]) + _f(point[1] + normal[1]) + _f(point[2] + normal[2]),
498
+ ]
499
+ th += 1
500
+ histories += [RULER, f"/TH/RWALL/{th}", "wall", f"{'DEF':>10s}", _i(1)]
501
+ else:
502
+ free = loading.kind != "shear" and loading.lateral == "free"
503
+ held_nodes, anchor = lower_nodes, None
504
+ if free: # one node of the lower face held across too: no rigid drift
505
+ face = np.asarray(nodes[lower_nodes], dtype=float)
506
+ anchor = int(lower_nodes[np.argmin(np.linalg.norm(face - face.mean(axis=0), axis=1))])
507
+ held_nodes = lower_nodes[lower_nodes != anchor]
508
+ g_lower = group("lower face", held_nodes) if len(held_nodes) else None
509
+ g_upper = group("upper face", upper_nodes)
510
+ held = np.ones(3, dtype=int)
511
+ if free:
512
+ held[:] = 0
513
+ held[axis] = 1
514
+ upper_held = np.zeros(3, dtype=int) if free else np.ones(3, dtype=int)
515
+ upper_held[drive] = 0
516
+ bcs = []
517
+ if g_lower is not None:
518
+ bcs.append(("lower face held", held, g_lower))
519
+ if anchor is not None:
520
+ bcs.append(
521
+ ("a node of the lower face held", np.ones(3, dtype=int), group("anchor", [anchor]))
522
+ )
523
+ if upper_held.any():
524
+ bcs.append(("upper face held across the drive", upper_held, g_upper))
525
+ for k, (text, dofs, gid) in enumerate(bcs, start=1):
526
+ lines += [
527
+ RULER,
528
+ f"/BCS/{k}",
529
+ text,
530
+ "# Tra rot skew_ID grnod_ID",
531
+ f" {dofs[0]}{dofs[1]}{dofs[2]} 000" + _i(0) + _i(gid),
532
+ ]
533
+ table = loading.velocity_function(end)
534
+ lines += [
535
+ RULER,
536
+ "/FUNCT/" + str(funct),
537
+ "velocity of the upper face (share of its speed)",
538
+ "# X Y",
539
+ ]
540
+ lines += [_f(t) + _f(s) for t, s in table]
541
+ lines += [
542
+ RULER,
543
+ "/IMPVEL/1",
544
+ "upper face driven",
545
+ "#funct_IDT Dir skew_ID sens_ID grnod_ID frame_ID Icoor",
546
+ _i(funct) + f"{'XYZ'[drive]:>10s}" + _i(0) + _i(0) + _i(g_upper) + _i(0) + _i(0),
547
+ "# Ascale_x Fscale_Y Tstart Tstop",
548
+ _f(1.0) + _f(sign * speed) + _f(0.0) + _f(10.0 * end),
549
+ ]
550
+ reactions = tuple(f"REAC{'XYZ'[a]}" for a in dict.fromkeys((axis, drive)))
551
+ node_history("reactions of the lower face", lower_nodes, reactions, "L")
552
+ node_history("reactions of the upper face", upper_nodes, reactions, "U")
553
+ values = len(reactions) * (len(lower_nodes) + len(upper_nodes))
554
+ history = int(max(100, min(int(history), MAX_HISTORY_VALUES // max(values, 1))))
555
+ if loading.contact:
556
+ lines += [
557
+ RULER,
558
+ "/SURF/PART/EXT/1",
559
+ "outer surface of the solid",
560
+ *_ids(parts.values()),
561
+ RULER,
562
+ "/INTER/TYPE24/1",
563
+ "self contact of the outer surface",
564
+ "# Surf_ID1 Surf_ID2 Istf "
565
+ " Irem_i2 Idel",
566
+ _i(1) + _i(0) + _i(0) + " " * 20 + _i(0) + " " * 10 + _i(0),
567
+ "#grnod_IDs Iedge "
568
+ " Edge_angle Gap_max_s Gap_max_m",
569
+ _i(0) + " " * 20 + _i(0) + _f(0.0) + _f(0.0) + _f(0.0),
570
+ "# Stmin Stmax Igap0 Ipen0 Ipen_max",
571
+ _f(0.0) + _f(0.0) + _i(0) + _i(0) + _f(0.0),
572
+ "# Stfac Fric "
573
+ " Tstart Tstop",
574
+ _f(0.0) + _f(loading.friction) + " " * 20 + _f(0.0) + _f(10.0 * end),
575
+ "# IBC Inacti "
576
+ " VISs Tpressfit",
577
+ " " * 30 + _i(0) + _f(0.0) + " " * 20 + _f(0.0),
578
+ "# Ifric Ifiltr Xfreq "
579
+ " sens_ID fric_ID",
580
+ _i(0) + _i(0) + _f(0.0) + " " * 10 + _i(0) + " " * 30 + _i(0),
581
+ ]
582
+ th += 1
583
+ histories += [RULER, f"/TH/PART/{th}", "parts", f"{'DEF':>10s}", *_ids(parts.values())]
584
+ lines += histories
585
+ lines += [RULER, "/END"]
586
+ starter = directory / f"{name}_0000.rad"
587
+ starter.write_text("\n".join(lines) + "\n", encoding="ascii", newline="\n")
588
+ # the Engine input
589
+ cycles = end / dt
590
+ every = max(1, round(min(cycles, 1e9) / 200))
591
+ engine_lines = [
592
+ "#RADIOSS ENGINE",
593
+ f"# morphoGen {__version__}: {_title(title or name)}",
594
+ RULER,
595
+ f"/RUN/{name}/1",
596
+ _f(end),
597
+ "/TFILE",
598
+ _f(end / int(history)),
599
+ "/ANIM/DT",
600
+ _f(0.0) + _f(end / int(frames)),
601
+ *[f"/ANIM/VECT/{v}" for v in ANIM_VECTORS],
602
+ *[f"/ANIM/ELEM/{v}" for v in ANIM_ELEMENTS],
603
+ f"/PRINT/-{every}",
604
+ ]
605
+ if time_step:
606
+ engine_lines += [
607
+ "/DT/NODA/CST/0",
608
+ "# DT_scale DT_min",
609
+ _f(0.9) + _f(float(time_step)),
610
+ ]
611
+ engine_lines.append(RULER)
612
+ engine = directory / f"{name}_0001.rad"
613
+ engine.write_text("\n".join(engine_lines) + "\n", encoding="ascii", newline="\n")
614
+ np.savez_compressed(
615
+ directory / f"{name}_mesh.npz",
616
+ nodes=nodes,
617
+ elements=elements,
618
+ phase=phase,
619
+ numbers=numbers,
620
+ lower_nodes=lower_nodes,
621
+ upper_nodes=upper_nodes,
622
+ kind=np.array(kind),
623
+ )
624
+ area = float(np.prod(np.delete(lengths, axis)))
625
+ manifest = {
626
+ "morphogen": __version__,
627
+ "name": name,
628
+ "title": _title(title or name),
629
+ "units": list(units.names),
630
+ "loading": loading.to_config(),
631
+ "axis": axis,
632
+ "driven": drive,
633
+ "sign": sign,
634
+ "speed": speed,
635
+ "lower": lower.tolist(),
636
+ "upper": upper.tolist(),
637
+ "lengths": lengths.tolist(),
638
+ "area": area,
639
+ "volume": float(np.prod(lengths)),
640
+ "solid_volume": float(volumes.sum()),
641
+ "mass": mass,
642
+ "end_time": end,
643
+ "frames": int(frames),
644
+ "history": int(history),
645
+ "critical_time_step": dt,
646
+ "time_step": float(time_step) if time_step else None,
647
+ "cycles": float(end / max(dt, float(time_step or 0.0))),
648
+ "elements": kind,
649
+ "n_nodes": n_nodes,
650
+ "n_elements": len(elements),
651
+ "parts": {str(q): k for q, k in parts.items()},
652
+ "materials": {str(q): materials[q].to_config() for q in present},
653
+ "laws": {str(q): materials[q].law for q in present},
654
+ "phase_names": {str(k): v for k, v in names.items()},
655
+ "groups": groups,
656
+ "faces": {"lower": len(lower_nodes), "upper": len(upper_nodes)},
657
+ "wall": wall,
658
+ }
659
+ (directory / MANIFEST).write_text(json.dumps(manifest, indent=1), encoding="utf-8")
660
+ return RadiossInputs(directory, name, starter, engine, manifest)
661
+
662
+
663
+ # -- outputs -------------------------------------------------------------------------------
664
+
665
+ _NUMBER = r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[EeDd][-+]?\d+)?"
666
+ _CYCLE = re.compile(rf"^\s*(\d+)\s+({_NUMBER})\s+({_NUMBER})\s+[A-Za-z]")
667
+
668
+
669
+ @dataclass
670
+ class RadiossListing:
671
+ """What the listing of a run of Radioss tells: its cycles, times and time steps (the
672
+ lines printed every few cycles), its errors and whether it ended normally (None
673
+ while it runs, or when the listing does not say)."""
674
+
675
+ cycles: np.ndarray
676
+ times: np.ndarray
677
+ steps: np.ndarray
678
+ errors: list[str]
679
+ normal: bool | None
680
+
681
+ @property
682
+ def time(self) -> float:
683
+ return float(self.times[-1]) if len(self.times) else 0.0
684
+
685
+
686
+ def read_radioss_listing(path) -> RadiossListing:
687
+ """The cycles, times and errors of the listing of a Starter or Engine run
688
+ (``<name>_0000.out``, ``<name>_0001.out``)."""
689
+ text = Path(path).read_text(encoding="utf-8", errors="replace")
690
+ cycles, times, steps = [], [], []
691
+ for line in text.splitlines():
692
+ m = _CYCLE.match(line)
693
+ if m:
694
+ cycles.append(int(m.group(1)))
695
+ times.append(float(m.group(2).replace("D", "E").replace("d", "e")))
696
+ steps.append(float(m.group(3).replace("D", "E").replace("d", "e")))
697
+ errors = []
698
+ lines = text.splitlines()
699
+ for k, line in enumerate(lines):
700
+ if re.search(r"\bERROR\s+ID\b|^\s*\*+\s*ERROR\b|\bERROR\s*:", line):
701
+ detail = " ".join(s.strip() for s in lines[k : k + 4] if s.strip())
702
+ errors.append(re.sub(r"\s+", " ", detail)[:300])
703
+ upper = text.upper()
704
+ if "ERROR TERMINATION" in upper:
705
+ normal = False
706
+ elif "NORMAL TERMINATION" in upper:
707
+ normal = True
708
+ else:
709
+ normal = None
710
+ return RadiossListing(
711
+ np.array(cycles, dtype=np.int64), np.array(times), np.array(steps), errors, normal
712
+ )
713
+
714
+
715
+ def read_radioss_th(path) -> dict[str, np.ndarray]:
716
+ """The columns of a time history converted to CSV (``th_to_csv``): name -> values,
717
+ the first column, the time, under ``"time"`` as well. The names are those of the
718
+ header (stripped of their quotes and spaces); a header given twice gets ``#2``..."""
719
+ with open(path, encoding="utf-8", errors="replace", newline="") as f:
720
+ sample = f.read(4096)
721
+ f.seek(0)
722
+ try:
723
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t ")
724
+ except csv.Error:
725
+ dialect = csv.excel
726
+ rows = [r for r in csv.reader(f, dialect) if any(c.strip() for c in r)]
727
+ if not rows:
728
+ raise ValueError(f"{path}: an empty time history")
729
+
730
+ def numeric(row):
731
+ try:
732
+ [float(c) for c in row if c.strip()]
733
+ except ValueError:
734
+ return False
735
+ return True
736
+
737
+ header = None
738
+ if not numeric(rows[0]):
739
+ header, rows = rows[0], rows[1:]
740
+ rows = [[float(c) for c in r if c.strip()] for r in rows if numeric(r)]
741
+ if not rows:
742
+ raise ValueError(f"{path}: no values")
743
+ width = min(len(r) for r in rows)
744
+ data = np.array([r[:width] for r in rows], dtype=float)
745
+ names = []
746
+ for k in range(width):
747
+ base = header[k].strip().strip('"').strip() if header and k < len(header) else ""
748
+ base = base or ("time" if k == 0 else f"column {k}")
749
+ candidate, n = base, 1
750
+ while candidate in names:
751
+ n += 1
752
+ candidate = f"{base}#{n}"
753
+ names.append(candidate)
754
+ out = {n: data[:, k] for k, n in enumerate(names)}
755
+ out.setdefault("time", data[:, 0])
756
+ return out
757
+
758
+
759
+ def read_manifest(directory) -> dict:
760
+ """The manifest of a run written by :func:`write_radioss`."""
761
+ path = Path(directory) / MANIFEST
762
+ if not path.is_file():
763
+ raise ValueError(f"no run of morphoGen in {directory} (no {MANIFEST})")
764
+ return json.loads(path.read_text(encoding="utf-8"))