Skip to content

Class pylset_base

Provides device and precision handling and the finite difference operators, which honor the boundary condition of each axis.

Bases: setup_grid

Methods:

__init__

__init__(domain_size: ndarray, ndiv: ndarray, config: Dict[str, Any]) -> None

Initialize the base level set setup with grid, device and precision settings.

Parameters:

Name Type Description Default
domain_size ndarray of float, shape (ndim,)

Physical size of the domain along each axis.

required
ndiv ndarray of int, shape (ndim,)

Number of grid points along each axis.

required
config dict

Configuration parameters as key-value pairs. See the pyLSET overview for the complete list.

required

Raises:

Type Description
ValueError

If dtype_gpu is not torch.float32 or torch.float64.

ValueError

If a GPU is requested but none is available.

get_advection_term

get_advection_term(f: Tensor, velocity: Sequence[Union[float, Tensor]], scheme: str = 'WENO5Z') -> torch.Tensor

Upwind approximation of u . grad f for the advection equation f_t + u . grad f = 0.

Along each axis the one sided difference on the upwind side of the local velocity component is used (Osher and Fedkiw 2003, Chapter 3), of first order ('Upwind'), second order ENO ('ENO2', Osher and Shu 1991) or fifth order WENO ('WENO5', Jiang and Peng 2000, or 'WENO5Z' with the weights of Borges et al. 2008). The ghost cells follow the boundary conditions (periodic wrap or even reflection).

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
velocity sequence of float or torch.Tensor

One velocity component per axis, each a number or a tensor broadcastable to ndiv.

required
scheme str

'Upwind', 'ENO2', 'WENO5' or 'WENO5Z' (default).

'WENO5Z'

Returns:

Name Type Description
term Tensor

Approximation of u . grad f, with the shape of f.

get_boundary_frame_matrices

get_boundary_frame_matrices(orientation_a, orientation_b, normal)

Orientations of two crystals in the frame of the boundary between them.

Given orientation matrices g (lab to crystal, v_crystal = g v_lab) and a lab frame unit normal pointing from crystal a into crystal b, returns P = T g_a^T and Q = T g_b^T, where T rotates the lab frame so that the normal becomes the x axis. P and Q are crystal to boundary frame matrices, and the first row of P is the normal in the frame of crystal a. This is the input of grain boundary energy models such as GB5DOF. Works with numpy arrays or torch tensors.

Parameters:

Name Type Description Default
orientation_a (ndarray or Tensor, shape(n, 3, 3))

Orientation matrices of the two crystals.

required
orientation_b (ndarray or Tensor, shape(n, 3, 3))

Orientation matrices of the two crystals.

required
normal (ndarray or Tensor, shape(n, 3))

Unit normals pointing from crystal a into crystal b.

required

Returns:

Type Description
P, Q : ndarray or torch.Tensor, shape (n, 3, 3)

get_cubic_symmetry_operators

get_cubic_symmetry_operators() -> np.ndarray

The 24 proper rotations of the cubic point group.

Returns:

Name Type Description
ops (ndarray, shape(24, 3, 3))

Rotation matrices.

get_curvature_flow_term

get_curvature_flow_term(f: Tensor, eps: float = 1e-12) -> torch.Tensor

Evaluate |grad f| div(grad f / |grad f|) with central differences.

This is the right hand side of mean curvature flow, phi_t = mu gamma |grad phi| div(grad phi/|grad phi|), written as (|grad f|^2 lap f - grad f . H grad f) / |grad f|^2, where H is the Hessian. For a signed distance function it equals the Laplacian of f.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
eps float

Regularization of |grad f|^2 in the denominator.

1e-12

Returns:

Name Type Description
term Tensor

Curvature flow term.

get_device

get_device() -> torch.device

Get the PyTorch device used for computations.

Returns:

Name Type Description
device device

CPU or CUDA device.

get_disorientation

get_disorientation(orientation_a: ndarray, orientation_b: ndarray, symmetry: str = 'cubic', convention: str = 'lab_to_crystal') -> Tuple[np.ndarray, np.ndarray]

Disorientation angle and axis between pairs of 3D crystal orientations.

The angle is that of get_misorientation_angle(). The axis is given in crystal coordinates and, for cubic symmetry, in the fundamental zone with the switching symmetry, that is with components u >= v >= w >= 0 (the standard stereographic triangle). The proper rotations of the cubic group permute the axis components with sign changes of determinant +1, and exchanging the two grains reverses the axis, which together allow any permutation and any signs.

Parameters:

Name Type Description Default
orientation_a (ndarray, shape(n, 3, 3))

Rotation matrices.

required
orientation_b (ndarray, shape(n, 3, 3))

Rotation matrices.

required
symmetry str

'cubic' or 'none'.

'cubic'
convention str

'lab_to_crystal' (default) or 'crystal_to_lab', see get_misorientation_angle().

'lab_to_crystal'

Returns:

Name Type Description
theta (ndarray, shape(n))

Disorientation angle in radians.

axis (ndarray, shape(n, 3))

Unit rotation axis in crystal coordinates. Zero where the angle is zero. With symmetry 'none' the axis is that of g_a g_b^T.

get_dminus

get_dminus(f: Tensor, axis: int) -> torch.Tensor

Backward difference along an axis, (f[i] - f[i-1])/h.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
axis int

Spatial axis.

required

Returns:

Name Type Description
d Tensor

Backward difference.

get_dplus

get_dplus(f: Tensor, axis: int) -> torch.Tensor

Forward difference along an axis, (f[i+1] - f[i])/h.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
axis int

Spatial axis.

required

Returns:

Name Type Description
d Tensor

Forward difference.

get_dtype_cpu

get_dtype_cpu() -> type

Get the NumPy floating point type used for host arrays.

Returns:

Name Type Description
dtype_cpu type

NumPy floating point type.

get_dtype_gpu

get_dtype_gpu() -> torch.dtype

Get the PyTorch floating point type used for device tensors.

Returns:

Name Type Description
dtype_gpu dtype

torch.float32 or torch.float64.

get_grad_norm_godunov

get_grad_norm_godunov(f: Tensor, sign: Tensor) -> torch.Tensor

Upwind (Godunov) approximation of |grad f| for f_t + a |grad f| = 0.

The upwind direction depends on the sign of the speed a (Osher and Fedkiw 2003, Section 6.2). Note that the pyLSET evolution equation phi_t = V |grad phi| corresponds to a = -V.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
sign Tensor

Sign of the speed a, broadcastable to f. Positive values select the branch for a > 0.

required

Returns:

Name Type Description
grad_norm Tensor

Upwind approximation of |grad f|.

get_gradient

get_gradient(f: Tensor) -> List[torch.Tensor]

Second order central difference gradient.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required

Returns:

Name Type Description
grad list of torch.Tensor

One component per spatial axis.

get_heaviside_smoothed

get_heaviside_smoothed(f: Union[ndarray, Tensor], width: float) -> Union[np.ndarray, torch.Tensor]

Smoothed Heaviside function of a level set field.

H = 0 for f < -width, H = 1 for f > width and H = (1 + f/width + sin(pi f/width)/pi)/2 in between (Osher and Fedkiw 2003, eq. 1.22). The result has the type (NumPy or PyTorch) of the input.

Parameters:

Name Type Description Default
f ndarray or Tensor

Level set field, positive inside.

required
width float

Half width of the smoothing zone.

required

Returns:

Name Type Description
H ndarray or Tensor

Smoothed Heaviside function, between 0 and 1.

get_laplacian

get_laplacian(f: Tensor) -> torch.Tensor

Second order central difference Laplacian.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required

Returns:

Name Type Description
lap Tensor

Laplacian of f.

get_mean_curvature

get_mean_curvature(f: Tensor, eps: float = 1e-12) -> torch.Tensor

Mean curvature (sum of principal curvatures) of the level sets of f.

With the pyLSET convention (positive inside) the outward normal is n = -grad f / |grad f| and the curvature kappa = div n is positive for a convex domain. For a circle of radius R, kappa = 1/R; for a sphere, 2/R.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
eps float

Regularization of |grad f|.

1e-12

Returns:

Name Type Description
kappa Tensor

Mean curvature.

get_misorientation_angle

get_misorientation_angle(orientation_a: ndarray, orientation_b: ndarray, symmetry: Union[str, int] = 'cubic', convention: str = 'lab_to_crystal') -> np.ndarray

Disorientation angle between pairs of crystal orientations.

The disorientation is the misorientation with the smallest rotation angle among all symmetrically equivalent descriptions, taking the crystal symmetry of both grains and the switching symmetry (exchange of the two grains) into account. For the angle alone, the switching symmetry does not change the result.

In 2D, orientations are angles (radians) and symmetry is the n-fold rotational symmetry of the crystal (an integer, for example 4 or 6, 'cubic' for the 4-fold symmetry of a square lattice, or 'none'). In 3D, orientations are rotation matrices and symmetry is 'cubic' (the 24 proper rotations of the cubic point group) or 'none'.

Parameters:

Name Type Description Default
orientation_a ndarray

Shape (n,) of angles in 2D, or (n, 3, 3) of rotation matrices in 3D.

required
orientation_b ndarray

Shape (n,) of angles in 2D, or (n, 3, 3) of rotation matrices in 3D.

required
symmetry str or int

Crystal symmetry, see above.

'cubic'
convention str

Convention of 3D matrices, 'lab_to_crystal' (default, v_crystal = g v_lab, as stored by set_domain_orientations()) or 'crystal_to_lab'. With the wrong convention the crystal symmetry is applied on the wrong side and the angles are wrong.

'lab_to_crystal'

Returns:

Name Type Description
theta (ndarray, shape(n))

Disorientation angle in radians.

get_normal

get_normal(f: Tensor, eps: float = 1e-12) -> List[torch.Tensor]

Outward unit normal n = -grad f / |grad f| (pyLSET sign convention).

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
eps float

Regularization of |grad f|.

1e-12

Returns:

Name Type Description
n list of torch.Tensor

One component per spatial axis.

get_read_shockley_energy

get_read_shockley_energy(theta: ndarray, energy_max: float = 1.0, theta_max: float = np.radians(15.0), energy_min: float = 0.0) -> np.ndarray

Read–Shockley interface energy as a function of misorientation.

gamma = energy_max (theta/theta_max)(1 - ln(theta/theta_max)) for theta < theta_max and energy_max above (Read and Shockley 1950). A lower bound energy_min avoids vanishing energies of nearly coincident orientations.

Parameters:

Name Type Description Default
theta ndarray

Misorientation angle in radians.

required
energy_max float

Energy of high angle boundaries.

1.0
theta_max float

Transition angle in radians, 15 degrees by default.

radians(15.0)
energy_min float

Lower bound of the energy.

0.0

Returns:

Name Type Description
gamma ndarray

Interface energy.

get_shifted

get_shifted(f: Tensor, axis: int, step: int) -> torch.Tensor

Shift a field along a spatial axis, honoring the boundary condition of that axis.

The returned tensor g satisfies g[..., i, ...] = f[..., i + step, ...], with indices outside the domain mapped by the periodic or mirror condition. The spatial axes are the last ndim dimensions of f, so leading dimensions (for example a stack of level set fields) are allowed.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
axis int

Spatial axis, 0 for x, 1 for y and 2 for z.

required
step int

Shift in grid points. Positive values fetch the neighbor in the positive direction.

required

Returns:

Name Type Description
g Tensor

Shifted field with the same shape as f.

get_sigmoidal_mobility

get_sigmoidal_mobility(theta: ndarray, mobility_max: float = 1.0, theta_max: float = np.radians(15.0), b: float = 5.0, n: float = 4.0) -> np.ndarray

Sigmoidal interface mobility as a function of misorientation.

mu = mobility_max (1 - exp(-b (theta/theta_max)^n)), which gives low mobility for low angle boundaries (Huang and Humphreys 2000).

Parameters:

Name Type Description Default
theta ndarray

Misorientation angle in radians.

required
mobility_max float

Mobility of high angle boundaries.

1.0
theta_max float

Transition angle in radians, 15 degrees by default.

radians(15.0)
b float

Shape parameters, 5 and 4 by default.

5.0
n float

Shape parameters, 5 and 4 by default.

5.0

Returns:

Name Type Description
mu ndarray

Interface mobility.

get_sign_smoothed

get_sign_smoothed(f: Tensor, width: float) -> torch.Tensor

Smoothed sign function f / sqrt(f^2 + width^2).

Parameters:

Name Type Description Default
f Tensor

Field.

required
width float

Smoothing width, usually one grid spacing.

required

Returns:

Name Type Description
s Tensor

Smoothed sign of f.

get_smooth_area

get_smooth_area(phi: Union[ndarray, Tensor], width: Optional[float] = None) -> Union[float, np.ndarray]

Area enclosed by the zero contour of a 2D level set field.

The area is the integral of the smoothed Heaviside function of phi (get_heaviside_smoothed()). Unlike a count of positive grid points, it resolves changes in area far below one cell. For a signed distance function the smoothing gives a small systematic overestimate of curved areas, about 0.13 (width/R)^2 relative error for a circle of radius R.

Parameters:

Name Type Description Default
phi ndarray or torch.Tensor, shape ndiv or (n_fields, *ndiv)

Level set field or stack of fields, positive inside.

required
width float

Half width of the smoothing zone. Defaults to 1.5 times the largest grid spacing.

None

Returns:

Name Type Description
area float or ndarray

Enclosed area, one value per field for a stack of fields.

Raises:

Type Description
ValueError

If the grid is not 2D.

get_smooth_volume

get_smooth_volume(phi: Union[ndarray, Tensor], width: Optional[float] = None) -> Union[float, np.ndarray]

Volume enclosed by the zero contour of a 3D level set field.

The volume is the integral of the smoothed Heaviside function of phi (get_heaviside_smoothed()). For a signed distance function the smoothing gives a small systematic overestimate of curved volumes, about 0.39 (width/R)^2 relative error for a sphere of radius R.

Parameters:

Name Type Description Default
phi ndarray or torch.Tensor, shape ndiv or (n_fields, *ndiv)

Level set field or stack of fields, positive inside.

required
width float

Half width of the smoothing zone. Defaults to 1.5 times the largest grid spacing.

None

Returns:

Name Type Description
volume float or ndarray

Enclosed volume, one value per field for a stack of fields.

Raises:

Type Description
ValueError

If the grid is not 3D.

get_stiffness_flow_term

get_stiffness_flow_term(f: Tensor, stiffness: Tensor, eps: float = 1e-12) -> torch.Tensor

Evaluate Gamma : (P H P), the weighted curvature flow term with a stiffness tensor.

H is the Hessian of f, P = I - n n the projection onto the tangent plane of its level sets, with n = grad f/|grad f|, and Gamma a symmetric tensor field, the interface stiffness. The term is evaluated as Gamma : H - 2 (Gamma n).(H n) + (n.Gamma n)(n.H n) with central differences. With Gamma = P it equals get_curvature_flow_term(), and with Gamma = s P in 2D it is s times that term.

Parameters:

Name Type Description Default
f Tensor

Field with shape (..., *ndiv).

required
stiffness Tensor

Tensor components with shape (ndim (ndim + 1)/2, *ndiv), in the order xx, yy, xy in 2D and xx, yy, zz, xy, xz, yz in 3D.

required
eps float

Regularization of |grad f|^2.

1e-12

Returns:

Name Type Description
term Tensor

Weighted curvature flow term with the shape of f.

get_time_stamp

get_time_stamp() -> str

Get a time stamp string.

Returns:

Name Type Description
time_stamp str

Current date and time as 'YYYY-MM-DD HH:MM:SS'.

get_verbose

get_verbose() -> bool

Get the verbosity level.

Returns:

Name Type Description
verbose bool

Current verbosity flag.

set_verbose

set_verbose(verbose: bool) -> None

Set the verbosity level.

Parameters:

Name Type Description Default
verbose bool

True to print timing and status information.

required

to_device

to_device(array: Union[ndarray, Tensor]) -> torch.Tensor

Copy an array to the computing device with the device precision.

Parameters:

Name Type Description Default
array ndarray or Tensor

Array to copy.

required

Returns:

Name Type Description
tensor Tensor

Contiguous tensor on the computing device.

to_host

to_host(tensor: Tensor) -> np.ndarray

Copy a device tensor to a NumPy array with the host precision.

Parameters:

Name Type Description Default
tensor Tensor

Tensor to copy.

required

Returns:

Name Type Description
array ndarray

Host copy of the tensor.