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/ebsd.py ADDED
@@ -0,0 +1,881 @@
1
+ """Orientation maps of electron backscatter diffraction (EBSD): the text files of the
2
+ acquisition systems, and the grains of a map.
3
+
4
+ Two formats are read and written: ``.ang`` (EDAX/TSL OIM: Euler angles in radians, a
5
+ header of comments) and ``.ctf`` (Oxford Instruments/HKL Channel 5: Euler angles in
6
+ degrees, a header of keys). A map (:class:`EBSDMap`) holds, at each point of a
7
+ rectangular grid of steps ``(dx, dy)``, the phase (0: a point that was not indexed) and
8
+ the orientation of the crystal (Bunge Euler angles, degrees), with the measures of
9
+ quality of the file; its rows are those of the file, from the top of the image. A
10
+ hexagonal grid (``.ang``) is read row by row onto a rectangular one of the same steps:
11
+ every other row is then half a step away from where it was measured.
12
+
13
+ **Axes.** The axes of a map are those of its image as the acquisition systems show it:
14
+ the first to the right (along the columns), the second upwards (against the rows, which
15
+ the files number from the top), the third towards the viewer, out of the sample. A
16
+ ``.ctf`` file gives the orientations in these axes. An ``.ang`` file gives them in axes
17
+ turned about the third one, by an angle that depends on a setting of the software
18
+ (:data:`ANG_SETTINGS`): with the usual one its first axis (the rolling direction) points
19
+ down the image and its second one to the right. The maps are read with their
20
+ orientations brought into the axes of the image (``axes="map"``), so that the grains of
21
+ a polycrystal and their lattices are in the same axes; ``axes="file"`` keeps the angles
22
+ of the file, and :meth:`EBSDMap.turned` brings the orientations into any other axes.
23
+
24
+ The axes of the crystals are those of morphoGen (:mod:`morphogen.texture`): for the
25
+ hexagonal and trigonal lattices the first axis along ``a = [2 -1 -1 0]``, as in an
26
+ ``.ang`` file; a ``.ctf`` file has it along ``a* = [1 0 -1 0]``, and its crystals are
27
+ turned by 30 degrees about ``c`` when they are read (and back when they are written).
28
+
29
+ **Grains** (:meth:`EBSDMap.grains`). Two neighbouring points of the same phase belong to
30
+ one grain when their disorientation (:func:`morphogen.texture.disorientation`, with the
31
+ symmetries of the phase) is below a threshold; the grains are the connected sets of such
32
+ points. Each has its mean orientation (:func:`morphogen.texture.mean_orientation`) and
33
+ the spread of its points about it. The grains of fewer points than a minimum are
34
+ dropped, and the points without a grain (those that were not indexed, the dropped ones)
35
+ take the grain of the nearest point that has one. The result (:class:`Grains`) gives a
36
+ polycrystal (:meth:`Grains.microstructure`: the map extruded through a thickness, with
37
+ the labels and the orientations of its grains) for the solvers of the homogenization.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import math
43
+ import re
44
+ from dataclasses import dataclass
45
+ from pathlib import Path
46
+
47
+ import numpy as np
48
+ from numba import njit
49
+ from scipy import ndimage
50
+
51
+ from morphogen.domain import Domain
52
+ from morphogen.orientations import euler_to_matrix, matrix_to_euler, uniform_unit_vectors
53
+ from morphogen.seeding import make_rng
54
+ from morphogen.texture import CLASSES, _nearest_rotation, _turns, ipf_colours, symmetries
55
+
56
+ #: The symmetry of a phase in an ``.ang`` file (the point group of its proper rotations)
57
+ #: as a Laue class of :data:`morphogen.texture.CLASSES`
58
+ ANG_SYMMETRY = {43: "cubic", 23: "m-3", 62: "hexagonal", 6: "6/m", 42: "tetragonal",
59
+ 4: "4/m", 32: "trigonal", 3: "-3", 22: "orthorhombic", 2: "monoclinic",
60
+ 1: "triclinic"} # fmt: skip
61
+ #: The Laue group of a phase in a ``.ctf`` file
62
+ CTF_LAUE = {11: "cubic", 10: "m-3", 9: "hexagonal", 8: "6/m", 7: "trigonal", 6: "-3",
63
+ 5: "tetragonal", 4: "4/m", 3: "orthorhombic", 2: "monoclinic",
64
+ 1: "triclinic"} # fmt: skip
65
+ #: The settings of the axes of the orientations of an ``.ang`` file (numbered as by the
66
+ #: reader of MTEX): the angle (degrees) about the third axis from them to the axes of
67
+ #: the image of the map. The first axis of the orientations points down the image with
68
+ #: the setting 1 (the usual one), up with the setting 2, to the right with the setting 3
69
+ #: and to the left with the setting 4
70
+ ANG_SETTINGS = {1: 90.0, 2: -90.0, 3: 0.0, 4: 180.0}
71
+ #: The axes in which the orientations of a map are read and written
72
+ AXES = ("map", "file")
73
+ #: The classes whose first axis is along a* in a ``.ctf`` file and along a in morphoGen
74
+ _ABOUT_C = ("hexagonal", "6/m", "trigonal", "-3")
75
+
76
+
77
+ def _check_axes(axes: str, setting: int = 1) -> None:
78
+ if axes not in AXES:
79
+ raise ValueError(f"axes: one of {AXES}, got {axes!r}")
80
+ if setting not in ANG_SETTINGS:
81
+ raise ValueError(f"setting: one of {tuple(ANG_SETTINGS)}, got {setting!r}")
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class Phase:
86
+ """A phase of a map: its name, its Laue class (one of
87
+ :data:`morphogen.texture.CLASSES`; none when the file gives another one: its
88
+ orientations are then compared without symmetry) and the constants of its cell (a,
89
+ b, c and the three angles)."""
90
+
91
+ name: str = ""
92
+ lattice: str | None = "cubic"
93
+ cell: tuple[float, ...] = (1.0, 1.0, 1.0, 90.0, 90.0, 90.0)
94
+
95
+ def __post_init__(self) -> None:
96
+ if self.lattice is not None and self.lattice not in CLASSES:
97
+ raise ValueError(f"phase: a lattice among {CLASSES} (or none), got {self.lattice!r}")
98
+ object.__setattr__(self, "cell", tuple(float(v) for v in self.cell))
99
+
100
+ @property
101
+ def c_over_a(self) -> float:
102
+ """The ratio of the third constant of the cell to the first."""
103
+ return self.cell[2] / self.cell[0] if len(self.cell) >= 3 and self.cell[0] > 0 else 1.0
104
+
105
+
106
+ @njit(cache=True)
107
+ def _root(parent, i):
108
+ while parent[i] != i:
109
+ parent[i] = parent[parent[i]]
110
+ i = parent[i]
111
+ return i
112
+
113
+
114
+ @njit(cache=True)
115
+ def _close(a, b, ops, count, cosine) -> bool:
116
+ """Whether the disorientation of two crystals is below the angle of ``cosine``."""
117
+ best = -4.0
118
+ for s in range(count):
119
+ trace = 0.0
120
+ for i in range(3):
121
+ for j in range(3):
122
+ d = b[j, 0] * a[i, 0] + b[j, 1] * a[i, 1] + b[j, 2] * a[i, 2]
123
+ trace += ops[s, i, j] * d
124
+ if trace > best:
125
+ best = trace
126
+ return 0.5 * (best - 1.0) >= cosine
127
+
128
+
129
+ @njit(cache=True)
130
+ def _segment(g, phase, ops, counts, cosine):
131
+ """The connected sets of neighbouring points of one phase whose disorientation is
132
+ below the angle of ``cosine``: a label per point (-1: not indexed), from 0."""
133
+ ny, nx = phase.shape
134
+ parent = np.arange(ny * nx)
135
+ for iy in range(ny):
136
+ for ix in range(nx):
137
+ p = phase[iy, ix]
138
+ if p <= 0:
139
+ continue
140
+ i = iy * nx + ix
141
+ if ix + 1 < nx and phase[iy, ix + 1] == p:
142
+ if _close(g[iy, ix], g[iy, ix + 1], ops[p], counts[p], cosine):
143
+ a, b = _root(parent, i), _root(parent, i + 1)
144
+ if a != b:
145
+ parent[max(a, b)] = min(a, b)
146
+ if iy + 1 < ny and phase[iy + 1, ix] == p:
147
+ if _close(g[iy, ix], g[iy + 1, ix], ops[p], counts[p], cosine):
148
+ a, b = _root(parent, i), _root(parent, i + nx)
149
+ if a != b:
150
+ parent[max(a, b)] = min(a, b)
151
+ labels = np.full(ny * nx, -1, dtype=np.int32)
152
+ count = 0
153
+ for i in range(ny * nx):
154
+ if phase[i // nx, i % nx] <= 0:
155
+ continue
156
+ r = _root(parent, i)
157
+ if labels[r] < 0:
158
+ labels[r] = count
159
+ count += 1
160
+ labels[i] = labels[r]
161
+ return labels.reshape(ny, nx), count
162
+
163
+
164
+ @njit(cache=True)
165
+ def _grain_sums(g, labels, phase, reference, ops, counts, total, angle):
166
+ """For each grain, the sum of the matrices of its points (``total``), each taken as
167
+ the symmetric equivalent nearest to the reference of the grain, and the sum of their
168
+ disorientations from it (``angle``, radians)."""
169
+ total[:, :, :] = 0.0
170
+ angle[:] = 0.0
171
+ ny, nx = labels.shape
172
+ for iy in range(ny):
173
+ for ix in range(nx):
174
+ k = labels[iy, ix]
175
+ if k < 0:
176
+ continue
177
+ p = phase[iy, ix]
178
+ best = -4.0
179
+ which = 0
180
+ for s in range(counts[p]):
181
+ trace = 0.0
182
+ for i in range(3):
183
+ for j in range(3):
184
+ d = 0.0
185
+ for m in range(3):
186
+ d += g[iy, ix, j, m] * reference[k, i, m]
187
+ trace += ops[p, s, i, j] * d
188
+ if trace > best:
189
+ best = trace
190
+ which = s
191
+ for i in range(3):
192
+ for m in range(3):
193
+ e = 0.0
194
+ for j in range(3):
195
+ e += ops[p, which, i, j] * g[iy, ix, j, m]
196
+ total[k, i, m] += e
197
+ angle[k] += math.acos(min(1.0, max(-1.0, 0.5 * (best - 1.0))))
198
+
199
+
200
+ @dataclass(frozen=True)
201
+ class Grains:
202
+ """The grains of an orientation map (:meth:`EBSDMap.grains`)."""
203
+
204
+ #: The grain of each point, ``(ny, nx)``; -1: none
205
+ labels: np.ndarray
206
+ #: The mean orientation of each grain (Bunge Euler angles, degrees), ``(n, 3)``
207
+ orientations: np.ndarray
208
+ #: The phase of each grain (from 1: ``phases[phase - 1]``)
209
+ phase: np.ndarray
210
+ #: The number of points of each grain
211
+ size: np.ndarray
212
+ #: The mean disorientation (degrees) of the indexed points of each grain from its
213
+ #: mean orientation
214
+ spread: np.ndarray
215
+ #: The steps of the grid along x and y, and its unit of length
216
+ step: tuple[float, float]
217
+ #: The phases of the map
218
+ phases: tuple[Phase, ...] = ()
219
+ unit: str = "um"
220
+
221
+ @property
222
+ def count(self) -> int:
223
+ return len(self.size)
224
+
225
+ @property
226
+ def areas(self) -> np.ndarray:
227
+ """The area of each grain."""
228
+ return self.size * (self.step[0] * self.step[1])
229
+
230
+ @property
231
+ def diameters(self) -> np.ndarray:
232
+ """The diameter of the disc of the area of each grain."""
233
+ return 2.0 * np.sqrt(self.areas / math.pi)
234
+
235
+ def lattice(self, phase: int = 1) -> str:
236
+ """The Laue class of a phase (``"triclinic"`` when the file does not give it)."""
237
+ known = self.phases[phase - 1].lattice if 0 < phase <= len(self.phases) else None
238
+ return known or "triclinic"
239
+
240
+ def table(self) -> dict:
241
+ """The grains as the columns of a table (:func:`morphogen.io.write_table`): the
242
+ number of each grain, its phase, its Bunge angles (degrees), its number of
243
+ points, its area, its diameter and the spread of its orientations (degrees)."""
244
+ return {
245
+ "grain": np.arange(self.count),
246
+ "phase": self.phase,
247
+ "phi1": self.orientations[:, 0],
248
+ "Phi": self.orientations[:, 1],
249
+ "phi2": self.orientations[:, 2],
250
+ "points": self.size,
251
+ "area": self.areas,
252
+ "diameter": self.diameters,
253
+ "spread": self.spread,
254
+ }
255
+
256
+ def boundaries(self):
257
+ """The boundaries between the grains of one phase: the pairs of neighbouring
258
+ grains ``(b, 2)``, the length of the boundary of each pair (the sides of the
259
+ points that they share, in the unit of the map) and its disorientation
260
+ (degrees, with the symmetries of the phase)."""
261
+ from morphogen.texture import disorientation
262
+
263
+ lab = self.labels
264
+ found: dict[tuple[int, int], float] = {}
265
+ # (neighbours along the columns share a side of the step of the rows, and conversely)
266
+ sides = ((lab[:, :-1], lab[:, 1:], self.step[1]), (lab[:-1, :], lab[1:, :], self.step[0]))
267
+ for first, second, length in sides:
268
+ keep = (first != second) & (first >= 0) & (second >= 0)
269
+ a, b = first[keep], second[keep]
270
+ keep = self.phase[a] == self.phase[b]
271
+ low, high = np.minimum(a[keep], b[keep]), np.maximum(a[keep], b[keep])
272
+ pairs, counts = np.unique(np.stack([low, high], axis=1), axis=0, return_counts=True)
273
+ for (i, j), n in zip(pairs.tolist(), counts.tolist(), strict=True):
274
+ found[(i, j)] = found.get((i, j), 0.0) + n * length
275
+ if not found:
276
+ return np.empty((0, 2), dtype=np.int64), np.empty(0), np.empty(0)
277
+ pairs = np.array(sorted(found), dtype=np.int64)
278
+ lengths = np.array([found[tuple(p)] for p in pairs.tolist()])
279
+ angles = np.empty(len(pairs))
280
+ g = euler_to_matrix(self.orientations)
281
+ for k in np.unique(self.phase[pairs[:, 0]]):
282
+ of = self.phase[pairs[:, 0]] == k
283
+ angles[of] = disorientation(g[pairs[of, 0]], g[pairs[of, 1]], self.lattice(int(k)))
284
+ return pairs, lengths, angles
285
+
286
+ def summary(self, *, poles=None, halfwidth: float = 10.0) -> dict:
287
+ """The numbers of the grains of a map, phase by phase: the grains, their share
288
+ of the area, their mean diameter (by number and by area), the mean spread inside
289
+ them, the number of their boundaries with the mean of their disorientations by
290
+ length (40.74 degrees for cubic crystals at random) and, for the cubic and
291
+ hexagonal phases, the largest density of the pole figures of the families
292
+ ``poles`` (lists of indices; {100}, {110}, {111} or (0001), {10-10}, {10-11} by
293
+ default), the grains weighted by their areas, in multiples of a random texture."""
294
+ from morphogen.texture import pole_figure
295
+
296
+ pairs, lengths, angles = self.boundaries()
297
+ out = {"grains": self.count, "unit": self.unit, "phases": []}
298
+ defaults = {"cubic": ((1, 0, 0), (1, 1, 0), (1, 1, 1)),
299
+ "hexagonal": ((0, 0, 0, 1), (1, 0, -1, 0), (1, 0, -1, 1))} # fmt: skip
300
+ for k, phase in enumerate(self.phases, start=1):
301
+ of = self.phase == k
302
+ if not of.any():
303
+ continue
304
+ areas = self.areas[of]
305
+ between = of[pairs[:, 0]] if len(pairs) else np.zeros(0, dtype=bool)
306
+ entry = {
307
+ "phase": k,
308
+ "name": phase.name or f"phase {k}",
309
+ "lattice": self.lattice(k),
310
+ "grains": int(of.sum()),
311
+ "area_fraction": float(areas.sum() / self.areas.sum()),
312
+ "mean_diameter": float(self.diameters[of].mean()),
313
+ "mean_diameter_by_area": float(np.sum(areas * self.diameters[of]) / areas.sum()),
314
+ "mean_spread": float(self.spread[of].mean()),
315
+ "boundaries": int(between.sum()),
316
+ }
317
+ if between.any():
318
+ entry["mean_disorientation"] = float(
319
+ np.sum(lengths[between] * angles[between]) / lengths[between].sum()
320
+ )
321
+ family = {"m-3": "cubic", "6/m": "hexagonal"}.get(entry["lattice"], entry["lattice"])
322
+ if family in defaults:
323
+ ratio = phase.c_over_a if family == "hexagonal" else None
324
+ entry["pole_figures"] = {}
325
+ for indices in poles or defaults[family]:
326
+ figure = pole_figure(self.orientations[of], indices, family, weights=areas,
327
+ halfwidth=halfwidth, c_over_a=ratio) # fmt: skip
328
+ name = "".join(str(int(v)) for v in indices)
329
+ entry["pole_figures"][name] = figure.maximum
330
+ out["phases"].append(entry)
331
+ return out
332
+
333
+ def microstructure(self, thickness: float | None = None, *, periodic: bool = False):
334
+ """The polycrystal of the map: a lattice of one cell through a thickness (the
335
+ smaller step by default), each cell with the phase, the label and the
336
+ orientation of its grain (:class:`~morphogen.models.lattice_field.LatticeField`;
337
+ the points without a grain are of phase 0), in the axes of the image of the map:
338
+ the last row of the map along the first axis, at the origin."""
339
+ from morphogen.models.lattice_field import LatticeField
340
+
341
+ ny, nx = self.labels.shape
342
+ depth = float(min(self.step) if thickness is None else thickness)
343
+ domain = Domain((nx * self.step[0], ny * self.step[1], depth), periodic=periodic,
344
+ unit=self.unit) # fmt: skip
345
+ labels = np.ascontiguousarray(self.labels[::-1].T[:, :, None])
346
+ phases = np.where(labels >= 0, self.phase[np.maximum(labels, 0)], 0).astype(np.uint8)
347
+ return LatticeField(domain, phases, labels=labels, orientations=self.orientations)
348
+
349
+
350
+ class EBSDMap:
351
+ """An orientation map on a rectangular grid.
352
+
353
+ Parameters
354
+ ----------
355
+ euler
356
+ Bunge Euler angles (degrees) of the crystal of each point, ``(ny, nx, 3)``: the
357
+ rows of the file, from the top of the image (the second axis points against
358
+ them), and the columns along the first axis.
359
+ phase
360
+ The phase of each point, ``(ny, nx)``: 0 for a point that was not indexed, ``k``
361
+ for the phase ``phases[k - 1]``.
362
+ step
363
+ The steps of the grid along x and y.
364
+ phases
365
+ The phases of the map (one cubic phase by default).
366
+ quality
367
+ Other arrays ``(ny, nx)`` of the file by name (``"iq"`` and ``"ci"`` of an
368
+ ``.ang`` file; ``"bands"``, ``"error"``, ``"mad"``, ``"bc"`` and ``"bs"`` of a
369
+ ``.ctf`` file).
370
+ """
371
+
372
+ def __init__(self, euler, phase, step=(1.0, 1.0), phases=None, quality=None,
373
+ unit: str = "um") -> None: # fmt: skip
374
+ self.euler = np.ascontiguousarray(euler, dtype=float)
375
+ self.phase = np.ascontiguousarray(phase, dtype=np.int32)
376
+ if self.euler.ndim != 3 or self.euler.shape[2] != 3:
377
+ raise ValueError("euler: an array (ny, nx, 3)")
378
+ if self.phase.shape != self.euler.shape[:2]:
379
+ raise ValueError("phase: an array (ny, nx), as the Euler angles")
380
+ self.step = (float(step[0]), float(step[1]))
381
+ if not (self.step[0] > 0 and self.step[1] > 0):
382
+ raise ValueError("step: two positive lengths")
383
+ self.phases = tuple(phases) if phases else (Phase(),)
384
+ if self.phase.max(initial=0) > len(self.phases) or self.phase.min(initial=0) < 0:
385
+ raise ValueError("phase: from 0 (not indexed) to the number of phases")
386
+ self.quality = {k: np.asarray(v) for k, v in (quality or {}).items()}
387
+ for name, values in self.quality.items():
388
+ if values.shape != self.phase.shape:
389
+ raise ValueError(f"quality {name!r}: an array (ny, nx)")
390
+ self.unit = str(unit)
391
+
392
+ # -- description ---------------------------------------------------------------------
393
+
394
+ @property
395
+ def shape(self) -> tuple[int, int]:
396
+ """The numbers of rows and of columns."""
397
+ return self.phase.shape
398
+
399
+ @property
400
+ def size(self) -> tuple[float, float]:
401
+ """The lengths of the map along x and y."""
402
+ return (self.shape[1] * self.step[0], self.shape[0] * self.step[1])
403
+
404
+ @property
405
+ def indexed(self) -> np.ndarray:
406
+ """The points that were indexed."""
407
+ return self.phase > 0
408
+
409
+ def lattice(self, phase: int = 1) -> str:
410
+ """The Laue class of a phase (``"triclinic"`` when the file does not give it)."""
411
+ return self.phases[phase - 1].lattice or "triclinic"
412
+
413
+ def orientations(self, phase: int | None = None) -> np.ndarray:
414
+ """The Euler angles ``(n, 3)`` of the indexed points (of one phase)."""
415
+ mask = self.indexed if phase is None else self.phase == phase
416
+ return self.euler[mask]
417
+
418
+ def colours(self, direction=(0.0, 0.0, 1.0)) -> np.ndarray:
419
+ """The map as an image ``(ny, nx, 3)`` of colours (from 0 to 1): each point by the
420
+ direction of its crystal along a direction of the sample
421
+ (:func:`morphogen.texture.ipf_colours`); black where it was not indexed, grey for
422
+ a phase whose lattice has no colour key."""
423
+ out = np.zeros((*self.shape, 3))
424
+ for k, phase in enumerate(self.phases, start=1):
425
+ mask = self.phase == k
426
+ if not mask.any():
427
+ continue
428
+ key = {"cubic": "cubic", "m-3": "cubic", "hexagonal": "hexagonal",
429
+ "6/m": "hexagonal"}.get(phase.lattice) # fmt: skip
430
+ if key:
431
+ out[mask] = ipf_colours(self.euler[mask], direction, key)
432
+ else:
433
+ out[mask] = 0.5
434
+ return out
435
+
436
+ # -- other maps ----------------------------------------------------------------------
437
+
438
+ def _with(self, **changes) -> EBSDMap:
439
+ fields = {"euler": self.euler, "phase": self.phase, "step": self.step,
440
+ "phases": self.phases, "quality": self.quality, "unit": self.unit} # fmt: skip
441
+ fields.update(changes)
442
+ return EBSDMap(**fields)
443
+
444
+ def turned(self, rotation) -> EBSDMap:
445
+ """The map with its orientations in other axes of the sample: ``rotation`` (3 x
446
+ 3) gives the new axes in the old ones (its rows), so that ``g`` becomes ``g
447
+ rotation^T``. The positions of the points are not changed."""
448
+ r = np.asarray(rotation, dtype=float).reshape(3, 3)
449
+ if not np.allclose(r @ r.T, np.eye(3), atol=1e-9) or np.linalg.det(r) < 0:
450
+ raise ValueError("rotation: a rotation matrix")
451
+ g = euler_to_matrix(self.euler.reshape(-1, 3)) @ r.T
452
+ euler = matrix_to_euler(g).reshape(self.euler.shape)
453
+ return self._with(euler=np.where(self.indexed[..., None], euler, 0.0))
454
+
455
+ def _about_c(self, angle: float) -> EBSDMap:
456
+ """The map with the crystals of its hexagonal and trigonal phases described in
457
+ axes turned by ``angle`` degrees about ``c`` (the third Euler angle shifted)."""
458
+ euler = self.euler.copy()
459
+ for k, phase in enumerate(self.phases, start=1):
460
+ if phase.lattice in _ABOUT_C:
461
+ mask = self.phase == k
462
+ euler[mask, 2] = np.mod(euler[mask, 2] - angle, 360.0)
463
+ return self._with(euler=euler)
464
+
465
+ def _about_normal(self, angle: float) -> EBSDMap:
466
+ """The map with its orientations in axes of the sample turned by ``angle``
467
+ degrees about the third one (the first Euler angle shifted)."""
468
+ if angle == 0.0:
469
+ return self
470
+ euler = self.euler.copy()
471
+ mask = self.indexed
472
+ euler[mask, 0] = np.mod(euler[mask, 0] - angle, 360.0)
473
+ return self._with(euler=euler)
474
+
475
+ def cropped(self, columns: slice, rows: slice) -> EBSDMap:
476
+ """The part of the map of some columns and rows."""
477
+ quality = {k: v[rows, columns] for k, v in self.quality.items()}
478
+ return self._with(euler=self.euler[rows, columns], phase=self.phase[rows, columns],
479
+ quality=quality) # fmt: skip
480
+
481
+ @classmethod
482
+ def from_grains(cls, labels, orientations, step=(1.0, 1.0), *, phase=None, phases=None,
483
+ unit: str = "um") -> EBSDMap: # fmt: skip
484
+ """The map of an image of labels ``(ny, nx)``, its rows from the top, whose
485
+ grains have the given orientations (and phases, 1 by default); negative labels
486
+ are points that were not indexed. The section of a computed polycrystal
487
+ (:func:`synthetic_map`), to be written for the tools that read the maps."""
488
+ lab = np.asarray(labels)
489
+ e = np.asarray(orientations, dtype=float).reshape(-1, 3)
490
+ of = np.ones(len(e), dtype=np.int32) if phase is None else np.asarray(phase, np.int32)
491
+ inside = lab >= 0
492
+ index = np.maximum(lab, 0)
493
+ return cls(np.where(inside[..., None], e[index], 0.0), np.where(inside, of[index], 0),
494
+ step, phases, unit=unit) # fmt: skip
495
+
496
+ # -- grains --------------------------------------------------------------------------
497
+
498
+ def grains(self, threshold: float = 5.0, *, min_size: int = 1, fill: bool = True) -> Grains:
499
+ """The grains of the map: connected sets of neighbouring points of one phase
500
+ whose disorientation is below ``threshold`` degrees, those of fewer than
501
+ ``min_size`` points dropped; with ``fill`` the points without a grain take that
502
+ of the nearest point that has one."""
503
+ if not 0.0 < threshold < 180.0:
504
+ raise ValueError("threshold: an angle between 0 and 180 degrees")
505
+ ny, nx = self.shape
506
+ groups = [np.eye(3)[None]] + [symmetries(p.lattice or "triclinic") for p in self.phases]
507
+ counts = np.array([len(s) for s in groups], dtype=np.int64)
508
+ ops = np.zeros((len(groups), counts.max(), 3, 3))
509
+ for k, s in enumerate(groups):
510
+ ops[k, : len(s)] = s
511
+ g = euler_to_matrix(self.euler.reshape(-1, 3)).reshape(ny, nx, 3, 3)
512
+ labels, count = _segment(g, self.phase, ops, counts, math.cos(math.radians(threshold)))
513
+ size = np.bincount(labels[labels >= 0], minlength=count)
514
+ if min_size > 1: # the small grains: dropped, the others numbered again
515
+ keep = size >= min_size
516
+ new = np.where(keep, np.cumsum(keep) - 1, -1).astype(np.int32)
517
+ labels = np.where(labels >= 0, new[np.maximum(labels, 0)], -1).astype(np.int32)
518
+ count = int(keep.sum())
519
+ if count == 0:
520
+ raise ValueError(
521
+ "grains: no grain in the map (no point indexed, or min_size too large)"
522
+ )
523
+ measured = labels >= 0
524
+ # the phase and a reference of each grain: its first point
525
+ first = np.full(count, -1, dtype=np.int64)
526
+ flat = labels.ravel()
527
+ order = np.flatnonzero(flat >= 0)
528
+ first[flat[order][::-1]] = order[::-1]
529
+ phase = self.phase.ravel()[first].astype(np.int32)
530
+ reference = g.reshape(-1, 3, 3)[first].copy()
531
+ total, angle = np.empty((count, 3, 3)), np.empty(count)
532
+ for _ in range(2):
533
+ _grain_sums(g, labels, self.phase, reference, ops, counts, total, angle)
534
+ reference = np.stack([_nearest_rotation(t) for t in total])
535
+ _grain_sums(g, labels, self.phase, reference, ops, counts, total, angle)
536
+ points = np.bincount(labels[measured], minlength=count)
537
+ spread = np.degrees(angle / np.maximum(points, 1))
538
+ if fill and not measured.all():
539
+ nearest = ndimage.distance_transform_edt(
540
+ ~measured, sampling=(self.step[1], self.step[0]), return_distances=False,
541
+ return_indices=True,
542
+ ) # fmt: skip
543
+ labels = labels[nearest[0], nearest[1]]
544
+ size = np.bincount(labels[labels >= 0], minlength=count)
545
+ return Grains(np.ascontiguousarray(labels, dtype=np.int32), matrix_to_euler(reference),
546
+ phase, size, spread, self.step, self.phases, self.unit) # fmt: skip
547
+
548
+
549
+ # -- the .ang files of EDAX/TSL ------------------------------------------------------------
550
+
551
+
552
+ def _ang_phases(header: list[str]) -> tuple[Phase, ...]:
553
+ phases, current = [], None
554
+ for line in header:
555
+ text = line.lstrip("#").strip()
556
+ if re.match(r"Phase\s+\d+", text):
557
+ current = {"name": "", "lattice": None, "cell": (1.0, 1.0, 1.0, 90.0, 90.0, 90.0)}
558
+ phases.append(current)
559
+ elif current is not None:
560
+ match = re.match(r"(\w+)\s*(.*)", text)
561
+ key, value = (match.group(1), match.group(2).strip()) if match else ("", "")
562
+ if key == "MaterialName":
563
+ current["name"] = value
564
+ elif key == "Symmetry":
565
+ current["lattice"] = ANG_SYMMETRY.get(int(float(value.split()[0])))
566
+ elif key == "LatticeConstants":
567
+ current["cell"] = tuple(float(v) for v in value.split()[:6])
568
+ return tuple(Phase(**p) for p in phases) or (Phase(),)
569
+
570
+
571
+ def read_ang(path, *, axes: str = "map", setting: int = 1) -> EBSDMap:
572
+ """The map of an ``.ang`` file (EDAX/TSL OIM): the columns phi1, PHI, phi2 (radians),
573
+ x, y, image quality, confidence index and phase of its rows, on the square or
574
+ hexagonal grid of its header. A point is not indexed where its confidence index is
575
+ negative or its angles are out of range. The orientations are brought into the axes
576
+ of the map (``axes="map"``; ``setting``: that of the system, one of
577
+ :data:`ANG_SETTINGS`) or left in those of the file (``axes="file"``)."""
578
+ _check_axes(axes, setting)
579
+ with open(path, encoding="utf-8", errors="replace") as handle:
580
+ header = [line for line in handle if line.startswith("#")]
581
+ keys = {}
582
+ for line in header:
583
+ match = re.match(r"#\s*(GRID|XSTEP|YSTEP|NCOLS_ODD|NCOLS_EVEN|NROWS)\s*:\s*(\S+)", line)
584
+ if match:
585
+ keys[match.group(1)] = match.group(2)
586
+ data = np.loadtxt(path, comments="#", ndmin=2)
587
+ if data.shape[1] < 5:
588
+ raise ValueError(f"{path}: an .ang file has five columns at least (angles, x, y)")
589
+ x, y = data[:, 3], data[:, 4]
590
+ dx = float(keys["XSTEP"]) if "XSTEP" in keys else _step(x)
591
+ dy = float(keys["YSTEP"]) if "YSTEP" in keys else _step(y)
592
+ hexagonal = keys.get("GRID", "SqrGrid").lower().startswith("hex")
593
+ rows = np.rint((y - y.min()) / dy).astype(np.int64)
594
+ shift = np.where(rows % 2 == 1, 0.5, 0.0) if hexagonal else 0.0
595
+ columns = np.rint((x - x.min()) / dx - shift).astype(np.int64)
596
+ columns = np.maximum(columns, 0)
597
+ ny, nx = int(rows.max()) + 1, int(columns.max()) + 1
598
+ phases = _ang_phases(header)
599
+ euler = np.degrees(data[:, :3])
600
+ ci = data[:, 6] if data.shape[1] > 6 else np.zeros(len(data))
601
+ indexed = (ci >= 0.0) & np.all(
602
+ (data[:, :3] >= -1e-6) & (data[:, :3] <= 2 * math.pi + 1e-3), axis=1
603
+ )
604
+ listed = data[:, 7].astype(np.int64) if data.shape[1] > 7 else np.zeros(len(data), np.int64)
605
+ if len(phases) == 1:
606
+ number = np.ones(len(data), dtype=np.int64)
607
+ else:
608
+ number = np.clip(listed, 0, len(phases))
609
+ indexed &= number > 0
610
+ out_euler = np.zeros((ny, nx, 3))
611
+ out_phase = np.zeros((ny, nx), dtype=np.int32)
612
+ out_euler[rows, columns] = np.where(indexed[:, None], euler, 0.0)
613
+ out_phase[rows, columns] = np.where(indexed, number, 0)
614
+ quality = {}
615
+ for name, column in (("iq", 5), ("ci", 6)):
616
+ if data.shape[1] > column:
617
+ values = np.zeros((ny, nx))
618
+ values[rows, columns] = data[:, column]
619
+ quality[name] = values
620
+ ebsd = EBSDMap(out_euler, out_phase, (dx, dy), phases, quality)
621
+ return ebsd._about_normal(ANG_SETTINGS[setting]) if axes == "map" else ebsd
622
+
623
+
624
+ def _step(values: np.ndarray) -> float:
625
+ """The step of a grid from the coordinates of its points."""
626
+ unique = np.unique(np.round(values, 9))
627
+ return float(np.min(np.diff(unique))) if unique.size > 1 else 1.0
628
+
629
+
630
+ def write_ang(path, ebsd: EBSDMap, *, axes: str = "map", setting: int = 1) -> Path:
631
+ """Writes a map as an ``.ang`` file on a square grid (angles in radians; a point that
632
+ was not indexed has a confidence index of -1). ``axes="map"``: the orientations of
633
+ the map are in the axes of its image, and are written in those of the system
634
+ (``setting``); ``axes="file"``: they are written as they are."""
635
+ _check_axes(axes, setting)
636
+ if axes == "map":
637
+ ebsd = ebsd._about_normal(-ANG_SETTINGS[setting])
638
+ path = Path(path)
639
+ ny, nx = ebsd.shape
640
+ codes = {v: k for k, v in ANG_SYMMETRY.items()}
641
+ lines = ["# TEM_PIXperUM 1.000000", "# x-star 0.500000",
642
+ "# y-star 0.500000", "# z-star 0.500000",
643
+ "# WorkingDistance 15.000000", "#"] # fmt: skip
644
+ for k, phase in enumerate(ebsd.phases, start=1):
645
+ cell = " ".join(f"{v:.3f}" for v in phase.cell[:6])
646
+ lines += [f"# Phase {k}", f"# MaterialName \t{phase.name or f'phase {k}'}",
647
+ "# Formula \t", "# Info \t\t",
648
+ f"# Symmetry {codes.get(phase.lattice, 1)}",
649
+ f"# LatticeConstants {cell}", "# NumberFamilies 0", "#"] # fmt: skip
650
+ lines += ["# GRID: SqrGrid", f"# XSTEP: {ebsd.step[0]:.6f}", f"# YSTEP: {ebsd.step[1]:.6f}",
651
+ f"# NCOLS_ODD: {nx}", f"# NCOLS_EVEN: {nx}", f"# NROWS: {ny}", "#",
652
+ "# OPERATOR: \tmorphoGen", "# SAMPLEID: \t", "# SCANID: \t", "#"] # fmt: skip
653
+ yy, xx = np.meshgrid(np.arange(ny) * ebsd.step[1], np.arange(nx) * ebsd.step[0], indexing="ij")
654
+ indexed = ebsd.indexed
655
+ table = np.column_stack([
656
+ np.radians(ebsd.euler.reshape(-1, 3)), xx.ravel(), yy.ravel(),
657
+ ebsd.quality.get("iq", np.where(indexed, 100.0, 0.0)).ravel(),
658
+ np.where(indexed, ebsd.quality.get("ci", np.ones((ny, nx))), -1.0).ravel(),
659
+ (ebsd.phase if len(ebsd.phases) > 1 else np.zeros((ny, nx))).ravel(),
660
+ np.ones(ny * nx), np.zeros(ny * nx),
661
+ ]) # fmt: skip
662
+ with open(path, "w", encoding="utf-8") as handle:
663
+ handle.write("\n".join(lines) + "\n")
664
+ np.savetxt(handle, table, fmt="%9.5f %9.5f %9.5f %12.5f %12.5f %8.1f %6.3f %2d %6d %6.3f")
665
+ return path
666
+
667
+
668
+ # -- the .ctf files of Oxford Instruments/HKL ----------------------------------------------
669
+
670
+
671
+ def read_ctf(path, *, axes: str = "map") -> EBSDMap:
672
+ """The map of a ``.ctf`` file (Channel Text File): the phases of its header, and the
673
+ columns Phase, X, Y, Euler1, Euler2, Euler3 (degrees) of its rows, with the bands,
674
+ the error, the mean angular deviation and the contrasts; the phase 0 is a point that
675
+ was not indexed. Decimal commas are read. The orientations of the file are in the
676
+ axes of the image of the map (``axes``: both values give them as they are); the
677
+ hexagonal and trigonal crystals are turned to the axes of morphoGen (the first along
678
+ ``a``)."""
679
+ _check_axes(axes)
680
+ with open(path, encoding="utf-8", errors="replace") as handle:
681
+ lines = handle.read().splitlines()
682
+ keys: dict[str, str] = {}
683
+ phases: list[Phase] = []
684
+ start = None
685
+ k = 0
686
+ while k < len(lines):
687
+ parts = lines[k].split("\t") if "\t" in lines[k] else lines[k].split()
688
+ if not parts:
689
+ k += 1
690
+ continue
691
+ if parts[0] == "Phases":
692
+ for line in lines[k + 1 : k + 1 + int(parts[1])]:
693
+ item = line.replace(",", ".").split("\t")
694
+ cell = [float(v) for v in item[0].split(";")] + [
695
+ float(v) for v in item[1].split(";")
696
+ ]
697
+ laue = int(item[3]) if len(item) > 3 and item[3].strip() else 0
698
+ phases.append(Phase(item[2] if len(item) > 2 else "", CTF_LAUE.get(laue), cell))
699
+ k += int(parts[1])
700
+ elif parts[0] == "Phase" and "Euler1" in parts:
701
+ start = k
702
+ break
703
+ elif len(parts) >= 2:
704
+ keys[parts[0]] = parts[1]
705
+ k += 1
706
+ if start is None:
707
+ raise ValueError(
708
+ f"{path}: no table of points (a line 'Phase X Y ... Euler1 Euler2 Euler3')"
709
+ )
710
+ names = [name.strip() for name in lines[start].split("\t")]
711
+ body = lines[start + 1 :]
712
+ if body and "," in body[0]:
713
+ body = [line.replace(",", ".") for line in body]
714
+ data = np.loadtxt(body, ndmin=2)
715
+ column = {name: data[:, i] for i, name in enumerate(names) if i < data.shape[1]}
716
+ x, y = column["X"], column["Y"]
717
+ dx = float(keys["XStep"].replace(",", ".")) if "XStep" in keys else _step(x)
718
+ dy = float(keys["YStep"].replace(",", ".")) if "YStep" in keys else _step(y)
719
+ columns = np.rint((x - x.min()) / dx).astype(np.int64)
720
+ rows = np.rint((y - y.min()) / dy).astype(np.int64)
721
+ nx = int(keys["XCells"]) if "XCells" in keys else int(columns.max()) + 1
722
+ ny = int(keys["YCells"]) if "YCells" in keys else int(rows.max()) + 1
723
+ number = np.clip(column["Phase"].astype(np.int64), 0, max(len(phases), 1))
724
+ euler = np.zeros((ny, nx, 3))
725
+ phase = np.zeros((ny, nx), dtype=np.int32)
726
+ angles = np.column_stack([column["Euler1"], column["Euler2"], column["Euler3"]])
727
+ euler[rows, columns] = np.where(number[:, None] > 0, angles, 0.0)
728
+ phase[rows, columns] = number
729
+ quality = {}
730
+ for name in ("Bands", "Error", "MAD", "BC", "BS"):
731
+ if name in column:
732
+ values = np.zeros((ny, nx))
733
+ values[rows, columns] = column[name]
734
+ quality[name.lower()] = values
735
+ return EBSDMap(euler, phase, (dx, dy), tuple(phases) or None, quality)._about_c(30.0)
736
+
737
+
738
+ def write_ctf(path, ebsd: EBSDMap, *, axes: str = "map") -> Path:
739
+ """Writes a map as a ``.ctf`` file (angles in degrees; the phase 0 for a point that
740
+ was not indexed). The orientations are written as they are: the axes of the image of
741
+ the map are those of the file (``axes``: both values). The hexagonal and trigonal
742
+ crystals are written with their first axis along ``a*``."""
743
+ _check_axes(axes)
744
+ ebsd = ebsd._about_c(-30.0)
745
+ path = Path(path)
746
+ ny, nx = ebsd.shape
747
+ codes = {v: k for k, v in CTF_LAUE.items()}
748
+ settings = ("Mag\t0.0000\tCoverage\t0\tDevice\t0\tKV\t0.0000\tTiltAngle\t0.0000\tTiltAxis\t0"
749
+ "\tDetectorOrientationE1\t0.0000\tDetectorOrientationE2\t0.0000"
750
+ "\tDetectorOrientationE3\t0.0000\tWorkingDistance\t0.0000"
751
+ "\tInsertionDistance\t0.0000\t") # fmt: skip
752
+ lines = ["Channel Text File", "Prj\tmorphoGen", "Author\tmorphoGen", "JobMode\tGrid",
753
+ f"XCells\t{nx}", f"YCells\t{ny}", f"XStep\t{ebsd.step[0]:.6f}",
754
+ f"YStep\t{ebsd.step[1]:.6f}", "AcqE1\t0.0000", "AcqE2\t0.0000", "AcqE3\t0.0000",
755
+ f"Euler angles refer to Sample Coordinate system (CS0)!\t{settings}",
756
+ f"Phases\t{len(ebsd.phases)}"] # fmt: skip
757
+ for k, phase in enumerate(ebsd.phases, start=1):
758
+ cell = list(phase.cell[:6]) + [90.0] * (6 - len(phase.cell[:6]))
759
+ lengths = ";".join(f"{v:.3f}" for v in cell[:3])
760
+ angles = ";".join(f"{v:.3f}" for v in cell[3:6])
761
+ lines.append(f"{lengths}\t{angles}\t{phase.name or f'phase {k}'}"
762
+ f"\t{codes.get(phase.lattice, 1)}\t0\t\t\t") # fmt: skip
763
+ lines.append("Phase\tX\tY\tBands\tError\tEuler1\tEuler2\tEuler3\tMAD\tBC\tBS")
764
+ yy, xx = np.meshgrid(np.arange(ny) * ebsd.step[1], np.arange(nx) * ebsd.step[0], indexing="ij")
765
+ indexed = ebsd.indexed
766
+ zero = np.zeros((ny, nx))
767
+ table = np.column_stack([
768
+ ebsd.phase.ravel(), xx.ravel(), yy.ravel(),
769
+ ebsd.quality.get("bands", np.where(indexed, 8, 0)).ravel(),
770
+ ebsd.quality.get("error", zero).ravel(),
771
+ ebsd.euler.reshape(-1, 3),
772
+ ebsd.quality.get("mad", np.where(indexed, 0.5, 0.0)).ravel(),
773
+ ebsd.quality.get("bc", np.where(indexed, 128, 0)).ravel(),
774
+ ebsd.quality.get("bs", np.where(indexed, 128, 0)).ravel(),
775
+ ]) # fmt: skip
776
+ with open(path, "w", encoding="utf-8") as handle:
777
+ handle.write("\n".join(lines) + "\n")
778
+ np.savetxt(handle, table, delimiter="\t",
779
+ fmt=["%d", "%.4f", "%.4f", "%d", "%d", "%.4f", "%.4f", "%.4f", "%.4f", "%d",
780
+ "%d"]) # fmt: skip
781
+ return path
782
+
783
+
784
+ def synthetic_map(micro, shape, *, layer: int = 0, orientations=None, phase=None, phases=None,
785
+ scatter: float = 0.0, missing: float = 0.0, boundaries: float = 0.0,
786
+ seed=None) -> EBSDMap: # fmt: skip
787
+ """The map that an acquisition would give of a layer of a polycrystal: the cells of
788
+ ``micro`` (a microstructure with labels and ``orientations``: a tessellation, grains
789
+ grown or measured) on the grid ``shape`` (nx, ny, nz) of its domain, the layer
790
+ ``layer`` along its third axis, seen from the end of that axis (the axes of the map
791
+ are those of the domain). Each point has the orientation of its cell
792
+ (``orientations``: other ones, per cell; ``phase``: the phase of each cell, 1 by
793
+ default, among ``phases``), turned about a random axis by an angle of the half-normal
794
+ law of standard deviation ``scatter`` degrees; a share ``missing`` of the points, and
795
+ a share ``boundaries`` of those next to another cell, are not indexed."""
796
+ if not (scatter >= 0 and 0 <= missing <= 1 and 0 <= boundaries <= 1):
797
+ raise ValueError("synthetic_map: scatter >= 0, missing and boundaries between 0 and 1")
798
+ image = micro.labels(shape)
799
+ if not 0 <= layer < image.data.shape[2]:
800
+ raise ValueError(f"layer: from 0 to {image.data.shape[2] - 1}")
801
+ labels = np.ascontiguousarray(image.data[:, ::-1, layer].T) # (the rows from the top)
802
+ given = micro.orientations if orientations is None else orientations
803
+ if given is None:
804
+ raise ValueError("synthetic_map: the cells have no orientations (crystal_orientations)")
805
+ step = (float(image.spacing[0]), float(image.spacing[1]))
806
+ ebsd = EBSDMap.from_grains(labels, given, step, phase=phase, phases=phases,
807
+ unit=micro.domain.unit) # fmt: skip
808
+ rng, _ = make_rng(seed)
809
+ ny, nx = labels.shape
810
+ euler, number = ebsd.euler, ebsd.phase.copy()
811
+ if scatter > 0:
812
+ angles = np.radians(np.abs(rng.normal(0.0, scatter, ny * nx)))
813
+ turns = _turns(uniform_unit_vectors(rng, ny * nx), angles)
814
+ euler = matrix_to_euler(euler_to_matrix(euler.reshape(-1, 3)) @ turns).reshape(ny, nx, 3)
815
+ lost = rng.random((ny, nx)) < missing
816
+ if boundaries > 0:
817
+ edge = np.zeros((ny, nx), dtype=bool)
818
+ edge[:, :-1] |= labels[:, :-1] != labels[:, 1:]
819
+ edge[:, 1:] |= labels[:, :-1] != labels[:, 1:]
820
+ edge[:-1, :] |= labels[:-1, :] != labels[1:, :]
821
+ edge[1:, :] |= labels[:-1, :] != labels[1:, :]
822
+ lost |= edge & (rng.random((ny, nx)) < boundaries)
823
+ number[lost] = 0
824
+ return EBSDMap(np.where(number[..., None] > 0, euler, 0.0), number, step, ebsd.phases,
825
+ unit=ebsd.unit) # fmt: skip
826
+
827
+
828
+ def example_map(name: str = "ebsd_map.ctf") -> Path:
829
+ """The path of a map that comes with morphoGen (``ebsd_map.ctf``: the map of the
830
+ template ``ebsd``, a section of a polycrystal of nickel as an acquisition would give
831
+ it, written by examples/ebsd_map.py)."""
832
+ from importlib import resources
833
+
834
+ path = Path(str(resources.files("morphogen") / "templates" / name))
835
+ if Path(name).suffix.lower() not in (".ang", ".ctf") or not path.is_file():
836
+ raise ValueError(f"example_map: no map {name!r} comes with morphoGen")
837
+ return path
838
+
839
+
840
+ def read_ebsd(path, *, axes: str = "map", setting: int = 1) -> EBSDMap:
841
+ """The map of an ``.ang`` or a ``.ctf`` file (by its extension), its orientations in
842
+ the axes of the map (``axes="map"``; ``setting``: that of the system of an ``.ang``
843
+ file) or in those of the file (``axes="file"``)."""
844
+ suffix = Path(path).suffix.lower()
845
+ if suffix == ".ang":
846
+ return read_ang(path, axes=axes, setting=setting)
847
+ if suffix == ".ctf":
848
+ _check_axes(axes, setting)
849
+ return read_ctf(path, axes=axes)
850
+ raise ValueError(f"{path}: an orientation map is an .ang or a .ctf file")
851
+
852
+
853
+ def write_ebsd(path, ebsd: EBSDMap, *, axes: str = "map", setting: int = 1) -> Path:
854
+ """Writes a map as an ``.ang`` or a ``.ctf`` file (by its extension); ``axes`` and
855
+ ``setting`` as in :func:`read_ebsd`."""
856
+ suffix = Path(path).suffix.lower()
857
+ if suffix == ".ang":
858
+ return write_ang(path, ebsd, axes=axes, setting=setting)
859
+ if suffix == ".ctf":
860
+ _check_axes(axes, setting)
861
+ return write_ctf(path, ebsd, axes=axes)
862
+ raise ValueError(f"{path}: an orientation map is an .ang or a .ctf file")
863
+
864
+
865
+ __all__ = [
866
+ "ANG_SETTINGS",
867
+ "ANG_SYMMETRY",
868
+ "AXES",
869
+ "CTF_LAUE",
870
+ "EBSDMap",
871
+ "Grains",
872
+ "Phase",
873
+ "example_map",
874
+ "read_ang",
875
+ "read_ctf",
876
+ "read_ebsd",
877
+ "synthetic_map",
878
+ "write_ang",
879
+ "write_ctf",
880
+ "write_ebsd",
881
+ ]