Miscellaneous#

Auxiliary functionality, mainly used internally by the pre- and post-processing tools.

Table#

class damask.Table(shapes={}, data=None, comments=None)[source]#

Manipulate multi-dimensional spreadsheet-like data.

Attributes:
labels

Methods

allclose(other[, rtol, atol, equal_nan])

Test whether all values are approximately equal to corresponding ones of other Table.

append(other)

Append other table vertically (similar to numpy.vstack).

copy()

Return deepcopy(self).

delete(label)

Delete column data.

get(label)

Get column data.

isclose(other[, rtol, atol, equal_nan])

Report where values are approximately equal to corresponding ones of other Table.

join(other)

Append other table horizontally (similar to numpy.hstack).

load(fname)

Load from ASCII table file.

load_ang(fname)

Load from ang file.

rename(old, new[, info])

Rename column data.

save(fname[, with_labels])

Save as plain text file.

set(label, data[, info])

Add new or replace existing column data.

sort_by(labels[, ascending])

Sort table by data of given columns.

copy()#

Return deepcopy(self).

Create deep copy.

isclose(other, rtol=1e-05, atol=1e-08, equal_nan=True)[source]#

Report where values are approximately equal to corresponding ones of other Table.

Parameters:
otherdamask.Table

Table to compare against.

rtolfloat, optional

Relative tolerance of equality.

atolfloat, optional

Absolute tolerance of equality.

equal_nanbool, optional

Consider matching NaN values as equal. Defaults to True.

Returns:
masknumpy.ndarray of bool

Mask indicating where corresponding table values are close.

allclose(other, rtol=1e-05, atol=1e-08, equal_nan=True)[source]#

Test whether all values are approximately equal to corresponding ones of other Table.

Parameters:
otherdamask.Table

Table to compare against.

rtolfloat, optional

Relative tolerance of equality.

atolfloat, optional

Absolute tolerance of equality.

equal_nanbool, optional

Consider matching NaN values as equal. Defaults to True.

Returns:
answerbool

Whether corresponding values are close between both tables.

static load(fname)[source]#

Load from ASCII table file.

Initial comments are marked by ‘#’, the first non-comment line containing the column labels.

  • Vector data column labels are indicated by ‘1_v, 2_v, …, n_v’.

  • Tensor data column labels are indicated by ‘3x3:1_T, 3x3:2_T, …, 3x3:9_T’.

Parameters:
fnamefile, str, or pathlib.Path

Filename or file for reading.

Returns:
loadeddamask.Table

Table data from file.

static load_ang(fname)[source]#

Load from ang file.

A valid TSL ang file has to have the following columns:

  • Euler angles (Bunge notation) in radians, 3 floats, label ‘eu’.

  • Spatial position in meters, 2 floats, label ‘pos’.

  • Image quality, 1 float, label ‘IQ’.

  • Confidence index, 1 float, label ‘CI’.

  • Phase ID, 1 int, label ‘ID’.

  • SEM signal, 1 float, label ‘intensity’.

  • Fit, 1 float, label ‘fit’.

Parameters:
fnamefile, str, or pathlib.Path

Filename or file for reading.

Returns:
loadeddamask.Table

Table data from file.

get(label)[source]#

Get column data.

Parameters:
labelstr

Column label.

Returns:
datanumpy.ndarray

Array of column data.

set(label, data, info=None)[source]#

Add new or replace existing column data.

Parameters:
labelstr

Column label.

datanumpy.ndarray

Column data. First dimension needs to match number of rows.

infostr, optional

Human-readable information about the data.

Returns:
updateddamask.Table

Updated table.

delete(label)[source]#

Delete column data.

Parameters:
labelstr

Column label.

Returns:
updateddamask.Table

Updated table.

rename(old, new, info=None)[source]#

Rename column data.

Parameters:
label_oldstr or iterable of str

Old column label(s).

label_newstr or iterable of str

New column label(s).

Returns:
updateddamask.Table

Updated table.

sort_by(labels, ascending=True)[source]#

Sort table by data of given columns.

Parameters:
labelstr or list

Column labels for sorting.

ascendingbool or list, optional

Set sort order.

Returns:
updateddamask.Table

Updated table.

append(other)[source]#

Append other table vertically (similar to numpy.vstack).

Requires matching labels/shapes and order.

Parameters:
otherdamask.Table

Table to append.

Returns:
updateddamask.Table

Updated table.

join(other)[source]#

Append other table horizontally (similar to numpy.hstack).

Requires matching number of rows and no common labels.

Parameters:
otherdamask.Table

Table to join.

Returns:
updateddamask.Table

Updated table.

save(fname, with_labels=True)[source]#

Save as plain text file.

Parameters:
fnamefile, str, or pathlib.Path

Filename or file for writing.

with_labelsbool, optional

Write column labels. Defaults to True.


Crystal#

class damask.Crystal(*, family=None, lattice=None, a=None, b=None, c=None, alpha=None, beta=None, gamma=None, degrees=False)[source]#

Representation of a crystal as (general) crystal family or (more specific) as a scaled Bravais lattice.

Examples

Cubic crystal family:

>>> import damask
>>> cubic = damask.Crystal(family='cubic')
>>> cubic
Crystal family: cubic

Body-centered cubic Bravais lattice with parameters of iron:

>>> import damask
>>> Fe = damask.Crystal(lattice='cI', a=287e-12)
>>> Fe
Crystal family: cubic
Bravais lattice: cI
a=2.87e-10 m, b=2.87e-10 m, c=2.87e-10 m
α=90°, β=90°, γ=90°
Attributes:
basis_real

Return orthogonal real space crystal basis.

basis_reciprocal

Return reciprocal (dual) crystal basis.

immutable

Return immutable lattice parameters.

lattice_points

Return lattice points.

orientation_relationships

Return labels of orientation relationships.

parameters

Return lattice parameters a, b, c, alpha, beta, gamma.

ratio

Return axes ratios of own lattice.

standard_triangle

Corners of the standard triangle.

symmetry_operations

Symmetry operations as Rotations.

Methods

kinematics(mode)

Return crystal kinematics systems.

relation_operations(model)

Crystallographic orientation relationships for phase transformations.

to_frame(*[, uvw, hkl])

Calculate crystal frame vector corresponding to lattice direction [uvw] or plane normal (hkl).

to_lattice(*[, direction, plane])

Calculate lattice vector corresponding to crystal frame direction or plane normal.

property parameters#

Return lattice parameters a, b, c, alpha, beta, gamma.

property immutable#

Return immutable lattice parameters.

property orientation_relationships#

Return labels of orientation relationships.

property standard_triangle#

Corners of the standard triangle.

Notes

Not yet defined for monoclinic.

References

Bases are computed from

>>> basis = {
...    'cubic' :       np.linalg.inv(np.array([[0.,0.,1.],                           # direction of red
...                                            [1.,0.,1.]/np.sqrt(2.),               #              green
...                                            [1.,1.,1.]/np.sqrt(3.)]).T),          #              blue
...    'hexagonal' :   np.linalg.inv(np.array([[0.,0.,1.],                           # direction of red
...                                            [1.,0.,0.],                           #              green
...                                            [np.sqrt(3.),1.,0.]/np.sqrt(4.)]).T), #              blue
...    'tetragonal' :  np.linalg.inv(np.array([[0.,0.,1.],                           # direction of red
...                                            [1.,0.,0.],                           #              green
...                                            [1.,1.,0.]/np.sqrt(2.)]).T),          #              blue
...    'orthorhombic': np.linalg.inv(np.array([[0.,0.,1.],                           # direction of red
...                                            [1.,0.,0.],                           #              green
...                                            [0.,1.,0.]]).T),                      #              blue
...    }
property symmetry_operations#

Symmetry operations as Rotations.

property ratio#

Return axes ratios of own lattice.

property basis_real#

Return orthogonal real space crystal basis.

References

C.T. Young and J.L. Lytton, Journal of Applied Physics 43:1408–1417, 1972 https://doi.org/10.1063/1.1661333

property basis_reciprocal#

Return reciprocal (dual) crystal basis.

property lattice_points#

Return lattice points.

to_lattice(*, direction=None, plane=None)[source]#

Calculate lattice vector corresponding to crystal frame direction or plane normal.

Parameters:
direction|planenumpy.ndarray, shape (…,3)

Real space vector along direction or reciprocal space vector along plane normal.

Returns:
Millernumpy.ndarray, shape (…,3)

Lattice vector of direction or plane. Use util.scale_to_coprime to convert to (integer) Miller indices.

to_frame(*, uvw=None, hkl=None)[source]#

Calculate crystal frame vector corresponding to lattice direction [uvw] or plane normal (hkl).

Parameters:
uvw|hklnumpy.ndarray, shape (…,3)

Miller indices of crystallographic direction or plane normal.

Returns:
vectornumpy.ndarray, shape (…,3)

Crystal frame vector in real space along [uvw] direction or in reciprocal space along (hkl) plane normal.

Examples

Crystal frame vector (real space) of Magnesium corresponding to [1,1,0] direction:

>>> import damask
>>> Mg = damask.Crystal(lattice='hP', a=321e-12, c=521e-12)
>>> Mg.to_frame(uvw=[1, 1, 0])
array([1.60500000e-10, 2.77994155e-10, 0.00000000e+00])

Crystal frame vector (reciprocal space) of Titanium along (1,0,0) plane normal:

>>> import damask
>>> Ti = damask.Crystal(lattice='hP', a=0.295e-9, c=0.469e-9)
>>> Ti.to_frame(hkl=(1, 0, 0))
array([ 3.38983051e+09,  1.95711956e+09, -4.15134508e-07])
kinematics(mode)[source]#

Return crystal kinematics systems.

Parameters:
mode{‘slip’,’twin’}

Deformation mode.

Returns:
direction_planedictionary

Directions and planes of deformation mode families.

relation_operations(model)[source]#

Crystallographic orientation relationships for phase transformations.

Parameters:
modelstr

Name of orientation relationship.

Returns:
operations(string, damask.Rotation)

Resulting lattice and rotations characterizing the orientation relationship.

References

S. Morito et al., Journal of Alloys and Compounds 577:s587-s592, 2013 https://doi.org/10.1016/j.jallcom.2012.02.004

K. Kitahara et al., Acta Materialia 54(5):1279-1288, 2006 https://doi.org/10.1016/j.actamat.2005.11.001

Y. He et al., Journal of Applied Crystallography 39:72-81, 2006 https://doi.org/10.1107/S0021889805038276

H. Kitahara et al., Materials Characterization 54(4-5):378-386, 2005 https://doi.org/10.1016/j.matchar.2004.12.015

Y. He et al., Acta Materialia 53(4):1179-1190, 2005 https://doi.org/10.1016/j.actamat.2004.11.021


VTK#

class damask.VTK(vtk_data)[source]#

Spatial visualization (and potentially manipulation).

High-level interface to VTK.

Attributes:
N_cells

Number of cells in vtkdata.

N_points

Number of points in vtkdata.

comments

Return the comments.

labels

Labels of datasets.

Methods

as_ASCII()

ASCII representation of the VTK data.

from_image_data(cells, size[, origin])

Create VTK of type vtk.vtkImageData.

from_poly_data(points)

Create VTK of type vtk.polyData.

from_rectilinear_grid(grid)

Create VTK of type vtk.vtkRectilinearGrid.

from_unstructured_grid(nodes, connectivity, ...)

Create VTK of type vtk.vtkUnstructuredGrid.

get(label)

Get either cell or point data.

load(fname[, dataset_type])

Load from VTK file.

save(fname[, parallel, compress])

Save as VTK file.

set([label, data, info, table])

Add new or replace existing point or cell data.

show([label, colormap])

Render.

copy

property comments#

Return the comments.

property N_points#

Number of points in vtkdata.

property N_cells#

Number of cells in vtkdata.

property labels#

Labels of datasets.

static from_image_data(cells, size, origin=array([0., 0., 0.]))[source]#

Create VTK of type vtk.vtkImageData.

This is the common type for grid solver results.

Parameters:
cellssequence of int, len (3)

Number of cells along each dimension.

sizesequence of float, len (3)

Physical length along each dimension.

originsequence of float, len (3), optional

Coordinates of grid origin.

Returns:
newdamask.VTK

VTK-based geometry without nodal or cell data.

static from_unstructured_grid(nodes, connectivity, cell_type)[source]#

Create VTK of type vtk.vtkUnstructuredGrid.

This is the common type for mesh solver results.

Parameters:
nodesnumpy.ndarray, shape (:,3)

Spatial position of the nodes.

connectivitynumpy.ndarray of np.dtype = np.int64

Cell connectivity (0-based), first dimension determines #Cells, second dimension determines #Nodes/Cell.

cell_typestr

Name of the vtk.vtkCell subclass. Tested for TRIANGLE, QUAD, TETRA, and HEXAHEDRON.

Returns:
newdamask.VTK

VTK-based geometry without nodal or cell data.

static from_poly_data(points)[source]#

Create VTK of type vtk.polyData.

This is the common type for point-wise data.

Parameters:
pointsnumpy.ndarray, shape (:,3)

Spatial position of the points.

Returns:
newdamask.VTK

VTK-based geometry without nodal or cell data.

static from_rectilinear_grid(grid)[source]#

Create VTK of type vtk.vtkRectilinearGrid.

Parameters:
gridsequence of sequences of floats, len (3)

Grid coordinates along x, y, and z directions.

Returns:
newdamask.VTK

VTK-based geometry without nodal or cell data.

static load(fname, dataset_type=None)[source]#

Load from VTK file.

Parameters:
fnamestr or pathlib.Path

Filename for reading. Valid extensions are .vti, .vtu, .vtp, .vtr, and .vtk.

dataset_type{‘ImageData’, ‘UnstructuredGrid’, ‘PolyData’, ‘RectilinearGrid’}, optional

Name of the vtk.vtkDataSet subclass when opening a .vtk file.

Returns:
loadeddamask.VTK

VTK-based geometry from file.

as_ASCII()[source]#

ASCII representation of the VTK data.

save(fname, parallel=True, compress=True)[source]#

Save as VTK file.

Parameters:
fnamestr or pathlib.Path

Filename for writing.

parallelbool, optional

Write data in parallel background process. Defaults to True.

compressbool, optional

Compress with zlib algorithm. Defaults to True.

set(label=None, data=None, info=None, *, table=None)[source]#

Add new or replace existing point or cell data.

Data can either be a numpy.array, which requires a corresponding label, or a damask.Table.

Parameters:
labelstr, optional

Label of data array.

datanumpy.ndarray or numpy.ma.MaskedArray, optional

Data to add or replace. First array dimension needs to match either number of cells or number of points.

infostr, optional

Human-readable information about the data.

table: damask.Table, optional

Data to add or replace. Each table label is individually considered. Number of rows needs to match either number of cells or number of points.

Notes

If the number of cells equals the number of points, the data is added to both.

get(label)[source]#

Get either cell or point data.

Cell data takes precedence over point data, i.e. this function assumes that labels are unique among cell and point data.

Parameters:
labelstr

Data label.

Returns:
datanumpy.ndarray

Data stored under the given label.

show(label=None, colormap='cividis')[source]#

Render.

Parameters:
labelstr, optional

Label of the dataset to show.

colormapdamask.Colormap or str, optional

Colormap for visualization of dataset. Defaults to ‘cividis’.

Notes

See http://compilatrix.com/article/vtk-1 for further ideas.


util#

Miscellaneous helper functionality.

damask.util.srepr(msg, glue='\n')[source]#

Join items with glue string.

Parameters:
msgobject with __repr__ or sequence of objects with __repr__

Items to join.

gluestr, optional

Glue used for joining operation. Defaults to ‘n’.

Returns:
joinedstr

String representation of the joined items.

damask.util.emph(msg)[source]#

Format with emphasis.

Parameters:
msgobject with __repr__ or sequence of objects with __repr__

Message to format.

Returns:
formattedstr

Formatted string representation of the joined items.

damask.util.deemph(msg)[source]#

Format with deemphasis.

Parameters:
msgobject with __repr__ or sequence of objects with __repr__

Message to format.

Returns:
formattedstr

Formatted string representation of the joined items.

damask.util.warn(msg)[source]#

Format for warning.

Parameters:
msgobject with __repr__ or sequence of objects with __repr__

Message to format.

Returns:
formattedstr

Formatted string representation of the joined items.

damask.util.strikeout(msg)[source]#

Format as strikeout.

Parameters:
msgobject with __repr__ or iterable of objects with __repr__

Message to format.

Returns:
formattedstr

Formatted string representation of the joined items.

damask.util.run(cmd, wd='./', env=None, timeout=None)[source]#

Run a command.

Parameters:
cmdstr

Command to be executed.

wdstr, optional

Working directory of process. Defaults to ‘./’.

envdict, optional

Environment for execution.

timeoutinteger, optional

Timeout in seconds.

Returns:
stdout, stderr(str, str)

Output of the executed command.

damask.util.open_text(fname, mode='r')[source]#

Open a text file.

Parameters:
fnamefile, str, or pathlib.Path

Name or handle of file.

mode: {‘r’,’w’}, optional

Access mode: ‘r’ead or ‘w’rite, defaults to ‘r’.

Returns:
ffile handle
damask.util.natural_sort(key)[source]#

Natural sort.

For use in python’s ‘sorted’.

References

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

damask.util.show_progress(iterable, N_iter=None, prefix='', bar_length=50)[source]#

Decorate a loop with a progress bar.

Use similar like enumerate.

Parameters:
iterableiterable

Iterable to be decorated.

N_iterint, optional

Total number of iterations. Required if iterable is not a sequence.

prefixstr, optional

Prefix string.

bar_lengthint, optional

Length of progress bar in characters. Defaults to 50.

damask.util.scale_to_coprime(v)[source]#

Scale vector to co-prime (relatively prime) integers.

Parameters:
vsequence of float, len (:)

Vector to scale.

Returns:
mnumpy.ndarray, shape (:)

Vector scaled to co-prime numbers.

damask.util.project_equal_angle(vector, direction='z', normalize=True, keepdims=False)[source]#

Apply equal-angle projection to vector.

Parameters:
vectornumpy.ndarray, shape (…,3)

Vector coordinates to be projected.

direction{‘x’, ‘y’, ‘z’}

Projection direction. Defaults to ‘z’.

normalizebool

Ensure unit length of input vector. Defaults to True.

keepdimsbool

Maintain three-dimensional output coordinates. Defaults to False.

Returns:
coordinatesnumpy.ndarray, shape (…,2 | 3)

Projected coordinates.

Notes

Two-dimensional output uses right-handed frame spanned by the next and next-next axis relative to the projection direction, e.g. x-y when projecting along z and z-x when projecting along y.

Examples

>>> import damask
>>> import numpy as np
>>> project_equal_angle(np.ones(3))
    [0.3660254, 0.3660254]
>>> project_equal_angle(np.ones(3),direction='x',normalize=False,keepdims=True)
    [0, 0.5, 0.5]
>>> project_equal_angle([0,1,1],direction='y',normalize=True,keepdims=False)
    [0.41421356, 0]
damask.util.project_equal_area(vector, direction='z', normalize=True, keepdims=False)[source]#

Apply equal-area projection to vector.

Parameters:
vectornumpy.ndarray, shape (…,3)

Vector coordinates to be projected.

direction{‘x’, ‘y’, ‘z’}

Projection direction. Defaults to ‘z’.

normalizebool

Ensure unit length of input vector. Defaults to True.

keepdimsbool

Maintain three-dimensional output coordinates. Defaults to False.

Returns:
coordinatesnumpy.ndarray, shape (…,2 | 3)

Projected coordinates.

Notes

Two-dimensional output uses right-handed frame spanned by the next and next-next axis relative to the projection direction, e.g. x-y when projecting along z and z-x when projecting along y.

Examples

>>> import damask
>>> import numpy as np
>>> project_equal_area(np.ones(3))
    [0.45970084, 0.45970084]
>>> project_equal_area(np.ones(3),direction='x',normalize=False,keepdims=True)
    [0.0, 0.70710678, 0.70710678]
>>> project_equal_area([0,1,1],direction='y',normalize=True,keepdims=False)
    [0.5411961, 0.0]
damask.util.execution_stamp(class_name, function_name=None)[source]#

Timestamp the execution of a (function within a) class.

damask.util.hybrid_IA(dist, N, rng_seed=None)[source]#

Hybrid integer approximation.

Parameters:
distnumpy.ndarray

Distribution to be approximated

Nint

Number of samples to draw.

rng_seed{None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional

A seed to initialize the BitGenerator. Defaults to None. If None, then fresh, unpredictable entropy will be pulled from the OS.

damask.util.shapeshifter(fro, to, mode='left', keep_ones=False)[source]#

Return dimensions that reshape ‘fro’ to become broadcastable to ‘to’.

Parameters:
frotuple

Original shape of array.

totuple

Target shape of array after broadcasting. len(to) cannot be less than len(fro).

mode{‘left’, ‘right’}, optional

Indicates whether new axes are preferably added to either left or right of the original shape. Defaults to ‘left’.

keep_onesbool, optional

Treat ‘1’ in fro as literal value instead of dimensional placeholder. Defaults to False.

Returns:
new_dimstuple

Dimensions for reshape.

Examples

>>> import numpy as np
>>> from damask import util
>>> a = np.ones((3,4,2))
>>> b = np.ones(4)
>>> b_extended = b.reshape(util.shapeshifter(b.shape,a.shape))
>>> (a * np.broadcast_to(b_extended,a.shape)).shape
(3,4,2)
damask.util.shapeblender(a, b)[source]#

Return a shape that overlaps the rightmost entries of ‘a’ with the leftmost of ‘b’.

Parameters:
atuple

Shape of first array.

btuple

Shape of second array.

Examples

>>> shapeblender((4,4,3),(3,2,1))
    (4,4,3,2,1)
>>> shapeblender((1,2),(1,2,3))
    (1,2,3)
>>> shapeblender((1,),(2,2,1))
    (1,2,2,1)
>>> shapeblender((3,2),(3,2))
    (3,2)
damask.util.extend_docstring(extra_docstring)[source]#

Decorator: Append to function’s docstring.

Parameters:
extra_docstringstr

Docstring to append.

damask.util.extended_docstring(f, extra_docstring)[source]#

Decorator: Combine another function’s docstring with a given docstring.

Parameters:
ffunction

Function of which the docstring is taken.

extra_docstringstr

Docstring to append.

damask.util.DREAM3D_base_group(fname)[source]#

Determine the base group of a DREAM.3D file.

The base group is defined as the group (folder) that contains a ‘SPACING’ dataset in a ‘_SIMPL_GEOMETRY’ group.

Parameters:
fnamestr or pathlib.Path

Filename of the DREAM.3D (HDF5) file.

Returns:
pathstr

Path to the base group.

damask.util.DREAM3D_cell_data_group(fname)[source]#

Determine the cell data group of a DREAM.3D file.

The cell data group is defined as the group (folder) that contains a dataset in the base group whose length matches the total number of points as specified in ‘_SIMPL_GEOMETRY/DIMENSIONS’.

Parameters:
fnamestr or pathlib.Path

Filename of the DREAM.3D (HDF5) file.

Returns:
pathstr

Path to the cell data group.

damask.util.Bravais_to_Miller(*, uvtw=None, hkil=None)[source]#

Transform 4 Miller–Bravais indices to 3 Miller indices of crystal direction [uvw] or plane normal (hkl).

Parameters:
uvtw|hkilnumpy.ndarray, shape (…,4)

Miller–Bravais indices of crystallographic direction [uvtw] or plane normal (hkil).

Returns:
uvw|hklnumpy.ndarray, shape (…,3)

Miller indices of [uvw] direction or (hkl) plane normal.

damask.util.Miller_to_Bravais(*, uvw=None, hkl=None)[source]#

Transform 3 Miller indices to 4 Miller–Bravais indices of crystal direction [uvtw] or plane normal (hkil).

Parameters:
uvw|hklnumpy.ndarray, shape (…,3)

Miller indices of crystallographic direction [uvw] or plane normal (hkl).

Returns:
uvtw|hkilnumpy.ndarray, shape (…,4)

Miller–Bravais indices of [uvtw] direction or (hkil) plane normal.

damask.util.dict_prune(d)[source]#

Recursively remove empty dictionaries.

Parameters:
ddict

Dictionary to prune.

Returns:
pruneddict

Pruned dictionary.

damask.util.dict_flatten(d)[source]#

Recursively remove keys of single-entry dictionaries.

Parameters:
ddict

Dictionary to flatten.

Returns:
flatteneddict

Flattened dictionary.

damask.util.tail_repack(extended, existing=[])[source]#

Repack tailing characters into single string if all are new.

Parameters:
extendedstr or list of str

Extended string list with potentially autosplitted tailing string relative to existing.

existinglist of str

Base string list.

Returns:
repackedlist of str

Repacked version of extended.

Examples

>>> tail_repack(['a','new','e','n','t','r','y'],['a','new'])
    ['a','new','entry']
>>> tail_repack(['a','new','shiny','e','n','t','r','y'],['a','new'])
    ['a','new','shiny','e','n','t','r','y']
damask.util.aslist(arg)[source]#

Transform argument to list.

Parameters:
argint or collection of int or None

Entity to transform into list.

Returns:
transformedlist

Entity transformed into list.

class damask.util.ProgressBar(total, prefix, bar_length)[source]#

Report progress of an interation as a status bar.

Works for 0-based loops, ETA is estimated by linear extrapolation.

Methods

update


grid_filters#

Filters for operations on regular grids.

The grids are defined as (x,y,z,…) where x is fastest and z is slowest. This convention is consistent with the layout in grid vti files.

When converting to/from a plain list (e.g. storage in ASCII table), the following operations are required for tensorial data:

  • D3 = D1.reshape(cells+(-1,),order=’F’).reshape(cells+(3,3))

  • D1 = D3.reshape(cells+(-1,)).reshape(-1,9,order=’F’)

damask.grid_filters.curl(size, f)[source]#

Calculate curl of a vector or tensor field in Fourier space.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

fnumpy.ndarray, shape (:,:,:,3) or (:,:,:,3,3)

Periodic field of which the curl is calculated.

Returns:
∇ × fnumpy.ndarray, shape (:,:,:,3) or (:,:,:,3,3)

Curl of f.

damask.grid_filters.divergence(size, f)[source]#

Calculate divergence of a vector or tensor field in Fourier space.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

fnumpy.ndarray, shape (:,:,:,3) or (:,:,:,3,3)

Periodic field of which the divergence is calculated.

Returns:
∇ · fnumpy.ndarray, shape (:,:,:,1) or (:,:,:,3)

Divergence of f.

damask.grid_filters.gradient(size, f)[source]#

Calculate gradient of a scalar or vector field in Fourier space.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

fnumpy.ndarray, shape (:,:,:,1) or (:,:,:,3)

Periodic field of which the gradient is calculated.

Returns:
∇ fnumpy.ndarray, shape (:,:,:,3) or (:,:,:,3,3)

Divergence of f.

damask.grid_filters.coordinates0_point(cells, size, origin=array([0., 0., 0.]))[source]#

Cell center positions (undeformed).

Parameters:
cellssequence of int, len (3)

Number of cells.

sizesequence of float, len (3)

Physical size of the periodic field.

originsequence of float, len(3), optional

Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].

Returns:
x_p_0numpy.ndarray, shape (:,:,:,3)

Undeformed cell center coordinates.

damask.grid_filters.displacement_fluct_point(size, F)[source]#

Cell center displacement field from fluctuation part of the deformation gradient field.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

Returns:
u_p_fluctnumpy.ndarray, shape (:,:,:,3)

Fluctuating part of the cell center displacements.

damask.grid_filters.displacement_avg_point(size, F)[source]#

Cell center displacement field from average part of the deformation gradient field.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

Returns:
u_p_avgnumpy.ndarray, shape (:,:,:,3)

Average part of the cell center displacements.

damask.grid_filters.displacement_point(size, F)[source]#

Cell center displacement field from deformation gradient field.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

Returns:
u_pnumpy.ndarray, shape (:,:,:,3)

Cell center displacements.

damask.grid_filters.coordinates_point(size, F, origin=array([0., 0., 0.]))[source]#

Cell center positions.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

originsequence of float, len(3), optional

Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].

Returns:
x_pnumpy.ndarray, shape (:,:,:,3)

Cell center coordinates.

damask.grid_filters.cellsSizeOrigin_coordinates0_point(coordinates0, ordered=True)[source]#

Return grid ‘DNA’, i.e. cells, size, and origin from 1D array of point positions.

Parameters:
coordinates0numpy.ndarray, shape (:,3)

Undeformed cell center coordinates.

orderedbool, optional

Expect coordinates0 data to be ordered (x fast, z slow). Defaults to True.

Returns:
cells, size, originThree numpy.ndarray, each of shape (3)

Information to reconstruct grid.

damask.grid_filters.coordinates0_node(cells, size, origin=array([0., 0., 0.]))[source]#

Nodal positions (undeformed).

Parameters:
cellssequence of int, len (3)

Number of cells.

sizesequence of float, len (3)

Physical size of the periodic field.

originsequence of float, len(3), optional

Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].

Returns:
x_n_0numpy.ndarray, shape (:,:,:,3)

Undeformed nodal coordinates.

damask.grid_filters.displacement_fluct_node(size, F)[source]#

Nodal displacement field from fluctuation part of the deformation gradient field.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

Returns:
u_n_fluctnumpy.ndarray, shape (:,:,:,3)

Fluctuating part of the nodal displacements.

damask.grid_filters.displacement_avg_node(size, F)[source]#

Nodal displacement field from average part of the deformation gradient field.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

Returns:
u_n_avgnumpy.ndarray, shape (:,:,:,3)

Average part of the nodal displacements.

damask.grid_filters.displacement_node(size, F)[source]#

Nodal displacement field from deformation gradient field.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

Returns:
u_pnumpy.ndarray, shape (:,:,:,3)

Nodal displacements.

damask.grid_filters.coordinates_node(size, F, origin=array([0., 0., 0.]))[source]#

Nodal positions.

Parameters:
sizesequence of float, len (3)

Physical size of the periodic field.

Fnumpy.ndarray, shape (:,:,:,3,3)

Deformation gradient field.

originsequence of float, len(3), optional

Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].

Returns:
x_nnumpy.ndarray, shape (:,:,:,3)

Nodal coordinates.

damask.grid_filters.cellsSizeOrigin_coordinates0_node(coordinates0, ordered=True)[source]#

Return grid ‘DNA’, i.e. cells, size, and origin from 1D array of nodal positions.

Parameters:
coordinates0numpy.ndarray, shape (:,3)

Undeformed nodal coordinates.

orderedbool, optional

Expect coordinates0 data to be ordered (x fast, z slow). Defaults to True.

Returns:
cells, size, originThree numpy.ndarray, each of shape (3)

Information to reconstruct grid.

damask.grid_filters.point_to_node(cell_data)[source]#

Interpolate periodic point data to nodal data.

Parameters:
cell_datanumpy.ndarray, shape (:,:,:,…)

Data defined on the cell centers of a periodic grid.

Returns:
node_datanumpy.ndarray, shape (:,:,:,…)

Data defined on the nodes of a periodic grid.

damask.grid_filters.node_to_point(node_data)[source]#

Interpolate periodic nodal data to point data.

Parameters:
node_datanumpy.ndarray, shape (:,:,:,…)

Data defined on the nodes of a periodic grid.

Returns:
cell_datanumpy.ndarray, shape (:,:,:,…)

Data defined on the cell centers of a periodic grid.

damask.grid_filters.coordinates0_valid(coordinates0)[source]#

Check whether coordinates form a regular grid.

Parameters:
coordinates0numpy.ndarray, shape (:,3)

Array of undeformed cell coordinates.

Returns:
validbool

Whether the coordinates form a regular grid.

damask.grid_filters.regrid(size, F, cells)[source]#

Return mapping from coordinates in deformed configuration to a regular grid.

Parameters:
sizesequence of float, len (3)

Physical size.

Fnumpy.ndarray, shape (:,:,:,3,3), shape (:,:,:,3,3)

Deformation gradient field.

cellssequence of int, len (3)

Cell count along x,y,z of remapping grid.


tensor#

Tensor mathematics.

All routines operate on numpy.ndarrays of shape (…,3,3).

damask.tensor.deviatoric(T)[source]#

Calculate deviatoric part of a tensor.

Parameters:
Tnumpy.ndarray, shape (…,3,3)

Tensor of which the deviatoric part is computed.

Returns:
T’numpy.ndarray, shape (…,3,3)

Deviatoric part of T.

damask.tensor.eigenvalues(T_sym)[source]#

Eigenvalues, i.e. principal components, of a symmetric tensor.

Parameters:
T_symnumpy.ndarray, shape (…,3,3)

Symmetric tensor of which the eigenvalues are computed.

Returns:
lambdanumpy.ndarray, shape (…,3)

Eigenvalues of T_sym sorted in ascending order, each repeated according to its multiplicity.

damask.tensor.eigenvectors(T_sym, RHS=False)[source]#

Eigenvectors of a symmetric tensor.

Parameters:
T_symnumpy.ndarray, shape (…,3,3)

Symmetric tensor of which the eigenvectors are computed.

RHS: bool, optional

Enforce right-handed coordinate system. Defaults to False.

Returns:
xnumpy.ndarray, shape (…,3,3)

Eigenvectors of T_sym sorted in ascending order of their associated eigenvalues.

damask.tensor.spherical(T, tensor=True)[source]#

Calculate spherical part of a tensor.

Parameters:
Tnumpy.ndarray, shape (…,3,3)

Tensor of which the spherical part is computed.

tensorbool, optional

Map spherical part onto identity tensor. Defaults to True.

Returns:
pnumpy.ndarray, shape (…,3,3)

unless tensor == False: shape (…,) Spherical part of tensor T. p is an isotropic tensor.

damask.tensor.symmetric(T)[source]#

Symmetrize tensor.

Parameters:
Tnumpy.ndarray, shape (…,3,3)

Tensor of which the symmetrized values are computed.

Returns:
T_symnumpy.ndarray, shape (…,3,3)

Symmetrized tensor T.

damask.tensor.transpose(T)[source]#

Transpose tensor.

Parameters:
Tnumpy.ndarray, shape (…,3,3)

Tensor of which the transpose is computed.

Returns:
T.Tnumpy.ndarray, shape (…,3,3)

Transpose of tensor T.


mechanics#

Finite-strain continuum mechanics.

All routines operate on numpy.ndarrays of shape (…,3,3).

damask.mechanics.deformation_Cauchy_Green_left(F)[source]#

Calculate left Cauchy-Green deformation tensor (Finger deformation tensor).

Parameters:
Fnumpy.ndarray, shape (…,3,3)

Deformation gradient.

Returns:
Bnumpy.ndarray, shape (…,3,3)

Left Cauchy-Green deformation tensor.

damask.mechanics.deformation_Cauchy_Green_right(F)[source]#

Calculate right Cauchy-Green deformation tensor.

Parameters:
Fnumpy.ndarray, shape (…,3,3)

Deformation gradient.

Returns:
Cnumpy.ndarray, shape (…,3,3)

Right Cauchy-Green deformation tensor.

damask.mechanics.equivalent_strain_Mises(epsilon)[source]#

Calculate the Mises equivalent of a strain tensor.

Parameters:
epsilonnumpy.ndarray, shape (…,3,3)

Symmetric strain tensor of which the von Mises equivalent is computed.

Returns:
epsilon_vMnumpy.ndarray, shape (…)

Von Mises equivalent strain of epsilon.

damask.mechanics.equivalent_stress_Mises(sigma)[source]#

Calculate the Mises equivalent of a stress tensor.

Parameters:
sigmanumpy.ndarray, shape (…,3,3)

Symmetric stress tensor of which the von Mises equivalent is computed.

Returns:
sigma_vMnumpy.ndarray, shape (…)

Von Mises equivalent stress of sigma.

damask.mechanics.maximum_shear(T_sym)[source]#

Calculate the maximum shear component of a symmetric tensor.

Parameters:
T_symnumpy.ndarray, shape (…,3,3)

Symmetric tensor of which the maximum shear is computed.

Returns:
gamma_maxnumpy.ndarray, shape (…)

Maximum shear of T_sym.

damask.mechanics.rotation(T)[source]#

Calculate the rotational part of a tensor.

Parameters:
Tnumpy.ndarray, shape (…,3,3)

Tensor of which the rotational part is computed.

Returns:
Rdamask.Rotation, shape (…)

Rotational part of the vector.

damask.mechanics.strain(F, t, m)[source]#

Calculate strain tensor (Seth–Hill family).

Parameters:
Fnumpy.ndarray, shape (…,3,3)

Deformation gradient.

t{‘V’, ‘U’}

Type of the polar decomposition, ‘V’ for left stretch tensor and ‘U’ for right stretch tensor.

mfloat

Order of the strain.

Returns:
epsilonnumpy.ndarray, shape (…,3,3)

Strain of F.

References

https://en.wikipedia.org/wiki/Finite_strain_theory https://de.wikipedia.org/wiki/Verzerrungstensor

damask.mechanics.stress_Cauchy(P, F)[source]#

Calculate the Cauchy stress (true stress).

Resulting tensor is symmetrized as the Cauchy stress needs to be symmetric.

Parameters:
Pnumpy.ndarray, shape (…,3,3)

First Piola-Kirchhoff stress.

Fnumpy.ndarray, shape (…,3,3)

Deformation gradient.

Returns:
sigmanumpy.ndarray, shape (…,3,3)

Cauchy stress.

damask.mechanics.stress_second_Piola_Kirchhoff(P, F)[source]#

Calculate the second Piola-Kirchhoff stress.

Resulting tensor is symmetrized as the second Piola-Kirchhoff stress needs to be symmetric.

Parameters:
Pnumpy.ndarray, shape (…,3,3)

First Piola-Kirchhoff stress.

Fnumpy.ndarray, shape (…,3,3)

Deformation gradient.

Returns:
Snumpy.ndarray, shape (…,3,3)

Second Piola-Kirchhoff stress.

damask.mechanics.stretch_left(T)[source]#

Calculate left stretch of a tensor.

Parameters:
Tnumpy.ndarray, shape (…,3,3)

Tensor of which the left stretch is computed.

Returns:
Vnumpy.ndarray, shape (…,3,3)

Left stretch tensor from Polar decomposition of T.

damask.mechanics.stretch_right(T)[source]#

Calculate right stretch of a tensor.

Parameters:
Tnumpy.ndarray, shape (…,3,3)

Tensor of which the right stretch is computed.

Returns:
Unumpy.ndarray, shape (…,3,3)

Left stretch tensor from Polar decomposition of T.


solver.Marc#

class damask.solver.Marc(version='2022.1', marc_root='/opt/msc', damask_root='/tmp/13057_5ef284c96f59d82136f922564f75f27813e09226/DAMASK')[source]#

Wrapper to run DAMASK with MSC Marc.

Attributes:
library_path
tools_path

Methods

submit_job(model, job[, compile, ...])

Assemble command line arguments and call Marc executable.

submit_job(model, job, compile=False, optimization='', env=None)[source]#

Assemble command line arguments and call Marc executable.

Parameters:
modelstr

Name of model.

jobstr

Name of job.

compilebool, optional

Compile DAMASK_Marc user subroutine (and save for future use). Defaults to False.

optimizationstr, optional

Optimization level ‘’ (-O0), ‘l’ (-O1), or ‘h’ (-O3). Defaults to ‘’.

envdict, optional

Environment for execution.