# API reference¶

This reference manual details the public modules, classes, and functions in orix, as generated from their docstrings. Many of the docstrings contain examples, however, see the user guide and the demos for how to use orix.

Caution

orix is in an alpha stage, so there will be breaking changes with each release.

The list of top modules:

 base crystal_map Crystallographic map of rotations, crystal phases and key properties associated with every spatial coordinate in a 1D, 2D or 3D space. io Load and save utilities. plot Extensions of Matplotlib’s projections framework for plotting Vector3d, Rotation, and CrystalMap objects. projections Projections of orix.vector.Vector3d to various other representations. quaternion Four-dimensional objects. sampling Module for generating grids in orientation spaces. scalar Dimensionless quantities. vector Three-dimensional quantities.

## base¶

exception orix.base.DimensionError(this, data)

Bases: Exception

class orix.base.Object3d(data=None)

Bases: object

Base class for 3d objects.

property data_dim

The dimensions of the data.

For example, if data has shape (4, 4, 3), data_dim is 3.

Type

int

dim = None

The number of dimensions for this object.

Type

int

classmethod empty()

An empty object with the appropriate dimensions.

flatten()

Object3d : A new object with the same data in a single column.

reshape(*shape)

Returns a new object containing the same data with a new shape.

property shape

Shape of the object.

Type

tuple

property size

Total number of entries in this object.

Type

int

unique(return_index=False, return_inverse=False)

Returns a new object containing only this object’s unique entries.

Unless overridden, this method returns the numerically unique entries. Also removes zero entries which are assumed to be degenerate.

Parameters
• return_index (bool, optional) – If True, will also return the indices of the (flattened) data where the unique entries were found.

• return_inverse (bool, optional) – If True, will also return the indices to reconstruct the (flattened) data from the unique data.

Returns

• dat (Object3d) – The numerically unique entries.

• idx (numpy.ndarray, optional) – The indices of the unique data in the (flattened) array.

• inv (numpy.ndarray, optional) – The indices of the (flattened) data in the unique array.

## crystal_map¶

Crystallographic map of rotations, crystal phases and key properties associated with every spatial coordinate in a 1D, 2D or 3D space.

All map properties with a value in each data point are stored as 1D arrays.

 CrystalMap(rotations[, phase_id, x, y, z, …]) Crystallographic map of rotations, crystal phases and key properties associated with every spatial coordinate in a 1D, 2D or 3D space. CrystalMapProperties(dictionary, id[, …]) A class to store properties with in a CrystalMap instance. Phase([name, space_group, point_group, …]) Name, symmetry, and color of a phase in a crystallographic map. PhaseList([phases, names, space_groups, …]) A list of phases in a crystallographic map.

### Phase¶

 Return a deep copy using deepcopy() function.
class orix.crystal_map.Phase(name=None, space_group=None, point_group=None, structure=None, color=None)

Bases: object

Name, symmetry, and color of a phase in a crystallographic map.

__init__(name=None, space_group=None, point_group=None, structure=None, color=None)
Parameters
• name (str, optional) – Phase name. Overwrites the name in the structure object.

• space_group (int or diffpy.structure.spacegroups.SpaceGroup, optional) – Space group describing the symmetry operations resulting from associating the point group with a Bravais lattice, according to the International Tables of Crystallography. If None is passed (default), it is set to None.

• point_group (str or orix.quaternion.symmetry.Symmetry, optional) – Point group describing the symmetry operations of the phase’s crystal structure, according to the International Tables of Crystallography. If None is passed (default) and space_group is None, it set to None. If None is passed but space_group is not None, it is derived from the space group. If both point_group and space_group is not None, the space group needs to be derived from the point group.

• structure (diffpy.structure.Structure, optional) – Unit cell with atoms and a lattice. If None is passed (default), a default diffpy.structure.Structure object is created.

• color (str, optional) – Phase color. If None is passed (default), it is set to ‘tab:blue’ (first among the default Matplotlib colors).

Examples

>>> from diffpy.structure import Atom, Lattice, Structure
>>> from orix.crystal_map import Phase
>>> p = Phase(
...     name="al",
...     space_group=225,
...     structure=Structure(
...         atoms=[Atom("al", [0, 0, 0])],
...         lattice=Lattice(0.405, 0.405, 0.405, 90, 90, 90)
...     )
... )
>>> p
<name: al. space group: Fm-3m. point group: m-3m. proper point         ... group: 432. color: tab:blue>
>>> p.structure
[al   0.000000 0.000000 0.000000 1.0000]
>>> p.structure.lattice
Lattice(a=0.405, b=0.405, c=0.405, alpha=90, beta=90, gamma=90)

property color

Name of phase color.

property color_rgb

Phase color as RGB tuple.

deepcopy()

Return a deep copy using deepcopy() function.

property name

Phase name.

property point_group

Point group of phase.

property space_group

Space group of phase.

property structure

Phase unit cell.

### PhaseList¶

 add(value) Add phases to the end of a phase list, incrementing the phase IDs. Return a deep copy using copy.deepcopy() function. id_from_name(name) Get phase ID from phase name. Sort list according to phase ID.
class orix.crystal_map.PhaseList(phases=None, names=None, space_groups=None, point_groups=None, colors=None, ids=None, structures=None)

Bases: object

A list of phases in a crystallographic map.

Each phase in the list must have a unique phase id and name.

__init__(phases=None, names=None, space_groups=None, point_groups=None, colors=None, ids=None, structures=None)
Parameters
• phases (orix.crystal_map.Phase, a list of orix.crystal_map.Phase or a dictionary of orix.crystal_map.Phase, optional) – A list or dict of phases or a single phase. The other arguments are ignored if this is passed.

• names (str or list of str, optional) – Phase names. Overwrites the names in the structure objects.

• space_groups (int, diffpy.structure.spacegroups.SpaceGroup or list of int or diffpy.structure.spacegroups.SpaceGroup, optional) – Space groups.

• point_groups (str, int, orix.quaternion.symmetry.Symmetry or list of str, int or orix.quaternion.symmetry.Symmetry, optional) – Point groups.

• colors (str or list of str, optional) – Phase colors.

• ids (int, list of int or numpy.ndarray of int, optional) – Phase IDs.

• structures (diffpy.structure.Structure or list of diffpy.structure.Structure, optional) – Unit cells with atoms and a lattice of each phase. If None is passed (default), a default diffpy.structure.Structure object is created for each phase.

Examples

>>> from diffpy.structure import Atom, Lattice, Structure
>>> from orix.crystal_map import Phase, PhaseList
>>> pl = PhaseList(
...     names=["al", "cu"],
...     space_groups=[225] * 2,
...     structures=[
...         Structure(
...             atoms=[Atom("al", [0] * 3)],
...             lattice=Lattice(0.405, 0.405, 0.405, 90, 90, 90)
...         ),
...         Structure(
...             atoms=[Atom("cu", [0] * 3)],
...             lattice=Lattice(0.361, 0.361, 0.361, 90, 90, 90)
...         ),
...     ]
... )
>>> pl
Id  Name  Space group  Point group  Proper point group     Color
0    al        Fm-3m         m-3m                 432  tab:blue
1    cu        Fm-3m         m-3m                 432  tab:blue
>>> pl["al"].structure
[al   0.000000 0.000000 0.000000 1.0000]

add(value)

Add phases to the end of a phase list, incrementing the phase IDs.

Parameters

value (Phase, list of Phase or another PhaseList) – Phase(s) to add. If a PhaseList is added, the phase IDs in the old list are lost.

Examples

>>> from orix.crystal_map import Phase, PhaseList
>>> pl = PhaseList(names=["a", "b"], space_groups=[10, 20])
>>> pl
Id  Name  Space group  Point group  Proper point group       Color
0     a         P2/m          2/m                 112    tab:blue
1     b        C2221          222                 222  tab:orange
2     c         Pnc2          mm2                 211   tab:green
3     d         Ama2          mm2                 211     tab:red
4     e         None         None                None  tab:purple
5     f         Pbcn          mmm                 222   tab:brown
6     g         Fddd          mmm                 222    tab:pink

add_not_indexed()

Add a dummy phase to assign to not indexed data points.

The phase, named “not_indexed”, has a point_group equal to None, and a white color when plotted.

property colors

List of phase color names in the list.

property colors_rgb

List of phase color RGB values in the list.

deepcopy()

Return a deep copy using copy.deepcopy() function.

id_from_name(name)

Get phase ID from phase name.

Parameters

name (str) – Phase name.

property ids

Unique phase IDs in the list of phases.

property names

List of phase names in the list.

property point_groups

List of point groups of phases in the list.

property size

Number of phases in the list.

sort_by_id()

Sort list according to phase ID.

property space_groups

List of space groups of phases in the list.

property structures

List of phase structures.

### CrystalMap¶

 Return a deep copy using copy.deepcopy() function. get_map_data(item[, decimals, fill_value]) Return an array of a class instance attribute, with values equal to False in self.is_in_data set to fill_value, of map data shape.
class orix.crystal_map.CrystalMap(rotations, phase_id=None, x=None, y=None, z=None, phase_list=None, prop=None, scan_unit=None, is_in_data=None)

Bases: object

Crystallographic map of rotations, crystal phases and key properties associated with every spatial coordinate in a 1D, 2D or 3D space.

All properties are stored as 1D arrays, and reshaped when necessary.

__init__(rotations, phase_id=None, x=None, y=None, z=None, phase_list=None, prop=None, scan_unit=None, is_in_data=None)
Parameters
• rotations (orix.quaternion.rotation.Rotation) – Rotation of each data point. Must be passed with all spatial dimensions in the first array axis (flattened). May contain multiple rotations per point, included in the second array axes. Crystal map data size is set equal to the first array axis’ size.

• phase_id (numpy.ndarray, optional) – Phase ID of each pixel. IDs equal to -1 are considered not indexed. If None is passed (default), all points are considered to belong to one phase with ID 0.

• x (numpy.ndarray, optional) – Map x coordinate of each data point. If None is passed, the map is assumed to be 1D, and it is set to an array of increasing integers from 0 to the length of the phase_id array.

• y (numpy.ndarray, optional) – Map y coordinate of each data point. If None is passed, the map is assumed to be 1D, and it is set to None.

• z (numpy.ndarray, optional) – Map z coordinate of each data point. If None is passed, the map is assumed to be 2D or 1D, and it is set to None.

• phase_list (PhaseList, optional) – A list of phases in the data with their with names, space groups, point groups, and structures. The order in which the phases appear in the list is important, as it is this, and not the phases’ IDs, that is used to link the phases to the input phase_id if the IDs aren’t exactly the same as in phase_id. If None (default), a phase list with as many phases as there are unique phase IDs in phase_id is created.

• prop (dict of numpy.ndarray, optional) – Dictionary of properties of each data point.

• scan_unit (str, optional) – Length unit of the data. If None (default), “px” is used.

• is_in_data (np.ndarray, optional) – Array of booleans signifying whether a point is in the data.

Examples

>>> from diffpy.structure import Atom, Lattice, Structure
>>> import numpy as np
>>> from orix.crystal_map import CrystalMap
>>> from orix.quaternion.rotation import Rotation
>>> euler1, euler2, euler3, x, y, iq, dp, phase_id = np.loadtxt(
...     "/some/file.ang", unpack=True)
>>> euler_angles = np.column_stack((euler1, euler2, euler3))
>>> rotations = Rotation.from_euler(euler_angles)
>>> properties = {"iq": iq, "dp": dp}
>>> structures = [
...     Structure(
...         title="austenite",
...         atoms=[Atom("fe", [0] * 3)],
...         lattice=Lattice(0.360, 0.360, 0.360, 90, 90, 90)
...     ),
...     Structure(
...         title="ferrite",
...         atoms=[Atom("fe", [0] * 3)],
...         lattice=Lattice(0.287, 0.287, 0.287, 90, 90, 90)
...     )
... ]
>>> pl = PhaseList(space_groups=[225, 229], structures=structures)
>>> cm = CrystalMap(
...     rotations=rotations,
...     phase_id=phase_id,
...     x=x,
...     y=y,
...     phase_list=pl,
...     prop=properties,
... )

property all_indexed

Whether all points in data are indexed.

deepcopy()

Return a deep copy using copy.deepcopy() function.

property dx
property dy
property dz
get_map_data(item, decimals=3, fill_value=None)

Return an array of a class instance attribute, with values equal to False in self.is_in_data set to fill_value, of map data shape.

If item is “orientations”/”rotations” and there are multiple rotations per point, only the first rotation is used. Rotations are returned as Euler angles.

Parameters
• item (str or numpy.ndarray) – Name of the class instance attribute or a numpy.ndarray.

• decimals (int, optional) – How many decimals to round data point values to (default is 3).

• fill_value (None, optional) – Value to fill points not in the data with. If None (default), np.nan is used.

Returns

output_array – Array of the class instance attribute with points not in data set to fill_value, of float data type.

Return type

numpy.ndarray

property id

ID of points in data.

property is_indexed

Whether points in data are indexed.

property ndim

Number of data dimensions of points in data.

property orientations

Rotations, respecting symmetry, in data.

property phase_id

Phase IDs of points in data.

property phases_in_data

List of phases in data.

Needed because it can be useful to have phases not in data but in self.phases.

property prop

CrystalMapProperties dictionary with data properties in each data point.

property rotations

Rotations in data.

property rotations_per_point

Number of rotations per data point in data.

property rotations_shape

Shape of rotation object.

Map shape and possible multiple rotations per point are accounted for. 1-dimensions are squeezed out.

property shape

Shape of points in data.

property size

Total number of points in data.

property x

X coordinates of points in data.

property y

Y coordinates of points in data.

property z

Z coordinates of points in data.

### CrystalMapProperties¶

class orix.crystal_map.CrystalMapProperties(dictionary, id, is_in_data=None)

Bases: dict

A class to store properties with in a CrystalMap instance.

This class is a thin wrapper around dict. It overrides setting and getting property arrays in the dict to handle a data mask correctly, i.e. whether data points are considered to be in the data.

id

1D integer array with the id of each point in the data.

Type

numpy.ndarray

is_in_data

1D boolean array with True for points in the data, of the same size as the data.

Type

numpy.ndarray

## io¶

 load(filename, **kwargs) Load data from a supported file. loadang(file_string) Load .ang files. loadctf(file_string) Load .ang files. plugins save(filename, object2write[, overwrite]) Write data to a supported file format.

orix.io.load(filename, **kwargs)

Load data from a supported file.

Parameters
• filename (str) – Name of file to load.

• kwargs – Keyword arguments passed to the corresponding orix reader. See their individual docstrings for available arguments.

Returns

data – Crystal map read from the file.

Return type

CrystalMap

orix.io.loadang(file_string)

Load .ang files.

Parameters

file_string (str) – Path to the .ang file. This file is assumed to list the Euler angles in the Bunge convention in the first three columns.

Returns

Return type

Rotation

orix.io.loadctf(file_string)

Load .ang files.

Parameters

file_string (str) – Path to the .ctf file. This file is assumed to list the Euler angles in the Bunge convention in the columns 5, 6, and 7.

Returns

Return type

Rotation

orix.io.save(filename, object2write, overwrite=None, **kwargs)

Write data to a supported file format.

Parameters
• filename (str) – Name of file to write to.

• object2write (CrystalMap) – Object to write to file.

• overwrite (bool, optional) – If None and the file exists, the user is queried. If True (False) the file is (not) overwritten if it exists.

• kwargs – Keyword arguments passed to the corresponding orix writer. See their individual docstrings for available arguments.

### plugins¶

#### ang¶

orix.io.plugins.ang.file_reader(filename)

Return a CrystalMap object from a file in EDAX TLS’s .ang format. The map in the input is assumed to be 2D.

Many vendors produce an .ang file. Supported vendors are * EDAX TSL

• NanoMegas ASTAR Index

• EMsoft (from program EMdpmerge)

• orix

All points satisfying the following criteria are classified as not indexed:

• EDAX TSL: confidence index == -1

Parameters

filename (str) – Path and file name.

Returns

Return type

CrystalMap

orix.io.plugins.ang.file_writer(filename, xmap, index=None, image_quality_prop=None, confidence_index_prop=None, detector_signal_prop=None, pattern_fit_prop=None, extra_prop=None)

Write a CrystalMap to an .ang file readable (at least) by MTEX and EDAX TSL OIM Analysis v7.

The columns are phi1, Phi, phi2, x, y, image_quality, confidence_index, phase_id, detector_signal, and pattern_fit.

Parameters in masked out or non-indexed points are set to

• euler angles = 4 * pi

• image quality = 0

• confidence index = -1

• phase ID = 0 if single phase or -1 if multi phase

• pattern fit = 180

• detector signal = 0

• extra properties = 0

Parameters
• filename (str) – File name with an “.ang” file extension to write to.

• xmap (CrystalMap) – Crystal map to write to file.

• index (int, optional) – If the crystal map has more than one rotation/match and phase ID per point, this index can be set to write that “layer” of data to the file. For properties to be written as well, these must also have multiple values per point. To get the best match at every point, use None (default).

• image_quality_prop (str, optional) – Which map property to use as the image quality. If None (default), “iq” or “imagequality”, if present, is used, or just zeros. If the property has more than one value per point, only the first value is used.

• confidence_index_prop (str, optional) – Which map property to use as the confidence index. If None (default), “ci” or “confidenceindex”, if present, is used, or just zeros. If the property has more than one value per point, only the first value is used.

• detector_signal_prop (str, optional) – Which map property to use as the detector signal. If None (default), “ds”, or “detectorsignal”, if present, is used, or just zeros. If the property has more than one value per point, only the first value is used.

• pattern_fit_prop (str, optional) – Which map property to use as the pattern fit. If None (default), “fit” or “patternfit”, if present, is used, or just zeros. If the property has more than one value per point, only the first value is used.

• extra_prop (str or list of str, optional) – One or multiple properties to add as extra columns in the .ang file, as a string or a list of strings. If None (default), no extra properties are added.

#### emsoft_h5ebsd¶

orix.io.plugins.emsoft_h5ebsd.file_reader(filename, refined=False, **kwargs)

Return a CrystalMap object from a file in EMsoft’s dictionary indexing dot product file format.

Parameters
• filename (str) – Path and file name.

• refined (bool, optional) – Whether to return refined orientations (default is False).

• kwargs – Keyword arguments passed to h5py.File().

Returns

Return type

CrystalMap

#### orix_hdf5¶

orix.io.plugins.orix_hdf5.atom2dict(atom, dictionary=None)

Get a dictionary of one of a structure’s diffpy.structure.Structure.atoms content.

Only values necessary to initialize an atom object are returned.

Parameters
• atom (diffpy.structure.Structure.atom) – Atom in a structure.

• dictionary (dict, optional) – Dictionary to update with structure atom information. If None (default), a new dictionary is created.

Returns

dictionary – Dictionary with structure atoms information.

Return type

dict

orix.io.plugins.orix_hdf5.crystalmap2dict(crystal_map, dictionary=None)

Get a dictionary from a CrystalMap object with data and header keys with values.

Parameters
• crystal_map (CrystalMap) – Crystal map.

• dictionary (dict, optional) – Dictionary to update with crystal map information. If None (default), a new dictionary is created.

Returns

dictionary – Dictionary with crystal map information.

Return type

dict

orix.io.plugins.orix_hdf5.dict2atom(dictionary)

Get a diffpy.structure.Atom.atom object from a dictionary.

Parameters

dictionary (dict) – Dictionary with atom information.

Returns

Return type

Atom

orix.io.plugins.orix_hdf5.dict2crystalmap(dictionary)

Get a crystal map from necessary items in a dictionary.

Parameters

dictionary (dict) – Dictionary with crystal map information.

Returns

Return type

CrystalMap

orix.io.plugins.orix_hdf5.dict2hdf5group(dictionary, group, **kwargs)

Write a dictionary to datasets in a new group in an opened HDF5 file.

Parameters
• dictionary (dict) – Dataset names as keys with datasets as values.

• group (Group) – HDF5 group to write dictionary to.

• kwargs – Keyword arguments passed to Group.require_dataset.

orix.io.plugins.orix_hdf5.dict2lattice(dictionary)

Get a diffpy.structure.Lattice object from a dictionary.

Parameters

dictionary (dict) – Dictionary with lattice information.

Returns

Return type

Lattice

orix.io.plugins.orix_hdf5.dict2phase(dictionary)

Get a Phase object from a dictionary.

Parameters

dictionary (dict) – Dictionary with phase information.

Returns

Return type

Phase

orix.io.plugins.orix_hdf5.dict2phaselist(dictionary)

Get a PhaseList object from a dictionary.

Parameters

dictionary (dict) – Dictionary with phase list information.

Returns

Return type

PhaseList

orix.io.plugins.orix_hdf5.dict2structure(dictionary)

Get a diffpy.structure.Structure object from a dictionary.

Parameters

dictionary (dict) – Dictionary with structure information.

Returns

Return type

Structure

orix.io.plugins.orix_hdf5.file_reader(filename, **kwargs)

Return a CrystalMap object from a file in orix’ HDF5 file format.

Parameters
• filename (str) – Path and file name.

• kwargs – Keyword arguments passed to h5py.File().

Returns

Return type

CrystalMap

orix.io.plugins.orix_hdf5.file_writer(filename, crystal_map, **kwargs)

Write a CrystalMap object to an HDF5 file.

Parameters
• filename (str) – Name of file to write to.

• crystal_map (CrystalMap) – Object to write to file.

• kwargs – Keyword arguments passed to Group.require_dataset.

orix.io.plugins.orix_hdf5.hdf5group2dict(group, dictionary=None, recursive=False)

Return a dictionary with values from datasets in a group in an opened HDF5 file.

Parameters
• group (Group) – HDF5 group object.

• dictionary (dict, optional) – To fill dataset values into. If None (default), a new dictionary is created.

• recursive (bool, optional) – Whether to add subgroups to dictionary. Default is False.

Returns

dictionary – Dataset values in group (and subgroups if recursive=True).

Return type

dict

orix.io.plugins.orix_hdf5.lattice2dict(lattice, dictionary=None)

Get a dictionary of a structure’s diffpy.structure.Structure.lattice content.

Only values necessary to initialize a lattice object are returned.

Parameters
• lattice (diffpy.structure.Structure.lattice) – Structure lattice.

• dictionary (dict, optional) – Dictionary to update with structure lattice information. If None (default), a new dictionary is created.

Returns

dictionary – Dictionary with structure lattice information.

Return type

dict

orix.io.plugins.orix_hdf5.phase2dict(phase, dictionary=None)

Get a dictionary of a phase.

Parameters
• phase (Phase) – Phase to write to file.

• dictionary (dict, optional) – Dictionary to update with information from a single phase. If None (default), a new dictionary is created.

Returns

dictionary – Dictionary with information from a single phase.

Return type

dict

orix.io.plugins.orix_hdf5.phaselist2dict(phases, dictionary=None)

Get a dictionary of phases.

Parameters
• phases (PhaseList) – Phases to write to file.

• dictionary (dict, optional) – Dictionary to update with information from multiple phases. If None (default), a new dictionary is created.

Returns

dictionary – Dictionary with information from multiple phases.

Return type

dict

orix.io.plugins.orix_hdf5.structure2dict(structure, dictionary=None)

Get a dictionary of a phase’s diffpy.structure.Structure content.

Only values necessary to initialize a structure object are returned.

Parameters
• structure (diffpy.structure.Structure) – Phase structure with a lattice and atoms.

• dictionary (dict, optional) – Dictionary to update with structure information. If None (default), a new dictionary is created.

Returns

dictionary – Dictionary with structure information.

Return type

dict

## plot¶

Extensions of Matplotlib’s projections framework for plotting Vector3d, Rotation, and CrystalMap objects.

Example of usage:

>>> import matplotlib.pyplot as plt
>>> from orix import plot, vector
>>> fig, ax = plt.subplots(subplot_kw=dict(projections="stereographic"))
>>> ax.scatter(vector.Vector3d([[0, 0, 1], [1, 0, 1]]))

 AxAnglePlot(fig[, rect, azim, elev, sharez, …]) Plot rotations in an Axes-Angle projection. CrystalMapPlot(fig, rect[, facecolor, …]) 2D plotting of CrystalMap objects. RodriguesPlot(fig[, rect, azim, elev, …]) Plot rotations in a Rodrigues-Frank projection. RotationPlot(fig[, rect, azim, elev, …]) StereographicPlot(*args[, polar_resolution, …]) Stereographic projection plot.

### AxAnglePlot¶

class orix.plot.AxAnglePlot(fig, rect=None, *args, azim=- 60, elev=30, sharez=None, proj_type='persp', box_aspect=None, **kwargs)

Bases: orix.plot.rotation_plot.RotationPlot

Plot rotations in an Axes-Angle projection.

### CrystalMapPlot¶

 add_colorbar([label]) Add an opinionated colorbar to the figure. add_overlay(crystal_map, item) Use a crystal map property as gray scale values of a phase map. add_scalebar(crystal_map, **kwargs) Add a scalebar to the axes object via AnchoredSizeBar. plot_map(crystal_map[, value, scalebar, …]) Plot a 2D map with any CrystalMap attribute as map values. Remove all white padding outside of the figure.
class orix.plot.CrystalMapPlot(fig, rect, facecolor=None, frameon=True, sharex=None, sharey=None, label='', xscale=None, yscale=None, box_aspect=None, **kwargs)

Bases: matplotlib.axes._axes.Axes

2D plotting of CrystalMap objects.

add_colorbar(label=None, **kwargs)

Add an opinionated colorbar to the figure.

Parameters
• label (str, optional) – Colorbar title, default is None.

• kwargs – Keyword arguments passed to mpl_toolkits.axes_grid1.make_axes_locatable.append_axes().

Returns

cbar – Colorbar.

Return type

matplotlib.colorbar

Examples

>>> cm
Phase  Orientations   Name       Symmetry  Color
1      5657 (48.4%)   austenite  432       tab:blue
2      6043 (51.6%)   ferrite    432       tab:orange
Properties: iq, dp
Scan unit: um


Plot a map property and add a colorbar

>>> fig = plt.figure()
>>> im = ax.plot_map(cm, cm.dp, cmap="inferno")


If the default options are not satisfactory, the colorbar can be updated

>>> cbar.ax.set_ylabel(ylabel="dp", rotation=90)

add_overlay(crystal_map, item)

Use a crystal map property as gray scale values of a phase map.

The property’s range is adjusted to [0, 1] for maximum contrast.

Parameters
• crystal_map (orix.crystal_map.CrystalMap) – Crystal map object to obtain necessary data from.

• item (str) – Name of map property to scale phase array with. The property range is adjusted for maximum contrast.

Examples

>>> cm
Phase  Orientations   Name       Symmetry  Color
1      5657 (48.4%)   austenite  432       tab:blue
2      6043 (51.6%)   ferrite    432       tab:orange
Properties: iq, dp
Scan unit: um


Plot a phase map with a map property as overlay

>>> fig = plt.figure()
>>> im = ax.plot_map(cm)

add_scalebar(crystal_map, **kwargs)

Add a scalebar to the axes object via AnchoredSizeBar.

To find an appropriate scalebar width, this snippet from MTEX written by Eric Payton and Philippe Pinard is used: https://github.com/mtex-toolbox/mtex/blob/b8fc167d06d453a2b3e212b1ac383acbf85a5a27/plotting/scaleBar.m,

Parameters
• crystal_map (orix.crystal_map.CrystalMap) – Crystal map object to obtain necessary data from.

• kwargs – Keyword arguments passed to mpl_toolkits.axes_grid1.anchored_artists.AnchoredSizeBar(). alpha can also be passed, to set the scalebar transparency.

Returns

bar – Scalebar.

Return type

mpl_toolkits.axes_grid1.anchored_artists.AnchoredSizeBar

Examples

>>> cm
Phase  Orientations   Name       Symmetry  Color
1      5657 (48.4%)   austenite  432       tab:blue
2      6043 (51.6%)   ferrite    432       tab:orange
Properties: iq, dp
Scan unit: um


Create a phase map without a scale bar and add it afterwards

>>> fig = plt.figure()
>>> im = ax.plot_map(cm, scalebar=False)
>>> sbar = ax.add_scalebar(cm, loc=4, frameon=False)

name = 'plot_map'
plot_map(crystal_map, value=None, scalebar=True, scalebar_properties=None, legend=True, legend_properties=None, axes=None, depth=None, **kwargs)matplotlib.image.AxesImage

Plot a 2D map with any CrystalMap attribute as map values.

Wraps matplotlib.axes.Axes.imshow(), see that method for relevant keyword arguments.

Parameters
• crystal_map (orix.crystal_map.CrystalMap) – Crystal map object to obtain data to plot from.

• value (numpy.ndarray, optional) – Attribute array to plot. If value is None (default), a phase map is plotted.

• scalebar (bool, optional) – Whether to add a scalebar (default is True) along the horizontal map dimension.

• scalebar_properties (dict) – Dictionary of keyword arguments passed to mpl_toolkits.axes_grid1.anchored_artists.AnchoredSizeBar().

• legend (bool, optional) – Whether to add a legend to the plot. This is only implemented for a phase plot (in which case default is True).

• legend_properties (dict) – Dictionary of keyword arguments passed to matplotlib.axes.legend().

• axes (tuple of ints, optional) – Which data axes to plot if data has more than two dimensions. The index of data to plot in the final dimension is determined by depth. If None (default), data along the two last axes is plotted.

• depth (int, optional) – Which layer along the third axis to plot if data has more than two dimensions. If None (default), data in the first index (layer) is plotted.

• kwargs – Keyword arguments passed to matplotlib.axes.Axes.imshow().

Returns

im – Image object, to be used further to get data from etc.

Return type

matplotlib.image.AxesImage

Examples

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from orix import plot


Import a crystal map

>>> cm = load("/some/directory/data.ang")


Plot a phase map

>>> fig = plt.figure()  # Get figure
>>> ax = fig.add_subplot(projection="plot_map")  # Get axes
>>> im = ax.plot_map(cm)  # Get image


>>> ax.add_overlay(cm, cm.iq)


Plot an arbitrary map property, also changing scalebar location

>>> ax = plt.subplot(projection="plot_map")
>>> ax.plot_map(
...     cm, cm.dp, cmap="cividis", scalebar_properties={"loc": 4}
... )


>>> cbar = ax.add_colorbar("Dot product")  # Get colorbar


Plot orientation angle in degrees of one phase

>>> cm2 = cm["austenite"]
>>> austenite_angles = cm2.orientations.angle.data * 180 / np.pi
>>> fig = plt.figure()
>>> im = ax.plot_map(cm2, austenite_angles)
>>> ax.add_colorbar("Orientation angle [$^{\circ}$]")


Remove all figure and axes padding

>>> ax.remove_padding()


Write annotated figure to file

>>> fig.savefig(
...     "/some/directory/image.png",
...     bbox_inches="tight"
... )


Write un-annotated image to file

>>> plt.imsave("/some/directory/image2.png", im.get_array())

remove_padding()

Remove all white padding outside of the figure.

Examples

>>> cm
Phase  Orientations   Name       Symmetry  Color
1      5657 (48.4%)   austenite  432       tab:blue
2      6043 (51.6%)   ferrite    432       tab:orange
Properties: iq, dp
Scan unit: um


Remove all figure and axes padding of a phase map

>>> fig = plt.figure()
>>> ax.plot_map(cm)


### RodriguesPlot¶

class orix.plot.RodriguesPlot(fig, rect=None, *args, azim=- 60, elev=30, sharez=None, proj_type='persp', box_aspect=None, **kwargs)

Bases: orix.plot.rotation_plot.RotationPlot

Plot rotations in a Rodrigues-Frank projection.

### RotationPlot¶

class orix.plot.RotationPlot(fig, rect=None, *args, azim=- 60, elev=30, sharez=None, proj_type='persp', box_aspect=None, **kwargs)

### StereographicPlot¶

 azimuth_grid([resolution]) Set the azimuth grid resolution in degrees. polar_grid([resolution]) Set the polar grid resolution in degrees. scatter(*args, **kwargs) A scatter plot of vectors. show_hemisphere_label(**kwargs) Add a hemisphere label (“upper”/”lower”) to the upper left of the plane. set_labels([xlabel, ylabel, zlabel]) Set the reference frame’s axes labels. symmetry_marker(v, fold, **kwargs) Plot 2-, 3- 4- or 6-fold symmetry marker(s). text(*args, **kwargs) Add text to the axes.
class orix.plot.StereographicPlot(*args, polar_resolution=15, azimuth_resolution=15, **kwargs)

Bases: matplotlib.axes._axes.Axes

Stereographic projection plot. The projection is an equal angle projection and is typically used for visualizing 3D vectors in a 2D plane.

https://en.wikipedia.org/wiki/Stereographic_projection

Examples

>>> import matplotlib.pyplot as plt
>>> from orix import plot, vector
>>> fig, ax = plt.subplots(subplot_kw=dict(projections="stereographic"))
>>> ax.scatter(vector.Vector3d([[0, 0, 1], [1, 0, 1]]))

azimuth_grid(resolution=None)

Set the azimuth grid resolution in degrees.

Parameters

resolution (float, optional) – Aziumuth grid resolution in degrees. Default is 15 degrees. This can also be set upon initialization of the axes by passing azimuth_resolution to subplot_kw.

property hemisphere

Hemisphere to plot.

Returns

“upper” or “lower” plots the upper or lower hemisphere vectors. pole is derived from this attribute.

Return type

str

polar_grid(resolution=None)

Set the polar grid resolution in degrees.

Parameters

resolution (float, optional) – Polar grid resolution in degrees. Default is 15 degrees. This can also be set upon initialization of the axes by passing polar_resolution to the subplot_kw dictionary.

property pole

Projection pole, either -1 or 1, where -1 (1) means the projection point of the stereographic transform is the south (north) pole [00-1] ([001]), i.e. only vectors with z > 0 (z < 0) are plotted.

Derived from hemisphere.

scatter(*args, **kwargs)

A scatter plot of vectors.

This method overwrites matplotlib.axes.Axes.scatter(), see that method’s docstring for parameters.

Parameters
set_labels(xlabel='X', ylabel='Y', zlabel='Z', **kwargs)

Set the reference frame’s axes labels.

Parameters
• xlabel (str, False or None, optional) – X axis label, default is “X”. If False or None, this label is not shown.

• ylabel (str, False or None, optional) – Y axis label, default is “Y”. If False or None, this label is not shown.

• zlabel (str, False or None, optional) – Z axis label, default is “Z”. If False or None, this label is not shown.

show_hemisphere_label(**kwargs)

Add a hemisphere label (“upper”/”lower”) to the upper left of the plane.

Parameters

kwargs – Keyword arguments passed to matplotlib.axes.Axes.text().

symmetry_marker(v, fold, **kwargs)

Plot 2-, 3- 4- or 6-fold symmetry marker(s).

Parameters
• v (Vector3d) – Position of the marker(s) to plot.

• fold (int) – Which symmetry element to plot, can be either 2, 3, 4 or 6.

• kwargs – Keyword arguments passed to scatter().

text(*args, **kwargs)

This method overwrites matplotlib.axes.Axes.text(), see that method’s docstring for parameters.

Parameters

## projections¶

Projections of orix.vector.Vector3d to various other representations.

 Get stereographic coordinates (X, Y) from representations of vectors. Get 3D unit vectors or spherical coordinates from stereographic coordinates (X, Y).

### StereographicProjection¶

 inverse Return the corresponding inverse projection, InverseStereographicProjection, with the same projection pole. spherical2xy(azimuth, polar) Return stereographic coordinates (X, Y) from 3D unit vectors created from spherical coordinates, azimuth $$\phi$$ and polar $$\theta$$, defined as in the ISO 31-11 standard [SphericalWolfram]. spherical2xy_split(azimuth, polar) Return two sets of stereographic coordinates (X, Y) from 3D unit vectors created from spherical coordinates, azimuth $$\phi$$ and polar $$\theta$$, defined as in the ISO 31-11 standard [SphericalWolfram]: one set for vectors in the upper hemisphere, and one for the lower. Return stereographic coordinates (X, Y) of 3D unit vectors. Return two sets of stereographic coordinates (X, Y) from 3D unit vectors: one set for vectors in the upper hemisphere, and one for the lower.
class orix.projections.StereographicProjection(pole=- 1)

Get stereographic coordinates (X, Y) from representations of vectors.

__init__(pole=- 1)

Initialize projection by setting whether the south pole (-1) or north pole (1) is the projection point.

Parameters

pole (int, optional) – -1 or 1, where -1 (1) means the projection point is the south (north) pole [00-1] ([001]), i.e. only vectors with z > 0 (z < 0) are returned.

property inverse

Return the corresponding inverse projection, InverseStereographicProjection, with the same projection pole.

spherical2xy(azimuth, polar)

Return stereographic coordinates (X, Y) from 3D unit vectors created from spherical coordinates, azimuth $$\phi$$ and polar $$\theta$$, defined as in the ISO 31-11 standard [SphericalWolfram].

Parameters
Returns

• x (numpy.ndarray) – Stereographic coordinate X of shape same shape as the input vector shape. Only the vectors with $$z$$ coordinate positive (pole = -1) or negative (pole = 1) are returned.

• y (numpy.ndarray) – Stereographic coordinate Y of shape same shape as the input vector shape. Only the vectors with $$z$$ coordinate positive (pole = -1) or negative (pole = 1) are returned.

spherical2xy_split(azimuth, polar)

Return two sets of stereographic coordinates (X, Y) from 3D unit vectors created from spherical coordinates, azimuth $$\phi$$ and polar $$\theta$$, defined as in the ISO 31-11 standard [SphericalWolfram]: one set for vectors in the upper hemisphere, and one for the lower.

Parameters
Returns

• x_upper (numpy.ndarray) – Stereographic coordinate X of upper hemisphere vectors, of shape same shape as the input vector shape.

• y_upper (numpy.ndarray) – Stereographic coordinate Y of upper hemisphere vectors, of shape same shape as the input vector shape.

• x_lower (numpy.ndarray) – Stereographic coordinate X of lower hemisphere vectors, of shape same shape as the input vector shape.

• y_lower (numpy.ndarray) – Stereographic coordinate Y of lower hemisphere vectors, of shape same shape as the input vector shape.

vector2xy(v)

Return stereographic coordinates (X, Y) of 3D unit vectors.

Parameters

v (Vector3d) – If it’s not a unit vector, it will be made into one.

Returns

• x (numpy.ndarray) – Stereographic coordinate X of shape same shape as the input vector shape. Only the vectors with $$z$$ coordinate positive (pole = -1) or negative (pole = 1) are returned.

• y (numpy.ndarray) – Stereographic coordinate Y of shape same shape as the input vector shape. Only the vectors with $$z$$ coordinate positive (pole = -1) or negative (pole = 1) are returned.

Notes

The stereographic coordinates $$(X, Y)$$ are calculated from the unit vectors’ cartesian coordiantes $$(x, y, z)$$ as

$(X, Y) = \left(\frac{-px}{z - p}, \frac{-py}{z - p}\right),$

where $$p$$ is either 1 (north pole as projection point) or -1 (south pole as projection point).

static vector2xy_split(v)

Return two sets of stereographic coordinates (X, Y) from 3D unit vectors: one set for vectors in the upper hemisphere, and one for the lower.

Parameters

v (Vector3d) – If it’s not a unit vector, it will be made into one.

Returns

• x_upper (numpy.ndarray) – Stereographic coordinate X of upper hemisphere vectors, of shape same shape as the input vector shape.

• y_upper (numpy.ndarray) – Stereographic coordinate Y of upper hemisphere vectors, of shape same shape as the input vector shape.

• x_lower (numpy.ndarray) – Stereographic coordinate X of lower hemisphere vectors, of shape same shape as the input vector shape.

• y_lower (numpy.ndarray) – Stereographic coordinate Y of lower hemisphere vectors, of shape same shape as the input vector shape.

### InverseStereographicProjection¶

 xy2spherical(x, y) Return spherical coordinates, azimuth $$phi$$ and polar $$theta$$, defined as in the ISO 31-11 standard [SphericalWolfram], from stereographic coordinates (X, Y). xy2vector(x, y) Return 3D unit vectors from stereographic coordinates (X, Y).
class orix.projections.InverseStereographicProjection(pole=- 1)

Get 3D unit vectors or spherical coordinates from stereographic coordinates (X, Y).

__init__(pole=- 1)

Initialize inverse projection by setting whether the south pole (-1) or north pole (1) is the projection point.

Parameters

pole (int, optional) – -1 or 1, where -1 (1) means the projection point is the south (north) pole [00-1] ([001]), i.e. only vectors with z > 0 (z < 0) are returned.

xy2spherical(x, y)

Return spherical coordinates, azimuth $$phi$$ and polar $$theta$$, defined as in the ISO 31-11 standard [SphericalWolfram], from stereographic coordinates (X, Y).

Parameters
Returns

• azimuth (numpy.ndarray) – Azimuth spherical coordinate corresponding to (X, Y). Whether the coordinates for the upper or lower hemisphere points are returned is controlled by pole (-1 = upper, 1 = lower).

• theta (numpy.ndarray) – Polar spherical coordinate corresponding to (X, Y). Whether the coordinates for the upper or lower hemisphere points are returned is controlled by pole (-1 = upper, 1 = lower).

xy2vector(x, y)

Return 3D unit vectors from stereographic coordinates (X, Y).

Parameters
Returns

Unit vectors corresponding to the stereographic coordinates. Whether the upper or lower hemisphere points are returned is controlled by pole (-1 = upper, 1 = lower).

Return type

Vector3d

Notes

The 3D unit vectors $$(x, y, z)$$ are calculated from the stereographic coordinates $$(X, Y)$$ as

$(x, y, z) = \left( \frac{2x}{1 + x^2 + y^2}, \frac{2y}{1 + x^2 + y^2}, \frac{-p(1 - x^2 - y^2)}{1 + x^2 + y^2} \right),$

where $$p$$ is either 1 (north pole as projection point) or -1 (south pole as projection point).

## quaternion¶

Four-dimensional objects.

In a simplified sense, quaternions are an extension of the concept of complex numbers, represented by $$a + bi + cj + dk$$ where $$i$$, $$j$$, and $$k$$ are quaternion units and $$i^2 = j^2 = k^2 = ijk = -1$$. For further reference see the Wikipedia article.

Unit quaternions are efficient objects for representing rotations, and hence orientations.

 Orientation(data) Orientation object. A set of Rotation which are the normals of an orientation region. Misorientation(data) Misorientation object. Quaternion([data]) Basic quaternion object. Rotation(data) Rotation object. Symmetry(data) The set of rotations comprising a point group.

### Orientation and Misorientation¶

Rotations respecting symmetry.

An orientation is simply a rotation with respect to some reference frame. In this respect, an orientation is in fact a misorientation - a change of orientation - with respect to a reference of the identity rotation.

In orix, orientations and misorientations are distinguished from rotations only by the inclusion of a notion of symmetry. Consider the following example:

Both objects have undergone the same rotations with respect to the reference. However, because the square has fourfold symmetry, it is indistinguishable in both cases, and hence has the same orientation.

#### Orientation¶

 set_symmetry(symmetry) Assign a symmetry to this orientation.
class orix.quaternion.Orientation(data)

Bases: orix.quaternion.orientation.Misorientation

Orientation object.

Orientations represent misorientations away from a reference of identity and have only one associated symmetry.

Orientations support binary subtraction, producing a misorientation. That is, to compute the misorientation from $$o_1$$ to $$o_2$$, call o_2 - o_1.

set_symmetry(symmetry)

Assign a symmetry to this orientation.

Computes equivalent transformations which have the smallest angle of rotation and assigns these in-place.

Parameters

symmetry (Symmetry) –

Returns

The instance itself, with equivalent values.

Return type

Orientation

Examples

>>> from orix.quaternion.symmetry import C4
>>> data = np.array([[0.5, 0.5, 0.5, 0.5], [0, 1, 0, 0]])
>>> o = Orientation(data).set_symmetry((C4))
>>> o
Orientation (2,) 4
[[-0.7071  0.     -0.7071  0.    ]
[ 0.      1.      0.      0.    ]]

property symmetry

Symmetry

#### Misorientation¶

 distance([verbose, split_size]) Symmetry reduced distance equivalent([grain_exchange]) Equivalent misorientations set_symmetry(Gl, Gr[, verbose]) Assign symmetries to this misorientation.
class orix.quaternion.Misorientation(data)

Bases: orix.quaternion.rotation.Rotation

Misorientation object.

Misorientations represent transformations from one orientation, $$o_1$$ to another, $$o_2$$: $$o_2 \cdot o_1^{-1}$$.

They have symmetries associated with each of the starting orientations.

distance(verbose=False, split_size=100)

Symmetry reduced distance

Compute the shortest distance between all orientations considering symmetries.

Parameters
• verbose (bool) – Output progress bar while computing.

• split_size (int) – Size of block to compute at a time.

Returns

distance – 2D matrix containing the angular distance between every orientation, considering symmetries.

Return type

np.array

Examples

>>> import numpy as np
>>> from orix.quaternion.symmetry import C4, C2
>>> from orix.quaternion.orientation import Misorientation
>>> data = np.array([[0.5, 0.5, 0.5, 0.5], [0, 1, 0, 0]])
>>> m = Misorientation(data).set_symmetry(C4, C2)
>>> m.distance()
array([[3.14159265, 1.57079633],
[1.57079633, 0.        ]])

equivalent(grain_exchange=False)

Equivalent misorientations

grain_exchangebool

If true the rotation g and g^{-1} are considered to be identical

Returns

Return type

Misorientation

set_symmetry(Gl, Gr, verbose=False)

Assign symmetries to this misorientation.

Computes equivalent transformations which have the smallest angle of rotation and assigns these in-place.

Parameters
Returns

A new misorientation object with the assigned symmetry.

Return type

Misorientation

Examples

>>> from orix.quaternion.symmetry import C4, C2
>>> data = np.array([[0.5, 0.5, 0.5, 0.5], [0, 1, 0, 0]])
>>> m = Misorientation(data).set_symmetry(C4, C2)
>>> m
Misorientation (2,) 4, 2
[[-0.7071  0.7071  0.      0.    ]
[ 0.      1.      0.      0.    ]]

property symmetry

tuple of Symmetry

### OrientationRegion¶

A set of Rotation which are the normals of an orientation region.

 from_symmetry(s1[, s2]) The set of unique (mis)orientations of a symmetrical object. Produces suitable Rotations for the construction of a wireframe for self The vertices of the asymmetric domain.
class orix.quaternion.OrientationRegion(data)

Bases: orix.quaternion.rotation.Rotation

A set of Rotation which are the normals of an orientation region.

faces()
classmethod from_symmetry(s1, s2=Symmetry (1,) 1 [[1. 0. 0. 0.]])

The set of unique (mis)orientations of a symmetrical object.

Parameters
get_plot_data()

Produces suitable Rotations for the construction of a wireframe for self

vertices()

The vertices of the asymmetric domain.

Returns

Return type

Rotation

### Quaternion¶

class orix.quaternion.Quaternion(data=None)

Basic quaternion object.

Quaternions support the following mathematical operations:

• Unary negation.

• Inversion.

• Multiplication with other quaternions and vectors.

data

The numpy array containing the quaternion data.

Type

numpy.ndarray

a, b, c, d

The individual elements of each vector.

Type

Scalar

conj

The conjugate of this quaternion: $$q^* = a - bi - cj - dk$$

Type

Quaternion

dot(other)

Scalar : the dot product of this quaternion and the other.

dot_outer(other)

Scalar : the outer dot product of this quaternion and the other.

mean()

Calculates the mean quarternion with unitary weights

Notes

The method used here corresponds to the Equation (13) of http://www.acsu.buffalo.edu/~johnc/ave_quat07.pdf

outer(other)

Compute the outer product of this quaternion and the other object.

classmethod triple_cross(q1, q2, q3)

Pointwise cross product of three quaternions.

Parameters
• q1 (Quaternion) – Three quaternions for which to find the “triple cross”.

• q2 (Quaternion) – Three quaternions for which to find the “triple cross”.

• q3 (Quaternion) – Three quaternions for which to find the “triple cross”.

Returns

q

Return type

Quaternion

### Rotation¶

Point transformations of objects.

Rotations are transformations of three-dimensional space leaving the origin in place. Rotations can be parametrized numerous ways, but in orix are handled as unit quaternions. Rotations can act on vectors, or other rotations, but not scalars. They are often most easily visualised as being a turn of a certain angle about a certain axis.

Rotations can also be improper. An improper rotation in orix operates on vectors as a rotation by the unit quaternion, followed by inversion. Hence, a mirroring through the x-y plane can be considered an improper rotation of 180° about the z-axis, illustrated in the figure below.

 angle_with(other) The angle of rotation transforming this rotation to the other. dot_outer(other) Scalar : the outer dot product of this rotation and the other. A new object with the same data in a single column. from_euler(euler[, convention, direction]) Creates a rotation from an array of Euler angles. from_matrix(matrix) Creates rotations from orientation matrices [Rowenhorst2015]. from_neo_euler(neo_euler) Creates a rotation from a neo-euler (vector) representation. identity([shape]) Create identity rotations. outer(other) Compute the outer product of this rotation and the other object. random([shape]) Uniformly distributed rotations. random_vonmises([shape, alpha, reference, eps]) Random rotations with a simplified Von Mises-Fisher distribution. to_euler([convention]) Rotations as Euler angles. Rotations as orientation matrices [Rowenhorst2015]. unique([return_index, return_inverse, antipodal]) Returns a new object containing only this object’s unique entries.
class orix.quaternion.Rotation(data)

Bases: orix.quaternion.quaternion.Quaternion

Rotation object.

Rotations support the following mathematical operations:

• Unary negation.

• Inversion.

• Multiplication with other rotations and vectors.

Rotations inherit all methods from Quaternion although behaviour is different in some cases.

Rotations can be converted to other parametrizations, notably the neo-Euler representations. See NeoEuler.

property angle

the angle of rotation.

Type

Scalar

angle_with(other)

The angle of rotation transforming this rotation to the other.

Returns

Return type

Scalar

property antipodal

this and antipodally equivalent rotations.

Type

Rotation

property axis

the axis of rotation.

Type

Vector3d

dot_outer(other)

Scalar : the outer dot product of this rotation and the other.

flatten()

A new object with the same data in a single column.

classmethod from_euler(euler, convention='bunge', direction='crystal2lab')

Creates a rotation from an array of Euler angles.

Parameters
• euler (array-like) – Euler angles in the Bunge convention.

• convention (str) – Only ‘bunge’ is currently supported for new data

• direction (str) – ‘lab2crystal’ or ‘crystal2lab’

classmethod from_matrix(matrix)

Creates rotations from orientation matrices [Rowenhorst2015].

Parameters

matrix (array_like) – Array of orientation matrices.

Examples

>>> import numpy as np
>>> from orix.quaternion.rotation import Rotation
>>> r = Rotation.from_matrix(np.eye(3))
>>> np.allclose(r.data, [1, 0, 0, 0])
True
>>> r = Rotation.from_matrix(np.diag([1, -1, -1]))
>>> np.allclose(r.data, [0, 1, 0, 0])
True

classmethod from_neo_euler(neo_euler)

Creates a rotation from a neo-euler (vector) representation.

Parameters

neo_euler (NeoEuler) – Vector parametrization of a rotation.

classmethod identity(shape=(1))

Create identity rotations.

Parameters

shape (tuple) – The shape out of which to construct identity quaternions

property improper

True for improper rotations and False otherwise.

Type

ndarray

outer(other)

Compute the outer product of this rotation and the other object.

classmethod random(shape=(1))

Uniformly distributed rotations.

Parameters

shape (int or tuple of int, optional) – The shape of the required object.

classmethod random_vonmises(shape=(1), alpha=1.0, reference=(1, 0, 0, 0), eps=1e-06)

Random rotations with a simplified Von Mises-Fisher distribution.

Parameters
• shape (int or tuple of int, optional) – The shape of the required object.

• alpha (float) – Parameter for the VM-F distribution. Lower values lead to “looser” distributions.

• reference (Rotation) – The center of the distribution.

• eps (float) – A small fixed variable.

to_euler(convention='bunge')

Rotations as Euler angles.

Parameters

convention ('bunge') – The Euler angle convention used. Only ‘bunge’ is supported as present

Returns

Array of Euler angles in radians.

Return type

ndarray

to_matrix()

Rotations as orientation matrices [Rowenhorst2015].

Returns

Array of orientation matrices.

Return type

ndarray

References

Rowenhorst2015(1,2,3,4)

D. Rowenhorst, A. D. Rollett, G. S. Rohrer, M. Groeber, M. Jackson, P. J. Konijnenberg, M. De Graef, “Consistent representations of and conversions between 3D rotations,” Modelling and Simulation in Materials Science and Engineering 23 (2015), doi: https://doi.org/10.1088/0965-0393/23/8/083501

Examples

>>> import numpy as np
>>> from orix.quaternion.rotation import Rotation
>>> r = Rotation([1, 0, 0, 0])
>>> np.allclose(r.to_matrix(), np.eye(3))
True
>>> r = Rotation([0, 1, 0, 0])
>>> np.allclose(r.to_matrix(), np.diag([1, -1, -1]))
True

unique(return_index=False, return_inverse=False, antipodal=True)

Returns a new object containing only this object’s unique entries.

Two rotations are not unique if:

• they have the same propriety AND
• they have the same numerical value OR

• the numerical value of one is the negative of the other

Parameters
• return_index (bool, optional) – If True, will also return the indices of the (flattened) data where the unique entries were found.

• return_inverse (bool, optional) – If True, will also return the indices to reconstruct the (flattened) data from the unique data.

• antipodal (bool, optional) – If False, rotations representing the same transformation whose values are numerically different (negative) will not be considered unique.

### Symmetry¶

Collections of transformations representing a symmetry group.

An object’s symmetry can be characterized by the transformations relating symmetrically-equivalent views on that object. Consider the following shape.

This obviously has three-fold symmetry. If we rotated it by $$\frac{2}{3}\pi$$ or $$\frac{4}{3}\pi$$, the image would be unchanged. These angles, as well as $$0$$, or the identity, expressed as quaternions, form a group. Applying any operation in the group to any other results in another member of the group.

Symmetries can consist of rotations or inversions, expressed as improper rotations. A mirror symmetry is equivalent to a 2-fold rotation combined with inversion.

 from_generators(*generators) Create a Symmetry from a minimum list of generating transformations.
class orix.quaternion.Symmetry(data)

Bases: orix.quaternion.rotation.Rotation

The set of rotations comprising a point group.

property contains_inversion

True if this group contains inversion.

Type

bool

property diads
classmethod from_generators(*generators)

Create a Symmetry from a minimum list of generating transformations.

Parameters

generators (Rotation) – An arbitrary list of constituent transformations.

Returns

Return type

Symmetry

Examples

Combining a 180° rotation about [1, -1, 0] with a 4-fold rotoinversion axis along [0, 0, 1]

>>> myC2 = Symmetry([(1, 0, 0, 0), (0, 0.75**0.5, -0.75**0.5, 0)])
>>> myS4 = Symmetry([(1, 0, 0, 0), (0.5**0.5, 0, 0, 0.5**0.5)])
>>> myS4.improper = [0, 1]
>>> mySymmetry = Symmetry.from_generators(myC2, myS4)
>>> mySymmetry
Symmetry (8,)
[[ 1.      0.      0.      0.    ]
[ 0.      0.7071 -0.7071  0.    ]
[ 0.7071  0.      0.      0.7071]
[ 0.      0.     -1.      0.    ]
[ 0.      1.      0.      0.    ]
[-0.7071  0.      0.      0.7071]
[ 0.      0.      0.      1.    ]
[ 0.     -0.7071 -0.7071  0.    ]]

fundamental_sector()
get_axis_orders()
get_highest_order_axis()
property is_proper

True if this group contains only proper rotations.

Type

bool

property laue

this group plus inversion

Type

Symmetry

property laue_proper_subgroup

the proper subgroup of this group plus inversion.

Type

Symmetry

name = ''
property order

The number of elements of the group.

Type

int

property proper_subgroup

the largest proper group of this subgroup.

Type

Symmetry

property proper_subgroups

the proper groups that are subgroups of this group.

Type

list of Symmetry

property subgroups

the groups that are subgroups of this group.

Type

list of Symmetry

Other functions

orix.quaternion.symmetry.get_distinguished_points(s1, s2=Symmetry (1,) 1 [[1. 0. 0. 0.]])

Points symmetrically equivalent to identity with respect to s1 and s2

Parameters
Returns

Return type

Rotation

orix.quaternion.symmetry.get_point_group(space_group_number, proper=False)

Maps a space group number to its (proper) point group.

Parameters
• space_group_number (int) – Between 1 and 231.

• proper (bool, optional) – Whether to return the point group with proper rotations only (True), or just the point group (False). Default is False.

Returns

point_group – One of the 11 proper or 32 point groups.

Return type

orix.quaternion.symmetry.Symmetry

Examples

>>> from orix.quaternion.symmetry import get_point_group
>>> pgOh = get_point_group(225)
>>> pgOh.name
'm-3m'
>>> pgO = get_point_group(225, proper=True)
>>> pgO.name
'432'


## sampling¶

 get_sample_fundamental([resolution, …]) Generates an equispaced grid of rotations within a fundamental zone. get_sample_local([resolution, center, …]) Generates a grid of rotations about a given rotation uniform_SO3_sample(resolution) Returns rotations that are evenly spaced according to the Haar measure on SO3

Module for generating grids in orientation spaces.

orix.sampling.get_sample_fundamental(resolution=2, point_group=None, space_group=None)

Generates an equispaced grid of rotations within a fundamental zone.

Parameters
• resolution (float, optional) – The characteristic distance between a rotation and its neighbour (degrees)

• point_group (orix.quaternion.symmetry.Symmetry, optional) – One of the 11 proper point groups, defaults to None

• space_group (int, optional) – Between 1 and 231, defaults to None

Returns

q – Grid of rotations lying within the specified fundamental zone

Return type

orix.quaternion.rotation.Rotation

orix.sampling.utils.uniform_SO3_sample

Examples

>>> from orix.quaternion.symmetry import C2,C4
>>> grid = get_sample_fundamental(1, point_group=C2)

orix.sampling.get_sample_local(resolution=2, center=None, grid_width=10)

Generates a grid of rotations about a given rotation

Parameters
• resolution (float, optional) – The characteristic distance between a rotation and its neighbour (degrees)

• center (orix.quaternion.rotation.Rotation, optional) – The rotation at which the grid is centered. If None (default) uses the identity

• grid_width (float, optional) – The largest angle of rotation away from center that is acceptable (degrees)

Returns

q – Grid of rotations lying within grid_width of center

Return type

orix.quaternion.rotation.Rotation

orix.sampling_utils.uniform_SO3_sample

orix.sampling.uniform_SO3_sample(resolution)

Returns rotations that are evenly spaced according to the Haar measure on SO3

Parameters

resolution (float) – The characteristic distance between a rotation and its neighbour (degrees)

Returns

q – grid containing appropriate rotations

Return type

orix.quaternion.rotation.Rotation

## scalar¶

Dimensionless quantities.

As well as themselves representing physical quantities, Scalars may represent elements of higher-dimensional quantities, such as the x-component of a vector or the rotation angle of a quaternion.

class orix.scalar.Scalar(data)

Scalar base class.

Scalars currently support the following mathematical operations:

• Unary negation.

• Addition to other scalars, numerical types, and array_like objects.

• Subtraction to the above.

• Multiplication to the above.

• Element-wise boolean comparisons (==, < etc).

• Unary exponentiation.

flatten()

Scalar : A new object with the same data in a single column.

reshape(*args)

Returns a new Scalar containing the same data with a new shape.

property shape

Tuple of the shape of the Scalar.

Returns

Return type

tuple

## vector¶

Three-dimensional quantities.

Vectors can represent positions in three-dimensional space and are also commonly associated with motion, possessing both a magnitude and a direction. In orix they are often encountered as derived objects such as the rotation axis of a quaternion or the normal to the bounding planes of a spherical region.

 AxAngle([data]) The simplest neo-Eulerian representation. Homochoric([data]) Equal-volume mapping of the unit quaternion hemisphere. NeoEuler([data]) Base class for neo-Eulerian vectors. Rodrigues([data]) In Rodrigues space, straight lines map to rotations about a fixed axis. SphericalRegion([data]) A set of vectors representing normals segmenting a sphere. Vector3d([data]) Vector base class.

### AxAngle¶

 from_axes_angles(axes, angles) Create new AxAngle object explicitly from the given axes and angles.
class orix.vector.AxAngle(data=None)

Bases: orix.vector.neo_euler.NeoEuler

The simplest neo-Eulerian representation.

The Axis-Angle vector representing a rotation with rotation angle $$\theta$$ has magnitude $$\theta$$

property angle

the angle of rotation.

Type

Scalar

classmethod from_axes_angles(axes, angles)

Create new AxAngle object explicitly from the given axes and angles.

Parameters
• axes (Vector3d or array_like) – The axis of rotation.

• angles (array_like) – The angle of rotation, in radians.

Returns

Return type

AxAngle

classmethod from_rotation(rotation)

NeoEuler : Create a new vector from the given rotation.

### Homochoric¶

class orix.vector.Homochoric(data=None)

Bases: orix.vector.neo_euler.NeoEuler

Equal-volume mapping of the unit quaternion hemisphere.

The homochoric vector representing a rotation with rotation angle $$\theta$$ has magnitude $$\left[\frac{3}{4}(\theta - \sin\theta)\right]^{\frac{1}{3}}$$.

Notes

The homochoric transformation has no analytical inverse.

property angle

the angle of rotation.

Type

Scalar

classmethod from_rotation(rotation)

NeoEuler : Create a new vector from the given rotation.

### NeoEuler¶

 from_rotation(rotation) NeoEuler : Create a new vector from the given rotation.
class orix.vector.NeoEuler(data=None)

Bases: orix.vector.vector3d.Vector3d, abc.ABC

Base class for neo-Eulerian vectors.

abstract property angle

the angle of rotation.

Type

Scalar

property axis

the axis of rotation.

Type

Vector3d

abstract classmethod from_rotation(rotation)

NeoEuler : Create a new vector from the given rotation.

### Rodrigues¶

class orix.vector.Rodrigues(data=None)

Bases: orix.vector.neo_euler.NeoEuler

In Rodrigues space, straight lines map to rotations about a fixed axis.

The Rodrigues vector representing a rotation with rotation angle $$\theta$$ has magnitude $$\tan\frac{\theta}{2}$$.

property angle

the angle of rotation.

Type

Scalar

classmethod from_rotation(rotation)

NeoEuler : Create a new vector from the given rotation.

### SphericalRegion¶

Vectors describing a segment of a sphere.

Each entry represents a plane normal in 3-d. Vectors can lie in, on, or outside the spherical region.

Examples

>>> sr = SphericalRegion([0, 0, 1])  # Region above the x-y plane
>>> v = Vector3d([(0, 0, 1), (0, 0, -1), (1, 0, 0)])
>>> v < sr
array([ True, False, False], dtype=bool)
>>> v <= sr
array([ True, False,  True], dtype=bool)

class orix.vector.SphericalRegion(data=None)

Bases: orix.vector.vector3d.Vector3d

A set of vectors representing normals segmenting a sphere.

### Vector3d¶

 angle_with(other) Calculate the angles between vectors in ‘self’ and ‘other’ cross(other) The cross product of a vector with another vector. dot(other) The dot product of a vector with another vector. dot_outer(other) The outer dot product of a vector with another vector. from_polar(azimuth, polar[, radial]) Create a Vector3d from spherical coordinates according to the ISO 31-11 standard [SphericalWolfram]. get_nearest(x[, inclusive, tiebreak]) The vector among x with the smallest angle to this one. rotate([axis, angle]) Convenience function for rotating this vector. Return the azimuth $$\phi$$, polar $$\theta$$, and radial $$r$$ spherical coordinates, the angles in radians. Vector3d : a single unit vector parallel to the x-direction. Vector3d : a single unit vector parallel to the y-direction. Vector3d : a single unit vector parallel to the z-direction. zero([shape]) Returns zero vectors in the specified shape.
class orix.vector.Vector3d(data=None)

Vector base class.

Vectors support the following mathematical operations:

• Unary negation.

• Addition to other vectors, scalars, numbers, and compatible array-like objects.

• Subtraction to and from the above.

• Multiplication to scalars, numbers, and compatible array-like objects.

• Division by the same as multiplication. Division by a vector is not defined in general.

Examples

>>> v = Vector3d((1, 2, 3))
>>> w = Vector3d(np.array([[1, 0, 0], [0, 1, 1]]))

>>> w.x
Scalar (2,)
[1 0]

>>> v.unit
Vector3d (1,)
[[ 0.2673  0.5345  0.8018]]

>>> -v
Vector3d (1,)
[[-1 -2 -3]]

>>> v + w
Vector3d (2,)
[[2 2 3]
[1 3 4]]

>>> w - (2, -3)
Vector3d (2,)
[[-1 -2 -2]
[ 3  4  4]]

>>> 3 * v
Vector3d (1,)
[[3 6 9]]

>>> v / 2
Vector3d (1,)
[[0.5 1.0 1.5]]

>>> v / (2, -2)
Vector3d (1,)
[[0.5 1.0 1.5]
[-0.5 -1.0 -1.5]]

angle_with(other)

Calculate the angles between vectors in ‘self’ and ‘other’

Vectors must have compatible shapes for broadcasting to work.

Returns

The angle between the vectors, in radians.

Return type

Scalar

property azimuth

Azimuth spherical coordinate, i.e. the angle $$\phi \in [0, 2\pi]$$ from the positive z-axis to a point on the sphere, according to the ISO 31-11 standard [SphericalWolfram].

Returns

Return type

Scalar

cross(other)

The cross product of a vector with another vector.

Vectors must have compatible shape for broadcasting to work.

Returns

The class of ‘other’ is preserved.

Return type

Vector3d

Examples

>>> v = Vector3d(((1, 0, 0), (-1, 0, 0)))
>>> w = Vector3d((0, 1, 0))
>>> v.cross(w)
Vector3d (2,)
[[ 0  0  1]
[ 0  0 -1]]

dim = 3

The number of dimensions for this object.

Type

int

dot(other)

The dot product of a vector with another vector.

Vectors must have compatible shape.

Returns

Return type

Scalar

Examples

>>> v = Vector3d((0, 0, 1.0))
>>> w = Vector3d(((0, 0, 0.5), (0.4, 0.6, 0)))
>>> v.dot(w)
Scalar (2,)
[ 0.5  0. ]
>>> w.dot(v)
Scalar (2,)
[ 0.5  0. ]

dot_outer(other)

The outer dot product of a vector with another vector.

The dot product for every combination of vectors in self and other is computed.

Returns

Return type

Scalar

Examples

>>> v = Vector3d(((0.0, 0.0, 1.0), (1.0, 0.0, 0.0)))  # shape = (2, )
>>> w = Vector3d(((0.0, 0.0, 0.5), (0.4, 0.6, 0.0), (0.5, 0.5, 0.5)))  # shape = (3, )
>>> v.dot_outer(w)
Scalar (2, 3)
[[ 0.5  0.   0.5]
[ 0.   0.4  0.5]]
>>> w.dot_outer(v)  # shape = (3, 2)
Scalar (3, 2)
[[ 0.5  0. ]
[ 0.   0.4]
[ 0.5  0.5]]

classmethod from_polar(azimuth, polar, radial=1)

Create a Vector3d from spherical coordinates according to the ISO 31-11 standard [SphericalWolfram].

Parameters
• azimuth (array_like) – The azimuth angle, in radians.

• polar (array_like) – The polar angle, in radians.

• radial (array_like) – The radial distance. Defaults to 1 to produce unit vectors.

Returns

Return type

Vector3d

References

SphericalWolfram(1,2,3,4,5,6,7,8,9,10,11,12)

Weisstein, Eric W. “Spherical Coordinates,” From MathWorld–A Wolfram Web Resource, url: https://mathworld.wolfram.com/SphericalCoordinates.html

get_nearest(x, inclusive=False, tiebreak=None)

The vector among x with the smallest angle to this one.

Parameters
• x (Vector3d) –

• inclusive (bool) – if False (default) vectors exactly parallel to this will not be considered.

• tiebreak (Vector3d) – If multiple vectors are equally close to this one, tiebreak will be used as a secondary comparison. By default equal to (0, 0, 1).

Returns

Return type

Vector3d

mean()
property perpendicular
property polar

Polar spherical coordinate, i.e. the angle $$\theta \in [0, \pi]$$ from the positive z-axis to a point on the sphere, according to the ISO 31-11 standard [SphericalWolfram].

Returns

Return type

Scalar

property radial

Radial spherical coordinate, i.e. the distance from a point on the sphere to the origin, according to the ISO 31-11 standard [SphericalWolfram].

Returns

Return type

Scalar

rotate(axis=None, angle=0)

Convenience function for rotating this vector.

Shapes of ‘axis’ and ‘angle’ must be compatible with shape of this vector for broadcasting.

Parameters
• axis (Vector3d or array_like, optional) – The axis of rotation. Defaults to the z-vector.

• angle (array_like, optional) – The angle of rotation, in radians.

Returns

A new vector with entries rotated.

Return type

Vector3d

Examples

>>> from math import pi
>>> v = Vector3d((0, 1, 0))
>>> axis = Vector3d((0, 0, 1))
>>> angles = [0, pi/4, pi/2, 3*pi/4, pi]
>>> v.rotate(axis=axis, angle=angles)

to_polar()

Return the azimuth $$\phi$$, polar $$\theta$$, and radial $$r$$ spherical coordinates, the angles in radians. The coordinates are defined as in the ISO 31-11 standard [SphericalWolfram].

Returns

azimuth, polar, r

Return type

Scalar

property x

This vector’s x data.

Type

Scalar

classmethod xvector()

Vector3d : a single unit vector parallel to the x-direction.

property xyz

This vector’s components, useful for plotting.

Type

tuple of ndarray

property y

This vector’s y data.

Type

Scalar

classmethod yvector()

Vector3d : a single unit vector parallel to the y-direction.

property z

This vector’s z data.

Type

Scalar

classmethod zero(shape=(1))

Returns zero vectors in the specified shape.

Parameters

shape (tuple) –

Returns

Return type

Vector3d

classmethod zvector()

Vector3d : a single unit vector parallel to the z-direction.