upxo.viz.xphy.pole_figure module
pole_figure.py
Self-sufficient advanced pole figure plotting and analysis module for UPXO. Supports stereographic and equal-area projections, custom coloring (hemisphere, role, size, IPF), density contouring (MUD), and 3D slice integration.
- upxo.viz.xphy.pole_figure.cubic_symmetry_operators() ndarray[source]
Generate the 24 proper rotations for cubic symmetry (m-3m) as 3x3 matrices.
- upxo.viz.xphy.pole_figure.hexagonal_symmetry_operators() ndarray[source]
Generate the 12 proper rotations for hexagonal symmetry (6/mmm) as 3x3 matrices.
- upxo.viz.xphy.pole_figure.tetragonal_symmetry_operators() ndarray[source]
Generate the 8 proper rotations for tetragonal symmetry (4/mmm) as 3x3 matrices.
- upxo.viz.xphy.pole_figure.trigonal_symmetry_operators() ndarray[source]
Generate the 6 proper rotations for trigonal symmetry (32) as 3x3 matrices.
- upxo.viz.xphy.pole_figure.orthorhombic_symmetry_operators() ndarray[source]
Generate the 4 proper rotations for orthorhombic symmetry (222) as 3x3 matrices.
- upxo.viz.xphy.pole_figure.triclinic_symmetry_operators() ndarray[source]
Generate the identity rotation for triclinic symmetry (1) as 3x3 matrices.
- upxo.viz.xphy.pole_figure.matrix_to_quat(R: ndarray) ndarray[source]
Convert a stack of 3x3 rotation matrices to unit quaternions [w, x, y, z] with w >= 0.
- upxo.viz.xphy.pole_figure.compute_sample_symmetry_group(apply_sample_symmetries: bool = True, use_rd: bool = True, use_td: bool = True, use_nd: bool = True) List[ndarray][source]
Compute the mathematically closed group of the selected macroscopic sample-symmetry generators: 180-degree rotations about the Rolling (RD), Transverse (TD), and Normal (ND) sample directions. Returns a list of 3x3 matrices (always includes the identity).
- upxo.viz.xphy.pole_figure.matrix_to_euler_bunge(R: ndarray) ndarray[source]
Convert a stack of 3x3 rotation matrices (Bunge ZXZ convention, i.e. the R = Rz1 @ Rx @ Rz2 form used throughout this module) to Bunge Euler angles (phi1, Phi, phi2) in degrees, shape (N, 3) (or (3,) for a single matrix).
- upxo.viz.xphy.pole_figure.apply_sample_symmetry(orientations: ndarray, convention: str, group_ops: List[ndarray]) ndarray[source]
Replicate each orientation through every element of a closed sample-symmetry group (see compute_sample_symmetry_group), returning the concatenated set of replicas in the same convention as the input.
This is the standard way real (already-fixed) orientation data is symmetrized for sample-symmetric pole figures/densities: each measured orientation g is left-multiplied by every sample-symmetry operator M (g’ = M @ g), since M acts on the sample frame the orientation maps into – this is distinct from FCCTexture’s synthetic-generation use of sample symmetry, which instead samples new points around the symmetric-equivalent cluster centers of an ideal texture component.
- class upxo.viz.xphy.pole_figure.PoleFigure(orientations: ndarray, convention: str = 'quaternion', gids: ndarray | None = None, symmetry: str | ndarray = 'cubic', weights: ndarray | None = None)[source]
Bases:
objectSelf-sufficient pole figure generator, density analyzer, and dataset-to-dataset comparison tool for crystallographic orientations.
Wraps a stack of orientations (quaternion, Euler, or rotation-matrix convention) together with a crystal symmetry group, and provides:
Discrete pole figures –
plot_scatter(), colored by hemisphere, grain role, grain size, IPF direction, or a custom per-grain value.Continuous MUD (Multiples of Uniform Distribution) density fields over a pole family, computed with a numerically stable, antipodal-wrapped spherical von Mises-Fisher kernel –
plot_density()(2D contours) andplot_density_3d()(3D spherical dome, PyVista or Matplotlib backend).Density comparison between two
PoleFigureinstances evaluated on an identical grid (e.g. an EBSD reference vs. a synthetic structure) –compute_density_difference()andplot_density_difference().
Pole families may be named FCC families (
'100','110','111'), an arbitrary 3-digit Miller index string (e.g.'123'), or an explicit[h, k, l]seed vector; in every case the family is expanded to its full symmetric equivalents using the instance’ssymmetry_ops.- Parameters:
orientations (np.ndarray) – Orientation data. Shapes: - ‘quaternion’: (N, 4) - ‘euler_deg’ or ‘euler_rad’: (N, 3) - ‘matrix’: (N, 3, 3)
convention (str) – Convention type of orientations. Euler angles are Bunge ZXZ. A matrix and a quaternion describe the crystal -> sample rotation (the matrix euler_bunge_to_matrix gives, Rz Rx Rz). Quaternions stored the way DefDAP stores them (
EBSDReader.quat_ebsd,grain_avg_quats) are the quaternion of the transpose: convert them withdefdap_passive_to_active(orsample_frame_quatsin the Twinned pipeline) first, otherwise every pole is placed at its transposed position.gids (np.ndarray, optional) – Grain IDs corresponding to the orientations, used for metadata-based coloring.
symmetry (str or np.ndarray) – Crystal symmetry to use. Either a string (‘cubic’, ‘hexagonal’, ‘tetragonal’, ‘trigonal’, ‘orthorhombic’, ‘triclinic’) or a custom array of shape (M, 3, 3).
weights (np.ndarray, optional) – One non-negative weight per orientation (for example the volume of the grain). The MUD density is then the weighted mean of the kernels instead of the plain mean, so a heavy orientation counts for more; the plot of discrete poles is unchanged.
None(default) weights every orientation equally.
- FCC_POLES
Class-level lookup of raw (non-deduplicated) pole vectors for the standard FCC families
'100','110','111', each an(M, 3)array. Used as a fast path by_get_symmetric_poles()before falling back to symmetry-expanding an arbitrary Miller index.- Type:
- SYM_OPS
Class-level stack of the 24 proper cubic (m-3m) symmetry rotation matrices, shape (24, 3, 3), built once via
cubic_symmetry_operators(). Note this is independent of the per-instancesymmetry_opsattribute set in__init__, which reflects whateversymmetrywas actually requested (cubic or otherwise).- Type:
np.ndarray
- symmetry_ops
Instance attribute: the (M, 3, 3) stack of symmetry rotation matrices actually in effect for this instance (set from the
symmetryconstructor argument).- Type:
np.ndarray
- R_stack
Instance attribute: standardized (N, 3, 3) rotation matrices (crystal-to-sample) for the stored orientations.
- Type:
np.ndarray
- quats
Instance attribute: (N, 4) quaternions for the stored orientations, used for IPF coloring.
- Type:
np.ndarray
- gids
Instance attribute: grain IDs aligned with the orientations, if provided.
- Type:
np.ndarray or None
- FCC_POLES = {'100': array([[ 1, 0, 0], [-1, 0, 0], [ 0, 1, 0], [ 0, -1, 0], [ 0, 0, 1], [ 0, 0, -1]]), '110': array([[ 1, 1, 0], [-1, -1, 0], [ 1, -1, 0], [-1, 1, 0], [ 1, 0, 1], [-1, 0, -1], [ 1, 0, -1], [-1, 0, 1], [ 0, 1, 1], [ 0, -1, -1], [ 0, 1, -1], [ 0, -1, 1]]), '111': array([[ 1, 1, 1], [-1, -1, -1], [ 1, -1, -1], [-1, 1, 1], [ 1, 1, -1], [-1, -1, 1], [-1, 1, -1], [ 1, -1, 1]])}
- SYM_OPS = array([[[-1., -0., 0.], [-0., -1., 0.], [-0., -0., 1.]], [[-1., 0., -0.], [-0., 1., -0.], [-0., 0., -1.]], [[ 1., -0., -0.], [ 0., -1., -0.], [ 0., -0., -1.]], [[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]], [[-1., -0., -0.], [-0., -0., -1.], [-0., -1., -0.]], [[-1., 0., 0.], [-0., 0., 1.], [-0., 1., 0.]], [[ 1., -0., 0.], [ 0., -0., 1.], [ 0., -1., 0.]], [[ 1., 0., -0.], [ 0., 0., -1.], [ 0., 1., -0.]], [[-0., -1., -0.], [-1., -0., -0.], [-0., -0., -1.]], [[-0., 1., 0.], [-1., 0., 0.], [-0., 0., 1.]], [[ 0., -1., 0.], [ 1., -0., 0.], [ 0., -0., 1.]], [[ 0., 1., -0.], [ 1., 0., -0.], [ 0., 0., -1.]], [[-0., -1., 0.], [-0., -0., 1.], [-1., -0., 0.]], [[-0., 1., -0.], [-0., 0., -1.], [-1., 0., -0.]], [[ 0., -1., -0.], [ 0., -0., -1.], [ 1., -0., -0.]], [[ 0., 1., 0.], [ 0., 0., 1.], [ 1., 0., 0.]], [[-0., -0., 1.], [-1., -0., 0.], [-0., -1., 0.]], [[-0., 0., -1.], [-1., 0., -0.], [-0., 1., -0.]], [[ 0., -0., -1.], [ 1., -0., -0.], [ 0., -1., -0.]], [[ 0., 0., 1.], [ 1., 0., 0.], [ 0., 1., 0.]], [[-0., -0., -1.], [-0., -1., -0.], [-1., -0., -0.]], [[-0., 0., 1.], [-0., 1., 0.], [-1., 0., 0.]], [[ 0., -0., 1.], [ 0., -1., 0.], [ 1., -0., 0.]], [[ 0., 0., -1.], [ 0., 1., -0.], [ 1., 0., -0.]]])
- plot_scatter(pole_family: str | List[int] | Tuple[int, int, int] = '100', ax: matplotlib.pyplot.Axes | None = None, projection: str = 'stereographic', hemisphere: str = 'both_mapped', color_by: str = 'hemisphere', color_data: ndarray | Dict | None = None, ipf_direction: Tuple[float, float, float] = (0.0, 0.0, 1.0), x_label: str | None = None, y_label: str | None = None, z_label: str | None = None, title: str | None = None, **scatter_kwargs) Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes][source]
Plot the pole figure as a 2D scatter plot.
x_label / y_label / z_label : optional labels for the sample X/Y/Z directions (e.g. “RD”/”TD”/”ND”). X/Y are drawn as crosshair lines through the circle; Z is noted in a corner (it is the out-of-plane axis). Default None/None/None: no labels drawn, unchanged from prior behaviour.
- static auto_grid_points(half_width_deg: float = 7.5) int[source]
The grid resolution grid_points=’auto’ resolves to inside _compute_mud_grid, exposed standalone so callers that need to know the number ahead of time (e.g. to build resolution presets as fractions of it) don’t have to duplicate the formula or construct a real PoleFigure just to ask. Depends only on half_width_deg (the vMF kernel width), not on sample size – a fixed number for a given half-width, clipped to [80, 250].
- plot_density(pole_family: str | List[int] | Tuple[int, int, int] = '100', ax: matplotlib.pyplot.Axes | None = None, projection: str = 'equal_area', grid_points: int | str = 'auto', half_width_deg: float = 7.5, contour_scale: str = 'linear', clabel: bool = False, overlay_scatter: bool = False, scatter_color_by: str = 'ipf', scatter_color_data: ndarray | Dict | None = None, scatter_cmap: str = 'viridis', scatter_ipf_direction: ndarray = array([0, 0, 1]), scatter_hemisphere: str = 'both_mapped', cmap: str = 'viridis', levels: int = 10, mud_clip_min: float | None = None, mud_clip_max: float | None = None, x_label: str | None = None, y_label: str | None = None, z_label: str | None = None, colorbar_decimals: int | None = None, title: str | None = None, colorbar_label: str | None = None, colorbar_orientation: str = 'vertical') Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes][source]
Plot the pole figure as continuous density contours in Multiples of Uniform Distribution (MUD) using a numerically stable, proper antipodal-wrapped spherical von Mises-Fisher (vMF) kernel.
colorbar_decimals : optional number of decimal places for the colour-bar’s tick labels (e.g. 2 -> “1.23”). Default None: leave matplotlib’s own automatic tick formatting unchanged.
colorbar_label : optional title of the density colour bar; None keeps ‘MUD (Multiples of Uniform Distribution)’.
colorbar_orientation : ‘vertical’ (default) or ‘horizontal’.
mud_clip_min / mud_clip_max : optional lower/upper bounds to clip the computed MUD values to before building the color scale – either can be given alone. Useful for pinning a consistent color scale across multiple plots, or compressing outlier density spikes so the rest of the distribution stays visible. Default None/None: auto-scale to the data’s own min/max, unchanged from prior behaviour.
scatter_hemisphere : hemisphere selection for the optional scatter overlay (only used when overlay_scatter=True) – ‘upper’ | ‘lower’ | ‘both_mapped’ | ‘both_separate’, same semantics as plot_scatter’s hemisphere parameter. The density surface itself always folds both hemispheres onto the upper one (antipodal crystallographic symmetry), so this only affects which points the overlay draws.
scatter_color_by=’size’ colors the overlay markers by a continuous per-grain value (scatter_color_data, a dict mapping GID -> value, same convention as plot_scatter’s own color_by=’size’) and adds a SECOND colorbar labelled for that value, alongside the density surface’s own MUD colorbar – so a hybrid plot can show both scales at once instead of only the density’s.
x_label / y_label / z_label : optional labels for the sample X/Y/Z directions, same semantics as plot_scatter’s parameters of the same name. Default None/None/None: no labels drawn, unchanged from prior behaviour.
- compute_density_difference(other: PoleFigure, pole_family: str | List[int] | Tuple[int, int, int] = '100', grid_points: int | str = 'auto', half_width_deg: float = 7.5, unit_normalize: bool = False) dict[source]
Computes the difference between this PoleFigure’s MUD density field and other’s (e.g. an EBSD reference vs a synthetic structure), evaluated on an identical grid (same pole_family / grid_points / half_width_deg on both sides) so the two are directly comparable point-for-point – the pure-compute counterpart to
plot_density_difference(), which calls this internally and then draws the contour plot. self is treated as the reference/”real” side, other as the “synthetic” side.- unit_normalize=False (default): raw difference,
MUD.PF-REAL - MUD.PF-SYNTH.
unit_normalize=True: each field is divided by its own max before differencing, so the comparison is of shape rather than absolute magnitude,
(MUD.PF-REAL)/max - (MUD’.PF-SYNTH.)/max
- Parameters:
other (PoleFigure) – The second dataset to compare against (e.g. an EBSD reference). Its own orientations/symmetry are used to build its side of the density field.
pole_family (str or list or tuple, optional) – Pole family evaluated on both datasets – ‘100’, ‘110’, ‘111’, a 3-digit Miller index string, or an explicit [h, k, l] seed. Default ‘100’.
grid_points (int or 'auto', optional) – Grid resolution along each axis of the MUD grid, shared by both datasets. ‘auto’ resolves via
auto_grid_points(). Default ‘auto’. Pass an explicit integer (rather than ‘auto’) when comparing two datasets whose ‘auto’ resolution could otherwise differ, since a shape mismatch raises ValueError.half_width_deg (float, optional) – Half-width (degrees) of the vMF density kernel, shared by both datasets. Default 7.5.
unit_normalize (bool, optional) – If True, each field is normalized by its own maximum before differencing (comparison of shape rather than magnitude). If False (default), the raw MUD difference is used.
- Returns:
'Xi','Yi'– grid coordinate arrays.'zi_diff'– the difference field itself, same shape.'iqr'– interquartile range (float) ofzi_diff’s finite grid values – a single-number summary of how much the two pole figures disagree (lower = more alike), in MUD units (or normalized-shape units whenunit_normalize).- Return type:
- plot_density_difference(other: PoleFigure, pole_family: str | List[int] | Tuple[int, int, int] = '100', ax: matplotlib.pyplot.Axes | None = None, grid_points: int | str = 'auto', half_width_deg: float = 7.5, unit_normalize: bool = False, cmap: str = 'RdBu_r', levels: int = 10, x_label: str | None = None, y_label: str | None = None, z_label: str | None = None, colorbar_decimals: int | None = None, title: str | None = None) Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes][source]
Plots the difference between this PoleFigure’s MUD density field and other’s (e.g. an EBSD reference vs a synthetic structure). See
compute_density_difference()(called internally here) for the underlying math – this just draws the contour plot.A diverging colormap centered at zero is used since the difference can be positive or negative.
- Parameters:
other (PoleFigure) – The second dataset to compare against (e.g. an EBSD reference). Forwarded to
compute_density_difference().pole_family (str or list or tuple, optional) – Pole family evaluated on both datasets – ‘100’, ‘110’, ‘111’, a 3-digit Miller index string, or an explicit [h, k, l] seed. Default ‘100’.
ax (matplotlib.axes.Axes, optional) – Axes to draw into. Default None: a new standalone figure/axes is created and shown at the end.
grid_points (int or 'auto', optional) – Grid resolution shared by both datasets, forwarded to
compute_density_difference(). Default ‘auto’.half_width_deg (float, optional) – Half-width (degrees) of the vMF density kernel, shared by both datasets. Default 7.5.
unit_normalize (bool, optional) – If True, each field is normalized by its own maximum before differencing (comparison of shape rather than magnitude). Default False.
cmap (str, optional) – Diverging matplotlib colormap name, centered at zero. Default ‘RdBu_r’.
levels (int, optional) – Number of contour levels on each side of zero (the actual level array spans
2 * levels + 1values from-abs_maxtoabs_max). Default 10.x_label (str, optional) – Label for the sample X direction crosshair (e.g. “RD”). Default None: no label drawn.
y_label (str, optional) – Label for the sample Y direction crosshair (e.g. “TD”). Default None: no label drawn.
z_label (str, optional) – Corner label for the sample Z (out-of-plane) direction (e.g. “ND”). Default None: no label drawn.
colorbar_decimals (int, optional) – Number of decimal places for the colour-bar’s tick labels. Default None: matplotlib’s own automatic tick formatting.
title (str, optional) – Plot title. Default None: an auto-generated title naming the pole family is used.
- Returns:
fig (matplotlib.figure.Figure) – The figure containing the plot.
ax (matplotlib.axes.Axes) – The axes the difference contours were drawn into.
- plot_density_3d(pole_family: str | List[int] | Tuple[int, int, int] = '100', grid_points: int = 60, half_width_deg: float = 7.5, cmap: str = 'viridis', backend: str = 'pyvista', title: str | None = None) Any[source]
Plot the MUD density as a 3D spherical dome surface using PyVista (default) or Matplotlib.
- Parameters:
pole_family (str or list or tuple, optional) – Pole family to evaluate – ‘100’, ‘110’, ‘111’, a 3-digit Miller index string, or an explicit [h, k, l] seed. Default ‘100’.
grid_points (int, optional) – Number of points along each of the co-latitude (0-90 deg) and azimuth (0-360 deg) axes of the spherical evaluation grid. Default 60.
half_width_deg (float, optional) – Half-width (degrees) of the vMF density kernel. Default 7.5.
cmap (str, optional) – Matplotlib/PyVista colormap name for the MUD surface. Default ‘viridis’.
backend (str, optional) – Rendering backend: ‘pyvista’ (interactive 3D structured-grid surface) or ‘matplotlib’ (static 3D surface plot). Default ‘pyvista’; silently falls back to ‘matplotlib’ with a warning if PyVista is not installed.
title (str, optional) – Plot title. Default None: an auto-generated title naming the pole family is used.
- Returns:
When
backend='pyvista', the configuredpyvista.Plotterinstance (not yet shown). Whenbackend='matplotlib', a(fig, ax)tuple with the Matplotlib 3D figure and axes.- Return type:
pyvista.Plotter or tuple
- upxo.viz.xphy.pole_figure.plot_pole_figure_from_3d(lgi_3d: ndarray, quats_dict: Dict[int, ndarray], axis: int = 2, slice_idx: int | None = None, pole_family: str | List[int] | Tuple[int, int, int] = '100', ax: matplotlib.pyplot.Axes | None = None, plot_type: str = 'scatter', **kwargs) Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes][source]
Slices a 3D grain label grid, extracts active grain orientations, and plots their pole figure.
- Parameters:
lgi_3d (np.ndarray) – 3D grain label field (nz, ny, nx).
quats_dict (dict) – Dict mapping grain ID -> quaternion [w, x, y, z] of the crystal -> sample rotation (conjugate DefDAP-stored quaternions with
defdap_passive_to_activefirst).axis (int) – Slicing direction normal: 0=X, 1=Y, 2=Z.
slice_idx (int, optional) – Coordinate index along the sliced axis. Defaults to mid-slice.
pole_family (str or List[int]) – Target pole family to project.
ax (plt.Axes, optional) – Matplotlib axis.
plot_type (str) – Type of plot: ‘scatter’ or ‘density’.
**kwargs – Additional arguments passed to PoleFigure.plot_scatter or plot_density.
- upxo.viz.xphy.pole_figure.plot_components(components_dict: Dict[str, Any], convention: str = 'quaternion', pole_family: str | List[int] | Tuple[int, int, int] = '111', projection: str = 'stereographic', hemisphere: str = 'both_mapped', ax: matplotlib.pyplot.Axes | None = None, cmap: str = 'Set1', scatter_kwargs: Dict[str, Any] | None = None) Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes][source]
Plot scatter pole figure where each texture component group is colored uniquely and listed in the legend.
- upxo.viz.xphy.pole_figure.plot_variants(variants_list: List[ndarray], mean_eulers: ndarray, convention: str = 'quaternion', pole_family: str | List[int] | Tuple[int, int, int] = '111', projection: str = 'stereographic', hemisphere: str = 'both_mapped', ax: matplotlib.pyplot.Axes | None = None, cmap: str = 'tab20', scatter_kwargs: Dict[str, Any] | None = None) Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes][source]
Plot scatter pole figure for a single component where each symmetric variant is colored uniquely, with its mean Euler angles listed in the legend.