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.
- morphogen/__init__.py +60 -0
- morphogen/__main__.py +7 -0
- morphogen/_platform.py +55 -0
- morphogen/_public.py +153 -0
- morphogen/_utils.py +80 -0
- morphogen/_version.py +1 -0
- morphogen/analysis/__init__.py +174 -0
- morphogen/analysis/anisotropy.py +135 -0
- morphogen/analysis/basic.py +38 -0
- morphogen/analysis/cells.py +54 -0
- morphogen/analysis/connectivity.py +156 -0
- morphogen/analysis/correlation.py +195 -0
- morphogen/analysis/covariance.py +80 -0
- morphogen/analysis/fractal.py +54 -0
- morphogen/analysis/measures.py +188 -0
- morphogen/analysis/morphology.py +265 -0
- morphogen/analysis/particles.py +160 -0
- morphogen/analysis/percolation.py +2034 -0
- morphogen/analysis/power_laws.py +143 -0
- morphogen/analysis/random_sets.py +351 -0
- morphogen/analysis/stereology.py +289 -0
- morphogen/analysis/surface.py +107 -0
- morphogen/analysis/topology.py +92 -0
- morphogen/automata/__init__.py +74 -0
- morphogen/automata/engine.py +211 -0
- morphogen/automata/growth.py +686 -0
- morphogen/automata/lattice.py +143 -0
- morphogen/automata/reaction.py +255 -0
- morphogen/automata/rules.py +353 -0
- morphogen/automata/tilings.py +1715 -0
- morphogen/cli.py +3526 -0
- morphogen/config.py +2167 -0
- morphogen/contact/__init__.py +113 -0
- morphogen/contact/experiments.py +368 -0
- morphogen/contact/hertz.py +104 -0
- morphogen/contact/kernels.py +827 -0
- morphogen/contact/periodic.py +278 -0
- morphogen/contact/problem.py +578 -0
- morphogen/contact/surfaces.py +310 -0
- morphogen/coupling/__init__.py +43 -0
- morphogen/coupling/ageing.py +143 -0
- morphogen/coupling/diffusion.py +226 -0
- morphogen/coupling/fenicsx.py +484 -0
- morphogen/coupling/oxidation.py +447 -0
- morphogen/coupling/plates.py +247 -0
- morphogen/design/__init__.py +51 -0
- morphogen/design/csp.py +616 -0
- morphogen/design/frames.py +277 -0
- morphogen/design/search.py +287 -0
- morphogen/design/tiles.py +336 -0
- morphogen/distributions.py +312 -0
- morphogen/domain.py +203 -0
- morphogen/dynamics/__init__.py +179 -0
- morphogen/dynamics/model.py +638 -0
- morphogen/dynamics/openradioss.py +643 -0
- morphogen/dynamics/results.py +515 -0
- morphogen/fracture/__init__.py +170 -0
- morphogen/fracture/bulk.py +349 -0
- morphogen/fracture/cohesive.py +1614 -0
- morphogen/fracture/ductile.py +557 -0
- morphogen/fracture/lefm.py +1168 -0
- morphogen/fracture/mixed.py +1178 -0
- morphogen/fracture/periodic.py +733 -0
- morphogen/fracture/phasefield.py +714 -0
- morphogen/fracture/phasefield_finite.py +368 -0
- morphogen/fracture/surface.py +572 -0
- morphogen/fracture/toughness.py +566 -0
- morphogen/gpu.py +108 -0
- morphogen/gui/__init__.py +8 -0
- morphogen/gui/api.py +1927 -0
- morphogen/gui/desktop.py +387 -0
- morphogen/gui/icon.png +0 -0
- morphogen/gui/index.html +1909 -0
- morphogen/gui/server.py +229 -0
- morphogen/gui/tools/__init__.py +629 -0
- morphogen/gui/tools/compare.py +149 -0
- morphogen/gui/tools/contact.py +391 -0
- morphogen/gui/tools/couplings.py +1085 -0
- morphogen/gui/tools/crackfront.py +245 -0
- morphogen/gui/tools/design.py +224 -0
- morphogen/gui/tools/dynamics.py +824 -0
- morphogen/gui/tools/fracture.py +2586 -0
- morphogen/gui/tools/interop.py +1654 -0
- morphogen/gui/tools/learning.py +595 -0
- morphogen/gui/tools/mechanics.py +3881 -0
- morphogen/gui/tools/nonlocal_damage.py +1321 -0
- morphogen/gui/tools/phasefield.py +215 -0
- morphogen/gui/tools/physics.py +597 -0
- morphogen/gui/tools/stability.py +1756 -0
- morphogen/gui/tools/statistics.py +1408 -0
- morphogen/gui/viewer.js +1100 -0
- morphogen/homogenization/__init__.py +210 -0
- morphogen/homogenization/acoustics.py +566 -0
- morphogen/homogenization/amg.py +1005 -0
- morphogen/homogenization/apparent.py +1046 -0
- morphogen/homogenization/behaviours.cu +2285 -0
- morphogen/homogenization/behaviours.py +944 -0
- morphogen/homogenization/beremin.py +263 -0
- morphogen/homogenization/bifurcation.py +1085 -0
- morphogen/homogenization/bloch.py +507 -0
- morphogen/homogenization/bounds.py +226 -0
- morphogen/homogenization/core.py +458 -0
- morphogen/homogenization/coupled.py +1135 -0
- morphogen/homogenization/crystal.py +2967 -0
- morphogen/homogenization/dilatation.py +454 -0
- morphogen/homogenization/elements.py +157 -0
- morphogen/homogenization/fatigue.py +768 -0
- morphogen/homogenization/fe.py +1739 -0
- morphogen/homogenization/fenicsx.py +307 -0
- morphogen/homogenization/fft.py +499 -0
- morphogen/homogenization/fft_nonlinear.py +391 -0
- morphogen/homogenization/finite.py +613 -0
- morphogen/homogenization/flow.py +361 -0
- morphogen/homogenization/frames.py +1125 -0
- morphogen/homogenization/gpu.py +1241 -0
- morphogen/homogenization/harmonic.py +427 -0
- morphogen/homogenization/identification.py +579 -0
- morphogen/homogenization/kernels.py +760 -0
- morphogen/homogenization/laws.py +2061 -0
- morphogen/homogenization/materials.py +1080 -0
- morphogen/homogenization/mfront.py +589 -0
- morphogen/homogenization/networks.py +880 -0
- morphogen/homogenization/nonlinear.py +2612 -0
- morphogen/homogenization/ntfa.py +577 -0
- morphogen/homogenization/paths.py +476 -0
- morphogen/homogenization/photonic.py +467 -0
- morphogen/homogenization/poroelastic.py +212 -0
- morphogen/homogenization/porous.py +1120 -0
- morphogen/homogenization/postprocess.py +290 -0
- morphogen/homogenization/solvers.py +1140 -0
- morphogen/homogenization/tensors.py +240 -0
- morphogen/homogenization/voxel_fe.py +457 -0
- morphogen/homogenization/xfem.py +1016 -0
- morphogen/homogenization/zmat.py +1258 -0
- morphogen/iga/__init__.py +48 -0
- morphogen/iga/analysis.py +508 -0
- morphogen/iga/basis.py +214 -0
- morphogen/iga/geometry.py +501 -0
- morphogen/iga/homogenization.py +219 -0
- morphogen/iga/optimization.py +700 -0
- morphogen/iga/shapes.py +331 -0
- morphogen/image.py +128 -0
- morphogen/io/__init__.py +246 -0
- morphogen/io/amitex.py +741 -0
- morphogen/io/ebsd.py +881 -0
- morphogen/io/export.py +196 -0
- morphogen/io/geometry.py +158 -0
- morphogen/io/medit.py +147 -0
- morphogen/io/meshes.py +844 -0
- morphogen/io/metaimage.py +97 -0
- morphogen/io/mfront.py +1104 -0
- morphogen/io/native.py +57 -0
- morphogen/io/radioss.py +764 -0
- morphogen/io/solvers.py +371 -0
- morphogen/io/tables.py +278 -0
- morphogen/io/tiff.py +66 -0
- morphogen/io/vtk.py +701 -0
- morphogen/io/xdmf.py +200 -0
- morphogen/kernels/__init__.py +5 -0
- morphogen/kernels/annealing.py +192 -0
- morphogen/kernels/cells.py +69 -0
- morphogen/kernels/collective.py +87 -0
- morphogen/kernels/force_biased.py +595 -0
- morphogen/kernels/implicit.py +145 -0
- morphogen/kernels/leaves.py +132 -0
- morphogen/kernels/packing.py +304 -0
- morphogen/kernels/raster.py +279 -0
- morphogen/kernels/rsa.py +371 -0
- morphogen/kernels/union.py +135 -0
- morphogen/kernels/watershed.py +190 -0
- morphogen/laser/__init__.py +234 -0
- morphogen/laser/architectures.py +375 -0
- morphogen/laser/bending.py +216 -0
- morphogen/laser/cells.py +1694 -0
- morphogen/laser/design.py +940 -0
- morphogen/laser/figures.py +227 -0
- morphogen/laser/heat.py +804 -0
- morphogen/laser/materials.py +691 -0
- morphogen/laser/mechanics.py +1670 -0
- morphogen/laser/metallurgy.py +615 -0
- morphogen/laser/patterns.py +828 -0
- morphogen/laser/periodic.py +392 -0
- morphogen/laser/process.py +362 -0
- morphogen/laser/run.py +534 -0
- morphogen/laser/solid.py +216 -0
- morphogen/laser/specimen.py +200 -0
- morphogen/laser/structures.py +708 -0
- morphogen/learning/__init__.py +81 -0
- morphogen/learning/behaviour.py +398 -0
- morphogen/learning/data.py +328 -0
- morphogen/learning/learned.cpp +668 -0
- morphogen/learning/logarithmic.py +202 -0
- morphogen/learning/mfront.py +409 -0
- morphogen/learning/networks.py +767 -0
- morphogen/learning/run.py +212 -0
- morphogen/learning/standard.py +814 -0
- morphogen/learning/training.py +235 -0
- morphogen/mesh/__init__.py +29 -0
- morphogen/mesh/conforming.py +1423 -0
- morphogen/mesh/curved.py +600 -0
- morphogen/mesh/exact.py +1717 -0
- morphogen/mesh/octree.py +350 -0
- morphogen/mesh/polycrystal.py +1041 -0
- morphogen/mesh/polyhedra.py +677 -0
- morphogen/mesh/regularize.py +570 -0
- morphogen/mesh/surface.py +97 -0
- morphogen/mesh/tetra.py +512 -0
- morphogen/mesh/voxel.py +124 -0
- morphogen/micromorphic/__init__.py +31 -0
- morphogen/micromorphic/damage.py +359 -0
- morphogen/micromorphic/ductile.py +534 -0
- morphogen/micromorphic/finite.py +220 -0
- morphogen/micromorphic/microfoam.py +787 -0
- morphogen/micromorphic/space.py +341 -0
- morphogen/models/__init__.py +195 -0
- morphogen/models/affine.py +384 -0
- morphogen/models/automata.py +592 -0
- morphogen/models/base.py +500 -0
- morphogen/models/boolean.py +310 -0
- morphogen/models/bouligand.py +331 -0
- morphogen/models/branching.py +241 -0
- morphogen/models/combination.py +430 -0
- morphogen/models/deadleaves.py +766 -0
- morphogen/models/design.py +289 -0
- morphogen/models/ebsd.py +206 -0
- morphogen/models/fibers.py +1476 -0
- morphogen/models/foam.py +594 -0
- morphogen/models/gaussian.py +314 -0
- morphogen/models/growth.py +459 -0
- morphogen/models/hardcore.py +317 -0
- morphogen/models/hierarchical.py +269 -0
- morphogen/models/honeycomb.py +749 -0
- morphogen/models/implicit.py +177 -0
- morphogen/models/laminate.py +470 -0
- morphogen/models/lattice.py +351 -0
- morphogen/models/lattice_field.py +345 -0
- morphogen/models/levelset_foam.py +563 -0
- morphogen/models/nacre.py +411 -0
- morphogen/models/nested.py +924 -0
- morphogen/models/osteons.py +374 -0
- morphogen/models/pieces.py +167 -0
- morphogen/models/planar.py +126 -0
- morphogen/models/reconstruction.py +203 -0
- morphogen/models/scale_rich.py +1409 -0
- morphogen/models/scale_rich_3d.py +1616 -0
- morphogen/models/tessellation.py +735 -0
- morphogen/models/tiling_field.py +302 -0
- morphogen/models/tpms.py +197 -0
- morphogen/models/transparent.py +406 -0
- morphogen/models/union.py +141 -0
- morphogen/optimization/__init__.py +43 -0
- morphogen/optimization/cell.py +295 -0
- morphogen/optimization/filters.py +115 -0
- morphogen/optimization/mma.py +226 -0
- morphogen/optimization/run.py +219 -0
- morphogen/optimization/topology.py +632 -0
- morphogen/orientations.py +568 -0
- morphogen/parallel.py +599 -0
- morphogen/pipeline.py +978 -0
- morphogen/primitives.py +188 -0
- morphogen/results.py +564 -0
- morphogen/rve/__init__.py +73 -0
- morphogen/rve/report.py +627 -0
- morphogen/rve/scaling.py +363 -0
- morphogen/rve/study.py +1054 -0
- morphogen/rve/windows.py +345 -0
- morphogen/seeding.py +51 -0
- morphogen/settings.py +118 -0
- morphogen/stopping.py +48 -0
- morphogen/symmetry.py +384 -0
- morphogen/templates/activator_inhibitor.yaml +22 -0
- morphogen/templates/aggregation.yaml +23 -0
- morphogen/templates/boolean_cylinders.yaml +20 -0
- morphogen/templates/boolean_spheres.yaml +22 -0
- morphogen/templates/bouligand.yaml +28 -0
- morphogen/templates/cellular_automaton.yaml +25 -0
- morphogen/templates/coated_spheres.yaml +26 -0
- morphogen/templates/contact_fibers.yaml +27 -0
- morphogen/templates/cox_nanocomposite.yaml +22 -0
- morphogen/templates/cross_linked_fibers.yaml +26 -0
- morphogen/templates/curved_arcs.yaml +28 -0
- morphogen/templates/curved_fibers.yaml +24 -0
- morphogen/templates/dead_leaves.yaml +22 -0
- morphogen/templates/delaunay_network.yaml +22 -0
- morphogen/templates/dense_packing.yaml +22 -0
- morphogen/templates/diffusion.yaml +33 -0
- morphogen/templates/ebsd.yaml +34 -0
- morphogen/templates/ebsd_map.ctf +3087 -0
- morphogen/templates/fracture_composite.yaml +42 -0
- morphogen/templates/fracture_rubber.yaml +47 -0
- morphogen/templates/gaussian_excursion.yaml +17 -0
- morphogen/templates/graded_lattice.yaml +24 -0
- morphogen/templates/hardcore_fibers.yaml +22 -0
- morphogen/templates/hardcore_spheres.yaml +22 -0
- morphogen/templates/hierarchical_lattice.yaml +22 -0
- morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
- morphogen/templates/homogenization_beremin.yaml +50 -0
- morphogen/templates/homogenization_cleavage.yaml +51 -0
- morphogen/templates/homogenization_cleavage_band.yaml +55 -0
- morphogen/templates/homogenization_contact.yaml +43 -0
- morphogen/templates/homogenization_crack_closure.yaml +49 -0
- morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
- morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
- morphogen/templates/homogenization_crystallization.yaml +30 -0
- morphogen/templates/homogenization_debonding.yaml +43 -0
- morphogen/templates/homogenization_detwinning.yaml +58 -0
- morphogen/templates/homogenization_ductile_damage.yaml +47 -0
- morphogen/templates/homogenization_fatigue.yaml +40 -0
- morphogen/templates/homogenization_grain_fracture.yaml +56 -0
- morphogen/templates/homogenization_gyroid.yaml +30 -0
- morphogen/templates/homogenization_intergranular.yaml +43 -0
- morphogen/templates/homogenization_interphase.yaml +42 -0
- morphogen/templates/homogenization_mixed_loading.yaml +33 -0
- morphogen/templates/homogenization_ntfa.yaml +56 -0
- morphogen/templates/homogenization_piezoelectric.yaml +27 -0
- morphogen/templates/homogenization_polycrystal.yaml +30 -0
- morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
- morphogen/templates/homogenization_poroelastic.yaml +26 -0
- morphogen/templates/homogenization_rubber.yaml +40 -0
- morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
- morphogen/templates/homogenization_spheres.yaml +31 -0
- morphogen/templates/homogenization_transport.yaml +29 -0
- morphogen/templates/homogenization_twinning.yaml +54 -0
- morphogen/templates/homogenization_viscoelastic.yaml +34 -0
- morphogen/templates/homogenization_viscoplastic.yaml +42 -0
- morphogen/templates/homogenization_voronoi.yaml +26 -0
- morphogen/templates/homogenization_xfem.yaml +23 -0
- morphogen/templates/hyperuniform_cells.yaml +24 -0
- morphogen/templates/laguerre.yaml +18 -0
- morphogen/templates/laser_bending.yaml +35 -0
- morphogen/templates/laser_cells.yaml +38 -0
- morphogen/templates/laser_corrugated.yaml +36 -0
- morphogen/templates/level_set_foam.yaml +29 -0
- morphogen/templates/menger_sponge.yaml +17 -0
- morphogen/templates/nacre.yaml +25 -0
- morphogen/templates/nucleation_growth.yaml +25 -0
- morphogen/templates/optimize_auxetic.yaml +29 -0
- morphogen/templates/optimize_auxetic_3d.yaml +27 -0
- morphogen/templates/optimize_bulk.yaml +23 -0
- morphogen/templates/optimize_conductivity.yaml +20 -0
- morphogen/templates/osteons.yaml +28 -0
- morphogen/templates/penetrable_spheres.yaml +21 -0
- morphogen/templates/poisson_fibers.yaml +21 -0
- morphogen/templates/random_laminate.yaml +26 -0
- morphogen/templates/random_lattice.yaml +27 -0
- morphogen/templates/random_walk_fibers.yaml +26 -0
- morphogen/templates/reaction_diffusion.yaml +22 -0
- morphogen/templates/reconstruction.yaml +22 -0
- morphogen/templates/rve_cellular_automaton.yaml +23 -0
- morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
- morphogen/templates/rve_multiphysics.yaml +43 -0
- morphogen/templates/rve_poisson_fibers.yaml +22 -0
- morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
- morphogen/templates/rve_voronoi_windows.yaml +20 -0
- morphogen/templates/scale_rich_network.yaml +29 -0
- morphogen/templates/scale_rich_plates.yaml +30 -0
- morphogen/templates/sequential_dead_leaves.yaml +25 -0
- morphogen/templates/strut_lattice.yaml +21 -0
- morphogen/templates/tile_assembly.yaml +28 -0
- morphogen/templates/tpms.yaml +19 -0
- morphogen/templates/trabecular_bone.yaml +29 -0
- morphogen/templates/transparent_dead_leaves.yaml +23 -0
- morphogen/templates/vascular_tree.yaml +23 -0
- morphogen/templates/voronoi.yaml +20 -0
- morphogen/templates/wood.yaml +34 -0
- morphogen/templates/workflow.yaml +56 -0
- morphogen/texture.py +665 -0
- morphogen/theory.py +162 -0
- morphogen/viz/__init__.py +12 -0
- morphogen/viz/export.py +244 -0
- morphogen/viz/figures.py +707 -0
- morphogen/viz/png.py +148 -0
- morphogen/viz/sections.py +696 -0
- morphogen/viz/surfaces.py +1352 -0
- morphogen/viz/video.py +904 -0
- morphogen/viz/workflow.py +488 -0
- morphogen-1.0.0.dist-info/METADATA +2316 -0
- morphogen-1.0.0.dist-info/RECORD +381 -0
- morphogen-1.0.0.dist-info/WHEEL +4 -0
- morphogen-1.0.0.dist-info/entry_points.txt +5 -0
- morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
"""Orientation distributions of fibre axes, and random crystallographic orientations.
|
|
2
|
+
|
|
3
|
+
Fibre axes are given in configuration files as::
|
|
4
|
+
|
|
5
|
+
orientation: isotropic # uniform on the unit sphere
|
|
6
|
+
orientation: {type: aligned, direction: [0, 0, 1]} # all fibres along a direction
|
|
7
|
+
orientation: {type: planar, normal: [0, 0, 1]} # uniform in the plane normal to `normal`
|
|
8
|
+
orientation: {type: beta, beta: 0.1, axis: [0, 0, 1]} # Schladitz's beta law about `axis`
|
|
9
|
+
orientation: {type: girdle, sigma: 0.4, axis: [0, 0, 1]} # Gaussian girdle (Chatti et al.)
|
|
10
|
+
orientation: {type: von_mises_fisher, kappa: 10, axis: [0, 0, 1]} # about `axis`
|
|
11
|
+
orientation: {type: mixture, laws: [...], weights: [0.4, 0.6]} # Altendorf et al. 2014
|
|
12
|
+
|
|
13
|
+
Every law has a quadrature (:meth:`OrientationDistribution.quadrature`): axes and weights
|
|
14
|
+
that average functions of the axis (the covariances of the fibre models), and
|
|
15
|
+
:func:`angle_weights` gives the law of the angle between the axes and a direction.
|
|
16
|
+
|
|
17
|
+
Crystal orientations are Bunge Euler angles (phi1, Phi, phi2), convention ZXZ, of
|
|
18
|
+
rotations drawn uniformly on SO(3), of a fibre texture about the axes of one of these
|
|
19
|
+
laws (:func:`fibre_orientations`), or of the texture of an orientation map::
|
|
20
|
+
|
|
21
|
+
texture: {type: measured, file: map.ctf, spread: 2.0} # the grains of an EBSD map
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import math
|
|
27
|
+
from abc import ABC, abstractmethod
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
from morphogen._utils import unit_vector
|
|
33
|
+
|
|
34
|
+
#: Angles of the uniform grid of [0, pi/2] on which functions of the angle between an axis
|
|
35
|
+
#: and a direction are tabulated when a law has more axes than that (:func:`angle_weights`)
|
|
36
|
+
ANGLE_GRID = 193
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def uniform_unit_vectors(rng: np.random.Generator, n: int) -> np.ndarray:
|
|
40
|
+
"""``n`` directions uniformly distributed on the unit sphere."""
|
|
41
|
+
cos_t = rng.uniform(-1.0, 1.0, n)
|
|
42
|
+
phi = rng.uniform(0.0, 2.0 * np.pi, n)
|
|
43
|
+
sin_t = np.sqrt(np.maximum(0.0, 1.0 - cos_t**2))
|
|
44
|
+
return np.stack([sin_t * np.cos(phi), sin_t * np.sin(phi), cos_t], axis=1)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def orthonormal_basis(directions: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
48
|
+
"""Two unit vectors completing each direction into a right-handed orthonormal basis."""
|
|
49
|
+
d = np.asarray(directions, dtype=float).reshape(-1, 3)
|
|
50
|
+
# pick the coordinate axis least aligned with each direction
|
|
51
|
+
helper = np.zeros_like(d)
|
|
52
|
+
helper[np.arange(len(d)), np.argmin(np.abs(d), axis=1)] = 1.0
|
|
53
|
+
e1 = np.cross(d, helper)
|
|
54
|
+
e1 /= np.linalg.norm(e1, axis=1, keepdims=True)
|
|
55
|
+
e2 = np.cross(d, e1)
|
|
56
|
+
return e1, e2
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class OrientationDistribution(ABC):
|
|
60
|
+
"""Distribution of undirected axes."""
|
|
61
|
+
|
|
62
|
+
@abstractmethod
|
|
63
|
+
def sample(self, rng: np.random.Generator, n: int) -> np.ndarray:
|
|
64
|
+
"""Draw ``n`` unit vectors, shape (n, 3)."""
|
|
65
|
+
|
|
66
|
+
@abstractmethod
|
|
67
|
+
def to_config(self):
|
|
68
|
+
"""Plain configuration value."""
|
|
69
|
+
|
|
70
|
+
def quadrature(self, n: int = 24) -> tuple[np.ndarray, np.ndarray]:
|
|
71
|
+
"""Axes (m x 3) and weights (m, summing to 1) such that ``sum(w f(u))``
|
|
72
|
+
approximates ``E[f(u)]`` for smooth functions of the axis. The laws below have
|
|
73
|
+
rules of their own; this default takes ``8 n^2`` axes drawn from a fixed seed (a
|
|
74
|
+
deterministic Monte Carlo rule)."""
|
|
75
|
+
u = self.sample(np.random.default_rng(2026), 8 * n * n).reshape(-1, 3)
|
|
76
|
+
return u, np.full(len(u), 1.0 / len(u))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _about(axis, cosines, weights, azimuths: int) -> tuple[np.ndarray, np.ndarray]:
|
|
80
|
+
"""The product rule of the axes at the polar ``cosines`` (of the given weights)
|
|
81
|
+
about ``axis``, each at ``azimuths`` equally spaced azimuths."""
|
|
82
|
+
a = np.asarray(axis, dtype=float)
|
|
83
|
+
e1, e2 = orthonormal_basis(a[None])
|
|
84
|
+
phi = (np.arange(azimuths) + 0.5) * (2.0 * np.pi / azimuths)
|
|
85
|
+
c = np.clip(np.asarray(cosines, dtype=float), -1.0, 1.0)[:, None, None]
|
|
86
|
+
side = np.cos(phi)[None, :, None] * e1 + np.sin(phi)[None, :, None] * e2
|
|
87
|
+
u = c * a + np.sqrt(1.0 - c * c) * side
|
|
88
|
+
w = np.repeat(np.asarray(weights, dtype=float) / azimuths, azimuths)
|
|
89
|
+
return u.reshape(-1, 3), w
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _legendre(n: int, lo: float = 0.0, hi: float = 1.0) -> tuple[np.ndarray, np.ndarray]:
|
|
93
|
+
"""Gauss-Legendre nodes and weights of ``[lo, hi]`` (weights summing to its length)."""
|
|
94
|
+
x, w = np.polynomial.legendre.leggauss(int(n))
|
|
95
|
+
return lo + 0.5 * (x + 1.0) * (hi - lo), 0.5 * (hi - lo) * w
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class Isotropic(OrientationDistribution):
|
|
100
|
+
def sample(self, rng, n):
|
|
101
|
+
return uniform_unit_vectors(rng, int(n))
|
|
102
|
+
|
|
103
|
+
def to_config(self):
|
|
104
|
+
return "isotropic"
|
|
105
|
+
|
|
106
|
+
def quadrature(self, n=24):
|
|
107
|
+
"""Gauss-Legendre in the cosine to z (``n`` nodes) times ``2n`` azimuths."""
|
|
108
|
+
c, w = _legendre(n, -1.0, 1.0)
|
|
109
|
+
return _about((0.0, 0.0, 1.0), c, 0.5 * w, 2 * n)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass(frozen=True)
|
|
113
|
+
class Aligned(OrientationDistribution):
|
|
114
|
+
direction: tuple[float, float, float] = (0.0, 0.0, 1.0)
|
|
115
|
+
|
|
116
|
+
def __post_init__(self) -> None:
|
|
117
|
+
u = unit_vector(self.direction, "aligned.direction")
|
|
118
|
+
object.__setattr__(self, "direction", tuple(float(c) for c in u))
|
|
119
|
+
|
|
120
|
+
def sample(self, rng, n):
|
|
121
|
+
return np.tile(np.array(self.direction), (int(n), 1))
|
|
122
|
+
|
|
123
|
+
def to_config(self):
|
|
124
|
+
return {"type": "aligned", "direction": list(self.direction)}
|
|
125
|
+
|
|
126
|
+
def quadrature(self, n=24):
|
|
127
|
+
return np.array([self.direction]), np.ones(1)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True)
|
|
131
|
+
class Planar(OrientationDistribution):
|
|
132
|
+
"""Directions uniformly distributed in the plane orthogonal to ``normal``."""
|
|
133
|
+
|
|
134
|
+
normal: tuple[float, float, float] = (0.0, 0.0, 1.0)
|
|
135
|
+
|
|
136
|
+
def __post_init__(self) -> None:
|
|
137
|
+
u = unit_vector(self.normal, "planar.normal")
|
|
138
|
+
if np.max(np.abs(u - np.asarray(self.normal, dtype=float))) <= 1e-15:
|
|
139
|
+
u = np.asarray(self.normal, dtype=float) # a unit normal kept (round trips)
|
|
140
|
+
object.__setattr__(self, "normal", tuple(float(c) for c in u))
|
|
141
|
+
|
|
142
|
+
def sample(self, rng, n):
|
|
143
|
+
e1, e2 = orthonormal_basis(np.array([self.normal]))
|
|
144
|
+
phi = rng.uniform(0.0, 2.0 * np.pi, int(n))[:, None]
|
|
145
|
+
return np.cos(phi) * e1 + np.sin(phi) * e2
|
|
146
|
+
|
|
147
|
+
def to_config(self):
|
|
148
|
+
return {"type": "planar", "normal": list(self.normal)}
|
|
149
|
+
|
|
150
|
+
def quadrature(self, n=24):
|
|
151
|
+
"""``8n`` equally spaced azimuths in the plane (the trapezoidal rule)."""
|
|
152
|
+
return _about(self.normal, np.zeros(1), np.ones(1), 8 * n)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@dataclass(frozen=True)
|
|
156
|
+
class Beta(OrientationDistribution):
|
|
157
|
+
"""The beta law of Schladitz et al. (2006) about ``axis`` (Ohser & Schladitz 2009),
|
|
158
|
+
of density ``beta sin(t) / (4 pi (1 + (beta^2 - 1) cos^2 t)^(3/2))`` in the angle
|
|
159
|
+
``t`` to the axis: uniform for ``beta = 1``, concentrated on the axis as ``beta -> 0``
|
|
160
|
+
and on the plane normal to it as ``beta -> infinity``. Drawn as isotropic directions
|
|
161
|
+
whose component along the axis is divided by ``beta`` (the angular central Gaussian
|
|
162
|
+
law of ``diag(1, 1, 1 / beta^2)``), so that ``P(|cos t| <= c) = beta c / sqrt(1 +
|
|
163
|
+
(beta^2 - 1) c^2)``."""
|
|
164
|
+
|
|
165
|
+
beta: float = 1.0
|
|
166
|
+
axis: tuple[float, float, float] = (0.0, 0.0, 1.0)
|
|
167
|
+
|
|
168
|
+
def __post_init__(self) -> None:
|
|
169
|
+
if not (np.isfinite(self.beta) and self.beta > 0.0):
|
|
170
|
+
raise ValueError(f"beta.beta: a positive number, got {self.beta!r}")
|
|
171
|
+
u = unit_vector(self.axis, "beta.axis")
|
|
172
|
+
if np.max(np.abs(u - np.asarray(self.axis, dtype=float))) <= 1e-15:
|
|
173
|
+
u = np.asarray(self.axis, dtype=float) # a unit axis kept (round trips)
|
|
174
|
+
object.__setattr__(self, "beta", float(self.beta))
|
|
175
|
+
object.__setattr__(self, "axis", tuple(float(c) for c in u))
|
|
176
|
+
|
|
177
|
+
def sample(self, rng, n):
|
|
178
|
+
v = uniform_unit_vectors(rng, int(n))
|
|
179
|
+
a = np.array(self.axis)
|
|
180
|
+
v += (1.0 / self.beta - 1.0) * (v @ a)[:, None] * a
|
|
181
|
+
return v / np.linalg.norm(v, axis=1, keepdims=True)
|
|
182
|
+
|
|
183
|
+
def to_config(self):
|
|
184
|
+
return {"type": "beta", "beta": self.beta, "axis": list(self.axis)}
|
|
185
|
+
|
|
186
|
+
def quadrature(self, n=24):
|
|
187
|
+
"""The quantiles ``c = u / sqrt(beta^2 (1 - u^2) + u^2)`` of ``|cos t|`` at ``n``
|
|
188
|
+
Gauss-Legendre nodes ``u`` of [0, 1], both signs, times ``2n`` azimuths."""
|
|
189
|
+
u, w = _legendre(n)
|
|
190
|
+
c = u / np.sqrt(self.beta**2 * (1.0 - u * u) + u * u)
|
|
191
|
+
return _about(self.axis, np.concatenate([-c, c]), np.concatenate([w, w]) / 2.0, 2 * n)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass(frozen=True)
|
|
195
|
+
class Girdle(OrientationDistribution):
|
|
196
|
+
"""The Gaussian girdle of Chatti et al. (2018, eq. 3) about ``axis``: the angle ``t`` to
|
|
197
|
+
the axis of density proportional to ``sin(t) exp(-(t - pi/2)^2 / 2 sigma^2)`` on [0, pi]
|
|
198
|
+
(``sigma`` in radians), the azimuth uniform: axes gathered about the plane normal to the
|
|
199
|
+
axis as ``sigma -> 0``, isotropic as ``sigma`` grows (their compressed entangled fibres:
|
|
200
|
+
0.4; at most 20, where the density is within 0.4 % of the isotropic one: the rejection
|
|
201
|
+
below keeps fewer draws as ``sigma`` grows). Drawn by rejection: normal angles truncated
|
|
202
|
+
to [0, pi], each kept with the probability ``sin(t)``."""
|
|
203
|
+
|
|
204
|
+
sigma: float = 0.4
|
|
205
|
+
axis: tuple[float, float, float] = (0.0, 0.0, 1.0)
|
|
206
|
+
|
|
207
|
+
def __post_init__(self) -> None:
|
|
208
|
+
if not (np.isfinite(self.sigma) and self.sigma > 0.0):
|
|
209
|
+
raise ValueError(f"girdle.sigma: a positive angle in radians, got {self.sigma!r}")
|
|
210
|
+
if self.sigma > 20.0:
|
|
211
|
+
raise ValueError(
|
|
212
|
+
f"girdle.sigma: at most 20 radians, got {self.sigma!r} (the girdle is then "
|
|
213
|
+
"isotropic within 0.4 %: use the isotropic law)"
|
|
214
|
+
)
|
|
215
|
+
u = unit_vector(self.axis, "girdle.axis")
|
|
216
|
+
if np.max(np.abs(u - np.asarray(self.axis, dtype=float))) <= 1e-15:
|
|
217
|
+
u = np.asarray(self.axis, dtype=float) # a unit axis kept (round trips)
|
|
218
|
+
object.__setattr__(self, "sigma", float(self.sigma))
|
|
219
|
+
object.__setattr__(self, "axis", tuple(float(c) for c in u))
|
|
220
|
+
|
|
221
|
+
def sample(self, rng, n):
|
|
222
|
+
n = int(n)
|
|
223
|
+
angles = np.empty(0)
|
|
224
|
+
while len(angles) < n:
|
|
225
|
+
t = rng.normal(0.5 * np.pi, self.sigma, max(2 * (n - len(angles)), 64))
|
|
226
|
+
t = t[(t >= 0.0) & (t <= np.pi)]
|
|
227
|
+
angles = np.concatenate([angles, t[rng.random(len(t)) < np.sin(t)]])
|
|
228
|
+
t = angles[:n]
|
|
229
|
+
phi = rng.uniform(0.0, 2.0 * np.pi, n)
|
|
230
|
+
a = np.array(self.axis)
|
|
231
|
+
e1, e2 = orthonormal_basis(a)
|
|
232
|
+
side = np.cos(phi)[:, None] * e1 + np.sin(phi)[:, None] * e2
|
|
233
|
+
return np.cos(t)[:, None] * a + np.sin(t)[:, None] * side
|
|
234
|
+
|
|
235
|
+
def to_config(self):
|
|
236
|
+
return {"type": "girdle", "sigma": self.sigma, "axis": list(self.axis)}
|
|
237
|
+
|
|
238
|
+
def quadrature(self, n=24):
|
|
239
|
+
"""``2n`` Gauss-Legendre nodes of the angle ``t`` over ``pi/2 +- 8 sigma`` (within
|
|
240
|
+
[0, pi]) weighted by its density, times ``2n`` azimuths."""
|
|
241
|
+
lo, hi = (
|
|
242
|
+
max(0.0, 0.5 * np.pi - 8.0 * self.sigma),
|
|
243
|
+
min(np.pi, 0.5 * np.pi + 8.0 * self.sigma),
|
|
244
|
+
)
|
|
245
|
+
t, w = _legendre(2 * n, lo, hi)
|
|
246
|
+
w = w * np.sin(t) * np.exp(-((t - 0.5 * np.pi) ** 2) / (2.0 * self.sigma**2))
|
|
247
|
+
return _about(self.axis, np.cos(t), w / w.sum(), 2 * n)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@dataclass(frozen=True)
|
|
251
|
+
class VonMisesFisher(OrientationDistribution):
|
|
252
|
+
"""The von Mises-Fisher law about ``axis``, of density ``kappa exp(kappa cos t) / (4 pi
|
|
253
|
+
sinh kappa)`` in the angle ``t`` to the axis: uniform for ``kappa = 0``, concentrated
|
|
254
|
+
on the axis as ``kappa`` grows (``E[1 - cos t] ~ 1 / kappa``). Drawn by inverting the
|
|
255
|
+
law of ``w = cos t``, ``w = 1 + ln(u + (1 - u) e^(-2 kappa)) / kappa``, the azimuth
|
|
256
|
+
uniform (as the steps of :func:`morphogen.models.fibers.von_mises_fisher`)."""
|
|
257
|
+
|
|
258
|
+
kappa: float = 10.0
|
|
259
|
+
axis: tuple[float, float, float] = (0.0, 0.0, 1.0)
|
|
260
|
+
|
|
261
|
+
def __post_init__(self) -> None:
|
|
262
|
+
if not (np.isfinite(self.kappa) and self.kappa >= 0.0):
|
|
263
|
+
raise ValueError(f"von_mises_fisher.kappa: a non-negative number, got {self.kappa!r}")
|
|
264
|
+
u = unit_vector(self.axis, "von_mises_fisher.axis")
|
|
265
|
+
if np.max(np.abs(u - np.asarray(self.axis, dtype=float))) <= 1e-15:
|
|
266
|
+
u = np.asarray(self.axis, dtype=float) # a unit axis kept (round trips)
|
|
267
|
+
object.__setattr__(self, "kappa", float(self.kappa))
|
|
268
|
+
object.__setattr__(self, "axis", tuple(float(c) for c in u))
|
|
269
|
+
|
|
270
|
+
def _cosines(self, u) -> np.ndarray:
|
|
271
|
+
"""The quantiles of ``cos t`` at the probabilities ``u`` in (0, 1]."""
|
|
272
|
+
k = self.kappa
|
|
273
|
+
if k < 1e-8:
|
|
274
|
+
return 2.0 * u - 1.0
|
|
275
|
+
return 1.0 + np.log(u + (1.0 - u) * math.exp(-2.0 * k)) / k
|
|
276
|
+
|
|
277
|
+
def sample(self, rng, n):
|
|
278
|
+
n = int(n)
|
|
279
|
+
w = self._cosines(1.0 - rng.random(n))
|
|
280
|
+
phi = rng.uniform(0.0, 2.0 * np.pi, n)
|
|
281
|
+
a = np.array(self.axis)
|
|
282
|
+
e1, e2 = orthonormal_basis(a[None])
|
|
283
|
+
s = np.sqrt(np.clip(1.0 - w * w, 0.0, None))
|
|
284
|
+
return w[:, None] * a + s[:, None] * (np.cos(phi)[:, None] * e1 + np.sin(phi)[:, None] * e2)
|
|
285
|
+
|
|
286
|
+
def to_config(self):
|
|
287
|
+
return {"type": "von_mises_fisher", "kappa": self.kappa, "axis": list(self.axis)}
|
|
288
|
+
|
|
289
|
+
def quadrature(self, n=24):
|
|
290
|
+
"""The quantiles of ``cos t`` at ``2n`` Gauss-Legendre nodes of [0, 1], times
|
|
291
|
+
``2n`` azimuths."""
|
|
292
|
+
u, w = _legendre(2 * n)
|
|
293
|
+
return _about(self.axis, self._cosines(u), w, 2 * n)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@dataclass(frozen=True)
|
|
297
|
+
class Mixture(OrientationDistribution):
|
|
298
|
+
"""A mixture of laws: an axis follows ``laws[i]`` with the probability ``weights[i]``
|
|
299
|
+
(normalized), as the mixed beta laws of Altendorf, Jeulin & Willot (2014, eq. 2), an
|
|
300
|
+
orthotropic law of glass fibres (0.393 of a beta law of 0.114 about z, 0.607 of one of
|
|
301
|
+
10.1 about a normal to it)."""
|
|
302
|
+
|
|
303
|
+
laws: tuple[OrientationDistribution, ...] = (Isotropic(),)
|
|
304
|
+
weights: tuple[float, ...] | None = None
|
|
305
|
+
|
|
306
|
+
def __post_init__(self) -> None:
|
|
307
|
+
laws = tuple(self.laws)
|
|
308
|
+
if not laws or not all(isinstance(law, OrientationDistribution) for law in laws):
|
|
309
|
+
raise ValueError("mixture.laws: one or more orientation laws")
|
|
310
|
+
w = np.ones(len(laws)) if self.weights is None else np.asarray(self.weights, dtype=float)
|
|
311
|
+
if w.shape != (len(laws),) or not np.all(np.isfinite(w)) or np.any(w < 0) or w.sum() <= 0:
|
|
312
|
+
raise ValueError("mixture.weights: one non-negative weight per law, not all zero")
|
|
313
|
+
if abs(w.sum() - 1.0) > 1e-12: # normalized weights kept (round trips)
|
|
314
|
+
w = w / w.sum()
|
|
315
|
+
object.__setattr__(self, "laws", laws)
|
|
316
|
+
object.__setattr__(self, "weights", tuple(float(x) for x in w))
|
|
317
|
+
|
|
318
|
+
def sample(self, rng, n):
|
|
319
|
+
n = int(n)
|
|
320
|
+
which = rng.choice(len(self.laws), size=n, p=np.asarray(self.weights))
|
|
321
|
+
out = np.empty((n, 3))
|
|
322
|
+
for i, law in enumerate(self.laws):
|
|
323
|
+
idx = np.flatnonzero(which == i)
|
|
324
|
+
if len(idx):
|
|
325
|
+
out[idx] = law.sample(rng, len(idx)).reshape(-1, 3)
|
|
326
|
+
return out
|
|
327
|
+
|
|
328
|
+
def to_config(self):
|
|
329
|
+
return {"type": "mixture", "laws": [law.to_config() for law in self.laws],
|
|
330
|
+
"weights": list(self.weights)} # fmt: skip
|
|
331
|
+
|
|
332
|
+
def quadrature(self, n=24):
|
|
333
|
+
"""The rules of the laws, their weights times those of the mixture."""
|
|
334
|
+
rules = [law.quadrature(n) for law in self.laws]
|
|
335
|
+
u = np.concatenate([r[0].reshape(-1, 3) for r in rules])
|
|
336
|
+
w = np.concatenate([p * r[1] for p, r in zip(self.weights, rules, strict=True)])
|
|
337
|
+
return u, w
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
@dataclass(frozen=True)
|
|
341
|
+
class Measured(OrientationDistribution):
|
|
342
|
+
"""The texture of an orientation map (EBSD, :mod:`morphogen.io.ebsd`): the crystals
|
|
343
|
+
have the orientations of the grains of the map (``file``: an ``.ang`` or a ``.ctf``
|
|
344
|
+
file, or the name of a map that comes with morphoGen; ``threshold`` and
|
|
345
|
+
``min_size``: those of its grains; ``axes`` and ``setting``: those of its
|
|
346
|
+
orientations), each drawn with the area of its grain, then turned about a random
|
|
347
|
+
axis by an angle of the half-normal law of standard deviation ``spread`` degrees (0:
|
|
348
|
+
the orientations of the grains themselves). ``phase``: the phase of the map whose
|
|
349
|
+
grains are taken (the one of largest area by default). As a law of axes, it is that
|
|
350
|
+
of the third axes of these crystals."""
|
|
351
|
+
|
|
352
|
+
file: str = ""
|
|
353
|
+
spread: float = 0.0
|
|
354
|
+
threshold: float = 5.0
|
|
355
|
+
min_size: int = 5
|
|
356
|
+
phase: int | None = None
|
|
357
|
+
axes: str = "map"
|
|
358
|
+
setting: int = 1
|
|
359
|
+
|
|
360
|
+
def __post_init__(self) -> None:
|
|
361
|
+
if not self.file:
|
|
362
|
+
raise ValueError("measured.file: the orientation map (.ang or .ctf)")
|
|
363
|
+
if not (np.isfinite(self.spread) and self.spread >= 0.0):
|
|
364
|
+
raise ValueError(f"measured.spread: an angle, not negative, got {self.spread!r}")
|
|
365
|
+
object.__setattr__(self, "file", str(self.file))
|
|
366
|
+
object.__setattr__(self, "spread", float(self.spread))
|
|
367
|
+
object.__setattr__(self, "threshold", float(self.threshold))
|
|
368
|
+
object.__setattr__(self, "min_size", int(self.min_size))
|
|
369
|
+
self._model() # (the checks of its other parameters)
|
|
370
|
+
|
|
371
|
+
def _model(self):
|
|
372
|
+
from morphogen.models.ebsd import EBSD
|
|
373
|
+
|
|
374
|
+
try:
|
|
375
|
+
return EBSD(file=self.file, threshold=self.threshold, min_size=self.min_size,
|
|
376
|
+
axes=self.axes, setting=self.setting) # fmt: skip
|
|
377
|
+
except ValueError as exc:
|
|
378
|
+
raise ValueError(f"measured.{exc}") from None
|
|
379
|
+
|
|
380
|
+
def grains(self):
|
|
381
|
+
"""The orientations (Bunge angles, degrees) and the areas of the grains of the
|
|
382
|
+
phase of the map, and the Laue class of that phase."""
|
|
383
|
+
grains = self._model().grains()
|
|
384
|
+
phase = self.phase
|
|
385
|
+
if phase is None:
|
|
386
|
+
areas = np.bincount(grains.phase, weights=grains.areas)
|
|
387
|
+
phase = int(np.argmax(areas))
|
|
388
|
+
of = grains.phase == phase
|
|
389
|
+
if not of.any():
|
|
390
|
+
raise ValueError(f"measured.phase: no grain of the phase {phase} in the map")
|
|
391
|
+
return grains.orientations[of], grains.areas[of], grains.lattice(phase)
|
|
392
|
+
|
|
393
|
+
def orientations(self, rng: np.random.Generator, n: int) -> np.ndarray:
|
|
394
|
+
"""Bunge angles (degrees) of ``n`` crystals of the texture of the map."""
|
|
395
|
+
from morphogen.texture import sample_texture
|
|
396
|
+
|
|
397
|
+
euler, areas, _ = self.grains()
|
|
398
|
+
return sample_texture(rng, euler, int(n), weights=areas, spread=self.spread)
|
|
399
|
+
|
|
400
|
+
def sample(self, rng, n):
|
|
401
|
+
return euler_to_matrix(self.orientations(rng, n))[:, 2, :]
|
|
402
|
+
|
|
403
|
+
def to_config(self):
|
|
404
|
+
out = {"type": "measured", "file": self.file}
|
|
405
|
+
defaults = {"spread": 0.0, "threshold": 5.0, "min_size": 5, "phase": None, "axes": "map",
|
|
406
|
+
"setting": 1} # fmt: skip
|
|
407
|
+
for name, default in defaults.items():
|
|
408
|
+
if getattr(self, name) != default:
|
|
409
|
+
out[name] = getattr(self, name)
|
|
410
|
+
return out
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def half_sphere(n: int = 6) -> tuple[np.ndarray, np.ndarray]:
|
|
414
|
+
"""Directions of the half sphere ``z >= 0`` and their weights (summing to 1): ``n``
|
|
415
|
+
Gauss-Legendre cosines times ``2n`` azimuths, the mean over the directions of an even
|
|
416
|
+
function (``f(-u) = f(u)``)."""
|
|
417
|
+
c, w = _legendre(n)
|
|
418
|
+
return _about((0.0, 0.0, 1.0), c, w, 2 * n)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def angle_weights(orientation: OrientationDistribution, direction=None, n: int = 24, *,
|
|
422
|
+
grid: bool = False): # fmt: skip
|
|
423
|
+
"""The angles ``b`` in [0, pi/2] between the axes of ``orientation`` and ``direction``
|
|
424
|
+
(between undirected lines) and their weights, so that ``sum(w f(b))`` approximates
|
|
425
|
+
``E[f(b)]``: 128 Gauss-Legendre nodes of ``cos b`` in [0, 1] for isotropic axes or
|
|
426
|
+
without a direction (a direction uniform on the sphere); otherwise the angles of the
|
|
427
|
+
axes of the quadrature of the law, gathered on the :data:`ANGLE_GRID` nodes of a
|
|
428
|
+
uniform grid of [0, pi/2] when there are more, or always with ``grid`` (the weight of
|
|
429
|
+
an angle shared by the two nodes about it, in proportion to their nearness: linear
|
|
430
|
+
interpolation of ``f``)."""
|
|
431
|
+
if (direction is None or isinstance(orientation, Isotropic)) and not grid:
|
|
432
|
+
c, w = _legendre(128)
|
|
433
|
+
return np.arccos(c), w
|
|
434
|
+
if direction is None:
|
|
435
|
+
orientation, direction = Isotropic(), (0.0, 0.0, 1.0)
|
|
436
|
+
d = unit_vector(direction, "direction")
|
|
437
|
+
u, w = orientation.quadrature(n)
|
|
438
|
+
angle = np.arccos(np.clip(np.abs(u.reshape(-1, 3) @ d), 0.0, 1.0))
|
|
439
|
+
if len(angle) <= ANGLE_GRID and not grid:
|
|
440
|
+
return angle, w
|
|
441
|
+
grid = np.linspace(0.0, 0.5 * np.pi, ANGLE_GRID)
|
|
442
|
+
pos = angle / grid[1]
|
|
443
|
+
i = np.minimum(pos.astype(np.int64), ANGLE_GRID - 2)
|
|
444
|
+
frac = pos - i
|
|
445
|
+
out = np.zeros(ANGLE_GRID)
|
|
446
|
+
np.add.at(out, i, w * (1.0 - frac))
|
|
447
|
+
np.add.at(out, i + 1, w * frac)
|
|
448
|
+
return grid, out
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
_TYPES = "isotropic, aligned, planar, beta, girdle, von_mises_fisher, mixture, measured"
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def orientation_from_config(value, name: str = "orientation") -> OrientationDistribution:
|
|
455
|
+
"""An orientation distribution from a configuration value: its name (``isotropic``) or
|
|
456
|
+
a mapping with its ``type`` (isotropic, aligned, planar, beta, girdle,
|
|
457
|
+
von_mises_fisher, mixture; measured: the texture of an orientation map) and
|
|
458
|
+
parameters."""
|
|
459
|
+
if isinstance(value, OrientationDistribution):
|
|
460
|
+
return value
|
|
461
|
+
if isinstance(value, str):
|
|
462
|
+
value = {"type": value}
|
|
463
|
+
if not isinstance(value, dict) or "type" not in value:
|
|
464
|
+
raise ValueError(
|
|
465
|
+
f"{name}: expected 'isotropic' or a mapping with a 'type' key ({_TYPES}), got {value!r}"
|
|
466
|
+
)
|
|
467
|
+
cfg = dict(value)
|
|
468
|
+
kind = str(cfg.pop("type")).lower()
|
|
469
|
+
if kind == "mixture" and isinstance(cfg.get("laws"), (list, tuple)): # the laws first
|
|
470
|
+
laws = cfg["laws"]
|
|
471
|
+
cfg["laws"] = tuple(
|
|
472
|
+
orientation_from_config(v, f"{name}.laws[{i}]") for i, v in enumerate(laws)
|
|
473
|
+
)
|
|
474
|
+
try:
|
|
475
|
+
if kind == "isotropic" and not cfg:
|
|
476
|
+
return Isotropic()
|
|
477
|
+
if kind == "aligned" and set(cfg) <= {"direction"}:
|
|
478
|
+
return Aligned(tuple(cfg.get("direction", (0.0, 0.0, 1.0))))
|
|
479
|
+
if kind == "planar" and set(cfg) <= {"normal"}:
|
|
480
|
+
return Planar(tuple(cfg.get("normal", (0.0, 0.0, 1.0))))
|
|
481
|
+
if kind == "beta" and set(cfg) <= {"beta", "axis"}:
|
|
482
|
+
return Beta(float(cfg.get("beta", 1.0)), tuple(cfg.get("axis", (0.0, 0.0, 1.0))))
|
|
483
|
+
if kind == "girdle" and set(cfg) <= {"sigma", "axis"}:
|
|
484
|
+
axis = tuple(cfg.get("axis", (0.0, 0.0, 1.0)))
|
|
485
|
+
return Girdle(float(cfg.get("sigma", 0.4)), axis)
|
|
486
|
+
if kind in ("von_mises_fisher", "vmf") and set(cfg) <= {"kappa", "axis"}:
|
|
487
|
+
axis = tuple(cfg.get("axis", (0.0, 0.0, 1.0)))
|
|
488
|
+
return VonMisesFisher(float(cfg.get("kappa", 10.0)), axis)
|
|
489
|
+
if kind == "measured" and set(cfg) <= {"file", "spread", "threshold", "min_size",
|
|
490
|
+
"phase", "axes", "setting"}: # fmt: skip
|
|
491
|
+
return Measured(**cfg)
|
|
492
|
+
if kind == "mixture" and "laws" in cfg and set(cfg) <= {"laws", "weights"}:
|
|
493
|
+
if not isinstance(cfg["laws"], tuple):
|
|
494
|
+
raise ValueError("mixture.laws: a list of orientation laws")
|
|
495
|
+
weights = cfg.get("weights")
|
|
496
|
+
return Mixture(cfg["laws"], None if weights is None else tuple(map(float, weights)))
|
|
497
|
+
except (TypeError, ValueError) as exc:
|
|
498
|
+
raise ValueError(f"{name}: {exc}") from None
|
|
499
|
+
raise ValueError(f"{name}: invalid orientation {value!r}")
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def random_orientations(rng: np.random.Generator, n: int, *, degrees: bool = True) -> np.ndarray:
|
|
503
|
+
"""Bunge Euler angles (phi1, Phi, phi2) of ``n`` rotations uniform on SO(3).
|
|
504
|
+
|
|
505
|
+
Uniformity on SO(3) means phi1 and phi2 uniform on [0, 2 pi) and cos(Phi) uniform on
|
|
506
|
+
[-1, 1] (the Haar measure is sin(Phi) dphi1 dPhi dphi2 / 8 pi^2).
|
|
507
|
+
"""
|
|
508
|
+
phi1 = rng.uniform(0.0, 2.0 * np.pi, n)
|
|
509
|
+
Phi = np.arccos(rng.uniform(-1.0, 1.0, n))
|
|
510
|
+
phi2 = rng.uniform(0.0, 2.0 * np.pi, n)
|
|
511
|
+
euler = np.stack([phi1, Phi, phi2], axis=1)
|
|
512
|
+
return np.degrees(euler) if degrees else euler
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def fibre_orientations(
|
|
516
|
+
rng: np.random.Generator, n: int, law: OrientationDistribution, *, degrees: bool = True
|
|
517
|
+
) -> np.ndarray:
|
|
518
|
+
"""Bunge Euler angles of ``n`` crystals of a fibre texture: the third axis of each
|
|
519
|
+
crystal (the axis c of a hexagonal lattice) is a direction of the sample drawn from
|
|
520
|
+
``law`` (:class:`VonMisesFisher` about an axis: a basal texture; :class:`Planar`: axes
|
|
521
|
+
c in a plane...), and the crystal is turned about it by a uniform angle. A measured
|
|
522
|
+
texture (:class:`Measured`) gives the orientations of the grains of its map."""
|
|
523
|
+
if isinstance(law, Measured):
|
|
524
|
+
euler = law.orientations(rng, int(n))
|
|
525
|
+
return euler if degrees else np.radians(euler)
|
|
526
|
+
axes = np.asarray(law.sample(rng, int(n)), dtype=float).reshape(-1, 3)
|
|
527
|
+
axes /= np.linalg.norm(axes, axis=1)[:, None]
|
|
528
|
+
e1, e2 = orthonormal_basis(axes)
|
|
529
|
+
spin = rng.uniform(0.0, 2.0 * np.pi, len(axes))
|
|
530
|
+
c, s = np.cos(spin)[:, None], np.sin(spin)[:, None]
|
|
531
|
+
# the rows of g: the axes of the crystal in those of the sample (crystal = g @ sample)
|
|
532
|
+
g = np.stack([c * e1 + s * e2, -s * e1 + c * e2, axes], axis=1)
|
|
533
|
+
return matrix_to_euler(g, degrees=degrees)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def euler_to_matrix(euler, *, degrees: bool = True) -> np.ndarray:
|
|
537
|
+
"""Bunge (ZXZ, passive) rotation matrices g, crystal = g @ sample, shape (n, 3, 3)."""
|
|
538
|
+
e = np.asarray(euler, dtype=float).reshape(-1, 3)
|
|
539
|
+
if degrees:
|
|
540
|
+
e = np.radians(e)
|
|
541
|
+
c1, s1 = np.cos(e[:, 0]), np.sin(e[:, 0])
|
|
542
|
+
c, s = np.cos(e[:, 1]), np.sin(e[:, 1])
|
|
543
|
+
c2, s2 = np.cos(e[:, 2]), np.sin(e[:, 2])
|
|
544
|
+
g = np.empty((len(e), 3, 3))
|
|
545
|
+
g[:, 0, 0] = c1 * c2 - s1 * s2 * c
|
|
546
|
+
g[:, 0, 1] = s1 * c2 + c1 * s2 * c
|
|
547
|
+
g[:, 0, 2] = s2 * s
|
|
548
|
+
g[:, 1, 0] = -c1 * s2 - s1 * c2 * c
|
|
549
|
+
g[:, 1, 1] = -s1 * s2 + c1 * c2 * c
|
|
550
|
+
g[:, 1, 2] = c2 * s
|
|
551
|
+
g[:, 2, 0] = s1 * s
|
|
552
|
+
g[:, 2, 1] = -c1 * s
|
|
553
|
+
g[:, 2, 2] = c
|
|
554
|
+
return g
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def matrix_to_euler(g, *, degrees: bool = True) -> np.ndarray:
|
|
558
|
+
"""Inverse of :func:`euler_to_matrix`; angles in [0, 360) x [0, 180] x [0, 360)."""
|
|
559
|
+
g = np.asarray(g, dtype=float).reshape(-1, 3, 3)
|
|
560
|
+
Phi = np.arccos(np.clip(g[:, 2, 2], -1.0, 1.0))
|
|
561
|
+
sin_phi = np.sin(Phi)
|
|
562
|
+
regular = sin_phi > 1e-9
|
|
563
|
+
phi1 = np.where(
|
|
564
|
+
regular, np.arctan2(g[:, 2, 0], -g[:, 2, 1]), np.arctan2(g[:, 0, 1], g[:, 0, 0])
|
|
565
|
+
)
|
|
566
|
+
phi2 = np.where(regular, np.arctan2(g[:, 0, 2], g[:, 1, 2]), 0.0)
|
|
567
|
+
euler = np.stack([np.mod(phi1, 2 * np.pi), Phi, np.mod(phi2, 2 * np.pi)], axis=1)
|
|
568
|
+
return np.degrees(euler) if degrees else euler
|