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,371 @@
1
+ """Inputs of other programs: periodic boundary conditions for Abaqus and CalculiX,
2
+ grids and materials for DAMASK, seeds for Neper.
3
+
4
+ * :func:`write_periodic_equations` ties every node of the upper faces of a mesh with
5
+ matching opposite faces (conforming tetrahedra or voxels) to its image on the lower
6
+ faces and to three reference nodes, whose displacements (temperatures) are the
7
+ macroscopic strain (gradient) times the edges of the box. Meshes of whole periodic
8
+ cells tie the translates of every node of their boundary alike.
9
+ * :func:`write_damask` writes the grid of a polycrystal (``.vti`` with the ``material``
10
+ of each voxel) and its ``material.yaml``: one material per grain, with the quaternion
11
+ of its orientation (DAMASK convention, P = -1) and its phase.
12
+ * :func:`write_neper` writes the seeds, weights and orientations of a tessellation, and
13
+ the Neper command that builds it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ from morphogen._version import __version__
23
+ from morphogen.image import VoxelImage
24
+ from morphogen.mesh.tetra import TetMesh
25
+ from morphogen.mesh.voxel import VoxelMesh
26
+
27
+
28
+ def _box(mesh) -> tuple[np.ndarray, np.ndarray]:
29
+ if isinstance(mesh, TetMesh):
30
+ return np.asarray(mesh.lower, float), np.asarray(mesh.upper, float)
31
+ return mesh.nodes.min(axis=0), mesh.nodes.max(axis=0)
32
+
33
+
34
+ def _upper(mesh, axis: int) -> np.ndarray:
35
+ """Nodes of the upper face along ``axis``."""
36
+ if isinstance(mesh, TetMesh):
37
+ return mesh.face_nodes(axis, 1)
38
+ return np.flatnonzero(mesh.node_ijk[:, axis] == mesh.grid_shape[axis])
39
+
40
+
41
+ def periodic_images(mesh) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
42
+ """Nodes of the upper faces (``slaves``), their images on the lower faces
43
+ (``masters``, translated along every axis whose upper face holds the node) and the
44
+ periods between them, ``x_slave = x_master + shift * edges`` (shift: 0 or 1 along
45
+ each axis). Meshes of whole periodic cells: every node of their boundary that is a
46
+ translate of another, ``mesh.periodic_links()``."""
47
+ if not isinstance(mesh, (TetMesh, VoxelMesh)):
48
+ raise TypeError("periodic equations need a TetMesh or a VoxelMesh")
49
+ if isinstance(mesh, TetMesh) and mesh.whole:
50
+ if not mesh.matching_faces():
51
+ raise ValueError(
52
+ "periodic equations need a mesh of all the cells (their boundary made of "
53
+ "pairs of translated faces)"
54
+ )
55
+ return mesh.periodic_links()
56
+ n = mesh.n_nodes
57
+ image = []
58
+ on_upper = []
59
+ for axis in range(3):
60
+ pairs = mesh.periodic_pairs(axis)
61
+ upper = _upper(mesh, axis)
62
+ if len(pairs) != len(upper):
63
+ raise ValueError(
64
+ "periodic equations need matching opposite faces (a periodic conforming "
65
+ "mesh, or a voxel mesh of all the voxels)"
66
+ )
67
+ m = np.full(n, -1, dtype=np.int64)
68
+ m[pairs[:, 1]] = pairs[:, 0]
69
+ image.append(m)
70
+ flag = np.zeros(n, dtype=bool)
71
+ flag[upper] = True
72
+ on_upper.append(flag)
73
+ slaves = np.flatnonzero(on_upper[0] | on_upper[1] | on_upper[2])
74
+ masters = slaves.copy()
75
+ for axis in range(3):
76
+ sel = on_upper[axis][slaves]
77
+ masters[sel] = image[axis][masters[sel]]
78
+ if np.any(masters < 0): # pragma: no cover - guarded by the face check
79
+ raise ValueError("a node of an upper face has no periodic image")
80
+ return slaves, masters, np.stack([flag[slaves] for flag in on_upper], axis=1).astype(np.int64)
81
+
82
+
83
+ def write_periodic_equations(path, mesh, *, physics: str = "elastic") -> Path:
84
+ """Abaqus/CalculiX include file of periodic boundary conditions (``*INCLUDE`` it
85
+ after the mesh): reference nodes ``REF_X``, ``REF_Y``, ``REF_Z`` (numbered after the
86
+ nodes of the mesh), the node set ``CORNER`` (a node to fix against translation) and
87
+ ``*EQUATION`` blocks ``u(n) - u(image of n) - sum_d s_d u(REF_d) = 0``, with ``s_d``
88
+ the periods from the image to the node along each axis (1 for the upper faces of a
89
+ mesh of the box holding the node; -1, 0 or 1 for whole periodic cells), degrees of
90
+ freedom 1-3, or 11 for ``physics='thermal'``."""
91
+ if physics not in ("elastic", "thermal"):
92
+ raise ValueError("physics: 'elastic' or 'thermal'")
93
+ path = Path(path)
94
+ slaves, masters, shifts = periodic_images(mesh)
95
+ lower, upper = _box(mesh)
96
+ length = upper - lower
97
+ n = mesh.n_nodes
98
+ refs = n + 1 + np.arange(3) # 1-based ids of the reference nodes
99
+ dofs = (1, 2, 3) if physics == "elastic" else (11,)
100
+ corner = int(np.argmin(np.linalg.norm(mesh.nodes - lower, axis=1)))
101
+ names = ("REF_X", "REF_Y", "REF_Z")
102
+ area = np.prod(length) / length # faces normal to each axis
103
+ lines = [
104
+ f"** morphoGen {__version__}: periodic boundary conditions ({physics})",
105
+ "** Include after the mesh. Macroscopic strain E (gradient G): impose on REF_<d> the",
106
+ "** displacement E . L_d e_d (temperature G . L_d e_d), and fix CORNER, e.g.",
107
+ (
108
+ f"** *BOUNDARY: REF_X, 1, 1, E11*{length[0]:.9g}; REF_X, 2, 2, E21*...; ..."
109
+ if physics == "elastic"
110
+ else f"** *BOUNDARY: REF_X, 11, 11, G1*{length[0]:.9g}; REF_Y, 11, 11, G2*..."
111
+ ),
112
+ (
113
+ "** Macroscopic stress S (the reference nodes are the macroscopic degrees of "
114
+ "freedom):\n** fix the rotation (REF_X 2 and 3, REF_Y 3) and apply on REF_<d> the "
115
+ "force A_d S . e_d,\n** A_d the area of the face normal to d: "
116
+ + ", ".join(f"A_{n} = {a:.9g}" for n, a in zip("xyz", area, strict=True))
117
+ + "; e.g. *CLOAD: REF_X, 1, S11*A_x. Mixed: prescribe either per component."
118
+ if physics == "elastic"
119
+ else "** Macroscopic flux Q: apply on REF_<d> the concentrated flux -A_d Q_d, "
120
+ "A_d the area of the face normal to d: "
121
+ + ", ".join(f"A_{n} = {a:.9g}" for n, a in zip("xyz", area, strict=True))
122
+ ),
123
+ f"** Box: lower {' '.join(f'{v:.9g}' for v in lower)}, edges "
124
+ f"{' '.join(f'{v:.9g}' for v in length)}.",
125
+ "*NODE",
126
+ ]
127
+ for d in range(3):
128
+ x = upper + length * 0.1 * (np.arange(3) == d) # outside the box, for display
129
+ lines.append(f"{refs[d]}, {x[0]:.12g}, {x[1]:.12g}, {x[2]:.12g}")
130
+ for d, name in enumerate(names):
131
+ lines += [f"*NSET, NSET={name}", str(refs[d])]
132
+ lines += ["*NSET, NSET=CORNER", str(corner + 1)]
133
+ for s, m, shift in zip(slaves, masters, shifts.tolist(), strict=True):
134
+ terms_ref = [(refs[d], -float(shift[d])) for d in range(3) if shift[d]]
135
+ for dof in dofs:
136
+ terms = [(s + 1, dof, 1.0), (m + 1, dof, -1.0)] + [(r, dof, c) for r, c in terms_ref]
137
+ lines += ["*EQUATION", str(len(terms))]
138
+ for start in range(0, len(terms), 4): # at most four terms per line
139
+ chunk = terms[start : start + 4]
140
+ lines.append(", ".join(f"{a}, {b}, {c:g}" for a, b, c in chunk))
141
+ path.write_text("\n".join(lines) + "\n", encoding="ascii")
142
+ return path
143
+
144
+
145
+ # -- DAMASK --------------------------------------------------------------------------------
146
+
147
+
148
+ def euler_to_quaternion(euler) -> np.ndarray:
149
+ """Unit quaternions (w, x, y, z), w >= 0, of Bunge Euler angles in degrees, with the
150
+ conventions of DAMASK (passive rotation, P = -1; Rowenhorst et al. 2015)."""
151
+ e = 0.5 * np.radians(np.asarray(euler, dtype=float).reshape(-1, 3))
152
+ c, s = np.cos(e[:, 1]), np.sin(e[:, 1])
153
+ q = np.stack(
154
+ [
155
+ c * np.cos(e[:, 0] + e[:, 2]),
156
+ s * np.cos(e[:, 0] - e[:, 2]),
157
+ s * np.sin(e[:, 0] - e[:, 2]),
158
+ c * np.sin(e[:, 0] + e[:, 2]),
159
+ ],
160
+ axis=1,
161
+ )
162
+ q[q[:, 0] < 0] *= -1.0
163
+ return q
164
+
165
+
166
+ def _yaml_list(values) -> str:
167
+ return "[" + ", ".join(f"{float(v):.12g}" for v in values) + "]"
168
+
169
+
170
+ def write_damask(
171
+ stem,
172
+ grains: VoxelImage,
173
+ orientations,
174
+ grain_phases=None,
175
+ *,
176
+ phase_names: dict | None = None,
177
+ materials: dict | None = None,
178
+ ) -> list[Path]:
179
+ """DAMASK grid solver inputs: ``<stem>.vti`` (``material`` of each voxel: its grain,
180
+ numbered from 0 over the grains present) and ``<stem>_material.yaml`` (homogenization
181
+ ``SX``, one material per grain with its orientation and phase). ``grain_phases``
182
+ gives the phase of each grain label (default 1); ``phase_names`` the names of the
183
+ phases; ``materials`` (phase -> :class:`~morphogen.homogenization.Material`) fills
184
+ the elastic constants of the crystals (``Hooke``, in the units of the materials:
185
+ DAMASK expects pascals); the plastic behaviour is left to the user."""
186
+ from morphogen.io.vtk import write_vti
187
+
188
+ stem = Path(stem)
189
+ labels = np.asarray(grains.data)
190
+ if labels.dtype.kind not in "iu":
191
+ raise ValueError("DAMASK grids need an image of grain labels")
192
+ used, inverse = np.unique(labels, return_inverse=True)
193
+ orientations = np.asarray(orientations, dtype=float)
194
+ if orientations.ndim != 2 or orientations.shape[1] != 3 or len(orientations) <= used.max():
195
+ raise ValueError("orientations: Bunge angles (degrees) of every grain label")
196
+ phases = np.ones(int(used.max()) + 1, dtype=np.int64)
197
+ if grain_phases is not None:
198
+ phases = np.asarray(grain_phases, dtype=np.int64)
199
+ names = {int(p): f"phase_{int(p)}" for p in np.unique(phases[used])}
200
+ names.update({int(k): str(v) for k, v in (phase_names or {}).items()})
201
+ grid = grains.with_data(inverse.reshape(labels.shape).astype(np.int32), name="material")
202
+ vti = write_vti(stem.with_suffix(".vti"), [grid])
203
+ quats = euler_to_quaternion(orientations[used])
204
+ lines = [
205
+ f"# morphoGen {__version__}: DAMASK material configuration ({len(used)} grains)",
206
+ "homogenization:",
207
+ " SX:",
208
+ " N_constituents: 1",
209
+ " mechanical: {type: pass}",
210
+ "phase:",
211
+ ]
212
+ for p, name in names.items():
213
+ lines += [
214
+ f" {name}:",
215
+ " lattice: cF # to be checked: cF, cI, hP, tI...",
216
+ " mechanical:",
217
+ ]
218
+ lines.append(" output: [F, P, F_e, F_p, L_p, O]")
219
+ mat = (materials or {}).get(p)
220
+ if mat is not None and getattr(mat, "stiffness", None) is not None:
221
+ d = np.array(mat.stiffness)
222
+ keys = {"C_11": d[0, 0], "C_12": d[0, 1], "C_44": d[3, 3]}
223
+ if mat.symmetry == "hexagonal":
224
+ lines[-3] = " lattice: hP"
225
+ keys.update({"C_13": d[0, 2], "C_33": d[2, 2]})
226
+ inner = ", ".join(f"{k}: {v:.12g}" for k, v in keys.items())
227
+ lines.append(f" elastic: {{type: Hooke, {inner}}}")
228
+ else:
229
+ lines.append(" elastic: {type: Hooke} # to be completed")
230
+ lines.append("material:")
231
+ for g, q in zip(used, quats, strict=True):
232
+ lines += [
233
+ " - homogenization: SX",
234
+ " constituents:",
235
+ f" - phase: {names[int(phases[g])]}",
236
+ " v: 1.0",
237
+ f" O: {_yaml_list(q)}",
238
+ f" # grain {int(g)}",
239
+ ]
240
+ yaml_path = stem.parent / f"{stem.name}_material.yaml"
241
+ yaml_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
242
+ return [vti, yaml_path]
243
+
244
+
245
+ # -- Neper -----------------------------------------------------------------------------------
246
+
247
+
248
+ def write_neper(stem, tessellation) -> list[Path]:
249
+ """Seeds (``<stem>_seeds.txt``, coordinates in the box), weights (``_weights.txt``:
250
+ the radii of a Laguerre tessellation, sqrt of the morphoGen weights) and orientations
251
+ (``_ori.txt``: Bunge angles in degrees) of a tessellation, and ``<stem>_neper.sh``,
252
+ the command building it with Neper (``-morphooptiini``). Germs outside the box (the
253
+ window of a non-periodic tessellation) have no Neper equivalent: they are left out,
254
+ which changes the cells next to the faces."""
255
+ stem = Path(stem)
256
+ domain = tessellation.domain
257
+ germs = np.asarray(tessellation.germs, dtype=float) - np.asarray(domain.lower)
258
+ inside = np.all((germs >= 0) & (germs <= np.asarray(domain.lengths)), axis=1)
259
+ files = []
260
+ seeds = stem.parent / f"{stem.name}_seeds.txt"
261
+ np.savetxt(seeds, germs[inside], fmt="%.12g")
262
+ files.append(seeds)
263
+ ini = f"coo:file({seeds.name})"
264
+ if tessellation.weights is not None:
265
+ weights = stem.parent / f"{stem.name}_weights.txt"
266
+ np.savetxt(weights, np.sqrt(np.maximum(tessellation.weights[inside], 0.0)), fmt="%.12g")
267
+ files.append(weights)
268
+ ini += f",weight:file({weights.name})"
269
+ options = [
270
+ "-T",
271
+ f"-n {int(inside.sum())}",
272
+ '-domain "cube({})"'.format(",".join(f"{v:.12g}" for v in domain.lengths)),
273
+ f'-morphooptiini "{ini}"',
274
+ ]
275
+ if domain.periodic:
276
+ options.append("-periodicity all")
277
+ if tessellation.orientations is not None:
278
+ ori = stem.parent / f"{stem.name}_ori.txt"
279
+ np.savetxt(ori, np.asarray(tessellation.orientations)[inside], fmt="%.9g")
280
+ files.append(ori)
281
+ options.append(f'-ori "file({ori.name},des=euler-bunge)"')
282
+ options.append(f"-o {stem.name}")
283
+ script = stem.parent / f"{stem.name}_neper.sh"
284
+ lost = int((~inside).sum())
285
+ note = f"# {lost} germs outside the box left out\n" if lost else ""
286
+ script.write_text(
287
+ f"#!/bin/sh\n# morphoGen {__version__}: the tessellation with Neper (shifted to the "
288
+ f"origin)\n{note}neper " + " \\\n ".join(options) + "\n",
289
+ encoding="utf-8",
290
+ )
291
+ files.append(script)
292
+ return files
293
+
294
+
295
+ # -- FEniCSx ---------------------------------------------------------------------------------
296
+
297
+
298
+ def _xml_data(values: np.ndarray, number: str, precision: int) -> str:
299
+ values = np.asarray(values)
300
+ fmt = "%d" if number == "Int" else "%.17g"
301
+ rows = "\n".join(" ".join(fmt % v for v in row) for row in values.reshape(len(values), -1))
302
+ shape = " ".join(str(s) for s in values.shape)
303
+ return (
304
+ f'<DataItem Dimensions="{shape}" NumberType="{number}" Precision="{precision}" '
305
+ f'Format="XML">\n{rows}\n</DataItem>'
306
+ )
307
+
308
+
309
+ def write_fenicsx(path, mesh: TetMesh) -> Path:
310
+ """XDMF file of a tetrahedral mesh and its tags, as written and read by FEniCSx
311
+ (``dolfinx.io.XDMFFile``, ASCII encoding): the grid ``mesh`` (linear tetrahedra), the
312
+ cell tags ``phase`` (and ``grain`` for polycrystals) and the facet tags ``faces``
313
+ (the faces of the box: 1-6 for x0, x1, y0, y1, z0, z1; 1 for the faces bounding
314
+ whole periodic cells). Reading::
315
+
316
+ with XDMFFile(MPI.COMM_WORLD, path, "r") as f:
317
+ mesh = f.read_mesh(name="mesh")
318
+ phase = f.read_meshtags(mesh, name="phase")
319
+ mesh.topology.create_connectivity(2, 3)
320
+ faces = f.read_meshtags(mesh, name="faces")
321
+ """
322
+ path = Path(path)
323
+ lin = mesh.linear()
324
+ n = lin.n_elements
325
+ topology = _xml_data(lin.elements, "Int", 8)
326
+ tri, refs = [], []
327
+ if lin.whole:
328
+ tri.append(lin.outer_faces())
329
+ refs.append(np.ones(len(tri[0]), dtype=np.int64))
330
+ else:
331
+ for axis in range(3):
332
+ for side in (0, 1):
333
+ faces = lin.boundary_faces(axis, side)
334
+ tri.append(faces[:, :3])
335
+ refs.append(np.full(len(faces), 1 + 2 * axis + side))
336
+ tri, refs = np.concatenate(tri), np.concatenate(refs)
337
+ geometry_ref = "<xi:include xpointer=\"xpointer(/Xdmf/Domain/Grid[@Name='mesh']/Geometry)\"/>"
338
+
339
+ def tags(name, topo_type, cells, values):
340
+ return (
341
+ f' <Grid Name="{name}" GridType="Uniform">\n'
342
+ f" {geometry_ref}\n"
343
+ f' <Topology TopologyType="{topo_type}" NumberOfElements="{len(cells)}" '
344
+ f'NodesPerElement="{cells.shape[1]}">\n'
345
+ f"{_xml_data(cells, 'Int', 8)}\n"
346
+ " </Topology>\n"
347
+ f' <Attribute Name="{name}" AttributeType="Scalar" Center="Cell">\n'
348
+ f"{_xml_data(values, 'Int', 4)}\n"
349
+ " </Attribute>\n"
350
+ " </Grid>\n"
351
+ )
352
+
353
+ grids = [tags("phase", "Tetrahedron", lin.elements, lin.phase)]
354
+ if lin.cell is not None:
355
+ grids.append(tags("grain", "Tetrahedron", lin.elements, lin.cell))
356
+ grids.append(tags("faces", "Triangle", tri, refs))
357
+ text = (
358
+ '<?xml version="1.0"?>\n'
359
+ '<Xdmf Version="3.0" xmlns:xi="http://www.w3.org/2001/XInclude">\n'
360
+ " <Domain>\n"
361
+ ' <Grid Name="mesh" GridType="Uniform">\n'
362
+ f' <Topology TopologyType="Tetrahedron" NumberOfElements="{n}" NodesPerElement="4">\n'
363
+ f"{topology}\n"
364
+ " </Topology>\n"
365
+ ' <Geometry GeometryType="XYZ">\n'
366
+ f"{_xml_data(lin.nodes, 'Float', 8)}\n"
367
+ " </Geometry>\n"
368
+ " </Grid>\n" + "".join(grids) + " </Domain>\n</Xdmf>\n"
369
+ )
370
+ path.write_text(text, encoding="ascii")
371
+ return path
morphogen/io/tables.py ADDED
@@ -0,0 +1,278 @@
1
+ """Tables of results as raw data files: comma-separated values (``.csv``), text in
2
+ tab-separated columns under a ``#`` header (``.txt``, ``.tsv``: ``numpy.loadtxt`` reads
3
+ them) and Excel workbooks (``.xlsx``), without dependency: a workbook is a zip of a few
4
+ XML parts (Office Open XML), its strings inline, its header row bold and frozen.
5
+
6
+ A table is a list of records (dicts), a mapping of columns (name -> values) or a 2D array
7
+ (with ``header``); several tables (a mapping name -> table) become the sheets of a
8
+ workbook, or one text file each.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import csv
14
+ import math
15
+ import zipfile
16
+ from pathlib import Path
17
+ from xml.etree import ElementTree
18
+ from xml.sax.saxutils import escape
19
+
20
+ import numpy as np
21
+
22
+ FORMATS = {".csv": "csv", ".txt": "txt", ".tsv": "txt", ".dat": "txt", ".xlsx": "xlsx"}
23
+
24
+
25
+ def as_columns(table, header=None) -> tuple[list[str], list[list]]:
26
+ """The header and the columns (lists) of a table (records, columns or an array)."""
27
+ if isinstance(table, dict):
28
+ names = [str(k) for k in table]
29
+ columns = [
30
+ list(np.ravel(np.asarray(v, dtype=object))) if np.ndim(v) else [v]
31
+ for v in table.values()
32
+ ]
33
+ elif isinstance(table, (list, tuple)) and table and isinstance(table[0], dict):
34
+ names = []
35
+ for row in table:
36
+ names.extend(k for k in row if k not in names)
37
+ columns = [[row.get(k, "") for row in table] for k in names]
38
+ else:
39
+ data = np.atleast_2d(np.asarray(table, dtype=object))
40
+ names = list(header) if header is not None else [f"c{j + 1}" for j in range(data.shape[1])]
41
+ columns = [list(data[:, j]) for j in range(data.shape[1])]
42
+ if header is not None and len(header) == len(names):
43
+ names = [str(h) for h in header]
44
+ n = max((len(c) for c in columns), default=0)
45
+ columns = [c + [""] * (n - len(c)) for c in columns]
46
+ return names, columns
47
+
48
+
49
+ def _plain(value):
50
+ """A cell value as a Python number, bool or string."""
51
+ if isinstance(value, (bool, np.bool_)):
52
+ return bool(value)
53
+ if isinstance(value, (int, np.integer)):
54
+ return int(value)
55
+ if isinstance(value, (float, np.floating)):
56
+ return float(value)
57
+ return "" if value is None else str(value)
58
+
59
+
60
+ def _text(value, precision: int | None) -> str:
61
+ value = _plain(value)
62
+ if isinstance(value, float):
63
+ return repr(value) if precision is None else f"{value:.{precision}g}"
64
+ return str(value)
65
+
66
+
67
+ def _column_name(j: int) -> str:
68
+ out = ""
69
+ j += 1
70
+ while j:
71
+ j, r = divmod(j - 1, 26)
72
+ out = chr(65 + r) + out
73
+ return out
74
+
75
+
76
+ def _sheet_xml(names, columns) -> str:
77
+ rows = ['<row r="1">'] + [
78
+ f'<c r="{_column_name(j)}1" t="inlineStr" s="1"><is><t>{escape(n)}</t></is></c>'
79
+ for j, n in enumerate(names)
80
+ ]
81
+ rows.append("</row>")
82
+ for i in range(len(columns[0]) if columns else 0):
83
+ r = i + 2
84
+ cells = [f'<row r="{r}">']
85
+ for j, column in enumerate(columns):
86
+ value, ref = _plain(column[i]), f"{_column_name(j)}{r}"
87
+ if isinstance(value, bool):
88
+ cells.append(f'<c r="{ref}" t="b"><v>{int(value)}</v></c>')
89
+ elif isinstance(value, (int, float)):
90
+ if isinstance(value, float) and not math.isfinite(value):
91
+ cells.append(f'<c r="{ref}" t="inlineStr"><is><t>{value}</t></is></c>')
92
+ else:
93
+ cells.append(f'<c r="{ref}"><v>{value!r}</v></c>')
94
+ elif value != "":
95
+ cells.append(
96
+ f'<c r="{ref}" t="inlineStr"><is>'
97
+ f'<t xml:space="preserve">{escape(value)}</t></is></c>'
98
+ )
99
+ cells.append("</row>")
100
+ rows.extend(cells)
101
+ return (
102
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
103
+ '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
104
+ '<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" '
105
+ 'activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
106
+ "<sheetData>" + "".join(rows) + "</sheetData></worksheet>"
107
+ )
108
+
109
+
110
+ def _write_xlsx(path: Path, sheets: dict) -> None:
111
+ names = list(sheets)
112
+ main = "application/vnd.openxmlformats-officedocument.spreadsheetml"
113
+ rel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
114
+ overrides = "".join(
115
+ f'<Override PartName="/xl/worksheets/sheet{k + 1}.xml" ContentType="{main}.worksheet+xml"/>'
116
+ for k in range(len(names))
117
+ )
118
+ content = (
119
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
120
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
121
+ '<Default Extension="rels" '
122
+ 'ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
123
+ '<Default Extension="xml" ContentType="application/xml"/>'
124
+ f'<Override PartName="/xl/workbook.xml" ContentType="{main}.sheet.main+xml"/>'
125
+ f'<Override PartName="/xl/styles.xml" ContentType="{main}.styles+xml"/>'
126
+ + overrides
127
+ + "</Types>"
128
+ )
129
+ root_rels = (
130
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
131
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
132
+ f'<Relationship Id="rId1" Type="{rel}/officeDocument" '
133
+ 'Target="xl/workbook.xml"/></Relationships>'
134
+ )
135
+ sheets_xml = "".join(
136
+ f'<sheet name="{escape(str(n)[:31])}" sheetId="{k + 1}" r:id="rId{k + 1}"/>'
137
+ for k, n in enumerate(names)
138
+ )
139
+ workbook = (
140
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
141
+ '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
142
+ f'xmlns:r="{rel}"><sheets>{sheets_xml}</sheets></workbook>'
143
+ )
144
+ links = "".join(
145
+ f'<Relationship Id="rId{k + 1}" Type="{rel}/worksheet" '
146
+ f'Target="worksheets/sheet{k + 1}.xml"/>'
147
+ for k in range(len(names))
148
+ )
149
+ workbook_rels = (
150
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
151
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
152
+ + links
153
+ + f'<Relationship Id="rId{len(names) + 1}" Type="{rel}/styles" '
154
+ 'Target="styles.xml"/></Relationships>'
155
+ )
156
+ styles = (
157
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
158
+ '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
159
+ '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font>'
160
+ '<font><b/><sz val="11"/><name val="Calibri"/></font></fonts>'
161
+ '<fills count="2"><fill><patternFill patternType="none"/></fill>'
162
+ '<fill><patternFill patternType="gray125"/></fill></fills>'
163
+ '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
164
+ '<cellStyleXfs count="1">'
165
+ '<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
166
+ '<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
167
+ '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>'
168
+ "</styleSheet>"
169
+ )
170
+ with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as z:
171
+ z.writestr("[Content_Types].xml", content)
172
+ z.writestr("_rels/.rels", root_rels)
173
+ z.writestr("xl/workbook.xml", workbook)
174
+ z.writestr("xl/_rels/workbook.xml.rels", workbook_rels)
175
+ z.writestr("xl/styles.xml", styles)
176
+ for k, n in enumerate(names):
177
+ z.writestr(f"xl/worksheets/sheet{k + 1}.xml", _sheet_xml(*sheets[n]))
178
+
179
+
180
+ def write_table(
181
+ path, table, *, header=None, sheet: str = "data", precision: int | None = None
182
+ ) -> Path:
183
+ """Write a table to ``.csv``, ``.txt``/``.tsv``/``.dat`` or ``.xlsx`` (by its suffix);
184
+ ``precision`` significant digits for the text formats (all by default)."""
185
+ path = Path(path)
186
+ kind = FORMATS.get(path.suffix.lower())
187
+ if kind is None:
188
+ raise ValueError(f"write_table: a suffix among {sorted(FORMATS)}")
189
+ names, columns = as_columns(table, header)
190
+ path.parent.mkdir(parents=True, exist_ok=True)
191
+ if kind == "xlsx":
192
+ _write_xlsx(path, {sheet: (names, columns)})
193
+ elif kind == "csv":
194
+ with path.open("w", newline="", encoding="utf-8") as f:
195
+ w = csv.writer(f)
196
+ w.writerow(names)
197
+ for row in zip(*columns, strict=True):
198
+ w.writerow([_text(v, precision) for v in row])
199
+ else:
200
+ with path.open("w", encoding="utf-8") as f:
201
+ f.write("# " + "\t".join(names) + "\n")
202
+ for row in zip(*columns, strict=True):
203
+ f.write("\t".join(_text(v, precision) for v in row) + "\n")
204
+ return path
205
+
206
+
207
+ def write_tables(path, tables: dict, *, precision: int | None = None) -> list[Path]:
208
+ """Several tables: the sheets of one ``.xlsx`` workbook, or one text file each
209
+ (``<stem>_<name><suffix>``)."""
210
+ path = Path(path)
211
+ if path.suffix.lower() == ".xlsx":
212
+ path.parent.mkdir(parents=True, exist_ok=True)
213
+ _write_xlsx(path, {name: as_columns(t) for name, t in tables.items()})
214
+ return [path]
215
+ return [
216
+ write_table(path.with_name(f"{path.stem}_{name}{path.suffix}"), t, precision=precision)
217
+ for name, t in tables.items()
218
+ ]
219
+
220
+
221
+ def _number(text: str):
222
+ try:
223
+ value = float(text)
224
+ except ValueError:
225
+ return text
226
+ return (
227
+ int(value) if value.is_integer() and "." not in text and "e" not in text.lower() else value
228
+ )
229
+
230
+
231
+ def read_table(path, sheet: int = 0) -> dict[str, list]:
232
+ """The columns (name -> values) of a table written by :func:`write_table` (or any
233
+ simple ``.csv``, text or ``.xlsx`` table with a header row)."""
234
+ path = Path(path)
235
+ kind = FORMATS.get(path.suffix.lower())
236
+ if kind == "csv":
237
+ with path.open(newline="", encoding="utf-8") as f:
238
+ rows = list(csv.reader(f))
239
+ names, body = rows[0], rows[1:]
240
+ return {n: [_number(r[j]) for r in body] for j, n in enumerate(names)}
241
+ if kind == "txt":
242
+ lines = path.read_text(encoding="utf-8").splitlines()
243
+ names = lines[0].lstrip("#").strip().split("\t")
244
+ body = [line.split("\t") for line in lines[1:] if line.strip()]
245
+ return {n: [_number(r[j]) for r in body] for j, n in enumerate(names)}
246
+ if kind != "xlsx":
247
+ raise ValueError(f"read_table: a suffix among {sorted(FORMATS)}")
248
+ ns = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
249
+ with zipfile.ZipFile(path) as z:
250
+ shared = []
251
+ if "xl/sharedStrings.xml" in z.namelist():
252
+ root = ElementTree.fromstring(z.read("xl/sharedStrings.xml"))
253
+ shared = [
254
+ "".join(t.text or "" for t in si.iter(f"{{{ns['m']}}}t"))
255
+ for si in root.findall("m:si", ns)
256
+ ]
257
+ root = ElementTree.fromstring(z.read(f"xl/worksheets/sheet{sheet + 1}.xml"))
258
+ grid = []
259
+ for row in root.iter(f"{{{ns['m']}}}row"):
260
+ values = {}
261
+ for c in row.findall("m:c", ns):
262
+ ref, kind_c = c.get("r"), c.get("t")
263
+ col = 0
264
+ for ch in "".join(x for x in ref if x.isalpha()):
265
+ col = 26 * col + ord(ch) - 64
266
+ if kind_c == "inlineStr":
267
+ value = "".join(t.text or "" for t in c.iter(f"{{{ns['m']}}}t"))
268
+ elif kind_c == "s":
269
+ value = shared[int(c.find("m:v", ns).text)]
270
+ elif kind_c == "b":
271
+ value = c.find("m:v", ns).text == "1"
272
+ else:
273
+ v = c.find("m:v", ns)
274
+ value = _number(v.text) if v is not None else ""
275
+ values[col - 1] = value
276
+ grid.append(values)
277
+ names = [str(grid[0][j]) for j in sorted(grid[0])]
278
+ return {n: [r.get(j, "") for r in grid[1:]] for j, n in enumerate(names)}