microstructure Module¶
The microstructure module provide elementary classes to describe a crystallographic granular microstructure such as mostly present in metallic materials.
It contains several classes which are used to describe a microstructure composed of multiple grains, each one having its own crystallographic orientation:
- class pymicro.crystal.microstructure.Orientation(matrix)¶
Bases:
objectCrystallographic orientation class.
This follows the passive rotation definition which means that it brings the sample coordinate system into coincidence with the crystal coordinate system. Then one may express a vector \(V_c\) in the crystal coordinate system from the vector in the sample coordinate system \(V_s\) by:
\[V_c = g.V_s\]and inversely (because \(g^{-1}=g^T\)):
\[V_s = g^T.V_c\]Most of the code to handle rotations has been written to comply with the conventions laid in [2].
- __init__(matrix)¶
Initialization from the 9 components of the orientation matrix.
- orientation_matrix()¶
Returns the orientation matrix in the form of a 3x3 numpy array.
- to_crystal(v)¶
Transform a vector or a matrix from the sample frame to the crystal frame.
- Parameters:
v (ndarray) – a 3 component vector or a 3x3 array expressed in the sample frame.
- Returns:
the vector or matrix expressed in the crystal frame.
- to_sample(v)¶
Transform a vector or a matrix from the crystal frame to the sample frame.
- Parameters:
v (ndarray) – a 3 component vector or a 3x3 array expressed in the crystal frame.
- Returns:
the vector or matrix expressed in the sample frame.
- static cube()¶
Create the particular crystal orientation called Cube and which corresponds to euler angle (0, 0, 0).
- static brass()¶
Create the particular crystal orientation called Brass and which corresponds to euler angle (35.264, 45, 0).
- static copper()¶
Create the particular crystal orientation called Copper and which corresponds to euler angle (90, 35.264, 45).
- static s3()¶
Create the particular crystal orientation called S3 and which corresponds to euler angle (59, 37, 63).
- static goss()¶
Create the particular crystal orientation called Goss and which corresponds to euler angle (0, 45, 0).
- static shear()¶
Create the particular crystal orientation called shear and which corresponds to euler angle (45, 0, 0).
- static random()¶
Create a random crystal orientation.
- ipf_color(axis=array([0., 0., 1.]), symmetry=Symmetry.cubic, saturate=True)¶
Compute the IPF (inverse pole figure) colour for this orientation.
This method has bee adapted from the DCT code and works for most of the crystal symmetries.
- Parameters:
axis (ndarray) – the direction to use to compute the IPF colour.
symmetry (Symmetry) – the symmetry operator to use.
saturate (bool) – a flag to saturate the RGB values.
- Returns:
the IPF colour in RGB form.
- static compute_mean_orientation(rods, symmetry=Symmetry.cubic)¶
Compute the mean orientation.
This function computes a mean orientation from several data points representing orientations by averaging the corresponding Rodrigues vector. One caveat with this averaging method is if the vectors belong to different asymmetric domains, the mean orientation will be wrong.
To avoid this, we compute all equivalent rotation for all data points and then use kmeans clustering to separate all points. We do this using quaternions to avoid arbitrarily large rodrigues vectors when the rotation angle approaches pi (this would make the clustering algorithm fail). The number of clusters is known to be equal to the number of symmetry operators.
A mean orientation is then computed for each cluster and the one which belongs to the fundamental zone is returned.
- Parameters:
rods (ndarray) – a (n, 3) shaped array containing the Rodrigues
vectors of the orientations. :param Symmetry symmetry: the symmetry used to move orientations to their fundamental zone (cubic by default) :returns: the mean orientation as an Orientation instance.
- static compute_mean_rodrigues(rods, symmetry=Symmetry.cubic)¶
Compute the mean orientation as a rodrigues vector.
This function computes a mean orientation from several data points representing orientations by averaging the corresponding Rodrigues vector. One caveat with this averaging method is if the vectors belong to different asymmetric domains, the mean orientation will be wrong.
To avoid this, we compute all equivalent rotation for all data points and then use kmeans clustering to separate all points. We do this using quaternions to avoid arbitrarily large rodrigues vectors when the rotation angle approaches pi (this would make the clustering algorithm fail). The number of clusters is known to be equal to the number of symmetry operators.
A mean orientation is then computed for each cluster and the one which belongs to the fundamental zone is returned.
- Parameters:
rods (ndarray) – a (n, 3) shaped array containing the Rodrigues
vectors of the orientations. :param Symmetry symmetry: the symmetry used to move orientations to their fundamental zone (cubic by default) :returns: the mean orientation as a rodrigues vector.
- static fzDihedral(rod, n)¶
check if the given Rodrigues vector is in the fundamental zone.
After book from Morawiec :cite`Morawiec_2004`:
- inFZ(symmetry=Symmetry.cubic)¶
Check if the given Orientation lies within the fundamental zone.
For a given crystal symmetry, several rotations can describe the same physcial crystllographic arangement. The Rodrigues fundamental zone (also called the asymmetric domain) restricts the orientation space accordingly.
- Parameters:
symmetry – the Symmetry to use.
- Return bool:
True if this orientation is in the fundamental zone,
False otherwise.
- move_to_FZ(symmetry=Symmetry.cubic, verbose=False)¶
Compute the equivalent crystal orientation in the Fundamental Zone of a given symmetry.
- Parameters:
symmetry (Symmetry) – an instance of the Symmetry class.
verbose – flag for verbose mode.
- Returns:
a new Orientation instance which lies in the fundamental zone.
- rotate_orientation(rotation_xyz)¶
Rotate this grain orientation given the rotation matrix expressed in the laboratory coordinate system.
- Parameters:
rotation_xyz – a 3x3 array representing the rotation matrix to apply.
- Returns:
a new Orientation instance rotated.
- static misorientation_MacKenzie(psi)¶
Return the fraction of the misorientations corresponding to the given \(\psi\) angle in the reference solution derived By MacKenzie in his 1958 paper [1].
- Parameters:
psi – the misorientation angle in radians.
- Returns:
the value in the cummulative distribution corresponding to psi.
- static misorientation_axis_from_delta(delta)¶
Compute the misorientation axis from the misorientation matrix.
- Parameters:
delta – The 3x3 misorientation matrix.
- Returns:
the misorientation axis (normalised vector).
- misorientation_axis(orientation)¶
Compute the misorientation axis with another crystal orientation. This vector is by definition common to both crystalline orientations.
- Parameters:
orientation – an instance of
Orientationclass.- Returns:
the misorientation axis (normalised vector).
- static misorientation_angle_from_delta(delta)¶
Compute the misorientation angle from the misorientation matrix.
Compute the angle associated with this misorientation matrix \(\Delta g\). It is defined as \(\omega = \arccos(\text{trace}(\Delta g)/2-1)\). To avoid float rounding point error, the value of \(\cos\omega\) is clipped to [-1.0, 1.0].
Note
This does not account for the crystal symmetries. If you want to find the disorientation between two orientations, use the
disorientation()method.- Parameters:
delta – The 3x3 misorientation matrix.
- Returns float:
the misorientation angle in radians.
- disorientation(orientation, crystal_structure=Symmetry.triclinic)¶
Compute the disorientation another crystal orientation.
Considering all the possible crystal symmetries, the disorientation is defined as the combination of the minimum misorientation angle and the misorientation axis lying in the fundamental zone, which can be used to bring the two lattices into coincidence.
Note
Both orientations are supposed to have the same symmetry. This is not necessarily the case in multi-phase materials.
- Parameters:
orientation – an instance of
Orientationclass describing the other crystal orientation from which to compute the angle.crystal_structure – an instance of the Symmetry class describing the crystal symmetry, triclinic (no symmetry) by default.
- Returns tuple:
the misorientation angle in radians, the axis as a numpy vector (crystal coordinates), the axis as a numpy vector (sample coordinates).
- phi1()¶
Convenience method to expose the first Euler angle.
- Phi()¶
Convenience method to expose the second Euler angle.
- phi2()¶
Convenience method to expose the third Euler angle.
- plot(lattice=None)¶
create a figure to plot the orientation.
Create a 3D representation of a crystal lattice rotated by this orientation in the (X, Y, Z) local frame.
- Parameters:
lattice (Lattice) – an optional crystal lattice can be specified.
- compute_XG_angle(hkl, omega, verbose=False)¶
Compute the angle between the scattering vector \(\mathbf{G_{l}}\) and \(\mathbf{-X}\) the X-ray unit vector at a given angular position \(\omega\).
A given hkl plane defines the scattering vector \(\mathbf{G_{hkl}}\) by the miller indices in the reciprocal space. It is expressed in the cartesian coordinate system by \(\mathbf{B}.\mathbf{G_{hkl}}\) and in the laboratory coordinate system accounting for the crystal orientation by \(\mathbf{g}^{-1}.\mathbf{B}.\mathbf{G_{hkl}}\).
The crystal is assumed to be placed on a rotation stage around the laboratory vertical axis. The scattering vector can finally be written as \(\mathbf{G_l}=\mathbf{\Omega}.\mathbf{g}^{-1}.\mathbf{B}.\mathbf{G_{hkl}}\). The X-rays unit vector is \(\mathbf{X}=[1, 0, 0]\). So the computed angle is \(\alpha=acos(-\mathbf{X}.\mathbf{G_l}/||\mathbf{G_l}||\)
The Bragg condition is fulfilled when \(\alpha=\pi/2-\theta_{Bragg}\)
- Parameters:
hkl – the hkl plane, an instance of
HklPlaneomega – the angle of rotation of the crystal around the laboratory vertical axis.
verbose (bool) – activate verbose mode (False by default).
- Return float:
the angle between \(-\mathbf{X}\) and \(\mathbf{G_{l}}\) in degrees.
- static solve_trig_equation(A, B, C, verbose=False)¶
Solve the trigonometric equation in the form of:
\[A\cos\theta + B\sin\theta = C\]- Parameters:
A (float) – the A constant in the equation.
B (float) – the B constant in the equation.
C (float) – the C constant in the equation.
- Return tuple:
the two solutions angular values in degrees.
- dct_omega_angles(hkl, lambda_keV, verbose=False)¶
Compute the two omega angles which satisfy the Bragg condition.
For a given crystal orientation sitting on a vertical rotation axis, there is exactly two \(\omega\) positions in \([0, 2\pi]\) for which a particular \((hkl)\) reflexion will fulfil Bragg’s law.
According to the Bragg’s law, a crystallographic plane of a given grain will be in diffracting condition if:
\[\sin\theta=-[\mathbf{\Omega}.\mathbf{g}^{-1}\mathbf{G_c}]_1\]with \(\mathbf{\Omega}\) the matrix associated with the rotation axis:
\[\begin{split}\mathbf{\Omega}=\begin{pmatrix} \cos\omega & -\sin\omega & 0 \\ \sin\omega & \cos\omega & 0 \\ 0 & 0 & 1 \\ \end{pmatrix}\end{split}\]This method solves the associated second order equation to return the two corresponding omega angles.
- Parameters:
hkl – The given cristallographic plane
HklPlanelambda_keV (float) – The X-rays energy expressed in keV
verbose (bool) – Verbose mode (False by default)
- Returns tuple:
\((\omega_1, \omega_2)\) the two values of the rotation angle around the vertical axis (in degrees).
- rotating_crystal(hkl, lambda_keV, omega_step=0.5, display=True, verbose=False)¶
- static compute_instrument_transformation_matrix(rx_offset, ry_offset, rz_offset)¶
Compute instrument transformation matrix for given rotation offset.
This function compute a 3x3 rotation matrix (passive convention) that transforms the sample coordinate system by rotating around the 3 cartesian axes in this order: rotation around X is applied first, then around Y and finally around Z.
A sample vector \(V_s\) is consequently transformed into \(V'_s\) as:
\[V'_s = T^T.V_s\]- Parameters:
rx_offset (double) – value to apply for the rotation around X.
ry_offset (double) – value to apply for the rotation around Y.
rz_offset (double) – value to apply for the rotation around Z.
- Returns:
a 3x3 rotation matrix describing the transformation applied by the diffractometer.
- topotomo_tilts(hkl, T=None, verbose=False)¶
Compute the tilts for topotomography alignment.
- Parameters:
hkl – the hkl plane, an instance of
HklPlaneT (ndarray) – transformation matrix representing the diffractometer direction at omega=0.
verbose (bool) – activate verbose mode (False by default).
- Returns tuple:
(ut, lt) the two values of tilts to apply (in radians).
- static from_euler(euler, convention='Bunge')¶
Rotation matrix from Euler angles.
This is the classical method to obtain an orientation matrix by 3 successive rotations. The result depends on the convention used (how the successive rotation axes are chosen). In the Bunge convention, the first rotation is around Z, the second around the new X and the third one around the new Z. In the Roe convention, the second one is around Y.
- static from_rodrigues(rod)¶
- static from_Quaternion(q)¶
- static from_n1n2(n1, n2)¶
Create an orientation instance from the two vectors used in Amitex_FFTP which are the first two rows of the orientation matrix.
- Parameters:
n1 (np.array) – the first vector describing the orientation.
n2 (np.array) – the second vector describing the orientation.
- Returns:
an instance of the Orientation class.
- static from_amitex(data_dir='.', binary=True)¶
This methods reads the orientations from Amitex files.
The orientation data is read from 6 files: N1X.bin, N1Y.bin, N1Z.bin, N2X.bin, N2Y.bin and N2Z.bin (in binary format). The bin extension is replaced by txt for the ascii format.
- Parameters:
data_dir (str) – the folder where the orientation files are located.
binary (bool) – use binary format (True by default).
- Returns:
a list containing instances of the Orientation class.
- static transformation_matrix(hkl_1, hkl_2, n_1, n_2)¶
Compute the orientation matrix from the two known hkl plane normals.
The function build two orthonormal basis, one in the crystal frame and the other in the sample frame. the orientation matrix brings the second one into coincidence with first one.
- Parameters:
hkl_1 – the first HklPlane instance.
hkl_2 – the second HklPlane instance.
n_1 – a vector normal to the first lattice plane.
n_2 – a vector normal to the second lattice plane.
- Returns:
the corresponding 3x3 orientation matrix.
- static from_two_hkl_normals(hkl_1, hkl_2, xyz_normal_1, xyz_normal_2)¶
- static Zrot2OrientationMatrix(x1=None, x2=None, x3=None)¶
Compute the orientation matrix from the rotated coordinates given in the .inp file for Zebulon’s computations.
The function needs two of the three base vectors, the third one is computed using a cross product.
Note
Still need some tests to validate this function.
- Parameters:
x1 – the first basis vector.
x2 – the second basis vector.
x3 – the third basis vector.
- Returns:
the corresponding 3x3 orientation matrix.
- static OrientationMatrix2EulerSF(g)¶
Compute the Euler angles (in degrees) from the orientation matrix in a similar way as done in Mandel_crystal.c
- static OrientationMatrix2Euler(g)¶
Compute the Euler angles from the orientation matrix.
This conversion follows the paper of Rowenhorst et al. [2]. In particular when \(g_{33} = 1\) within the machine precision, there is no way to determine the values of \(\phi_1\) and \(\phi_2\) (only their sum is defined). The convention is to attribute the entire angle to \(\phi_1\) and set \(\phi_2\) to zero.
- Parameters:
g – The 3x3 orientation matrix
- Returns:
The 3 euler angles in degrees.
- static OrientationMatrix2Rodrigues(g)¶
Compute the rodrigues vector from the orientation matrix.
- Parameters:
g – The 3x3 orientation matrix representing the rotation.
- Returns:
The Rodrigues vector as a 3 components array.
- static OrientationMatrix2Quaternion(g, P=1)¶
- static Rodrigues2OrientationMatrix(rod)¶
Compute the orientation matrix from the Rodrigues vector.
- Parameters:
rod – The Rodrigues vector as a 3 components array.
- Returns:
The 3x3 orientation matrix representing the rotation.
- static Rodrigues2Axis(rod)¶
Compute the axis/angle representation from the Rodrigues vector.
- Parameters:
rod – The Rodrigues vector as a 3 components array.
- Returns:
A tuple in the (axis, angle) form.
- static Axis2OrientationMatrix(axis, angle)¶
Compute the (passive) orientation matrix associated the rotation defined by the given (axis, angle) pair.
- Parameters:
axis – the rotation axis.
angle – the rotation angle (degrees).
- Returns:
the 3x3 orientation matrix.
- static Axis2Quaternion(axis, angle, P=1)¶
Compute the quaternion associated the rotation defined by the given (axis, angle) pair.
- Parameters:
axis – the rotation axis.
angle – the rotation angle (degrees).
P (int) – convention (1 for active, -1 for passive)
- Returns:
the corresponding Quaternion.
- static Euler2Axis(euler)¶
Compute the (axis, angle) representation associated to this (passive) rotation expressed by the Euler angles.
- Parameters:
euler – 3 euler angles (in degrees).
- Returns:
a tuple containing the axis (a vector) and the angle (in radians).
- static Euler2Quaternion(euler, P=1)¶
Compute the quaternion from the 3 euler angles (in degrees).
- Parameters:
euler (tuple) – the 3 euler angles in degrees.
P (int) – +1 to compute an active quaternion (default), -1 for a passive quaternion.
- Returns:
a Quaternion instance representing the rotation.
- static Euler2Rodrigues(euler)¶
Compute the rodrigues vector from the 3 euler angles (in degrees).
- Parameters:
euler – the 3 Euler angles (in degrees).
- Returns:
the rodrigues vector as a 3 components numpy array.
- static eu2ro(euler)¶
Transform a series of euler angles into Rodrigues vectors.
- Parameters:
euler (ndarray) – the (n, 3) shaped array of Euler angles (radians).
- Returns:
a (n, 3) array with the Rodrigues vectors.
- static Euler2OrientationMatrix(euler)¶
Compute the orientation matrix \(\mathbf{g}\) associated with the 3 Euler angles \((\phi_1, \Phi, \phi_2)\).
The matrix is calculated via (see the euler_angles recipe in the cookbook for a detailed example):
\[\begin{split}\mathbf{g}=\begin{pmatrix} \cos\phi_1\cos\phi_2 - \sin\phi_1\sin\phi_2\cos\Phi & \sin\phi_1\cos\phi_2 + \cos\phi_1\sin\phi_2\cos\Phi & \sin\phi_2\sin\Phi \\ -\cos\phi_1\sin\phi_2 - \sin\phi_1\cos\phi_2\cos\Phi & -\sin\phi_1\sin\phi_2 + \cos\phi_1\cos\phi_2\cos\Phi & \cos\phi_2\sin\Phi \\ \sin\phi_1\sin\Phi & -\cos\phi_1\sin\Phi & \cos\Phi \\ \end{pmatrix}\end{split}\]- Parameters:
euler – The triplet of the Euler angles (in degrees).
- Return g:
The 3x3 orientation matrix.
- static Quaternion2Euler(q)¶
Compute Euler angles from a Quaternion :param q: Quaternion :return: Euler angles (in degrees, Bunge convention)
- static Quaternion2OrientationMatrix(q)¶
- static read_euler_txt(txt_path)¶
Read a set of euler angles from an ascii file.
This method is deprecated, please use read_orientations.
- Parameters:
txt_path (str) – path to the text file containing the euler angles.
- Returns dict:
a dictionary with the line number and the corresponding orientation.
- static read_orientations(txt_path, data_type='euler', **kwargs)¶
Read a set of grain orientations from a text file.
The text file must be organised in 3 columns (the other are ignored), corresponding to either the three euler angles or the three rodrigues vector components, depending on the data_type). Internally the ascii file is read by the genfromtxt function of numpy, to which additional keyworks (such as the delimiter) can be passed to via the kwargs dictionnary.
- Parameters:
txt_path (str) – path to the text file containing the orientations.
data_type (str) – ‘euler’ (default) or ‘rodrigues’.
kwargs (dict) – additional parameters passed to genfromtxt.
- Returns dict:
a dictionary with the line number and the corresponding orientation.
- static read_euler_from_zset_inp(inp_path)¶
Read a set of grain orientations from a z-set input file.
In z-set input files, the orientation data may be specified either using the rotation of two vector, euler angles or rodrigues components directly. For instance the following lines are extracted from a polycrystalline calculation file using the rotation keyword:
**elset elset1 *file au.mat *integration theta_method_a 1.0 1.e-9 150 *rotation x1 0.438886 -1.028805 0.197933 x3 1.038339 0.893172 1.003888 **elset elset2 *file au.mat *integration theta_method_a 1.0 1.e-9 150 *rotation x1 0.178825 -0.716937 1.043300 x3 0.954345 0.879145 1.153101 **elset elset3 *file au.mat *integration theta_method_a 1.0 1.e-9 150 *rotation x1 -0.540479 -0.827319 1.534062 x3 1.261700 1.284318 1.004174 **elset elset4 *file au.mat *integration theta_method_a 1.0 1.e-9 150 *rotation x1 -0.941278 0.700996 0.034552 x3 1.000816 1.006824 0.885212 **elset elset5 *file au.mat *integration theta_method_a 1.0 1.e-9 150 *rotation x1 -2.383786 0.479058 -0.488336 x3 0.899545 0.806075 0.984268
- Parameters:
inp_path (str) – the path to the ascii file to read.
- Returns dict:
a dictionary of the orientations associated with the elset names.
- slip_system_orientation_tensor(s)¶
Compute the orientation strain tensor m^s for this
Orientationand the given slip system.- Parameters:
s – an instance of
SlipSystem
\[M^s_{ij} = \left(l^s_i.n^s_j)\]
- slip_system_orientation_strain_tensor(s)¶
Compute the orientation strain tensor m^s for this
Orientationand the given slip system.- Parameters:
s – an instance of
SlipSystem
\[m^s_{ij} = \frac{1}{2}\left(l^s_i.n^s_j + l^s_j.n^s_i)\]
- slip_system_orientation_rotation_tensor(s)¶
Compute the orientation rotation tensor q^s for this
Orientationand the given slip system.- Parameters:
s – an instance of
SlipSystem
\[q^s_{ij} = \frac{1}{2}\left(l^s_i.n^s_j - l^s_j.n^s_i)\]
- schmid_factor(slip_system, load_direction=[0.0, 0.0, 1], unidirectional=False)¶
Compute the Schmid factor for this crystal orientation and the given slip system.
Note
The Schmid factor is usually regarded as positive (dislocation slip can happend in both shear directions), because of this, the absolute value of the dot product is returned. In some case, is can be useful to compute the unidirectional value of the Schmid factor, in this case, set the unidirectional parameter to True.
- Parameters:
slip_system – a SlipSystem instance.
load_direction – a unit vector describing the loading direction (default: vertical axis [0, 0, 1]).
unidirectional (bool) – if True, a positive value is not enforced.
- Return float:
a number between 0 ad 0.5 (or -0.5 and 0.5 with the
unidirectional option).
- compute_all_schmid_factors(slip_systems, unidirectional=False, load_direction=[0.0, 0.0, 1], verbose=False)¶
Compute all Schmid factors for this crystal orientation and the given list of slip systems.
- Parameters:
slip_systems – a list of the slip systems from which to compute the Schmid factor values.
load_direction – a unit vector describing the loading direction (default: vertical axis [0, 0, 1]).
unidirectional (bool) – if True, a positive value is not enforced.
verbose (bool) – activate verbose mode.
- Return list:
a list of the schmid factors.
- static compute_m_factor(o1, ss1, o2, ss2)¶
Compute the m factor with another slip system.
- Parameters:
o1 (Orientation) – the orientation the first grain.
ss1 (SlipSystem) – the slip system in the first grain.
o2 (Orientation) – the orientation the second grain.
ss2 (SlipSystem) – the slip system in the second grain.
- Returns:
the m factor as a float number < 1
- class pymicro.crystal.microstructure.Grain(grain_id, grain_orientation)¶
Bases:
objectClass defining a crystallographic grain.
A grain has a constant crystallographic Orientation and a grain id. The center attribute is the center of mass of the grain in world coordinates. The volume of the grain is normally expressed in mm unit especially when working in relation with a Microstructure instance; if the unit has not been set, the volume is then given in pixel/voxel unit.
- __init__(grain_id, grain_orientation)¶
- get_volume()¶
- get_volume_fraction(total_volume=None)¶
Compute the grain volume fraction.
- Parameters:
total_volume (float) – the total volume value to use.
- Return float:
the grain volume fraction as a number in the range [0, 1].
- schmid_factor(slip_system, load_direction=[0.0, 0.0, 1])¶
Compute the Schmid factor of this grain for the given slip system and loading direction.
- Parameters:
slip_system – a SlipSystem instance.
load_direction – a unit vector describing the loading direction (default: vertical axis [0, 0, 1]).
- Return float:
a number between 0 ad 0.5.
- SetVtkMesh(mesh)¶
Set the VTK mesh of this grain.
- Parameters:
mesh – the grain mesh in VTK format.
- add_vtk_mesh(array, contour=True, verbose=False)¶
Add a mesh to this grain.
This method process a labeled array to extract the geometry of the grain. The grain shape is defined by the pixels with a value of the grain id. A vtkUniformGrid object is created and thresholded or contoured depending on the value of the flag contour. The resulting mesh is returned, centered on the center of mass of the grain.
- Parameters:
array (ndarray) – a numpy array from which to extract the grain shape.
contour (bool) – a flag to use contour mode for the shape.
verbose (bool) – activate verbose mode.
- vtk_file_name()¶
- save_vtk_repr(file_name=None)¶
- load_vtk_repr(file_name, verbose=False)¶
- orientation_matrix()¶
A method to access the grain orientation matrix.
- Returns:
the grain 3x3 orientation matrix.
- dct_omega_angles(hkl, lambda_keV, verbose=False)¶
Compute the two omega angles which satisfy the Bragg condition.
For a grain with a given crystal orientation sitting on a vertical rotation axis, there is exactly two omega positions in [0, 2pi] for which a particular hkl reflexion will fulfil Bragg’s law. See
dct_omega_angles()of theOrientationclass.- Parameters:
hkl – The given cristallographic
HklPlanelambda_keV (float) – The X-rays energy expressed in keV
verbose (bool) – Verbose mode (False by default)
- Return tuple:
(w1, w2) the two values of the omega angle.
- static from_dct(label=1, data_dir='.')¶
Create a Grain instance from a DCT grain file.
- Parameters:
label (int) – the grain id.
data_dir (str) – the data root from where to fetch data files.
- Returns:
a new grain instance.
- class pymicro.crystal.microstructure.Microstructure(filename=None, name='micro', description='empty', verbose=False, overwrite_hdf5=False, phase=None, autodelete=False)¶
Bases:
SampleDataClass used to manipulate a full microstructure derived from the SampleData class.
As SampleData, this class is a data container for a mechanical sample and its microstructure, synchronized with a HDF5 file and a XML file Microstructure implements a hdf5 data model specific to polycrystalline sample data.
The dataset maintains a GrainData instance which inherits from tables.IsDescription and acts as a structured array containing the grain attributes such as id, orientations (in form of rodrigues vectors), volume and bounding box.
A list of CrystallinePhase instances (each on with its Lattice) is also associated to the microstructure and used for all crystallography calculations.
- __init__(filename=None, name='micro', description='empty', verbose=False, overwrite_hdf5=False, phase=None, autodelete=False)¶
Sample Data constructor, see class documentation.
- minimal_data_model()¶
Data model for a polycrystalline microstructure.
Specify the minimal contents of the hdf5 (Group names, paths and group types) in the form of a dictionary {content: location}. This extends ~pymicro.core.SampleData.minimal_data_model method.
- Returns:
a tuple containing the two dictionnaries.
- sync_phases(verbose=True) None¶
This method sync the _phases attribute with the content of the hdf5 file.
- set_phase(phase, id_number=None) None¶
Set a phase for the given phase_id.
If the phase id does not correspond to one of the existing phase, nothing is done.
- Parameters:
phase (CrystallinePhase) – the phase to use.
phase_id (int)
- set_phases(phase_list) None¶
Set a list of phases for this microstructure.
The different phases in the list are added in that order.
- Parameters:
phase_list (list) – the list of phases to use.
- set_phase_elastic_constants(elastic_constants, phase_id=1) None¶
Set the elastic constants of the given phase.
- Parameters:
elastic_constants (list) – the list of elastic constants to use,
this has to be in agreement with the symmetry of the phase. :param int phase_id: the id of the phase to use. :raise ValueError: if the elastic constants do not match the phase symmetry.
- get_number_of_phases() int¶
Return the number of phases in this microstructure.
Each crystal phase is stored in a list attribute: _phases. Note that it may be different (although it should not) from the different phase ids in the phase_map array.
- Return int:
the number of phases in the microstructure.
- get_number_of_grains(from_grain_map=False) int¶
Return the number of grains in this microstructure.
- Parameters:
from_grain_map (bool) – controls if the retrurned number of grains
comes from the grain data table or from the grain map. :return: the number of grains in the microstructure.
- add_phase(phase) None¶
Add a new phase to this microstructure.
Before adding this phase, the phase id is set to the corresponding id.
- Parameters:
phase (CrystallinePhase) – the phase to add.
- get_phase_list() list¶
Return the list of the phases in this microstructure.
- get_phase_ids_list() list¶
Return the list of the phase ids.
- get_phase(phase_id=1) CrystallinePhase¶
Get a crystalline phase.
If no phase_id is given, the first phase is returned.
- Parameters:
phase_id (int) – the id of the phase to return.
- Returns:
the CrystallinePhase corresponding to the id.
- get_lattice(phase_id=1) Lattice¶
Get the crystallographic lattice associated with this microstructure.
If no phase_id is given, the Lattice of the active phase is returned.
- Returns:
an instance of the Lattice class.
- get_grain_map() array¶
Get the active grain map as a numpy array.
The grain map is the image constituted by the grain ids or labels. Label zero is reserved for the background or unattributed voxels.
- Returns:
the grain map as a numpy array.
- get_phase_map()¶
Get the active phase map as a numpy array.
The phase map is an array of int where each voxel value tells you what is the local material phase with respect to the phase_list attribute.
- Returns:
the phase map as a numpy array.
- get_orientation_map()¶
Get the orientation map as a numpy array.
The orientation map is an array of triplets representing orientation data for each voxel in the forme of rodrigues vectors.
- Returns:
the orientation map as a numpy array.
- get_mask()¶
Get the mask as a numpy array.
The mask represent the sample outline. The value 1 means we are inside the sample, the value 0 means we are outside the sample.
- Returns:
the mask as a numpy array.
- get_ids_from_grain_map()¶
Return the list of grain ids found in the grain map.
By convention, only positive values are taken into account, 0 is reserved for the background and -1 for overlap regions.
- Returns:
a 1D numpy array containing the grain ids.
- get_grain_ids()¶
Return the grain ids found in the GrainDataTable.
- Returns:
a 1D numpy array containing the grain ids.
- static id_list_to_condition(id_list)¶
Convert a list of id to a condition to filter the grain table.
The condition will be interpreted using Numexpr typically using a read_where call on the grain data table.
- Parameters:
id_list (list) – a non empty list of the grain ids.
- Returns:
the condition as a string .
- get_grain_volumes(id_list=None)¶
Get the grain volumes.
The grain data table is queried and the volumes of the grains are returned in a single array. An optional list of grain ids can be used to restrict the grains, by default all the grain volumes are returned.
- Parameters:
id_list (list) – a non empty list of the grain ids.
- Returns:
a numpy array containing the grain volumes.
- get_grain_centers(id_list=None)¶
Get the grain centers.
The grain data table is queried and the centers of the grains are returned in a single array. An optional list of grain ids can be used to restrict the grains, by default all the grain centers are returned.
- Parameters:
id_list (list) – a non empty list of the grain ids.
- Returns:
a numpy array containing the grain centers.
- get_grain_rodrigues(id_list=None)¶
Get the grain rodrigues vectors.
The grain data table is queried and the rodrigues vectors of the grains are returned in a single array. An optional list of grain ids can be used to restrict the grains, by default all the grain rodrigues vectors are returned.
- Parameters:
id_list (list) – a non empty list of the grain ids.
- Returns:
a numpy array containing the grain rodrigues vectors.
- get_grain_orientations(id_list=None)¶
Get a list of the grain orientations.
The grain data table is queried to retreiv the rodrigues vectors. An optional list of grain ids can be used to restrict the grains. A list of Orientation instances is then created and returned.
- Parameters:
id_list (list) – a non empty list of the grain ids.
- Returns:
a list of the grain orientations.
- get_grain_bounding_boxes(id_list=None)¶
Get the grain bounding boxes.
The grain data table is queried and the bounding boxes of the grains are returned in a single array. An optional list of grain ids can be used to restrict the grains, by default all the grain bounding boxes are returned.
Note
The bounding boxes are returned in ascending order of the grain ids (not necessary the same order than the list if it is not ordered). The maximum length of the ids list is 256.
- Parameters:
id_list (list) – a non empty (preferably ordered) list of the
selected grain ids (with a maximum number of ids of 256). :return: a numpy array containing the grain bounding boxes. :raise: a ValueError if the length of the id list is larger than 256.
- get_voxel_size()¶
Get the voxel size for image data of the microstructure.
If this instance of Microstructure has no image data, None is returned.
- get_grain(gid)¶
Get a particular grain given its id.
This method browses the microstructure and return the grain corresponding to the given id. If the grain is not found, the method raises a ValueError.
- Parameters:
gid (int) – the grain id.
- Returns:
The method return a new Grain instance with the corresponding id.
- get_all_grains()¶
Build a list of Grain instances for all grains in this Microstructure.
- Returns:
a list of the grains.
- get_grain_positions()¶
Return all the grain positions as a numpy array of shape (n, 3) where n is the number of grains.
- Returns:
a numpy array of shape (n, 3) of the grain positions.
- get_grain_volume_fractions()¶
Compute all grains volume fractions.
- Returns:
a 1D numpy array with all grain volume fractions.
- get_grain_volume_fraction(gid, use_total_volume_value=None)¶
Compute the volume fraction of this grain.
- Parameters:
gid (int) – the grain id.
use_total_volume_value (float) – the total volume value to use.
- Return float:
the grain volume fraction as a number in the range [0, 1].
- set_orientations(orientations)¶
Store grain orientations array in GrainDataTable
orientation : (Ngrains, 3) array of rodrigues orientation vectors
- set_centers(centers)¶
Store grain centers array in GrainDataTable
centers : (Ngrains, 3) array of grain centers of mass
- set_bounding_boxes(bounding_boxes)¶
Store grain bounding boxes array in GrainDataTable
- set_volumes(volumes)¶
Store grain volumes array in GrainDataTable
- set_grain_phases(phases)¶
Store grain phases array in GrainDataTable
phases : 1D array of the phase id for each grain.
- set_lattice(lattice, phase_id=1)¶
Set the crystallographic lattice associated with this microstructure.
If no phase_id is specified, the lattice will be set for the first phase of the list.
- Parameters:
lattice (Lattice) – an instance of the Lattice class.
phase_id (int) – the id of the phase to set the lattice.
- set_active_grain_map(map_name='grain_map')¶
Set the active grain map name.
The active_grain_map string attribute is used to locate the array when the get_grain_map method is called. This allows to have multiple grain maps within a data set.
- set_active_phase_map(map_name='phase_map')¶
Set the active phase map name.
The active_phase_map string attribute is used to locate the array when the get_phase_map method is called. This allows to have multiple grain maps within a data set.
- set_grain_map(grain_map, voxel_size=None, map_name='grain_map', compression=None)¶
Set the grain map for this microstructure.
- Parameters:
grain_map (ndarray) – a 2D or 3D numpy array.
voxel_size (float) – the size of the voxels in mm unit. Used only if the CellData image Node must be created.
- set_phase_map(phase_map, voxel_size=None, map_name='phase_map', compression=None)¶
Set the phase map for this microstructure.
- Parameters:
phase_map (ndarray) – a 2D or 3D numpy array.
voxel_size (float) – the size of the voxels in mm unit. Used only if the CellData image Node must be created.
- update_phase_map_from_grains(grain_ids=None)¶
Update the phase map from the grain map.
This method update the phase map by setting the phase of all voxels of the grains to the appropriate value.
- Parameters:
grain_ids (list) – the list of the grains ids that are concerned by the update (all grain by default).
phase_id (int) – phase Id to set for the list of grains concerned by the update.
- set_orientation_map(orientation_map, compression=None)¶
Set the orientation_map map for this microstructure.
The orientation map is an array containing the voxel wise orientation data in form of Rodigues vectors.
- Parameters:
orientation_map (ndarray) – a 2D or 3D numpy array with rodrigues
vectors at each pixels. The size of the array must be compatible with the CellData node image dimensions.
- set_mask(mask, voxel_size=None, compression=None)¶
Set the mask for this microstructure.
- Parameters:
mask (ndarray) – a 2D or 3D numpy array.
voxel_size (float) – the size of the voxels in mm unit. Used only if the CellData image Node must be created.
- set_random_orientations()¶
Set random orientations for all grains in GrainDataTable
- remove_grains_not_in_map()¶
Remove from GrainDataTable grains that are not in the grain map.
- remove_small_grains(min_volume=1.0, sync_table=False, new_grain_map_name=None)¶
Remove from grain_map and grain data table small volume grains.
Removed grains in grain map will be replaced by background ID (0). To be sure that the method acts consistently with the current grain map, activate sync_table options.
- Parameters:
min_volume (float) – Grains whose volume is under or equal to this value willl be suppressed from grain_map and grain data table.
sync_table (bool) – If True, synchronize gran data table with grain map before removing grains.
new_grain_map_name (str) – If provided, store the new grain map with removed grain with this new name. If not, overright the current active grain map
- remove_grains_from_table(ids)¶
Remove from GrainDataTable the grains with given ids.
- Parameters:
ids (list) – Array of grain ids to remove from GrainDataTable
- add_grains(orientation_list, orientation_type='euler', grain_ids=None)¶
Add a list of grains to this microstructure.
This function adds a list of grains represented by their orientation (either a list of Euler angles or Rodrigues vectors) to the microstructure. If provided, the grain_ids list will be used for the grain ids.
- Parameters:
orientation_list (list) – a list of values representing the orientations.
orientation_type (str) – euler or rod for Euler angles (Bunge
passive convention and degrees) or Rodrigues vectors. :param list grain_ids: an optional list for the ids of the new grains.
- add_grains_in_map()¶
Add to GrainDataTable the grains in grain map missing in table.
The grains are added with a random orientation by convention.
- static random_texture(n=100, phase=None)¶
Generate a random texture microstructure.
- Parameters:
n (int) – the number of grain orientations in the microstructure.
phase (CrystallinePhase) – the phase to use for this microstructure.
- Returns:
a Microstructure instance with n randomly oriented grains.
- set_mesh(mesh_object=None, file=None, meshname='micro_mesh')¶
Add a mesh of the microstructure to the dataset.
Mesh can be input as a BasicTools mesh object or as a mesh file. Handled file format for now only include .geof (Zset software format).
- create_grain_ids_field(meshname=None, elset_prefix='grain_', store=True)¶
Create a grain Id field of grain orientations on the input mesh.
Creates a element wise field from the microsctructure mesh provided, adding to each element the value of the grain id of the local grain element set, as it is and if it is referenced in the GrainDataTable node.
Note
The grain elsets must be named with a prefix directly followed by the grain number. This means that if the elsets are named grain_1, grain_2, etc, the variable elset_prefix’ must be set to `grain_.
- Parameters:
meshname (str) – Name, Path or index name of the mesh on which an orientation map element field must be constructed
elset_prefix (str) – prefix to define the element sets representing the grains.
store (bool) – If True, store the grain ids field in MeshData group, with name grain_ids
- create_orientation_field(mesh_name=None, elset_prefix='grain_', store=True)¶
Create a vector field of grain orientations on the input mesh.
This method creates a element wise field on the microstructure mesh indicated, adding to each element the value of the Rodrigues vector of this grain as referenced in the GrainDataTable node.
- Parameters:
mesh_name (str) – Name, Path or index name of the mesh on which an orientation field must be constructed
elset_prefix (str) – prefix to define the element sets representing the grains.
store (bool) – If True, store the orientation field in corresponding mesh group, with name orientation_field.
- create_orientation_map(store=True)¶
Create a vector field in CellData of grain orientations.
Creates a (Nx, Ny, Nz, 3) or (Nx, Ny, 3) field from the microstructure grain_map, adding to each voxel the value of the Rodrigues vector of the local grain Id, as it is and if it is referenced in the GrainDataTable node.
- Parameters:
store (bool) – If True, store the orientation map in CellData image group, with name orientation_map
- add_grain_lattices_representation()¶
Add a mesh with one cell per grain representing the crystal lattices.
This function create a mesh with one cell per grain. Each cell is a hexahedron shaped as the crystal lattice and sclaed by the grain size. A scalar field of the grain ids is also attached to the mesh.
- Note:
The case of hexagonal lattice is handled by putting together 3 hexahedrons
to build a hexagonal prism since the VTK_HEXAGONAL_PRISM topology is not presently supported by the XDMF format.
- fz_grain_orientation_data(grain_id, plot=True, move_to_fz=True)¶
Plot the orientation data for this grain.
This function extracts orientation data for a given grain and creates a three dimensional plot in Rodrigues space.
- Parameters:
grain_id (int) – the grain id to retrieve orientation data.
plot (bool) – flag to create a 3D plot. If False, the Rodrigues
orientation data is simply returned. :param bool plot: flag to move the orientation data to the fundamental zone (the crystal lattice of the microstructure is used for that). :return: a numpy array of size (n, 3) with n being the number of data points for this grain.
- compute_god_map(id_list=None, store=True, recompute_mean_orientation=False)¶
Create a GOD (grain orientation deviation) map.
This method computes the grain orientation deviation map. For each grain in the list (all grain by default), the orientation of each voxel belonging to this grain is compared to the mean orientation in the grain and the resulting misorientation is assigned to the pixel.
A grain ids list can be used to restrict the grains where to compute the orientation deviation (the number of grains in the list must be 256 maximum). By default, this method uses the mean orientation in the GrainDataTable but the mean orientation can also be recomputed from the orientation map and grain map by activating the flag recompute_mean_orientation.
Note
This method needs both a grain map and an orientation map, a message will be displayed if this is not the case.
- Parameters:
id_list (list) – the list of the grain ids to include (compute
for all grains by default). :param bool recompute_mean_orientation: if True the mean grain orientation is recalculated from the orientatin map instead of using the value in the GrainDataTable. :param bool store: If True, store the grain orientation deviation map in the CellData group, with name grain_orientation_deviation.
- add_IPF_maps()¶
Add IPF maps to the data set.
IPF colors are computed for the 3 cartesian directions and stored into the h5 file in the CellData image group, with names ipf_map_100, ipf_map_010, ipf_map_001.
- create_IPF_map(axis=array([0., 0., 1.]))¶
Create a vector field in CellData to store the IPF colors.
Creates a (Nx, Ny, Nz, 3) field with the IPF color for each voxel. Note that this function assumes a single orientation per grain.
- Parameters:
axis – the unit vector for the load direction to compute IPF colors.
- view_slice(**kwargs)¶
A simple utility method to show one microstructure slice.
Refer to the view_map_slice methode in `pymicro.crystal.view`module for the kwargs definition.
- static rand_cmap(n=4096, first_is_black=False, seed=13)¶
Creates a random color map to color the grains.
The first color can be enforced to black and usually figure out the background. The random seed is fixed to consistently produce the same colormap.
- Parameters:
n (int) – the number of colors in the list.
first_is_black (bool) – set black as the first color of the list.
seed (int) – the random seed.
- Returns:
a matplotlib colormap.
- ipf_cmap()¶
Return a colormap with ipf colors for each grain.
- Returns:
a color map that can be directly used in pyplot.
- static from_grain_file(grain_file_path, col_id=0, col_phi1=1, col_phi=2, col_phi2=3, col_x=4, col_y=5, col_z=None, col_volume=None, autodelete=True)¶
Create a Microstructure reading grain infos from a file.
This file is typically created using EBSD. the usual pattern is: grain_id, phi1, phi, phi2, x, y, volume. The column number are tunable using the function arguments.
- print_grains_info(grain_list=None, as_string=False)¶
Print informations on the grains in the microstructure
- match_grains(m2, mis_tol=1, grains_to_match=None, grains_to_search=None, use_centers=False, center_tol=0.1, scale_m2=1.0, offset_m2=None, center_merit=10.0, verbose=False)¶
Match grains from a second microstructure to this microstructure.
This function try to find pair of grains based on a function of merit based on their orientations. This function can optionnally use the center of the grains. In this case several paramaters can be used to adjust the origin of the microstructure, their scale and the relative merit of the center proximity with respect to the orientation differences.
This function works only for microstructures with the same symmetry.
- Parameters:
m2 – the second instance of Microstructure from which to match the grains.
mis_tol (float) – the tolerance is misorientation to use to detect matches (in degrees).
use_grain_ids (list) – a list of ids to restrict the grains of the first microstructure in which to search for matches.
verbose (bool) – use the grain centers to build the function of merit.
center_tol (float) – the tolerance for 2 grains to be match together (in mm).
verbose – activate verbose mode.
- Raises:
ValueError – if the microstructures do not have the same symmetry.
- Return tuple:
a tuple of three lists holding respectively the matches,
the candidates for each match and the grains that were unmatched.
- match_orientation(orientation, use_grain_ids=None)¶
Find the best match between an orientation and the grains from this microstructure.
- Parameters:
orientation – an instance of Orientation to match the grains.
use_grain_ids (list) – a list of ids to restrict the grains in which to search for matches.
- Return tuple:
the grain id of the best match and the misorientation.
- find_neighbors(grain_id, distance=1)¶
Find the neighbor ids of a given grain.
This function find the ids of the neighboring grains. A mask is constructed by dilating the grain to encompass the immediate neighborhood of the grain. The ids can then be determined using numpy unique function.
- Parameters:
grain_id (int) – the grain id from which the neighbors need to be determined.
distance (int) – the distance to use for the dilation (default is 1 voxel).
- Returns:
a list (possibly empty) of the neighboring grain ids.
- dilate_grain(grain_id, dilation_steps=1, use_mask=False)¶
Dilate a single grain overwriting the neighbors.
- Parameters:
grain_id (int) – the grain id to dilate.
dilation_steps (int) – the number of dilation steps to apply.
use_mask (bool) – if True and that this microstructure has a mask, the dilation will be limited by it.
- static dilate_labels(array, dilation_steps=1, mask=None, dilation_ids=None, struct=None)¶
Dilate labels isotropically to fill the gap between them.
This code is based on the gtDilateGrains function from the DCT code. It has been extended to handle both 2D and 3D cases.
- Parameters:
array (ndarray) – the numpy array to dilate.
dilation_steps (int) – the number of dilation steps to apply.
mask (ndarray) – a msk to constrain the dilation (None by default).
dilation_ids (list) – a list to restrict the dilation to the given ids.
struct (ndarray) – the structuring element to use (strong connectivity by default).
- Returns:
the dilated array.
- dilate_grains(dilation_steps=1, dilation_ids=None, new_map_name='dilated_grain_map', update_microstructure_properties=False)¶
Dilate grains to fill the gap between them.
This function calls dilate_labels with the grain map of the microstructure. The grain properties and the phase map can be updated after the dilation by setting the update_microstructure_properties parameter to True.
- Parameters:
dilation_steps (int) – the number of dilation steps to apply to the grain map.
dilation_ids (list) – a list to restrict the dilation to the given ids.
new_map_name (str) – the name to use for the dilated grain map.
update_microstructure_properties (bool) – a flag to update all grains properties and update the microstructure phase map.
- clean_grain_map(new_map_name='grain_map_clean')¶
Apply a morphological cleaning treatment to the active grain map.
A Matlab morphological cleaner is called to smooth the morphology of the different IDs in the grain map.
This cleaning treatment is typically used to improve the quality of a mesh produced from the grain_map, or improved image based mechanical modelisation techniques results, such as FFT-based computational homogenization of the polycrystalline microstructure.
..Warning:
This method relies on the code of the `core.utils` and on Matlab code developed by F. Nguyen at the 'Centre des Matériaux, Mines Paris'. These tools and codes must be installed and referenced in the PATH of your workstation for this method to work. For more details, see the `utils` package.
- mesh_grain_map(mesher_opts={}, print_output=False)¶
Create a 2D or 3D conformal mesh from the grain map.
A Matlab multiphase_image mesher is called to create a conformal mesh of the grain map that is stored as a SampleData Mesh group in the MeshData Group of the Microstructure dataset. The mesh data will contain an element set per grain in the grain map.
..Warning:
This method relies on the code of the `core.utils`, on Matlab code developed by F. Nguyen at the 'Centre des Matériaux, Mines Paris', on the Z-set software and the Mesh GEMS software. These tools and codes must be installed and referenced in the PATH of your workstation for this method to work. For more details, see the `utils` package.
- crop(x_start=None, x_end=None, y_start=None, y_end=None, z_start=None, z_end=None, crop_name=None, autodelete=False, recompute_geometry=True, verbose=False)¶
Crop the microstructure to create a new one.
This method crops the CellData image group to a new microstructure, and adapts the GrainDataTable to the crop.
- Parameters:
x_start (int) – start value for slicing the first axis.
x_end (int) – end value for slicing the first axis.
y_start (int) – start value for slicing the second axis.
y_end (int) – end value for slicing the second axis.
z_start (int) – start value for slicing the third axis.
z_end (int) – end value for slicing the third axis.
crop_name (str) – the name for the cropped microstructure (the default is to append ‘_crop’ to the initial name).
autodelete (bool) – a flag to delete the microstructure files on the disk when it is not needed anymore.
recompute_geometry (bool) – if True (default), recompute the grain centers, volumes, and bounding boxes in the cropped microstructure. Use False when using a crop that do not cut grains, for instance when cropping a microstructure within the mask, to avoid the heavy computational cost of the grain geometry data update.
verbose (bool) – activate verbose mode.
- Returns:
a new Microstructure instance with the cropped grain map.
- sync_grain_table_with_grain_map(sync_geometry=False)¶
Update GrainDataTable with only grain IDs from active grain map.
- Parameters:
sync_geometry (bool) – If True, recomputes the geometrical parameters of the grains in the GrainDataTable from active grain map.
- renumber_grains(sort_by_size=False, new_map_name=None, only_grain_map=False)¶
Renumber the grains in the microstructure.
Renumber the grains from 1 to n, with n the total number of grains that are found in the active grain map array, so that the numbering is consecutive. Only positive grain ids are taken into account (the id 0 is reserved for the background).
- Parameters:
sort_by_size (bool) – use the grain volume to sort the grain ids (the larger grain will become grain 1, etc).
overwrite_active_map (bool) – if ‘True’, overwrites the active grain map with the renumbered map. If ‘False’, the active grain map is kept and a ‘renumbered_grain_map’ is added to CellData.
new_map_name (str) – Used as name for the renumbered grain map field if is not None and overwrite_active_map is False.
only_grain_map (bool) – If True, do not modify the grain map and GrainDataTable in dataset, but return the renumbered grain_map as a numpy array.
- compute_grain_volume(gid)¶
Compute the volume of the grain given its id.
The total number of voxels with the given id is computed. The value is converted to mm unit using the voxel_size. The unit will be squared mm for a 2D grain map or cubed mm for a 3D grain map.
Warning
This function assume the grain bounding box is correct, call recompute_grain_bounding_boxes() if this is not the case.
- Parameters:
gid (int) – the grain id to consider.
- Returns:
the volume of the grain.
- compute_grain_center(gid)¶
Compute the center of masses of a grain given its id.
Warning
This function assume the grain bounding box is correct, call recompute_grain_bounding_boxes() if this is not the case.
- Parameters:
gid (int) – the grain id to consider.
- Returns:
a tuple with the center of mass in mm units (or voxel if the voxel_size is not specified).
- compute_grain_bounding_box(gid, as_slice=False)¶
Compute the grain bounding box indices in the grain map.
- Parameters:
gid (int) – the id of the grain.
as_slice (bool) – a flag to return the grain bounding box as a slice.
- Returns:
the bounding box coordinates.
- compute_grain_equivalent_diameters(id_list=None)¶
Compute the equivalent diameter for a list of grains.
- Parameters:
id_list (list) – the list of the grain ids to include (compute for all grains by default).
- Returns:
a 1D numpy array of the grain diameters.
- compute_grain_sphericities(id_list=None)¶
Compute the equivalent diameter for a list of grains.
The sphericity measures how close to a sphere is a given grain. It can be computed by the ratio between the surface area of a sphere with the same volume and the actual surface area of that grain.
\[\psi = \dfrac{\pi^{1/3}(6V)^{2/3}}{A}\]- Parameters:
id_list (list) – the list of the grain ids to include (compute for all grains by default).
- Returns:
a 1D numpy array of the grain diameters.
- compute_grain_aspect_ratios(id_list=None)¶
Compute the aspect ratio for a list of grains.
The aspect ratio is defined by the ratio between the major and minor axes of the equivalent ellipsoid of each grain.
- Parameters:
id_list (list) – the list of the grain ids to include (compute for all grains by default).
- Returns:
a 1D numpy array of the grain aspect ratios.
- recompute_grain_volumes(verbose=False)¶
Compute the volume of all grains in the microstructure.
Each grain volume is computed using the grain map. The value is assigned to the volume column of the GrainDataTable node. If the voxel size is specified, the grain volumes will be in mm unit, if not in voxel unit.
Note
A grain map need to be associated with this microstructure instance for the method to run.
- Parameters:
verbose (bool) – flag for verbose mode.
- Returns:
a 1D array with all grain volumes.
- recompute_grain_centers(verbose=False)¶
Compute and assign the center of all grains in the microstructure.
Each grain center is computed using its center of mass. The value is assigned to the grain.center attribute. If the voxel size is specified, the grain centers will be in mm unit, if not in voxel unit.
Note
A grain map need to be associated with this microstructure instance for the method to run.
- Parameters:
verbose (bool) – flag for verbose mode.
- Returns:
a 1D array with all grain centers.
- recompute_grain_bounding_boxes(verbose=False)¶
Compute and assign the center of all grains in the microstructure.
Each grain bounding box is computed in voxel unit. The value is assigned to the grain.bounding_box attribute.
Note
A grain map need to be associated with this microstructure instance for the method to run.
- Parameters:
verbose (bool) – flag for verbose mode.
- compute_grains_geometry(overwrite_table=False)¶
Compute grain geometry from the grain map.
This method computes the grain centers, volume and bounding boxes from the grain map and update the grain data table. This applies only to grains represented in the grain map. If other grains are present, their information is unchanged unless the option overwrite_table is activated.
- Parameters:
overwrite_table (bool) – if this is True, the grains present in the
data table and not in the grain map are removed from it.
- compute_grains_map_table_intersection(verbose=False)¶
Return grains that are both in grain map and grain table.
The method also returns the grains that are in the grain map but not in the grain table, and the grains that are in the grain table, but not in the grain map.
- Return array intersection:
array of grain ids that are in both grain map and grain data table.
- Return array not_in_map:
array of grain ids that are in grain data table but not in grain map.
- Return array not_in_table:
array of grain ids that are in grain map but not in grain data table.
- build_grain_table_from_grain_map()¶
Synchronizes and recomputes GrainDataTable from active grain map.
- graph()¶
Create the graph of this microstructure.
This method process a Microstructure instance using a Region Adgency Graph built with the crystal misorientation between neighbors as weights. The graph has a node per grain and a connection between neighboring grains of the same phase. The misorientation angle is attach to each edge.
- Return rag:
the region adjency graph of this microstructure.
- segment_mtr(labels_seg=None, mis_thr=20.0, min_area=500, store=False)¶
Segment micro-textured regions (MTR).
This method process a Microstructure instance to segment the MTR with the specified parameters.
- Parameters:
labels_seg (ndarray) – a pre-segmentation of the grain map, the full
grain map will be used if not specified. :param float mis_thr: threshold in misorientation used to cut the graph. :param int min_area: minimum area used to define a MTR. :param bool store: flag to store the segmented array in the microstructure. :return mtr_labels: array with the labels of the segmented regions.
- static voronoi(shape=(256, 256), n=50)¶
Simple voronoi tesselation to create a grain map.
The method works both in 2 and 3 dimensions and will create a sample with a size of 1 (domain from -0.5 to 0.5). The grains are labeled from 1 to n (included).
- Parameters:
shape (tuple) – grain map shape in 2 or 3 dimensions.
n (int) – number of grains to generate.
- Raise:
a ValueError if the shape has not size 2 or 3.
- Returns:
a 2D or 3D numpy array representing the grain map.
- to_amitex_fftp(binary=True, mat_file=True, algo_file=True, char_file=True, elasaniso_path='', add_grips=False, grip_size=10, grip_constants=(104100.0, 49440.0), add_exterior=False, exterior_size=10, use_mask=False)¶
Write orientation data to ascii files to prepare for FFT computation.
AMITEX_FFTP can be used to compute the elastoplastic response of polycrystalline microstructures. The calculation needs orientation data for each grain written in the form of the coordinates of the first two basis vectors expressed in the crystal local frame which is given by the first two rows of the orientation matrix. The values are written in 6 files N1X.txt, N1Y.txt, N1Z.txt, N2X.txt, N2Y.txt, N2Z.txt, each containing n values with n the number of grains. The data is written either in BINARY or in ASCII form.
Additional options exist to pad the grain map with two constant regions. One region called grips can be added on the top and bottom (third axis). The second region is around the sample (first and second axes).
- Parameters:
binary (bool) – flag to write the files in binary or ascii format.
mat_file (bool) – flag to write the material file for Amitex.
algo_file (bool) – flag to write the algorithm file for Amitex.
char_file (bool) – flag to write the loading file for Amitex.
elasaniso_path (str) – path for the libUmatAmitex.so in the Amitex_FFTP installation.
add_grips (bool) – add a constant region at the beginning and the end of the third axis.
grip_size (int) – thickness of the region.
grip_constants (tuple) – elasticity values for the grip (lambda, mu).
add_exterior (bool) – add a constant region around the sample at the beginning and the end of the first two axes.
exterior_size (int) – thickness of the exterior region.
use_mask (bool) – use mask to define exterior material, and use mask to extrude grips with same shapes as microstructure top and bottom surfaces.
- from_amitex_fftp(base_name, grip_size=0, ext_size=0, sim_prefix='Amitex', int_var_names={}, load_fields=True, compression_options={})¶
Read the output of a Amitex_fftp simulation and store the field in the dataset.
Read a Amitex_fftp result directory containing a mechanical simulation of the microstructure. See method to_amitex_fftp to generate input files for such simulation of Microstructure instances.
The results are stored as fields of the CellData group by default. If generated by the simulation, the strain and stress tensor fields are stored, as well as the internal variables fields.
Mechanical fields and macroscopic curves are stored. The latter is stored in the data group ‘/Mechanical_simulation’ as a structured array.
- Parameters:
base_name (str) – Basename of Amitex .std, .vtk output files to load in dataset.
grip_size (int, optional) – Thickness of the grips added to simulation unit cell by the method ‘to_amitex_fftp’ of this class, defaults to 0. This value corresponds to a number of voxels on both ends of the cell.
ext_size (int, optional) – Thickness of the exterior region added to simulation unit cell by the method ‘to_amitex_fftp’ of this class, defaults to 0. This value corresponds to a number of voxels on both ends of the cell.
sim_prefix (str, optional) – Prefix of the name of the fields that will be stored on the CellData group from simulation results.
int_var_names (dict, optional) – Dictionary whose keys are the names of internal variables stored in Amitex output files (varInt1, varInt2, …) and values are corresponding names for these variables in the dataset.
load_fields (bool) – Flag to control if the fields are imported from the vtk files.
compression_options (dict) – Dictionary containing the compression options to use for the imported fields.
- print_zset_material_block(mat_file, grain_prefix='_ELSET')¶
Outputs the material block corresponding to this microstructure for a finite element calculation with z-set.
- Parameters:
mat_file (str) – The name of the file where the material behaviour is located
grain_prefix (str) – The grain prefix used to name the elsets corresponding to the different grains
- to_dream3d()¶
Write the microstructure as a hdf5 file compatible with DREAM3D.
- static from_dream3d(file_path, main_key='DataContainers', data_container='DataContainer', ensemble_data='EnsembleData', grain_data='FeatureData', grain_orientations='AvgEulerAngles', grain_orientations_type='euler', grain_centroids='Centroids', cell_data='CellData', grain_ids='FeatureIds', mask='Mask', phases='Phases', orientations='EulerAngles', orientations_type='euler', ipf_color='IPFColor')¶
Read a microstructure from a Dream3d hdf5 file.
- Parameters:
file_path (str) – the path to the hdf5 file to read.
main_key (str) – the string describing the main key group.
data_container (str) – the string describing the data container group in the file.
ensemble_data (str) – the string describing the ensemble data group in the file.
grain_data (str) – the string describing the grain data group in the hdf5 file.
grain_orientations (str) – the string describing the average grain orientations in the hdf5 file.
grain_orientations_type (str) – the string describing the descriptor used for average grain orientation data.
grain_centroids (str) – the string describing the grain centroids in the hdf5 file.
cell_data (str) – the string describing the cell data group in the file.
grain_ids (str) – the string describing the field representing grain ids within the cell_data data group.
mask (str) – the string describing the field representing the sample mask within the cell_data data group.
phases (str) – the string describing the field representing the sample phases within the cell_data data group.
orientations (str) – the string describing the field representing voxel wise orientations within the cell_data data group.
orientations_type (str) – the string describing the descriptor used for the orientation field.
- Returns:
a Microstructure instance created from the dream3d file.
- static copy_sample(src_micro_file, dst_micro_file, overwrite=False, get_object=False, dst_name=None, autodelete=False)¶
Initiate a new SampleData object and files from existing one
- static from_neper(neper_file_path)¶
Create a microstructure from a neper tesselation.
Neper is an open source program to generate polycristalline microstructure using voronoi tesselations. It is available at https://neper.info
- Parameters:
neper_file_path (str) – the path to the tesselation file generated by Neper.
- Returns:
a pymicro Microstructure instance.
- static from_labdct(labdct_file, data_dir='.', name=None, include_ipf_map=False, grain_map_key='GrainId', recompute_mean_orientation=False)¶
Create a microstructure from a DCT reconstruction.
- Parameters:
labdct_file (str) – the name of the file containing the labDCT data.
data_dir (str) – the path to the folder containing the HDF5 reconstruction file.
name (str) – the file name to use for this microstructure. By default, the suffix _data is added to the base name of the labDCT scan.
include_ipf_map (bool) – if True, the IPF maps will be included in the microstructure fields.
grain_map_key (str) – string defining the path to the grain map (GrainId by default).
recompute_mean_orientation (bool) – it True, the orientation of each grain is computed from the rodrigues map (this may take a long time).
- Returns:
a Microstructure instance created from the labDCT reconstruction file.
- static from_dct(data_dir='.', grain_file='index.mat', use_dct_path=True, vol_file='phase_01_vol.mat', vol_key='vol', mask_file='volume_mask.mat', mask_key='vol', phase_file='volume.mat', phase_key='phases', rod_map_file='phase_01_vol.mat', rod_map_key='dmvol', roi=None, verbose=True)¶
Create a microstructure from a DCT reconstruction.
DCT reconstructions are stored in several files. The indexed grain informations are stored in a matlab file in the ‘4_grains/phase_01’ folder. Then, the reconstructed volume file (labeled image) is stored in the ‘5_reconstruction’ folder as an hdf5 file, possibly stored alongside a mask file coming from the absorption reconstruction.
- Parameters:
data_dir (str) – the path to the folder containing the reconstruction data.
grain_file (str) – the name of the file containing grains info.
use_dct_path (bool) – if True, the grain_file should be located in 4_grains/phase_01 folder and the vol_file and mask_file in the 5_reconstruction folder.
vol_file (str) – the name of the volume file.
vol_key (str) – the key to access the volume in the hdf5 file.
mask_file (str) – the name of the mask file.
mask_key (str) – the key to access the mask in the hdf5 file.
phase_file (str) – the name of the file containing the phase map array.
phase_key (str) – the key to access the phase array in the hdf5 file.
rod_map_file (str) – the name of the file containing the local orientations as a rodrigues vector array.
rod_map_key (str) – the key to access the phase rodrigues vector array in the file.
roi (list) – specify a region of interest by a list of 6 integers in the form [x1, x2, y1, y2, z1, z2] to crop the grain map.
verbose (bool) – activate verbose mode.
- Returns:
a Microstructure instance created from the DCT reconstruction.
- static from_legacy_h5(file_path, filename=None)¶
read a microstructure object from a HDF5 file created by pymicro until version 0.4.5.
- Parameters:
file_path (str) – the path to the file to read.
- Returns:
the new Microstructure instance created from the file.
- static from_ebsd(file_path, roi=None, ds=1, tol=5.0, min_ci=0.2, phase_list=None, ref_frame_id=2, grain_ids=None)¶
“Create a microstructure from an EBSD scan.
- Parameters:
file_path (str) – the path to the file to read.
roi (list) – a list of 4 integers in the form [x1, x2, y1, y2] to crop the EBSD scan.
ds (int) – integer value to downsample the data.
tol (float) – the misorientation angle tolerance to segment the grains (default is 5 degrees).
min_ci (float) – minimum confidence index for a pixel to be a valid EBSD measurement.
phase_list (list) – a list of CrystallinePhase to overwrite the ones in the file, this is particularly useful for osc files as phases cannot be read from them at the moment.
- Returns:
a new instance of Microstructure.
- static merge_microstructures(micros, overlap, translation_offset=[0, 0, 0], key_array_to_merge='/CellData', plot=False)¶
Merge two Microstructure instances together.
The function works for two microstructures with grain maps and an overlap between them along the Z direction. Temporary Microstructures restricted to the overlap regions are created and grains are matched between the two based on a disorientation tolerance.
The method is written such that the end slices of the grain map of the first scan in the micros list must correspond to the beginning of the grain map of the second scan.
Note
The overlap value can be negative, in that case, the first and last layers of the two microstructure are used to match grains and the merged microstructure is constructed with a gap that may be filled later with the dilate_grains method.
Note
The two microstructure must have the same crystal lattice and the same voxel_size for this method to run.
- Parameters:
key_array_to_merge (str) – the path to the arrays to merge in the hdf5 files.
micros (list) – a list containing the two microstructures to merge.
overlap (int) – the overlap to use.
translation_offset (list) – a manual translation (in voxels) offset to add to the result.
plot (bool) – a flag to plot some results.
- Returns:
a new Microstructure instance containing the merged microstructure.
- get_grain_boundaries_map(kernel_size=3)¶
method to compute grain boundaries map using microstructure grain_map
- resample(resampling_factor, resample_name=None, autodelete=False, recompute_geometry=True, verbose=False)¶
Resample the microstructure by a given factor to create a new one.
This method resamples the CellData image group to a new microstructure, and adapts the GrainDataTable to the resampled.
- Parameters:
resample_factor (int) – the factor used for resolution degradation
resample_name (str) – the name for the resampled microstructure (the default is to append ‘_resampled’ to the initial name).
autodelete (bool) – a flag to delete the microstructure files on the disk when it is not needed anymore.
recompute_geometry (bool) – if True (default), recompute the grain centers, volumes, and bounding boxes in the resampled microstructure. Use False when using a resample that do not cut grains, for instance when resampling a microstructure within the mask, to avoid the heavy computational cost of the grain geometry data update.
verbose (bool) – activate verbose mode.
- Returns:
a new Microstructure instance with the resampled grain map.