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/texture.py ADDED
@@ -0,0 +1,665 @@
1
+ """Crystallographic textures: the orientations of the crystals of a polycrystal — measured
2
+ (the maps of electron backscatter diffraction, :mod:`morphogen.io.ebsd`) or computed
3
+ (the lattices that slip and twins turn along a loading path) —, their symmetries, their
4
+ disorientations, and the figures that show them.
5
+
6
+ Orientations are Bunge Euler angles (phi1, Phi, phi2) in degrees, an array ``(n, 3)``, or
7
+ the matrices ``g`` of :func:`morphogen.orientations.euler_to_matrix`, an array ``(n, 3,
8
+ 3)``: ``crystal = g @ sample``, the rows of ``g`` are the axes of the crystal in those of
9
+ the sample. The axes of the crystal are those of
10
+ :mod:`morphogen.homogenization.crystal`: the edges of the cube; for a hexagonal lattice,
11
+ ``a_1 = [2 -1 -1 0]`` along the first axis and ``c`` along the third.
12
+
13
+ **Symmetries.** A crystal turned by a rotation ``S`` of its point group is the same
14
+ crystal: ``g`` and ``S g`` are one orientation (:func:`symmetries`: 24 rotations of the
15
+ cube, 12 of the hexagonal prism, and those of the nine other Laue classes).
16
+
17
+ **Disorientation.** The rotation that brings the axes of a crystal ``a`` onto those of a
18
+ crystal ``b`` is ``g_b g_a^T``; their disorientation is the smallest angle of the
19
+ rotations ``S g_b g_a^T``, ``S`` in the group (:func:`disorientation`): at most 62.8
20
+ degrees for cubic crystals, 93.8 for hexagonal ones. For two cubic crystals of random
21
+ orientations its density is that of Mackenzie (1958) and Handscomb (1958)
22
+ (:func:`mackenzie`): mean 40.7 degrees.
23
+
24
+ **Pole figures.** The normals of the planes ``{hkl}`` of a crystal, ``g^T n`` in the axes
25
+ of the sample (:func:`poles`), are shown on a disc (:func:`project`: stereographic or
26
+ equal-area projection of the upper hemisphere, the first axis of the sample to the
27
+ right, the second upwards, the third towards the reader). Their density
28
+ (:func:`pole_figure`) is in multiples of that of a random texture: each pole is spread
29
+ by an axial von Mises-Fisher kernel of a given half-width, whose mean over the sphere is
30
+ one, so that the mean of the density over the sphere is one for any texture.
31
+
32
+ **Inverse pole figures.** The direction of the crystal that lies along a direction of
33
+ the sample (the axis of a tension), ``g d``, is brought into the fundamental sector of
34
+ the lattice by its symmetries (:func:`inverse_poles`: the triangle [001], [011], [111]
35
+ of the cube; the sector between [0001], [2 -1 -1 0] and [1 0 -1 0] of the hexagonal
36
+ lattice), and gives each crystal a colour (:func:`ipf_colours`: red, green and blue at
37
+ these corners).
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import math
43
+ from dataclasses import dataclass
44
+
45
+ import numpy as np
46
+ from numba import njit, prange
47
+
48
+ from morphogen.homogenization.crystal import _rotations, _vector
49
+ from morphogen.orientations import euler_to_matrix, matrix_to_euler, uniform_unit_vectors
50
+
51
+ #: The lattices whose planes and directions are known (pole figures, inverse pole figures)
52
+ LATTICES = ("cubic", "hexagonal")
53
+ #: The eleven Laue classes (:func:`symmetries`): the class of highest symmetry of each
54
+ #: system by the name of the system (m-3m, 6/mmm, 4/mmm, -3m, mmm, 2/m and -1), the four
55
+ #: others by their symbol
56
+ CLASSES = ("cubic", "hexagonal", "tetragonal", "trigonal", "orthorhombic", "monoclinic",
57
+ "triclinic", "m-3", "6/m", "4/m", "-3") # fmt: skip
58
+ #: Projections of the hemisphere on the unit disc
59
+ PROJECTIONS = ("stereographic", "equal_area")
60
+ #: The ratio c/a of a hexagonal lattice of close-packed spheres (the default of the planes
61
+ #: and directions that depend on it)
62
+ IDEAL_RATIO = math.sqrt(8.0 / 3.0)
63
+
64
+
65
+ def _matrices(orientations) -> np.ndarray:
66
+ """The matrices ``(n, 3, 3)`` of orientations given as Euler angles ``(n, 3)`` (or
67
+ ``(3,)``: one crystal), in degrees, or as matrices ``(n, 3, 3)``."""
68
+ a = np.asarray(orientations, dtype=float)
69
+ if a.ndim == 3 and a.shape[1:] == (3, 3):
70
+ return np.ascontiguousarray(a)
71
+ if a.ndim in (1, 2) and a.shape[-1] == 3:
72
+ return euler_to_matrix(a.reshape(-1, 3))
73
+ raise ValueError(
74
+ f"orientations: Euler angles (n, 3) or matrices (n, 3, 3), got an array {a.shape}"
75
+ )
76
+
77
+
78
+ def _turns(axes, angles) -> np.ndarray:
79
+ """The rotations ``(n, 3, 3)`` of ``angles`` (radians) about ``axes`` ``(n, 3)``."""
80
+ u = np.asarray(axes, dtype=float).reshape(-1, 3)
81
+ u = u / np.linalg.norm(u, axis=1)[:, None]
82
+ t = np.asarray(angles, dtype=float).reshape(-1)
83
+ k = np.zeros((len(u), 3, 3))
84
+ k[:, 0, 1], k[:, 0, 2] = -u[:, 2], u[:, 1]
85
+ k[:, 1, 0], k[:, 1, 2] = u[:, 2], -u[:, 0]
86
+ k[:, 2, 0], k[:, 2, 1] = -u[:, 1], u[:, 0]
87
+ return np.eye(3) + np.sin(t)[:, None, None] * k + (1.0 - np.cos(t))[:, None, None] * (k @ k)
88
+
89
+
90
+ def _turn(axis, angle: float) -> np.ndarray:
91
+ """The rotation of ``angle`` (radians) about ``axis``."""
92
+ return _turns(axis, angle)[0]
93
+
94
+
95
+ def symmetries(lattice: str = "cubic") -> np.ndarray:
96
+ """The proper rotations of a Laue class, ``(m, 3, 3)``, in the axes of the crystal:
97
+ 24 for ``"cubic"`` (m-3m), 12 for ``"hexagonal"`` (6/mmm), 8 for ``"tetragonal"``
98
+ (4/mmm), 6 for ``"trigonal"`` (-3m, the three-fold axis along the third axis, a
99
+ two-fold one along the first), 4 for ``"orthorhombic"`` (mmm), 2 for ``"monoclinic"``
100
+ (2/m, the two-fold axis along the second axis) and the identity alone for
101
+ ``"triclinic"`` (-1); 12 for ``"m-3"`` (the rotations of the tetrahedron), and the
102
+ 6, 4 and 3 rotations about the third axis for ``"6/m"``, ``"4/m"`` and ``"-3"``."""
103
+ if lattice in ("cubic", "hexagonal"):
104
+ return np.array(_rotations(lattice))
105
+ x, y, z = np.eye(3)
106
+ if lattice == "m-3": # (of the rotations of the cube, the even permutations of its axes)
107
+ return np.array([r for r in _rotations("cubic") if np.linalg.det(np.abs(r)) > 0])
108
+ about_z = {"6/m": 6, "4/m": 4, "-3": 3}
109
+ if lattice in about_z:
110
+ n = about_z[lattice]
111
+ return np.array([_turn(z, k * 2.0 * math.pi / n) for k in range(n)])
112
+ if lattice == "tetragonal":
113
+ quarter = [_turn(z, k * math.pi / 2.0) for k in range(4)]
114
+ return np.array(quarter + [_turn(x, math.pi) @ q for q in quarter])
115
+ if lattice == "trigonal":
116
+ third = [_turn(z, k * 2.0 * math.pi / 3.0) for k in range(3)]
117
+ return np.array(third + [_turn(x, math.pi) @ q for q in third])
118
+ if lattice == "orthorhombic":
119
+ return np.array([np.eye(3)] + [_turn(a, math.pi) for a in (x, y, z)])
120
+ if lattice == "monoclinic":
121
+ return np.array([np.eye(3), _turn(y, math.pi)])
122
+ if lattice == "triclinic":
123
+ return np.eye(3)[None]
124
+ raise ValueError(f"lattice: one of {CLASSES}, got {lattice!r}")
125
+
126
+
127
+ @njit(parallel=True, cache=True)
128
+ def _disorientations(ga, gb, ops, out):
129
+ """``out[p]``: the disorientation (radians) of the crystals ``ga[p]`` and ``gb[p]``
130
+ (one of the two arrays may hold a single crystal): the angle of the rotation ``S g_b
131
+ g_a^T`` of largest trace, from its sine (the length of its axial vector) and its
132
+ cosine — exact to rounding for crystals that are close, where the cosine alone gives
133
+ the square root of the rounding."""
134
+ na, nb = ga.shape[0], gb.shape[0]
135
+ for p in prange(out.size):
136
+ a = ga[p % na]
137
+ b = gb[p % nb]
138
+ # d = g_b g_a^T
139
+ d00 = b[0, 0] * a[0, 0] + b[0, 1] * a[0, 1] + b[0, 2] * a[0, 2]
140
+ d01 = b[0, 0] * a[1, 0] + b[0, 1] * a[1, 1] + b[0, 2] * a[1, 2]
141
+ d02 = b[0, 0] * a[2, 0] + b[0, 1] * a[2, 1] + b[0, 2] * a[2, 2]
142
+ d10 = b[1, 0] * a[0, 0] + b[1, 1] * a[0, 1] + b[1, 2] * a[0, 2]
143
+ d11 = b[1, 0] * a[1, 0] + b[1, 1] * a[1, 1] + b[1, 2] * a[1, 2]
144
+ d12 = b[1, 0] * a[2, 0] + b[1, 1] * a[2, 1] + b[1, 2] * a[2, 2]
145
+ d20 = b[2, 0] * a[0, 0] + b[2, 1] * a[0, 1] + b[2, 2] * a[0, 2]
146
+ d21 = b[2, 0] * a[1, 0] + b[2, 1] * a[1, 1] + b[2, 2] * a[1, 2]
147
+ d22 = b[2, 0] * a[2, 0] + b[2, 1] * a[2, 1] + b[2, 2] * a[2, 2]
148
+ best = -4.0
149
+ which = 0
150
+ for s in range(ops.shape[0]):
151
+ o = ops[s]
152
+ trace = (o[0, 0] * d00 + o[0, 1] * d10 + o[0, 2] * d20
153
+ + o[1, 0] * d01 + o[1, 1] * d11 + o[1, 2] * d21
154
+ + o[2, 0] * d02 + o[2, 1] * d12 + o[2, 2] * d22) # fmt: skip
155
+ if trace > best:
156
+ best = trace
157
+ which = s
158
+ o = ops[which]
159
+ # the axial vector of m = o d
160
+ x = (o[2, 0] * d01 + o[2, 1] * d11 + o[2, 2] * d21
161
+ - o[1, 0] * d02 - o[1, 1] * d12 - o[1, 2] * d22) # fmt: skip
162
+ y = (o[0, 0] * d02 + o[0, 1] * d12 + o[0, 2] * d22
163
+ - o[2, 0] * d00 - o[2, 1] * d10 - o[2, 2] * d20) # fmt: skip
164
+ z = (o[1, 0] * d00 + o[1, 1] * d10 + o[1, 2] * d20
165
+ - o[0, 0] * d01 - o[0, 1] * d11 - o[0, 2] * d21) # fmt: skip
166
+ out[p] = math.atan2(0.5 * math.sqrt(x * x + y * y + z * z), 0.5 * (best - 1.0))
167
+
168
+
169
+ def disorientation(a, b, lattice: str = "cubic") -> np.ndarray:
170
+ """The disorientations (degrees) of the crystals ``a`` and ``b`` of a lattice, pair
171
+ by pair (as many of each, or one of the two alone: of every crystal from it): the
172
+ smallest angle of the rotations that bring the one onto the other, over the
173
+ symmetries of the lattice."""
174
+ ga, gb = _matrices(a), _matrices(b)
175
+ if len(ga) != len(gb) and 1 not in (len(ga), len(gb)):
176
+ raise ValueError(f"disorientation: {len(ga)} crystals and {len(gb)}")
177
+ out = np.empty(max(len(ga), len(gb)))
178
+ _disorientations(ga, gb, symmetries(lattice), out)
179
+ return np.degrees(out)
180
+
181
+
182
+ @njit(cache=True)
183
+ def _sum_nearest(g, weights, reference, ops, total):
184
+ """``total``: the weighted sum of the crystals ``g``, each taken as that of its
185
+ symmetric equivalents which is nearest to ``reference``."""
186
+ total[:, :] = 0.0
187
+ for k in range(g.shape[0]):
188
+ best = -4.0
189
+ which = 0
190
+ for s in range(ops.shape[0]):
191
+ trace = 0.0
192
+ for i in range(3):
193
+ for j in range(3):
194
+ d = 0.0
195
+ for m in range(3):
196
+ d += g[k, j, m] * reference[i, m]
197
+ trace += ops[s, i, j] * d
198
+ if trace > best:
199
+ best = trace
200
+ which = s
201
+ for i in range(3):
202
+ for m in range(3):
203
+ e = 0.0
204
+ for j in range(3):
205
+ e += ops[which, i, j] * g[k, j, m]
206
+ total[i, m] += weights[k] * e
207
+
208
+
209
+ def _nearest_rotation(m: np.ndarray) -> np.ndarray:
210
+ """The rotation nearest to a matrix (its polar factor, a determinant of one)."""
211
+ u, _, vt = np.linalg.svd(m)
212
+ d = np.sign(np.linalg.det(u @ vt))
213
+ return u @ np.diag([1.0, 1.0, d]) @ vt
214
+
215
+
216
+ def mean_orientation(orientations, lattice: str = "cubic", weights=None):
217
+ """The mean orientation of crystals that are close to one another (the points of a
218
+ grain) and their spread: the Euler angles (degrees) of the rotation nearest to the
219
+ weighted sum of their matrices, each crystal taken as that of its symmetric
220
+ equivalents which is nearest to the mean (three passes from the crystal of largest
221
+ weight), and the weighted mean of their disorientations from it (degrees)."""
222
+ g = _matrices(orientations)
223
+ w = np.ones(len(g)) if weights is None else np.asarray(weights, dtype=float).ravel()
224
+ if w.shape != (len(g),) or len(g) == 0 or not w.sum() > 0:
225
+ raise ValueError("mean_orientation: one positive weight per crystal")
226
+ w = w / w.sum()
227
+ ops = symmetries(lattice)
228
+ mean = g[int(np.argmax(w))].copy()
229
+ total = np.empty((3, 3))
230
+ for _ in range(3):
231
+ _sum_nearest(g, w, mean, ops, total)
232
+ mean = _nearest_rotation(total)
233
+ spread = float(np.sum(w * disorientation(g, mean[None], lattice)))
234
+ return matrix_to_euler(mean)[0], spread
235
+
236
+
237
+ def crystal_axes(indices, lattice: str = "cubic", *, plane: bool = True,
238
+ c_over_a: float | None = None) -> np.ndarray: # fmt: skip
239
+ """The distinct axes of a family of planes ``{hkl}`` (their normals) or of directions
240
+ ``<uvw>`` of a lattice, unit vectors ``(m, 3)`` in the axes of the crystal, one for
241
+ each pair of opposite ones: Miller indices of the cube; Miller-Bravais indices
242
+ ``(hkil)`` of the hexagonal lattice (or three: ``i = -h - k``), of ratio ``c_over_a``
243
+ (:data:`IDEAL_RATIO` by default)."""
244
+ if lattice not in LATTICES:
245
+ raise ValueError(f"lattice: one of {LATTICES} for planes and directions, got {lattice!r}")
246
+ idx = [int(v) for v in indices]
247
+ if lattice == "hexagonal" and len(idx) == 3:
248
+ idx = [idx[0], idx[1], -idx[0] - idx[1], idx[2]]
249
+ if len(idx) != (3 if lattice == "cubic" else 4) or not any(idx):
250
+ raise ValueError(f"indices: three (cubic) or four (hexagonal) integers, got {indices!r}")
251
+ ratio = IDEAL_RATIO if c_over_a is None else float(c_over_a)
252
+ v = _vector(idx, lattice, ratio if lattice == "hexagonal" else None, plane)
253
+ v = v / np.linalg.norm(v)
254
+ found: list[np.ndarray] = []
255
+ for s in symmetries(lattice):
256
+ w = s @ v
257
+ if not any(abs(abs(float(w @ f)) - 1.0) < 1e-9 for f in found):
258
+ first = w[np.flatnonzero(np.abs(w) > 1e-9)[0]]
259
+ found.append(w if first > 0 else -w)
260
+ return np.array(found)
261
+
262
+
263
+ def poles(orientations, indices, lattice: str = "cubic", *, plane: bool = True,
264
+ c_over_a: float | None = None) -> np.ndarray: # fmt: skip
265
+ """The axes of a family of planes or directions of each crystal in the axes of the
266
+ sample, unit vectors ``(n, m, 3)``: ``g^T v`` for each axis ``v`` of
267
+ :func:`crystal_axes`."""
268
+ axes = crystal_axes(indices, lattice, plane=plane, c_over_a=c_over_a)
269
+ return np.einsum("nji,mj->nmi", _matrices(orientations), axes)
270
+
271
+
272
+ def project(directions, projection: str = "stereographic") -> np.ndarray:
273
+ """The points of the unit disc of directions ``(..., 3)`` of the sample, folded onto
274
+ the upper hemisphere (a direction and its opposite are one axis): the first axis of
275
+ the sample to the right, the second upwards, the third at the centre. At the angle
276
+ ``t`` from the third axis, the radius is ``tan(t / 2)`` (``"stereographic"``:
277
+ angles are kept) or ``sqrt(2) sin(t / 2)`` (``"equal_area"``: areas are kept)."""
278
+ if projection not in PROJECTIONS:
279
+ raise ValueError(f"projection: one of {PROJECTIONS}, got {projection!r}")
280
+ d = np.asarray(directions, dtype=float)
281
+ d = d / np.linalg.norm(d, axis=-1, keepdims=True)
282
+ d = np.where(d[..., 2:3] < 0.0, -d, d)
283
+ z = d[..., 2:3]
284
+ scale = 1.0 / (1.0 + z) if projection == "stereographic" else 1.0 / np.sqrt(1.0 + z)
285
+ return d[..., :2] * scale
286
+
287
+
288
+ def unproject(points, projection: str = "stereographic") -> np.ndarray:
289
+ """The directions of the upper hemisphere of points ``(..., 2)`` of the unit disc
290
+ (the inverse of :func:`project`)."""
291
+ if projection not in PROJECTIONS:
292
+ raise ValueError(f"projection: one of {PROJECTIONS}, got {projection!r}")
293
+ p = np.asarray(points, dtype=float)
294
+ r2 = np.sum(p * p, axis=-1, keepdims=True)
295
+ if projection == "stereographic":
296
+ z = (1.0 - r2) / (1.0 + r2)
297
+ return np.concatenate([p * (1.0 + z), z], axis=-1)
298
+ z = 1.0 - r2
299
+ return np.concatenate([p * np.sqrt(np.maximum(2.0 - r2, 0.0)), z], axis=-1)
300
+
301
+
302
+ @njit(parallel=True, cache=True)
303
+ def _axial_density(points, axes, weights, kappa, out):
304
+ """``out[q] = sum_p weights[p] K(points[q] . axes[p])`` with the axial von Mises-Fisher
305
+ kernel ``K(t) = kappa cosh(kappa t) / sinh(kappa)``, of mean one over the sphere
306
+ (terms below 1e-12 of the largest are left out)."""
307
+ scale = kappa / (1.0 - math.exp(-2.0 * kappa))
308
+ cut = 1.0 + math.log(1e-12) / kappa
309
+ for q in prange(points.shape[0]):
310
+ x, y, z = points[q, 0], points[q, 1], points[q, 2]
311
+ s = 0.0
312
+ for p in range(axes.shape[0]):
313
+ t = abs(x * axes[p, 0] + y * axes[p, 1] + z * axes[p, 2])
314
+ if t > cut:
315
+ s += weights[p] * (math.exp(kappa * (t - 1.0)) + math.exp(-kappa * (t + 1.0)))
316
+ out[q] = scale * s
317
+
318
+
319
+ def _concentration(halfwidth: float) -> float:
320
+ """The concentration of the kernel whose value is halved at ``halfwidth`` degrees
321
+ from its axis."""
322
+ if not 0.0 < halfwidth < 90.0:
323
+ raise ValueError(f"halfwidth: an angle between 0 and 90 degrees, got {halfwidth!r}")
324
+ return math.log(2.0) / (1.0 - math.cos(math.radians(halfwidth)))
325
+
326
+
327
+ def axis_density(directions, axes, weights=None, halfwidth: float = 10.0) -> np.ndarray:
328
+ """The density of axes on the sphere (unit vectors ``(p, 3)``, a vector and its
329
+ opposite being one axis, of ``weights`` that sum to one by default) at the directions
330
+ ``(q, 3)``, in multiples of the uniform density: each axis spread by a kernel of
331
+ half-width ``halfwidth`` degrees."""
332
+ d = np.ascontiguousarray(np.asarray(directions, dtype=float).reshape(-1, 3))
333
+ a = np.ascontiguousarray(np.asarray(axes, dtype=float).reshape(-1, 3))
334
+ w = np.full(len(a), 1.0 / max(len(a), 1)) if weights is None else np.asarray(weights, float)
335
+ if w.shape != (len(a),):
336
+ raise ValueError("axis_density: one weight per axis")
337
+ out = np.empty(len(d))
338
+ _axial_density(d, a, np.ascontiguousarray(w), _concentration(halfwidth), out)
339
+ return out
340
+
341
+
342
+ @dataclass(frozen=True)
343
+ class PoleFigure:
344
+ """The density of the poles of a family of planes (or of directions) on the disc of
345
+ a projection, in multiples of that of a random texture."""
346
+
347
+ #: The indices of the family, its lattice and whether they are those of planes
348
+ indices: tuple
349
+ lattice: str
350
+ plane: bool
351
+ #: The projection of the hemisphere, and the half-width (degrees) of the kernel
352
+ projection: str
353
+ halfwidth: float
354
+ #: The coordinates of the columns and of the rows of the grid, from -1 to 1
355
+ x: np.ndarray
356
+ #: ``density[i, j]`` at the point ``(x[i], x[j])`` of the disc; NaN outside it
357
+ density: np.ndarray
358
+
359
+ @property
360
+ def maximum(self) -> float:
361
+ """The largest density of the figure."""
362
+ return float(np.nanmax(self.density))
363
+
364
+ def at(self, direction) -> float:
365
+ """The density at the grid point of the disc nearest to a direction of the
366
+ sample."""
367
+ p = project(np.asarray(direction, dtype=float), self.projection)
368
+ gap = (self.x[:, None] - p[0]) ** 2 + (self.x[None, :] - p[1]) ** 2
369
+ gap[np.isnan(self.density)] = np.inf
370
+ i, j = np.unravel_index(int(np.argmin(gap)), gap.shape)
371
+ return float(self.density[i, j])
372
+
373
+
374
+ def pole_figure(orientations, indices, lattice: str = "cubic", *, weights=None,
375
+ halfwidth: float = 10.0, resolution: int = 101,
376
+ projection: str = "equal_area", plane: bool = True,
377
+ c_over_a: float | None = None) -> PoleFigure: # fmt: skip
378
+ """The pole figure of a family of planes ``indices`` of crystals of a lattice
379
+ (``weights``: the volume of each, equal by default): the density of their poles on a
380
+ grid of ``resolution`` points across the disc of a projection, in multiples of that of
381
+ a random texture, each pole spread by a kernel of half-width ``halfwidth`` degrees."""
382
+ if resolution < 3:
383
+ raise ValueError("resolution: three points at least across the disc")
384
+ directions = poles(orientations, indices, lattice, plane=plane, c_over_a=c_over_a)
385
+ n, m, _ = directions.shape
386
+ w = np.ones(n) if weights is None else np.asarray(weights, dtype=float).ravel()
387
+ if w.shape != (n,) or n == 0 or not w.sum() > 0:
388
+ raise ValueError("pole_figure: one positive weight per crystal")
389
+ each = np.repeat(w / (w.sum() * m), m)
390
+ x = np.linspace(-1.0, 1.0, int(resolution))
391
+ grid = np.stack(np.meshgrid(x, x, indexing="ij"), axis=-1)
392
+ inside = np.sum(grid * grid, axis=-1) <= 1.0 + 1e-12
393
+ density = np.full(grid.shape[:2], np.nan)
394
+ density[inside] = axis_density(unproject(grid[inside], projection),
395
+ directions.reshape(-1, 3), each, halfwidth) # fmt: skip
396
+ return PoleFigure(tuple(int(v) for v in indices), lattice, bool(plane), projection,
397
+ float(halfwidth), x, density) # fmt: skip
398
+
399
+
400
+ def fundamental_directions(directions, lattice: str = "cubic") -> np.ndarray:
401
+ """Directions of a crystal ``(n, 3)`` (in its axes) brought into the fundamental
402
+ sector of the lattice by its symmetries and the inversion: unit vectors with ``0 <=
403
+ x <= y <= z`` for the cube (the triangle of [001], [011] and [111]); with ``z >= 0``
404
+ and an azimuth between 0 (``[2 -1 -1 0]``) and 30 degrees (``[1 0 -1 0]``) for the
405
+ hexagonal lattice."""
406
+ if lattice not in LATTICES:
407
+ raise ValueError(f"lattice: one of {LATTICES} for inverse pole figures, got {lattice!r}")
408
+ c = np.asarray(directions, dtype=float).reshape(-1, 3)
409
+ c = c / np.linalg.norm(c, axis=1)[:, None]
410
+ if lattice == "cubic":
411
+ return np.sort(np.abs(c), axis=1)
412
+ radius = np.hypot(c[:, 0], c[:, 1])
413
+ azimuth = np.mod(np.arctan2(c[:, 1], c[:, 0]), math.pi / 3.0)
414
+ azimuth = np.where(azimuth > math.pi / 6.0, math.pi / 3.0 - azimuth, azimuth)
415
+ return np.stack([radius * np.cos(azimuth), radius * np.sin(azimuth), np.abs(c[:, 2])], axis=1)
416
+
417
+
418
+ def inverse_poles(orientations, direction=(0.0, 0.0, 1.0), lattice: str = "cubic") -> np.ndarray:
419
+ """The direction of each crystal that lies along a direction of the sample, ``g d``,
420
+ in the fundamental sector of the lattice (:func:`fundamental_directions`): unit
421
+ vectors ``(n, 3)`` in the axes of the crystal."""
422
+ if lattice not in LATTICES:
423
+ raise ValueError(f"lattice: one of {LATTICES} for inverse pole figures, got {lattice!r}")
424
+ d = np.asarray(direction, dtype=float)
425
+ d = d / np.linalg.norm(d)
426
+ return fundamental_directions(np.einsum("nij,j->ni", _matrices(orientations), d), lattice)
427
+
428
+
429
+ def direction_colours(directions, lattice: str = "cubic") -> np.ndarray:
430
+ """The colours ``(n, 3)`` (red, green, blue, from 0 to 1) of directions of a crystal:
431
+ red, green and blue at the corners of the fundamental sector — [001], [011] and
432
+ [111] of the cube; [0001], [2 -1 -1 0] and [1 0 -1 0] of the hexagonal lattice — and
433
+ their mixtures in between, the largest of the three brought to one."""
434
+ c = fundamental_directions(directions, lattice)
435
+ if lattice == "cubic":
436
+ rgb = np.stack([c[:, 2] - c[:, 1], c[:, 1] - c[:, 0], math.sqrt(3.0) * c[:, 0]], axis=1)
437
+ else:
438
+ share = np.arctan2(c[:, 1], c[:, 0]) / (math.pi / 6.0)
439
+ basal = np.hypot(c[:, 0], c[:, 1])
440
+ rgb = np.stack([c[:, 2], basal * (1.0 - share), basal * share], axis=1)
441
+ rgb = np.maximum(rgb, 0.0)
442
+ return rgb / np.maximum(rgb.max(axis=1, keepdims=True), 1e-300)
443
+
444
+
445
+ def ipf_colours(orientations, direction=(0.0, 0.0, 1.0), lattice: str = "cubic") -> np.ndarray:
446
+ """The colours ``(n, 3)`` of crystals by the direction that they have along a
447
+ direction of the sample (:func:`direction_colours` of ``g d``): the colours of an
448
+ inverse pole figure map."""
449
+ return direction_colours(inverse_poles(orientations, direction, lattice), lattice)
450
+
451
+
452
+ #: The corners of the fundamental sector of a lattice (crystal directions), with their
453
+ #: names: the colours red, green and blue of :func:`direction_colours`
454
+ SECTOR_CORNERS = {
455
+ "cubic": (((0.0, 0.0, 1.0), "001"), ((0.0, 1.0, 1.0), "011"), ((1.0, 1.0, 1.0), "111")),
456
+ "hexagonal": (((0.0, 0.0, 1.0), "0001"), ((1.0, 0.0, 0.0), "2-1-10"),
457
+ ((math.sqrt(3.0), 1.0, 0.0), "10-10")),
458
+ } # fmt: skip
459
+
460
+
461
+ def sector_points(directions, lattice: str = "cubic") -> np.ndarray:
462
+ """The points ``(n, 2)`` of the fundamental sector, as an inverse pole figure shows
463
+ it (the stereographic projection about the third axis of the crystal), of directions
464
+ of a crystal: [001] at the origin, [011] on the first axis and [111] above it for the
465
+ cube; [0001] at the origin, ``[2 -1 -1 0]`` on the first axis and ``[1 0 -1 0]``
466
+ above it for the hexagonal lattice."""
467
+ c = fundamental_directions(directions, lattice)
468
+ p = c[:, :2] / (1.0 + c[:, 2:3])
469
+ return p[:, ::-1] if lattice == "cubic" else p
470
+
471
+
472
+ def _sector_directions(points, lattice: str):
473
+ """The directions of the points of the plane of an inverse pole figure, and whether
474
+ they are in the fundamental sector."""
475
+ p = np.asarray(points, dtype=float).reshape(-1, 2)
476
+ d = unproject(p[:, ::-1] if lattice == "cubic" else p, "stereographic")
477
+ if lattice == "cubic":
478
+ inside = (d[:, 0] >= -1e-12) & (d[:, 0] <= d[:, 1] + 1e-12) & (d[:, 1] <= d[:, 2] + 1e-12)
479
+ else:
480
+ azimuth = np.arctan2(d[:, 1], d[:, 0])
481
+ inside = (azimuth >= -1e-12) & (azimuth <= math.pi / 6.0 + 1e-12)
482
+ inside &= np.sum(p * p, axis=1) <= 1.0 + 1e-12
483
+ return d, inside
484
+
485
+
486
+ @dataclass(frozen=True)
487
+ class InversePoleFigure:
488
+ """The density of the directions of the crystals that lie along a direction of the
489
+ sample, on the fundamental sector of the lattice (the plane of
490
+ :func:`sector_points`), in multiples of that of a random texture."""
491
+
492
+ #: The direction of the sample, the lattice and the half-width (degrees) of the kernel
493
+ direction: tuple
494
+ lattice: str
495
+ halfwidth: float
496
+ #: The coordinates of the columns and of the rows of the grid
497
+ x: np.ndarray
498
+ y: np.ndarray
499
+ #: ``density[i, j]`` at the point ``(x[i], y[j])``; NaN outside the sector
500
+ density: np.ndarray
501
+
502
+ @property
503
+ def maximum(self) -> float:
504
+ """The largest density of the figure."""
505
+ return float(np.nanmax(self.density))
506
+
507
+ def at(self, direction) -> float:
508
+ """The density at the grid point of the sector nearest to a direction of the
509
+ crystal."""
510
+ p = sector_points(np.asarray(direction, dtype=float), self.lattice)[0]
511
+ gap = (self.x[:, None] - p[0]) ** 2 + (self.y[None, :] - p[1]) ** 2
512
+ gap[np.isnan(self.density)] = np.inf
513
+ i, j = np.unravel_index(int(np.argmin(gap)), gap.shape)
514
+ return float(self.density[i, j])
515
+
516
+
517
+ def inverse_pole_figure(orientations, direction=(0.0, 0.0, 1.0), lattice: str = "cubic", *,
518
+ weights=None, halfwidth: float = 10.0,
519
+ resolution: int = 101) -> InversePoleFigure: # fmt: skip
520
+ """The inverse pole figure of a direction of the sample (the axis of a tension):
521
+ the density of the directions ``g d`` of the crystals (``weights``: the volume of
522
+ each, equal by default) with all their equivalents by the symmetries of the lattice,
523
+ on a grid of ``resolution`` points across the fundamental sector, in multiples of
524
+ that of a random texture, each direction spread by a kernel of half-width
525
+ ``halfwidth`` degrees."""
526
+ if lattice not in LATTICES:
527
+ raise ValueError(f"lattice: one of {LATTICES} for inverse pole figures, got {lattice!r}")
528
+ if resolution < 3:
529
+ raise ValueError("resolution: three points at least across the sector")
530
+ g = _matrices(orientations)
531
+ w = np.ones(len(g)) if weights is None else np.asarray(weights, dtype=float).ravel()
532
+ if w.shape != (len(g),) or len(g) == 0 or not w.sum() > 0:
533
+ raise ValueError("inverse_pole_figure: one positive weight per crystal")
534
+ d = np.asarray(direction, dtype=float)
535
+ d = d / np.linalg.norm(d)
536
+ ops = symmetries(lattice)
537
+ along = np.einsum("sij,nj->nsi", ops, np.einsum("nij,j->ni", g, d))
538
+ each = np.repeat(w / (w.sum() * len(ops)), len(ops))
539
+ width, height = (math.sqrt(2.0) - 1.0, 0.3661) if lattice == "cubic" else (1.0, 0.5)
540
+ x = np.linspace(0.0, width, int(resolution))
541
+ y = np.linspace(0.0, height, max(3, round(resolution * height / width)))
542
+ grid = np.stack(np.meshgrid(x, y, indexing="ij"), axis=-1)
543
+ points, inside = _sector_directions(grid.reshape(-1, 2), lattice)
544
+ density = np.full(len(points), np.nan)
545
+ density[inside] = axis_density(points[inside], along.reshape(-1, 3), each, halfwidth)
546
+ return InversePoleFigure(tuple(float(v) for v in d), lattice, float(halfwidth), x, y,
547
+ density.reshape(len(x), len(y))) # fmt: skip
548
+
549
+
550
+ #: The angles (degrees) at which the density of Mackenzie changes its expression, and the
551
+ #: largest disorientation of two cubic crystals
552
+ MACKENZIE_ANGLES = (
553
+ 45.0,
554
+ 60.0,
555
+ math.degrees(2.0 * math.atan(math.sqrt(2.0) * (math.sqrt(2.0) - 1.0))),
556
+ math.degrees(2.0 * math.atan(math.sqrt(2.0 * (math.sqrt(2.0) - 1.0) ** 2
557
+ + (3.0 - 2.0 * math.sqrt(2.0)) ** 2))),
558
+ ) # fmt: skip
559
+
560
+
561
+ def mackenzie(angles) -> np.ndarray:
562
+ """The density, per degree, of the disorientation of two cubic crystals of random
563
+ orientations (Mackenzie 1958; Handscomb 1958) at ``angles`` (degrees): ``(2/15) (1 -
564
+ cos t)`` up to 45 degrees — 24 times the density of the angle of a random rotation —,
565
+ then less, as the rotations leave the fundamental zone through its faces {100} (45
566
+ degrees) and {111} (60 degrees), its edges (60.72) and its corners (62.80, the
567
+ largest disorientation). Its mean is 40.74 degrees."""
568
+ t = np.radians(np.asarray(angles, dtype=float))
569
+ r1, r2, r3, r4 = np.radians(MACKENZIE_ANGLES)
570
+ root = math.sqrt(2.0)
571
+ a = 3.0 * (root - 1.0)
572
+ b = a + 4.0 / math.sqrt(3.0)
573
+ rise = 1.0 - np.cos(t)
574
+ out = np.zeros_like(t)
575
+ m = (t >= 0.0) & (t <= r1)
576
+ out[m] = rise[m]
577
+ m = (t > r1) & (t <= r2)
578
+ out[m] = a * np.sin(t[m]) - 2.0 * rise[m]
579
+ m = (t > r2) & (t <= r4)
580
+ out[m] = b * np.sin(t[m]) - 6.0 * rise[m]
581
+ m = (t > r3) & (t < r4)
582
+ cot = 1.0 / np.tan(0.5 * t[m])
583
+ x = (root - 1.0) / np.sqrt(1.0 - (root - 1.0) ** 2 * cot**2)
584
+ y = (root - 1.0) ** 2 / np.sqrt(3.0 - cot**2)
585
+ first = 2.0 * (root - 1.0) * np.arccos(np.clip(x * cot, -1.0, 1.0))
586
+ first += np.arccos(np.clip(y * cot, -1.0, 1.0)) / math.sqrt(3.0)
587
+ second = 2.0 * np.arccos(np.clip((root + 1.0) * x / root, -1.0, 1.0))
588
+ second += np.arccos(np.clip((root + 1.0) * y / root, -1.0, 1.0))
589
+ out[m] += (12.0 / math.pi) * (second * rise[m] - first * np.sin(t[m]))
590
+ out[t >= r4] = 0.0
591
+ return (2.0 / 15.0) * out
592
+
593
+
594
+ def boundary_disorientations(labels, orientations, lattice: str = "cubic"):
595
+ """The disorientations across the boundaries of the grains of an image of labels (2D
596
+ or 3D; negative labels: no grain) whose grains have the given orientations: the pairs
597
+ of neighbouring grains ``(b, 2)``, the number of faces of pixels (voxels) that each
598
+ pair shares, and its disorientation (degrees)."""
599
+ lab = np.asarray(labels)
600
+ pairs = []
601
+ for axis in range(lab.ndim):
602
+ a = np.moveaxis(lab, axis, 0)
603
+ first, second = a[:-1].ravel(), a[1:].ravel()
604
+ keep = (first != second) & (first >= 0) & (second >= 0)
605
+ pairs.append(np.stack([np.minimum(first[keep], second[keep]),
606
+ np.maximum(first[keep], second[keep])], axis=1)) # fmt: skip
607
+ both = np.concatenate(pairs) if pairs else np.empty((0, 2), dtype=np.int64)
608
+ if not len(both):
609
+ return np.empty((0, 2), dtype=np.int64), np.empty(0, dtype=np.int64), np.empty(0)
610
+ unique, counts = np.unique(both, axis=0, return_counts=True)
611
+ g = _matrices(orientations)
612
+ angles = disorientation(g[unique[:, 0]], g[unique[:, 1]], lattice)
613
+ return unique.astype(np.int64), counts.astype(np.int64), angles
614
+
615
+
616
+ def sample_texture(rng: np.random.Generator, orientations, n: int, *, weights=None,
617
+ spread: float = 0.0) -> np.ndarray: # fmt: skip
618
+ """``n`` orientations (Euler angles, degrees) drawn from a measured texture: each is
619
+ one of the given crystals, drawn with its weight (the area of a grain of a map;
620
+ equal by default), then turned about a random axis by an angle of the half-normal
621
+ law of standard deviation ``spread`` degrees (0: the measured orientations
622
+ themselves). The crystals of a synthetic polycrystal then have the texture of the
623
+ map."""
624
+ g = _matrices(orientations)
625
+ w = np.ones(len(g)) if weights is None else np.asarray(weights, dtype=float).ravel()
626
+ if w.shape != (len(g),) or len(g) == 0 or not w.sum() > 0 or np.any(w < 0):
627
+ raise ValueError("sample_texture: one weight per crystal, none negative")
628
+ if spread < 0:
629
+ raise ValueError("spread: an angle, not negative")
630
+ drawn = g[rng.choice(len(g), size=int(n), p=w / w.sum())]
631
+ if spread > 0:
632
+ axes = uniform_unit_vectors(rng, int(n))
633
+ angles = np.radians(np.abs(rng.normal(0.0, float(spread), int(n))))
634
+ drawn = drawn @ _turns(axes, angles)
635
+ return matrix_to_euler(drawn)
636
+
637
+
638
+ __all__ = [
639
+ "CLASSES",
640
+ "IDEAL_RATIO",
641
+ "LATTICES",
642
+ "MACKENZIE_ANGLES",
643
+ "PROJECTIONS",
644
+ "SECTOR_CORNERS",
645
+ "InversePoleFigure",
646
+ "PoleFigure",
647
+ "axis_density",
648
+ "boundary_disorientations",
649
+ "crystal_axes",
650
+ "direction_colours",
651
+ "disorientation",
652
+ "fundamental_directions",
653
+ "inverse_pole_figure",
654
+ "inverse_poles",
655
+ "ipf_colours",
656
+ "mackenzie",
657
+ "mean_orientation",
658
+ "pole_figure",
659
+ "poles",
660
+ "project",
661
+ "sample_texture",
662
+ "sector_points",
663
+ "symmetries",
664
+ "unproject",
665
+ ]