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
morphogen/io/vtk.py ADDED
@@ -0,0 +1,701 @@
1
+ """VTK files: XML image data (.vti), legacy structured points (.vtk), unstructured grids (.vtu).
2
+
3
+ Voxel values are stored as cell data, x varying fastest. XML files use appended raw
4
+ binary data, optionally zlib-compressed; the reader also accepts base64 and ASCII data
5
+ written by other VTK-based tools.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import re
12
+ import struct
13
+ import xml.etree.ElementTree as ET
14
+ import zlib
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+
19
+ from morphogen.image import VoxelImage
20
+
21
+ _TO_VTK = {
22
+ "uint8": "UInt8",
23
+ "int8": "Int8",
24
+ "uint16": "UInt16",
25
+ "int16": "Int16",
26
+ "uint32": "UInt32",
27
+ "int32": "Int32",
28
+ "uint64": "UInt64",
29
+ "int64": "Int64",
30
+ "float32": "Float32",
31
+ "float64": "Float64",
32
+ }
33
+ _FROM_VTK = {v: np.dtype(k) for k, v in _TO_VTK.items()}
34
+ _BLOCK = 1 << 20
35
+
36
+
37
+ def _as_vtk_array(arr: np.ndarray) -> np.ndarray:
38
+ if arr.dtype == np.bool_:
39
+ return arr.astype(np.uint8)
40
+ if arr.dtype.name not in _TO_VTK:
41
+ raise ValueError(f"unsupported data type for VTK files: {arr.dtype}")
42
+ return arr
43
+
44
+
45
+ def _fortran_bytes(arr: np.ndarray) -> bytes:
46
+ """Bytes of a 3D array with x varying fastest, little-endian."""
47
+ a = np.ascontiguousarray(arr.transpose(2, 1, 0))
48
+ return a.astype(a.dtype.newbyteorder("<"), copy=False).tobytes()
49
+
50
+
51
+ def _encode_block(raw: bytes, compress: bool) -> bytes:
52
+ if not compress:
53
+ return struct.pack("<Q", len(raw)) + raw
54
+ chunks = [zlib.compress(raw[i : i + _BLOCK], 6) for i in range(0, len(raw), _BLOCK)] or [b""]
55
+ n = len(chunks)
56
+ last = len(raw) - (n - 1) * _BLOCK if raw else 0
57
+ partial = 0 if last == _BLOCK else last
58
+ header = struct.pack(f"<{3 + n}Q", n, _BLOCK, partial, *(len(c) for c in chunks))
59
+ return header + b"".join(chunks)
60
+
61
+
62
+ def _check_same_grid(images: list[VoxelImage]) -> VoxelImage:
63
+ ref = images[0]
64
+ for img in images[1:]:
65
+ if (
66
+ img.shape != ref.shape
67
+ or not np.allclose(img.spacing, ref.spacing)
68
+ or not np.allclose(img.origin, ref.origin)
69
+ ):
70
+ raise ValueError("all arrays of a file must share the same grid")
71
+ names = [img.name for img in images]
72
+ if len(set(names)) != len(names):
73
+ raise ValueError(f"array names must be unique, got {names}")
74
+ return ref
75
+
76
+
77
+ def write_vti(path, images, *, compress: bool = True) -> Path:
78
+ """Write one or several images on the same grid to a VTK XML ImageData file."""
79
+ images = [images] if isinstance(images, VoxelImage) else list(images)
80
+ ref = _check_same_grid(images)
81
+ nx, ny, nz = ref.shape
82
+ extent = f"0 {nx} 0 {ny} 0 {nz}"
83
+ origin = " ".join(repr(float(v)) for v in ref.origin)
84
+ spacing = " ".join(repr(float(v)) for v in ref.spacing)
85
+ blocks, arrays, offset = [], [], 0
86
+ for img in images:
87
+ arr = _as_vtk_array(img.data)
88
+ block = _encode_block(_fortran_bytes(arr), compress)
89
+ arrays.append(
90
+ f' <DataArray type="{_TO_VTK[arr.dtype.name]}" Name="{img.name}" '
91
+ f'format="appended" offset="{offset}"/>'
92
+ )
93
+ blocks.append(block)
94
+ offset += len(block)
95
+ compressor = ' compressor="vtkZLibDataCompressor"' if compress else ""
96
+ header = (
97
+ '<?xml version="1.0"?>\n'
98
+ f'<VTKFile type="ImageData" version="1.0" byte_order="LittleEndian" '
99
+ f'header_type="UInt64"{compressor}>\n'
100
+ f' <ImageData WholeExtent="{extent}" Origin="{origin}" Spacing="{spacing}">\n'
101
+ f' <Piece Extent="{extent}">\n'
102
+ f' <CellData Scalars="{images[0].name}">\n' + "\n".join(arrays) + "\n"
103
+ " </CellData>\n"
104
+ " </Piece>\n"
105
+ " </ImageData>\n"
106
+ ' <AppendedData encoding="raw">\n _'
107
+ )
108
+ path = Path(path)
109
+ with open(path, "wb") as f:
110
+ f.write(header.encode("ascii"))
111
+ for block in blocks:
112
+ f.write(block)
113
+ f.write(b"\n </AppendedData>\n</VTKFile>\n")
114
+ return path
115
+
116
+
117
+ # -- reading XML ----------------------------------------------------------------------
118
+
119
+
120
+ def _decode_binary(raw: bytes, dtype: np.dtype, count: int, header: str, compressed: bool):
121
+ """Decode a raw (already base64-decoded if needed) data block."""
122
+ hfmt, hsize = ("<Q", 8) if header == "UInt64" else ("<I", 4)
123
+ if not compressed:
124
+ (nbytes,) = struct.unpack(hfmt, raw[:hsize])
125
+ data = raw[hsize : hsize + nbytes]
126
+ else:
127
+ (nblocks,) = struct.unpack(hfmt, raw[:hsize])
128
+ values = struct.unpack(f"<{3 + nblocks}{hfmt[1]}", raw[: (3 + nblocks) * hsize])
129
+ sizes = values[3:]
130
+ pos = (3 + nblocks) * hsize
131
+ parts = []
132
+ for size in sizes:
133
+ parts.append(zlib.decompress(raw[pos : pos + size]))
134
+ pos += size
135
+ data = b"".join(parts)
136
+ return np.frombuffer(data, dtype=dtype.newbyteorder("<"), count=count)
137
+
138
+
139
+ def _b64len(nbytes: int) -> int:
140
+ return 4 * ((nbytes + 2) // 3)
141
+
142
+
143
+ def _decode_base64(text: bytes, header: str, compressed: bool) -> bytes:
144
+ """Decode a base64 data block (header and data encoded separately or together)."""
145
+ hsize = 8 if header == "UInt64" else 4
146
+ hfmt = "<Q" if header == "UInt64" else "<I"
147
+ # the first characters decode to the first value whatever the layout
148
+ first = base64.b64decode(text[: _b64len(hsize)])
149
+ if not compressed:
150
+ (nbytes,) = struct.unpack(hfmt, first[:hsize])
151
+ hbytes, dbytes = hsize, nbytes
152
+ else:
153
+ (nblocks,) = struct.unpack(hfmt, first[:hsize])
154
+ hbytes = (3 + nblocks) * hsize
155
+ head = base64.b64decode(text[: _b64len(hbytes)])[:hbytes]
156
+ dbytes = sum(struct.unpack(f"<{3 + nblocks}{hfmt[1]}", head)[3:])
157
+ # a separately encoded header ends with padding unless its size is a multiple of 3
158
+ separate = hbytes % 3 == 0 or text[_b64len(hbytes) - 1 : _b64len(hbytes)] == b"="
159
+ if separate:
160
+ head = base64.b64decode(text[: _b64len(hbytes)])[:hbytes]
161
+ start = _b64len(hbytes)
162
+ return head + base64.b64decode(text[start : start + _b64len(dbytes)])
163
+ return base64.b64decode(text[: _b64len(hbytes + dbytes)])[: hbytes + dbytes]
164
+
165
+
166
+ def _read_xml_arrays(path: Path):
167
+ content = Path(path).read_bytes()
168
+ split = content.find(b"<AppendedData")
169
+ if split >= 0:
170
+ xml_part = content[:split] + b"</VTKFile>"
171
+ tail = content[split:]
172
+ encoding = re.search(rb'encoding="(\w+)"', tail[:200])
173
+ encoding = encoding.group(1).decode() if encoding else "raw"
174
+ start = tail.find(b"_") + 1
175
+ appended = tail[start:]
176
+ else:
177
+ xml_part, appended, encoding = content, b"", "raw"
178
+ root = ET.fromstring(xml_part)
179
+ if root.get("byte_order", "LittleEndian") != "LittleEndian":
180
+ raise ValueError("only little-endian VTK XML files are supported")
181
+ header = root.get("header_type", "UInt32")
182
+ compressed = root.get("compressor") is not None
183
+ return root, appended, encoding, header, compressed
184
+
185
+
186
+ def _array_values(el, count, appended, encoding, header, compressed) -> np.ndarray:
187
+ dtype = _FROM_VTK[el.get("type")]
188
+ count = count * int(el.get("NumberOfComponents", "1"))
189
+ fmt = el.get("format", "ascii")
190
+ if fmt == "ascii":
191
+ return np.array((el.text or "").split(), dtype=dtype)[:count]
192
+ if fmt == "binary":
193
+ raw = _decode_base64("".join((el.text or "").split()).encode(), header, compressed)
194
+ return _decode_binary(raw, dtype, count, header, compressed)
195
+ offset = int(el.get("offset"))
196
+ if encoding == "base64":
197
+ raw = _decode_base64(appended[offset:], header, compressed)
198
+ else:
199
+ raw = appended[offset:]
200
+ return _decode_binary(raw, dtype, count, header, compressed)
201
+
202
+
203
+ def vti_names(path) -> list[str]:
204
+ """Names of the scalar arrays of a VTK XML ImageData file, from its header alone."""
205
+ head = b""
206
+ with open(path, "rb") as f:
207
+ while b"<AppendedData" not in head:
208
+ chunk = f.read(1 << 16)
209
+ if not chunk:
210
+ break
211
+ head += chunk
212
+ split = head.find(b"<AppendedData")
213
+ root = ET.fromstring(head[:split] + b"</VTKFile>" if split >= 0 else head)
214
+ piece = root.find("ImageData").find("Piece")
215
+ return [
216
+ el.get("Name", "data")
217
+ for section in ("CellData", "PointData")
218
+ if piece.find(section) is not None
219
+ for el in piece.find(section).findall("DataArray")
220
+ if int(el.get("NumberOfComponents", "1")) == 1
221
+ ]
222
+
223
+
224
+ def read_vti(path, names=None) -> list[VoxelImage]:
225
+ """Read the cell (or point) arrays of a VTK XML ImageData file (only those called
226
+ ``names``, if given: :func:`vti_names` lists them)."""
227
+ root, appended, encoding, header, compressed = _read_xml_arrays(Path(path))
228
+ image = root.find("ImageData")
229
+ ext = [int(v) for v in image.get("WholeExtent").split()]
230
+ npts = (ext[1] - ext[0] + 1, ext[3] - ext[2] + 1, ext[5] - ext[4] + 1)
231
+ origin = np.array([float(v) for v in image.get("Origin", "0 0 0").split()])
232
+ spacing = np.array([float(v) for v in image.get("Spacing", "1 1 1").split()])
233
+ origin = origin + spacing * np.array(ext[0::2])
234
+ piece = image.find("Piece")
235
+ out = []
236
+ for section, shape, shift in (
237
+ ("CellData", tuple(n - 1 for n in npts), 0.0),
238
+ ("PointData", npts, -0.5),
239
+ ):
240
+ node = piece.find(section)
241
+ if node is None:
242
+ continue
243
+ count = int(np.prod(shape))
244
+ for el in node.findall("DataArray"):
245
+ if int(el.get("NumberOfComponents", "1")) != 1:
246
+ continue
247
+ if names is not None and el.get("Name", "data") not in names:
248
+ continue
249
+ values = _array_values(el, count, appended, encoding, header, compressed)
250
+ data = values.reshape(shape[::-1]).transpose(2, 1, 0).copy()
251
+ out.append(
252
+ VoxelImage(
253
+ data=data,
254
+ spacing=tuple(spacing),
255
+ origin=tuple(origin + shift * spacing),
256
+ name=el.get("Name", "data"),
257
+ )
258
+ )
259
+ if not out and names is None:
260
+ raise ValueError(f"{path}: no scalar arrays found")
261
+ return out
262
+
263
+
264
+ # -- legacy VTK -------------------------------------------------------------------------
265
+
266
+ _TO_LEGACY = {
267
+ "uint8": "unsigned_char",
268
+ "int8": "char",
269
+ "uint16": "unsigned_short",
270
+ "int16": "short",
271
+ "uint32": "unsigned_int",
272
+ "int32": "int",
273
+ "uint64": "unsigned_long",
274
+ "int64": "long",
275
+ "float32": "float",
276
+ "float64": "double",
277
+ }
278
+ _FROM_LEGACY = {v: np.dtype(k) for k, v in _TO_LEGACY.items()}
279
+
280
+
281
+ def write_vtk(path, images, *, binary: bool = True) -> Path:
282
+ """Legacy VTK STRUCTURED_POINTS with cell data (big-endian binary or ASCII)."""
283
+ images = [images] if isinstance(images, VoxelImage) else list(images)
284
+ ref = _check_same_grid(images)
285
+ nx, ny, nz = ref.shape
286
+ path = Path(path)
287
+ with open(path, "wb") as f:
288
+ head = (
289
+ "# vtk DataFile Version 3.0\n"
290
+ f"morphoGen {ref.name}\n"
291
+ f"{'BINARY' if binary else 'ASCII'}\n"
292
+ "DATASET STRUCTURED_POINTS\n"
293
+ f"DIMENSIONS {nx + 1} {ny + 1} {nz + 1}\n"
294
+ f"ORIGIN {' '.join(repr(float(v)) for v in ref.origin)}\n"
295
+ f"SPACING {' '.join(repr(float(v)) for v in ref.spacing)}\n"
296
+ f"CELL_DATA {nx * ny * nz}\n"
297
+ )
298
+ f.write(head.encode("ascii"))
299
+ for img in images:
300
+ arr = _as_vtk_array(img.data)
301
+ f.write(f"SCALARS {img.name} {_TO_LEGACY[arr.dtype.name]} 1\n".encode("ascii"))
302
+ f.write(b"LOOKUP_TABLE default\n")
303
+ flat = np.ascontiguousarray(arr.transpose(2, 1, 0)).ravel()
304
+ if binary:
305
+ f.write(flat.astype(flat.dtype.newbyteorder(">")).tobytes())
306
+ f.write(b"\n")
307
+ else:
308
+ np.savetxt(f, flat.reshape(-1, 1), fmt="%.9g" if arr.dtype.kind == "f" else "%d")
309
+ return path
310
+
311
+
312
+ def read_vtk(path) -> list[VoxelImage]:
313
+ """Read scalar arrays of a legacy STRUCTURED_POINTS file (cell or point data)."""
314
+ content = Path(path).read_bytes()
315
+ pos = 0
316
+
317
+ def line():
318
+ nonlocal pos
319
+ end = content.index(b"\n", pos)
320
+ text = content[pos:end].decode("ascii", "replace").strip()
321
+ pos = end + 1
322
+ return text
323
+
324
+ line()
325
+ line()
326
+ mode = line().upper()
327
+ if line().upper() != "DATASET STRUCTURED_POINTS":
328
+ raise ValueError(f"{path}: only STRUCTURED_POINTS datasets are supported")
329
+ dims = origin = None
330
+ spacing = np.ones(3)
331
+ out, section, count = [], None, 0
332
+ while pos < len(content):
333
+ text = line()
334
+ if not text:
335
+ continue
336
+ key, *vals = text.split()
337
+ key = key.upper()
338
+ if key == "DIMENSIONS":
339
+ dims = np.array([int(v) for v in vals])
340
+ elif key == "ORIGIN":
341
+ origin = np.array([float(v) for v in vals])
342
+ elif key in ("SPACING", "ASPECT_RATIO"):
343
+ spacing = np.array([float(v) for v in vals])
344
+ elif key in ("CELL_DATA", "POINT_DATA"):
345
+ section, count = key, int(vals[0])
346
+ elif key == "METADATA":
347
+ while pos < len(content) and line():
348
+ pass
349
+ elif key == "FIELD":
350
+ for _ in range(int(vals[1])):
351
+ text = line()
352
+ while not text:
353
+ text = line()
354
+ name, ncomp, ntuples, tname = text.split()[:4]
355
+ dtype = _FROM_LEGACY[tname]
356
+ n = int(ncomp) * int(ntuples)
357
+ if mode == "BINARY":
358
+ be = dtype.newbyteorder(">")
359
+ values = np.frombuffer(content, dtype=be, count=n, offset=pos).astype(dtype)
360
+ pos += n * dtype.itemsize
361
+ else:
362
+ tokens = []
363
+ while len(tokens) < n:
364
+ tokens.extend(line().split())
365
+ values = np.array(tokens[:n], dtype=dtype)
366
+ if pos < len(content) and content[pos : pos + 1] == b"\n":
367
+ pos += 1
368
+ if content[pos : pos + 8] == b"METADATA":
369
+ line()
370
+ while pos < len(content) and line():
371
+ pass
372
+ if int(ncomp) != 1 or int(ntuples) != count:
373
+ continue
374
+ shape = tuple(dims - 1) if section == "CELL_DATA" else tuple(dims)
375
+ shift = 0.0 if section == "CELL_DATA" else -0.5
376
+ data = values.reshape(shape[::-1]).transpose(2, 1, 0).copy()
377
+ o = (origin if origin is not None else np.zeros(3)) + shift * spacing
378
+ out.append(
379
+ VoxelImage(data=data, spacing=tuple(spacing), origin=tuple(o), name=name)
380
+ )
381
+ elif key == "SCALARS":
382
+ name, dtype = vals[0], _FROM_LEGACY[vals[1]]
383
+ ncomp = int(vals[2]) if len(vals) > 2 else 1
384
+ if content[pos : pos + 12].upper() == b"LOOKUP_TABLE":
385
+ line()
386
+ n = count * ncomp
387
+ if mode == "BINARY":
388
+ be = dtype.newbyteorder(">")
389
+ values = np.frombuffer(content, dtype=be, count=n, offset=pos).astype(dtype)
390
+ pos += n * dtype.itemsize
391
+ else:
392
+ tokens = []
393
+ while len(tokens) < n:
394
+ tokens.extend(line().split())
395
+ values = np.array(tokens[:n], dtype=dtype)
396
+ if ncomp != 1:
397
+ continue
398
+ shape = tuple(dims - 1) if section == "CELL_DATA" else tuple(dims)
399
+ shift = 0.0 if section == "CELL_DATA" else -0.5
400
+ data = values.reshape(shape[::-1]).transpose(2, 1, 0).copy()
401
+ o = (origin if origin is not None else np.zeros(3)) + shift * spacing
402
+ out.append(VoxelImage(data=data, spacing=tuple(spacing), origin=tuple(o), name=name))
403
+ if not out:
404
+ raise ValueError(f"{path}: no scalar arrays found")
405
+ return out
406
+
407
+
408
+ # -- unstructured grids -----------------------------------------------------------------
409
+
410
+
411
+ def write_vtu(
412
+ path,
413
+ points,
414
+ cells,
415
+ cell_type: int,
416
+ cell_data: dict | None = None,
417
+ *,
418
+ point_data: dict | None = None,
419
+ field_data: dict | None = None,
420
+ compress: bool = True,
421
+ ) -> Path:
422
+ """VTK XML UnstructuredGrid with a single cell type.
423
+
424
+ Cell types: 12 hexahedron, 10 tetrahedron, 24 quadratic tetrahedron, 5 triangle.
425
+ ``cell_data`` and ``point_data`` map names to arrays of one value (shape ``(n,)``)
426
+ or several components (shape ``(n, k)``) per cell or point; ``field_data`` to small
427
+ arrays describing the whole grid.
428
+ """
429
+ points = np.ascontiguousarray(points, dtype=np.float64)
430
+ cells = np.ascontiguousarray(cells, dtype=np.int64)
431
+ n_cells, per_cell = cells.shape
432
+ arrays = [
433
+ ("Points", "Float64", 3, points.ravel(), "Points"),
434
+ ("connectivity", "Int64", 1, cells.ravel(), "Cells"),
435
+ ("offsets", "Int64", 1, np.arange(1, n_cells + 1, dtype=np.int64) * per_cell, "Cells"),
436
+ ("types", "UInt8", 1, np.full(n_cells, cell_type, dtype=np.uint8), "Cells"),
437
+ ]
438
+ sections = (("CellData", cell_data), ("PointData", point_data), ("FieldData", field_data))
439
+ for section, data in sections:
440
+ for name, values in (data or {}).items():
441
+ values = np.ascontiguousarray(values)
442
+ if section == "FieldData":
443
+ values = values.reshape(-1)
444
+ if values.dtype == np.bool_ or values.dtype.name not in _TO_VTK:
445
+ values = values.astype(np.int64)
446
+ ncomp = 1 if values.ndim == 1 else int(values.shape[1])
447
+ arrays.append((name, _TO_VTK[values.dtype.name], ncomp, values.ravel(), section))
448
+ xml = {"Points": [], "Cells": [], "CellData": [], "PointData": [], "FieldData": []}
449
+ blocks, offset = [], 0
450
+ for name, vtype, ncomp, values, section in arrays:
451
+ raw = values.astype(values.dtype.newbyteorder("<"), copy=False).tobytes()
452
+ block = _encode_block(raw, compress)
453
+ tuples = f' NumberOfTuples="{values.size}"' if section == "FieldData" else ""
454
+ indent = " " if section == "FieldData" else " "
455
+ xml[section].append(
456
+ f'{indent}<DataArray type="{vtype}" Name="{name}" NumberOfComponents="{ncomp}"'
457
+ f'{tuples} format="appended" offset="{offset}"/>'
458
+ )
459
+ blocks.append(block)
460
+ offset += len(block)
461
+ field = (
462
+ " <FieldData>\n" + "\n".join(xml["FieldData"]) + "\n </FieldData>\n"
463
+ if xml["FieldData"]
464
+ else ""
465
+ )
466
+ compressor = ' compressor="vtkZLibDataCompressor"' if compress else ""
467
+ header = (
468
+ '<?xml version="1.0"?>\n'
469
+ f'<VTKFile type="UnstructuredGrid" version="1.0" byte_order="LittleEndian" '
470
+ f'header_type="UInt64"{compressor}>\n'
471
+ " <UnstructuredGrid>\n"
472
+ + field
473
+ + f' <Piece NumberOfPoints="{len(points)}" NumberOfCells="{n_cells}">\n'
474
+ " <Points>\n" + "\n".join(xml["Points"]) + "\n </Points>\n"
475
+ " <Cells>\n" + "\n".join(xml["Cells"]) + "\n </Cells>\n"
476
+ " <CellData>\n" + "\n".join(xml["CellData"]) + "\n </CellData>\n"
477
+ " <PointData>\n" + "\n".join(xml["PointData"]) + "\n </PointData>\n"
478
+ " </Piece>\n"
479
+ " </UnstructuredGrid>\n"
480
+ ' <AppendedData encoding="raw">\n _'
481
+ )
482
+ path = Path(path)
483
+ with open(path, "wb") as f:
484
+ f.write(header.encode("ascii"))
485
+ for block in blocks:
486
+ f.write(block)
487
+ f.write(b"\n </AppendedData>\n</VTKFile>\n")
488
+ return path
489
+
490
+
491
+ def read_vtu(path) -> dict:
492
+ """Minimal reader of the files written by :func:`write_vtu` (points, cells, data)."""
493
+ root, appended, encoding, header, compressed = _read_xml_arrays(Path(path))
494
+ piece = root.find("UnstructuredGrid").find("Piece")
495
+ n_points = int(piece.get("NumberOfPoints"))
496
+ n_cells = int(piece.get("NumberOfCells"))
497
+
498
+ def values(el, count):
499
+ return _array_values(el, count, appended, encoding, header, compressed)
500
+
501
+ pts = values(piece.find("Points").find("DataArray"), n_points).reshape(n_points, 3)
502
+ cell_arrays = {el.get("Name"): el for el in piece.find("Cells").findall("DataArray")}
503
+ offsets = values(cell_arrays["offsets"], n_cells)
504
+ conn = values(cell_arrays["connectivity"], int(offsets[-1]) if n_cells else 0)
505
+ types = values(cell_arrays["types"], n_cells)
506
+ out = {}
507
+ for section, count in (("CellData", n_cells), ("PointData", n_points)):
508
+ data = {}
509
+ node = piece.find(section)
510
+ if node is not None:
511
+ for el in node.findall("DataArray"):
512
+ v = values(el, count)
513
+ ncomp = int(el.get("NumberOfComponents", "1"))
514
+ data[el.get("Name")] = v.reshape(count, ncomp) if ncomp > 1 else v
515
+ out[section] = data
516
+ fields = {}
517
+ node = root.find("UnstructuredGrid").find("FieldData")
518
+ if node is not None:
519
+ for el in node.findall("DataArray"):
520
+ fields[el.get("Name")] = values(el, int(el.get("NumberOfTuples", "1")))
521
+ per = int(offsets[0]) if n_cells else 0
522
+ return {
523
+ "points": pts,
524
+ "cells": conn.reshape(n_cells, per),
525
+ "types": types,
526
+ "cell_data": out["CellData"],
527
+ "point_data": out["PointData"],
528
+ "field_data": fields,
529
+ }
530
+
531
+
532
+ #: The number of nodes of the cell types of the legacy files (VTK's numbers)
533
+ _CELL_NODES = {1: 1, 3: 2, 5: 3, 9: 4, 10: 4, 12: 8, 13: 6, 14: 5, 22: 6, 23: 8, 24: 10, 25: 20}
534
+
535
+
536
+ def read_vtk_grid(path) -> dict:
537
+ """A legacy VTK file of an unstructured grid (ASCII or binary; the cells as counts
538
+ and nodes, or as the ``OFFSETS`` and ``CONNECTIVITY`` of VTK 5.1), e.g. an
539
+ animation of OpenRadioss converted by its ``anim_to_vtk``: ``points``, ``offsets``
540
+ (n + 1), ``connectivity``, ``types``, ``cell_data`` and ``point_data`` (name ->
541
+ values: ``SCALARS`` of one or more components, ``VECTORS``, ``TENSORS`` (n, 9),
542
+ ``NORMALS`` and the arrays of ``FIELD`` blocks) and ``field_data`` (the ``FIELD``
543
+ arrays given before the data of the points and cells). :func:`cells_of_type` picks
544
+ the cells of one type."""
545
+ content = Path(path).read_bytes()
546
+ pos = 0
547
+ size = len(content)
548
+
549
+ def line() -> str:
550
+ nonlocal pos
551
+ end = content.find(b"\n", pos)
552
+ end = size if end < 0 else end
553
+ text = content[pos:end].decode("latin-1").strip()
554
+ pos = end + 1
555
+ return text
556
+
557
+ def tokens(n: int, dtype) -> np.ndarray:
558
+ """``n`` values: ASCII tokens over as many lines as needed, or big-endian binary."""
559
+ nonlocal pos
560
+ dtype = np.dtype(dtype)
561
+ if binary:
562
+ values = np.frombuffer(content, dtype=dtype.newbyteorder(">"), count=n, offset=pos)
563
+ pos += n * dtype.itemsize
564
+ if pos < size and content[pos : pos + 1] == b"\n":
565
+ pos += 1
566
+ return values.astype(dtype)
567
+ found: list[bytes] = []
568
+ while len(found) < n:
569
+ if pos >= size:
570
+ raise ValueError(f"{path}: the file ends inside an array")
571
+ end = content.find(b"\n", pos)
572
+ end = size if end < 0 else end
573
+ found.extend(content[pos:end].split())
574
+ pos = end + 1
575
+ if len(found) > n:
576
+ raise ValueError(f"{path}: more values on a line than an array holds")
577
+ if dtype.kind in "iu":
578
+ return np.array([int(float(v)) for v in found], dtype=dtype)
579
+ return np.array([float(v) for v in found], dtype=dtype)
580
+
581
+ if not line().lower().startswith("# vtk datafile"):
582
+ raise ValueError(f"{path}: not a legacy VTK file")
583
+ line() # the title
584
+ mode = line().upper()
585
+ if mode not in ("ASCII", "BINARY"):
586
+ raise ValueError(f"{path}: ASCII or BINARY, got {mode!r}")
587
+ binary = mode == "BINARY"
588
+ text = line()
589
+ while not text and pos < size:
590
+ text = line()
591
+ if text.upper().split() != ["DATASET", "UNSTRUCTURED_GRID"]:
592
+ raise ValueError(f"{path}: not an UNSTRUCTURED_GRID dataset ({text!r})")
593
+
594
+ def dtype_of(name: str):
595
+ name = name.lower()
596
+ legacy = {**_FROM_LEGACY, "vtktypeint64": np.dtype("int64"),
597
+ "vtktypeint32": np.dtype("int32"), "vtkidtype": np.dtype("int64")} # fmt: skip
598
+ if name not in legacy:
599
+ raise ValueError(f"{path}: unknown data type {name!r}")
600
+ return legacy[name]
601
+
602
+ points = np.zeros((0, 3))
603
+ offsets = np.zeros(1, dtype=np.int64)
604
+ connectivity = np.zeros(0, dtype=np.int64)
605
+ types = np.zeros(0, dtype=np.int64)
606
+ data = {"FIELD": {}, "CELL_DATA": {}, "POINT_DATA": {}}
607
+ section, count = "FIELD", 0
608
+
609
+ def read_field(target: dict, n_arrays: int) -> None:
610
+ for _ in range(n_arrays):
611
+ head = line()
612
+ while not head and pos < size:
613
+ head = line()
614
+ name, ncomp, ntuples, kind = head.split()[:4]
615
+ values = tokens(int(ncomp) * int(ntuples), dtype_of(kind))
616
+ target[name] = values.reshape(int(ntuples), int(ncomp)) if int(ncomp) > 1 else values
617
+
618
+ while pos < size:
619
+ text = line()
620
+ if not text:
621
+ continue
622
+ key, *vals = text.split()
623
+ key = key.upper()
624
+ if key == "POINTS":
625
+ n = int(vals[0])
626
+ points = tokens(3 * n, dtype_of(vals[1])).astype(float).reshape(n, 3)
627
+ elif key == "CELLS":
628
+ n, total = int(vals[0]), int(vals[1])
629
+ nxt = content[pos : pos + 7].upper()
630
+ if nxt.startswith(b"OFFSETS"): # VTK 5.1: offsets then connectivity
631
+ kind = line().split()[1]
632
+ offsets = tokens(n, dtype_of(kind)).astype(np.int64)
633
+ kind = line().split()[1]
634
+ connectivity = tokens(total, dtype_of(kind)).astype(np.int64)
635
+ else: # the counts and nodes of each cell (32-bit integers in binary files)
636
+ flat = tokens(total, np.int32).astype(np.int64)
637
+ counts, k = [], 0
638
+ cells = []
639
+ while k < len(flat):
640
+ m = int(flat[k])
641
+ counts.append(m)
642
+ cells.append(flat[k + 1 : k + 1 + m])
643
+ k += m + 1
644
+ if len(counts) != n:
645
+ raise ValueError(f"{path}: {len(counts)} cells, the header says {n}")
646
+ offsets = np.concatenate([[0], np.cumsum(counts)]).astype(np.int64)
647
+ connectivity = np.concatenate(cells).astype(np.int64) if cells else connectivity
648
+ elif key == "CELL_TYPES":
649
+ types = tokens(int(vals[0]), np.int32).astype(np.int64)
650
+ elif key in ("CELL_DATA", "POINT_DATA"):
651
+ section, count = key, int(vals[0])
652
+ elif key == "FIELD":
653
+ read_field(data[section], int(vals[1]))
654
+ elif key in ("SCALARS", "VECTORS", "NORMALS", "TENSORS"):
655
+ name, kind = vals[0], vals[1]
656
+ ncomp = {"VECTORS": 3, "NORMALS": 3, "TENSORS": 9}.get(key)
657
+ if key == "SCALARS":
658
+ ncomp = int(vals[2]) if len(vals) > 2 else 1
659
+ if content[pos : pos + 12].upper().startswith(b"LOOKUP_TABLE"):
660
+ line()
661
+ values = tokens(count * ncomp, dtype_of(kind))
662
+ data[section][name] = values.reshape(count, ncomp) if ncomp > 1 else values
663
+ elif key == "LOOKUP_TABLE" and len(vals) > 1: # a colour table: skipped
664
+ tokens(4 * int(vals[1]), np.float32 if not binary else np.uint8)
665
+ elif key == "METADATA":
666
+ while pos < size and line():
667
+ pass
668
+ else:
669
+ raise ValueError(f"{path}: unknown keyword {key!r}")
670
+ if len(offsets) != len(types) + 1:
671
+ if len(offsets) == len(types) and len(types): # offsets given without the start
672
+ offsets = np.concatenate([[0], offsets])
673
+ elif len(types) or len(offsets) > 1:
674
+ raise ValueError(f"{path}: {len(types)} cell types for {len(offsets) - 1} cells")
675
+ return {
676
+ "points": points,
677
+ "offsets": offsets,
678
+ "connectivity": connectivity,
679
+ "types": types,
680
+ "cell_data": data["CELL_DATA"],
681
+ "point_data": data["POINT_DATA"],
682
+ "field_data": data["FIELD"],
683
+ }
684
+
685
+
686
+ def cells_of_type(grid: dict, cell_type: int) -> tuple[np.ndarray, np.ndarray]:
687
+ """The cells of one VTK type of a grid of :func:`read_vtk_grid`: their nodes (n, k)
688
+ and their indices among the cells (for their data)."""
689
+ types = np.asarray(grid["types"])
690
+ picked = np.flatnonzero(types == int(cell_type))
691
+ offsets = np.asarray(grid["offsets"])
692
+ if not len(picked):
693
+ k = _CELL_NODES.get(int(cell_type), 0)
694
+ return np.zeros((0, k), dtype=np.int64), picked
695
+ starts, ends = offsets[picked], offsets[picked + 1]
696
+ widths = np.unique(ends - starts)
697
+ if len(widths) != 1:
698
+ raise ValueError(f"cells of type {cell_type} with {widths.tolist()} nodes")
699
+ k = int(widths[0])
700
+ index = starts[:, None] + np.arange(k)[None, :]
701
+ return np.asarray(grid["connectivity"])[index], picked