upxo.pxtal.fm_steel_3d.orientation_assigner_3d module

OrientationAssigner3D: Worker class for assigning Kurdjumov-Sachs orientations.

This module contains the stateless orientation assignment logic using the Kurdjumov-Sachs (KS) relationship between FCC (austenite) and BCC (ferrite).

Classes:

OrientationAssigner3D: Orientation assignment worker.

class upxo.pxtal.fm_steel_3d.orientation_assigner_3d.OrientationAssigner3D(verbosity: int = 0, log_sink=None)[source]

Bases: object

Worker class for assigning crystal orientations to blocks via KS relationship.

This is a stateless utility class. It receives PAG orientations and block data, and returns BCC orientations for each block following the Kurdjumov-Sachs relationship (24 variants grouped into 4 packets).

All methods are instance methods to allow storing session config.

last_hagb_fallback_count: int | None
static get_ks_rotations() → ndarray[source]

Return the 24 Kurdjumov-Sachs rotation matrices.

One canonical KS variant is constructed from the physical relationship {111}FCC || {110}BCC, <110>FCC || <111>BCC, then the complete set of variants is generated by right-multiplying by all 24 cubic symmetry operators (varying the parent’s equivalent crystallographic labeling, the group action that actually produces the standard 24-member KS family – verified against MTEX’s own KurdjumovSachs()/variants() reference implementation to 1e-6 deg).

Returns:

Shape (24, 3, 3) array of rotation matrices.

Return type:

np.ndarray

assign_orientations_to_all_blocks(all_blocks: Dict[str, ndarray], clusters_dict: Dict[int, List[int]], pag_orientations: Dict[int, Tuple[float, float, float]], grain_to_plane_idx: Dict[int, int], ks_variant_selection: str = 'random_per_block', random_seed: int | None = None) → Tuple[Dict[str, Tuple[float, float, float]], Dict[str, int]][source]

Assign BCC orientations to all blocks using the KS orientation relationship.

Block name format: ‘B_{pag_id}_{grain_id}_{local_counter}’. Each grain within a PAG is one packet, identified by grain_id (parts[2]). grain_to_plane_idx records which of the four {111}FCC habit planes (0-3) was assigned to each grain during block generation. That index maps directly to the packet index returned by group_ks_variants_into_packets, so each block draws its KS variant from the physically correct set of 6 variants.

Parameters:
  • all_blocks (dict) – {block_id: voxel_coords_array}.

  • clusters_dict (dict) – {pag_id: [grain_id, …]}.

  • pag_orientations (dict) – {pag_id: (phi1_deg, Phi_deg, phi2_deg)}.

  • grain_to_plane_idx (dict) – {grain_id: plane_index (0-3)} — produced by generate_blocks_for_all_pags.

  • ks_variant_selection (str, optional) –

    How to pick a KS variant for each block within its packet.

    • 'random_per_block' (default) — adjacency-aware greedy graph-colouring: adjacent blocks within the same packet are assigned different KS variants wherever possible, with a random choice among the free variants.

    • 'deterministic' — always assign KS variant index 0 from the packet, ignoring adjacency. Produces a fully reproducible, spatially uniform variant map useful for debugging and analytical checks of the KS geometry.

  • random_seed (int, optional) – Random seed for reproducibility.

Returns:

block_orientationsdict

{block_id: (phi1_deg, Phi_deg, phi2_deg)}.

block_to_variant_idxdict

{block_id: variant_index (0-5)} — which of the 6 KS variants within its packet this block received. Preserved (rather than discarded once used to compute the Euler angles above) so callers can build per-packet variant-balance statistics, or group blocks by shared variant, without re-deriving it from the orientation matrices.

Return type:

tuple of (block_orientations, block_to_variant_idx)

static group_ks_variants_into_packets(variant_Rs: ndarray) → Dict[int, List[ndarray]][source]

Group 24 KS variants into 4 packets based on {110}BCC || {111}FCC planes.

Each packet corresponds to one of the four {111}FCC habit planes. For each variant, the {110}BCC plane normal is transformed back into the FCC frame and matched to the closest {111}FCC plane via dot product.

Parameters:

variant_Rs (np.ndarray) – Shape (24, 3, 3) array of KS variant rotation matrices.

Returns:

{packet_index (0-3): [list of variant rotation matrices]}.

Return type:

dict

verify_block_orientations(block_orientations: Dict[str, Tuple[float, float, float]], n_samples: int = 2) → Dict[str, any][source]

Verify block orientations are physically plausible.

Randomly samples pairs of blocks and computes misorientations. Expected values depend on their packet assignment and variant selection.

Parameters:
  • block_orientations (dict) – {block_id: (phi1, Phi, phi2)}.

  • n_samples (int, optional) – Number of random block pairs to check. Default 2.

Returns:

Verification results (e.g., misorientation statistics).

Return type:

dict

static cubic_euler_bunge_to_matrix_v1(phi1: ndarray, Phi: ndarray, phi2: ndarray, degrees: bool = True) → ndarray[source]

Convert Bunge Euler angles to rotation matrix (vectorized).

Despite the name, this returns the Bunge g matrix (sample -> crystal) – the transpose of upxo.xtalphy.crystal_orientation.euler_bunge_to_matrix, which returns R = Rz(phi1) Rx(Phi) Rz(phi2) (crystal -> sample) for the same angles. matrix_to_euler_bunge is this function’s inverse and also expects/returns g.

Parameters:
  • phi1 (np.ndarray) – Euler angles (1D arrays of same length, or scalars).

  • Phi (np.ndarray) – Euler angles (1D arrays of same length, or scalars).

  • phi2 (np.ndarray) – Euler angles (1D arrays of same length, or scalars).

  • degrees (bool, optional) – If True, input angles are in degrees. Default True.

Returns:

g matrices (sample -> crystal), shape (…, 3, 3).

Return type:

np.ndarray

static matrix_to_euler_bunge(R: ndarray, degrees: bool = True) → Tuple[float, float, float][source]

Convert rotation matrix to Bunge Euler angles.

Parameters:
  • R (np.ndarray) – Rotation matrix, shape (3, 3).

  • degrees (bool, optional) – If True, return angles in degrees. Default True.

Returns:

(phi1, Phi, phi2) in degrees (or radians).

Return type:

tuple

disorientation_deg(ea1: Tuple[float, float, float], ea2: Tuple[float, float, float], degrees: bool = True) → float[source]

Compute the cubic disorientation angle between two orientations.

Applies full bicrystal cubic symmetry: H_i @ ΔR @ H_j^T over all 24×24 = 576 combinations of the proper cubic operators (det = +1). Returns the minimum rotation angle (disorientation), which lies in [0°, 62.8°] for the cubic point group.

Use this instead of cubic_misorientation_old1 whenever a physically correct disorientation is required (e.g. PAG-PAG or block-block plots).

Parameters:
  • ea1 (tuple of (phi1, Phi, phi2)) – Bunge ZXZ Euler angles.

  • ea2 (tuple of (phi1, Phi, phi2)) – Bunge ZXZ Euler angles.

  • degrees (bool, optional) – If True, angles are in degrees. Default True.

Returns:

Disorientation angle in degrees.

Return type:

float

cubic_misorientation_old1(EA1: Tuple[float, float, float], EA2: Tuple[float, float, float], unique_tol_deg: float = 0.0001, degrees: bool = True) → Tuple[float, float, float][source]

Compute the cubic (m-3m) disorientation between two orientations.

The minimum rotation angle over all 24 x 24 crystal-symmetry-equivalent pairs, as in disorientation_deg and mtex orientation.angle.

Parameters:
  • EA1 (tuple or ndarray) – Bunge Euler angles.

  • EA2 (tuple or ndarray) – Bunge Euler angles.

  • unique_tol_deg (float, optional) – Tolerance for symmetry equivalence (degrees).

  • degrees (bool, optional) – If True, angles and result in degrees.

Returns:

(disorientation_angle_deg, reduced relative rotation matrix, disorientation_angle_deg).

Return type:

tuple

assign_pag_orientations_with_hagb(pag_ids: List[int], pag_neigh_map: Dict[int, List[int]], orientation_pool: List[Tuple[float, float, float]] | None = None, hagb_threshold: float = 15.0, random_seed: int | None = None, max_attempts: int = 1000) → Dict[int, Tuple[float, float, float]][source]

Assign FCC parent orientations to PAGs with a HAGB misorientation constraint.

For each PAG, a candidate orientation is drawn from orientation_pool (or from the uniform SO(3) distribution if pool is None) and accepted only if its cubic misorientation with every already-assigned neighbouring PAG is at least hagb_threshold degrees. This ensures all PAG-PAG boundaries are high-angle, which is physically required for martensite.

PAGs are processed in a random order to avoid systematic bias. If no valid candidate is found within max_attempts draws, the best candidate seen so far (highest minimum misorientation with neighbours) is used and a RuntimeWarning is emitted.

Parameters:
  • pag_ids (list of int) – PAG IDs to assign orientations to.

  • pag_neigh_map (dict) – {pag_id: [neighbor_pag_id, …]} adjacency map (from neigh_clid).

  • orientation_pool (list of (phi1, Phi, phi2), optional) – Pre-computed candidate Euler angle triples in degrees (Bunge ZXZ). If None, candidates are drawn from the uniform SO(3) distribution.

  • hagb_threshold (float, optional) – Minimum cubic misorientation in degrees required at every PAG-PAG interface. Default 15.0°.

  • random_seed (int, optional) – Seed for reproducibility.

  • max_attempts (int, optional) – Maximum draws per PAG before falling back to the best candidate seen. Default 1000.

Returns:

{pag_id: (phi1_deg, Phi_deg, phi2_deg)}. Also sets self.last_hagb_fallback_count to the number of PAGs that needed the best-effort fallback.

Return type:

dict

assign_subblock_orientations(all_subblocks: Dict[str, ndarray], block_orientations: Dict[str, Tuple[float, float, float]], intrablock_ori_spread_deg: float = 2.0, random_seed: int | None = None) → Dict[str, Tuple[float, float, float]][source]

Assign orientations to sub-blocks as small perturbations of their parent block.

Each sub-block receives the parent block orientation rotated by a random axis-angle perturbation sampled from Uniform(-spread, +spread) degrees. The rotation axis is drawn uniformly from the unit sphere.

Sub-block names are expected in the form ‘SB_{block_id}_{local}’ so that the parent block_id can be recovered by stripping ‘SB_’ prefix and the trailing ‘_{local}’ suffix.

Parameters:
  • all_subblocks (dict) – {subblock_id: voxel_coords_array} — only keys are used here.

  • block_orientations (dict) – {block_id: (phi1, Phi, phi2)} in degrees (Bunge ZXZ).

  • intrablock_ori_spread_deg (float, optional) – Half-width of the orientation spread in degrees. Each sub-block draws a perturbation angle from Uniform(-spread, +spread). Default 2.0.

  • random_seed (int, optional) – Seed for reproducibility.

Returns:

{subblock_id: (phi1, Phi, phi2)} in degrees.

Return type:

dict