Skip to content

Class pylset

The main class for level set simulations, combining all inherited capabilities.

Bases: setup_io

Main class for level set simulations of interface networks, for example grain boundaries.

It combines the inherited capabilities of the class hierarchy:

  • Grid definition and boundary conditions (pylset_grid)
  • Device and precision handling and finite difference operators (pylset_base)
  • Label maps, coloring and signed distance construction (pylset_pre)
  • File I/O (pylset_io)

Each domain (grain, particle or other region) is represented by a level set function phi that is a signed distance function, positive inside the domain. Without coloring, every domain has its own field. With coloring, domains that are not neighbors share a field to reduce memory use. Each domain carries a flag stating whether its level set is evolved (mobile) or immobile.

The class is configured with a parameter dictionary that defaults to the values in DEFAULTS. A typical time step consists of do_step_update(), do_interaction_correction() and do_reinitialization().

Methods:

__init__

__init__(domain_size: Union[List[float], ndarray], ndiv: Union[List[int], ndarray], config: Optional[Dict[str, Any]] = None, **kwargs: Any) -> None

Initialize a level set simulation.

Parameters:

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

Physical size of the domain, [Lx, Ly] in 2D or [Lx, Ly, Lz] in 3D.

required
ndiv array_like of int, shape (ndim,)

Number of grid points along each axis. Its length sets the dimensionality.

required
config dict

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

None
**kwargs dict

Individual configuration parameters. These override values in config.

{}

Raises:

Type Description
ValueError

If a configuration value is not valid.

Examples:

>>> sim = setup_simulation([64.0, 64.0], [128, 128], device_type='CPU')
>>> sim = setup_simulation([1.0, 1.0, 1.0], [96, 96, 96], config={'bc_z': 'Mirror'})

add_domain

add_domain(coordinates: Union[Sequence[float], ndarray], radius: float, orientations: Optional[ndarray] = None, reinitialize: bool = True) -> np.ndarray

Add new mobile domains, such as nuclei, as discs (2D) or spheres (3D).

Each new domain gets the exact signed distance to its disc or sphere, honoring periodic boundaries, and is cut out of the mobile domains it overlaps. With coloring, a new domain is placed in an existing field that has no domain within band_width plus two grid spacings of it, or in a new field if there is none, so the number of fields grows only when needed. Domains added in one call are placed one after the other, so they can share a field when they lie far enough apart. Without coloring, every new domain gets a new field. The new domains get the IDs following the largest existing ID, are mobile and have zero stored energy unless set_stored_energy() gives them another value. Call do_property_update() afterwards when interface properties or stored energies depend on the domains.

The function can be called at any time during a run, for example to add nuclei at a given rate. Disc or sphere radii should be at least a few grid spacings, since smaller domains are not resolved by the grid.

Parameters:

Name Type Description Default
coordinates (array_like, shape(n, ndim) or (ndim,))

Centers of the new domains. The number of rows is the number of domains and the number of columns must equal the grid dimension.

required
radius float

Radius of the discs or spheres.

required
orientations ndarray

Orientations of the new domains, required when orientations have been set by set_domain_orientations(). Shape (n,) of angles in 2D and (n, 3, 3) of orientation matrices in 3D, in the convention used there.

None
reinitialize bool

Reinitialize the fields that were changed (default True).

True

Returns:

Name Type Description
new_ids ndarray of int, shape (n,)

IDs of the new domains, in the order of coordinates.

Raises:

Type Description
ValueError

If the coordinates do not match the grid dimension or lie outside the grid, if the radius is not positive, if two new domains overlap, if a new domain overlaps an immobile domain, or if orientations are missing or of the wrong shape.

add_scalar_field

add_scalar_field(name: str, value: Any = 0.0, capacity: Any = 1.0, conductivity: Any = 1.0, source: Any = 0.0, time_scheme: str = 'Implicit', tolerance: float = 1e-08, max_iterations: int = 2000, preconditioner: str = 'Multigrid') -> setup_field

Add a scalar field, such as temperature or concentration, on the grid.

The field follows c du/dt = div(k grad u) + Q (see pylset_field.setup_field) and starts at the current time. Advance it with do_field_update(). Boundary conditions are set on the returned field with set_bc(). Faces of axes that are periodic for the level sets are periodic, the others are insulated ('Neumann' with zero flux) until set otherwise.

Parameters:

Name Type Description Default
name str

Name of the field, used by get_scalar_field().

required
value (float, ndarray or callable)

Initial value, a number, an array of shape ndiv or a function of the cell center coordinates.

0.0
capacity (float, ndarray or callable)

Capacity c, a number, an array or a function of the field f(u).

1.0
conductivity (float, ndarray or callable)

Conductivity k, given like the capacity.

1.0
source (float, ndarray or callable)

Volumetric source Q, a number, an array or a function f(x, y, t) or f(x, y, z, t) of the coordinates and the time.

0.0
time_scheme str

'Implicit' (default), 'Crank-Nicolson', 'Explicit' or 'Steady'.

'Implicit'
tolerance float

Relative residual of the conjugate gradient iterations.

1e-08
max_iterations int

Largest number of conjugate gradient iterations per update.

2000
preconditioner str

'Multigrid' (default) or 'Jacobi'.

'Multigrid'

Returns:

Name Type Description
field setup_field

The new field.

Raises:

Type Description
ValueError

If a field of the same name exists.

cleanup

cleanup() -> None

Release the level set fields and free GPU memory.

do_field_update

do_field_update() -> None

Advance all scalar fields to the current time of the level sets.

Each field is advanced by one step from its own time to the time of the simulation, so the fields can be updated every step or every few steps. With the default implicit scheme a step of any length is stable. A 'Steady' field is also solved at the first call, before the time has advanced. The field factors of set_field_dependence() are then applied.

do_interaction_correction

do_interaction_correction(method: Optional[str] = None, report: bool = False) -> Optional[Dict[str, float]]

Remove voids and overlaps between adjacent mobile level sets.

'MBO' applies phi_i <- (phi_i - max_{j != i} phi_j)/2 at every point (Merriman, Bence and Osher 1994). 'Losasso' subtracts the mean of the two largest values from every field (Losasso et al. 2006), which gives the same zero contours. Both should be applied to signed distance functions, so a reinitialization should precede the correction, and both destroy the signed distance property, so another reinitialization should follow.

The 'Lagrange' and 'Source' corrections are not projections but source terms in the evolution equation, applied by do_step_update(). 'Lagrange' adds -mu lambda (sum_j H(phi_j) - 1) with one global Lagrange multiplier (Zhao et al. 1996, Hallberg and Bulatov 2019), evaluated from the previous step. 'Source' adds -w_i Lambda (sum_j H(phi_j) - 1) with per domain weights (Li and Bernacki 2025, 2026), see set_domain_source_weights(). For these two methods this function only reports voids and overlaps.

Immobile level sets are not changed and are not used as competitors. The condition where interfaces meet immobile surfaces is set by contact_condition.

Parameters:

Name Type Description Default
method str

'MBO', 'Losasso', 'Lagrange' or 'Source'. Defaults to the configuration value correction_method. The source term methods only take effect when set as correction_method.

None
report bool

If True, return the void and overlap fractions before and after the correction.

False

Returns:

Name Type Description
result dict or None

With report=True, the keys 'void_before', 'overlap_before', 'void_after' and 'overlap_after' give fractions of grid points.

do_property_update

do_property_update() -> None

Evaluate interface energy and mobility fields from their functions.

The domains on either side of the interfaces are identified by get_interface_neighbors(). The energy and mobility functions given to set_interface_energy() and set_interface_mobility() are evaluated at the interface points and extended to the whole grid, and so are the stored energy differences given by set_stored_energy(). With the 'Stiffness' form, the interface stiffness is evaluated as well (a tensor in 3D), by finite differences of the energy with respect to the inclination angle. Call it at regular intervals, for example together with do_reinitialization(). It is called automatically by do_step_update() when the fields are missing.

do_recoloring

do_recoloring(separation: Optional[int] = None, reinitialize: bool = True) -> int

Reassign domains to level set fields to prevent coalescence.

With coloring, several domains share a level set field. During the evolution, topological changes can bring two domains of the same field close to each other, and they would merge if they came into contact. This function finds pairs of mobile domains in the same field whose distance in the current adjacency graph is at most separation (counted as in do_coloring()), and moves the smaller domain of each pair to a field where it has no conflicts, or to a new field (Krill and Chen 2002, Scholtes et al. 2015). The affected fields are reinitialized.

Call it at regular intervals, for example together with do_reinitialization(). With separation >= 2, a conflict is detected while the two domains are still separated by at least one other domain.

Parameters:

Name Type Description Default
separation int

Graph distance at or below which two domains may not share a field. Defaults to the configuration value coloring_separation. Domains touching at a corner count as neighbors.

None
reinitialize bool

Reinitialize the affected fields after moving domains (default True).

True

Returns:

Name Type Description
n_moved int

Number of domains moved to another field.

do_reinitialization

do_reinitialization(method: Optional[str] = None, band_width: Optional[float] = None, fields: Optional[Sequence[int]] = None) -> None

Restore the signed distance property of all mobile level set fields.

Parameters:

Name Type Description Default
method str

'PDE' (reinitialization equation of Sussman, Smereka and Osher 1994, second order with subcell resolution after du Chéné, Min and Gibou 2008), 'FSM' (fast sweeping), 'FMM' (fast marching, scikit-fmm, CPU) or 'Brute' (exact distance to the extracted interface, 2D). Defaults to the configuration value reinit_method.

None
band_width float

Half width, in units of the largest grid spacing, of the band in which the signed distance property is restored. Values outside the band are clamped. Defaults to the configuration value band_width.

None
fields sequence of int

Indices of the fields to reinitialize. Defaults to all mobile fields.

None
Notes

Immobile level sets are not changed.

Every reinitialization moves the zero contour slightly, while an explicit time step moves it by only about 0.1 h^2 kappa. Reinitializing after every time step therefore changes the effective mobility. For a shrinking circle of radius 16 grid spacings with the default 'Full' curvature form, the area shrinkage rate was 1.7 percent too high with 'PDE' and 37 percent too high with the first order 'FSM' when reinitializing every step, and 0.2 and 3.4 percent too high when reinitializing every 20 steps. The 'Laplacian' form needs signed distance functions at every step and is more sensitive to this error (2.3 percent with 'PDE' and 15 percent with 'FSM' every 20 steps).

do_step_update

do_step_update() -> None

Advance all mobile level set fields by one time step.

The interfaces move by curvature, with local mobility and energy, by stored energy differences if these are set with set_stored_energy() and with a prescribed velocity field if one is set with set_velocity_field(). Immobile fields are not changed. The interaction correction and the reinitialization are separate calls, do_interaction_correction() and do_reinitialization(). The fields are processed in batches of field_batch_size fields to limit the temporary memory.

Raises:

Type Description
RuntimeError

If no level set fields have been set.

get_advection_scheme

get_advection_scheme() -> str

Get the discretization of the advection term.

Returns:

Name Type Description
advection_scheme str

'Upwind', 'ENO2', 'WENO5' or 'WENO5Z'.

get_boundary_frames

get_boundary_frames(domain_a, domain_b, normal)

Orientations of the two domains at interface points in the boundary frame.

Returns the matrices used by grain boundary energy models such as GB5DOF (Bulatov, Reed and Kumar 2014) for FCC and uGBE for BCC, which take the orientations P and Q of the two grains as crystal to lab matrices in a frame where the boundary normal is the x axis, so that the first row of P is the boundary normal in the crystal frame of the first grain. The frame is found by rotating the lab frame so that normal maps to x. The rotation about the normal is arbitrary, which does not change the boundary. A model for the energy of the interfaces can then be given to set_interface_energy() as

def energy(domain_a, domain_b, normal):
    P, Q = sim.get_boundary_frames(domain_a, domain_b, normal)
    return gb5dof_batched(P, Q, 'Ni')

Works with numpy arrays, and with torch tensors on the device for functions set with on_device=True. 3D only.

Parameters:

Name Type Description Default
domain_a ndarray of int or torch.Tensor, shape (n,)

Domains on either side of the interface.

required
domain_b ndarray of int or torch.Tensor, shape (n,)

Domains on either side of the interface.

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

Unit normals pointing from domain_a into domain_b.

required

Returns:

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

Crystal to boundary frame matrices of domain_a and domain_b.

get_domain_map

get_domain_map() -> np.ndarray

Get the domain ID at every grid point.

Points inside an immobile domain get its ID. Other points get the ID of the domain with the largest positive mobile level set. Points where no level set is positive (voids) get -1.

With coloring, the domains sharing a field are told apart by connected components, which are matched to the previous domain map by largest overlap. Small fragments that match no domain of their field, which can appear at junctions, are given the ID of the nearest domain of the same field. A warning is printed if a component overlaps two domains of its field, which indicates coalescence (see do_recoloring()).

Returns:

Name Type Description
domain_map ndarray of int, shape ndiv

Domain ID at each grid point, -1 in voids.

get_domain_mobile

get_domain_mobile() -> Dict[int, bool]

Get the flag stating whether each domain is evolved (mobile) or immobile.

Returns:

Name Type Description
mobile dict

Maps domain ID to True (evolved) or False (immobile).

get_domain_orientations

get_domain_orientations(domain_ids: Optional[ndarray] = None) -> np.ndarray

Get domain orientations.

Parameters:

Name Type Description Default
domain_ids ndarray of int or torch.Tensor

Domains to look up. Defaults to all domains. With a tensor, the orientations are returned as a tensor on its device, which is what interface functions evaluated on the device need.

None

Returns:

Name Type Description
orientations ndarray or Tensor

Orientations in the order of domain_ids, angles in 2D and matrices g (lab to crystal, see set_domain_orientations()) in 3D.

get_domain_volumes

get_domain_volumes() -> Dict[int, float]

Get the volume (area in 2D) of every domain present in the domain map.

Returns:

Name Type Description
volumes dict

Maps domain ID to volume.

get_dtime

get_dtime() -> float

Get the time step used by do_step_update().

Returns:

Name Type Description
dtime float

The set time step, or the automatic time step if none is set.

Raises:

Type Description
ValueError

If no time step is set and nothing limits the automatic one.

get_field_batch_size

get_field_batch_size() -> Optional[int]

Get the number of level set fields processed together.

Returns:

Name Type Description
field_batch_size (int, Auto or None)

Number of fields per batch, 'Auto' if it follows from the grid size, None if all fields are processed at once.

get_interface_energy

get_interface_energy() -> Union[float, np.ndarray]

Get the interface energy.

Returns:

Name Type Description
interface_energy float or ndarray

Constant energy or host copy of the energy field.

get_interface_mobility

get_interface_mobility() -> Union[float, np.ndarray]

Get the interface mobility.

Returns:

Name Type Description
interface_mobility float or ndarray

Constant mobility or host copy of the mobility field.

get_interface_neighbors

get_interface_neighbors(width: Optional[float] = None) -> Dict[str, np.ndarray]

Identify the two domains on either side of the interface at grid points near interfaces.

At every grid point within width of an interface between mobile domains, the own field is the one with the largest value. The neighbor field is chosen among the other fields with values above -width as the one whose outward normal is most nearly opposite to the own normal (Hallberg and Bulatov 2019). This works without modification at triple junctions, triple lines and quadruple points. The domains are then taken from the domain map at the point and at short steps along the normal.

Parameters:

Name Type Description Default
width float

Half width of the interface zone. Defaults to 1.5 grid spacings.

None

Returns:

Name Type Description
neighbors dict

'index' (flat grid indices), 'domain_a' (domain at the point), 'domain_b' (domain across the interface) and 'normal' (unit normal pointing from domain_a into domain_b, shape (n, ndim)). The normal is that of phi_a - phi_b, computed from the own field and the neighbor field, so that both sides of an interface see the same normal.

get_junction_weights

get_junction_weights() -> Optional[Dict[str, np.ndarray]]

Source term weights near junctions, from the local interface energies.

At a junction between domains a, b and c, the pair energies are split into domain energies, e_a = (gamma_ab + gamma_ac - gamma_bc)/2 and so on, such that gamma_ab = e_a + e_b (Zhao et al. 1996). The 'Source' correction then gives each domain the weight w_a = e_mean/e_a, where e_mean is the mean of the three. For a T junction this is the weight ratio 1/(2R - 1) that Li and Bernacki found to give the equilibrium angles. The weights act at grid points where the third largest level set is above -junction_width grid spacings (by default the band width) and are blended to 1 with the distance to the third domain. Domain energies below 0.1 e_mean, which occur close to wetting, are raised to 0.1 e_mean.

Only used with an interface energy function, see set_interface_energy(). The pair energies are evaluated with the interface normal estimated from the two level sets.

Returns:

Name Type Description
weights dict or None

'index' (flat grid indices), 'field' (field index, shape (n, 3)), 'domain' (domain IDs, shape (n, 3)) and 'weight' (shape (n, 3)) for the three largest fields at each point. None without an energy function or with fewer than three mobile fields.

get_phi

get_phi() -> np.ndarray

Get the level set fields.

Returns:

Name Type Description
phi (ndarray, shape(n_fields, *ndiv))

Host copy of the level set fields.

get_phi_max

get_phi_max() -> np.ndarray

Get the maximum over all level set fields.

The result is positive almost everywhere and close to zero along the interface network, which makes it convenient for visualizing grain boundaries.

Returns:

Name Type Description
phi_max ndarray, shape ndiv

Maximum of all fields at each grid point.

get_scalar_field

get_scalar_field(name: str) -> setup_field

Get a scalar field by name.

Parameters:

Name Type Description Default
name str

Name given in add_scalar_field().

required

Returns:

Name Type Description
field setup_field

The field.

get_stable_dtime

get_stable_dtime() -> float

Get the automatic time step for explicit integration.

The forward Euler stability limit of the central difference Laplacian, dt (sum_k 2 mu gamma / h_k^2) <= 1 (Osher and Fedkiw 2003, eq. 4.7), is multiplied by the safety factor cfl. With stored energy, the rate max |mu (E_b - E_a)| / h of the upwind normal motion (eq. 6.2 of the same book) is added, and with a velocity field the rate sum_k max |u_k| / h_k of the advection (eq. 3.10 of the same book), evaluated at the current time.

Returns:

Name Type Description
dtime float

Automatic time step, infinite if nothing limits it (zero mobility and zero velocity).

get_step

get_step() -> int

Get the number of completed time steps.

Returns:

Name Type Description
step int

Step counter.

get_stored_energy

get_stored_energy() -> Optional[Dict[int, float]]

Get the stored energy of every domain.

Returns:

Name Type Description
stored_energy dict or None

Maps domain ID to stored energy, or None if no stored energy is set.

get_time

get_time() -> float

Get the current simulation time.

Returns:

Name Type Description
time float

Accumulated time.

get_update_scheme

get_update_scheme() -> str

Get the time integration scheme.

Returns:

Name Type Description
update_scheme str

'Euler', 'RK2' or 'RK3'.

get_velocity

get_velocity(time: Optional[float] = None) -> Optional[List[Union[float, torch.Tensor]]]

Get the prescribed velocity at a time.

Parameters:

Name Type Description Default
time float

Time at which a time dependent velocity is evaluated. Defaults to the current simulation time.

None

Returns:

Name Type Description
velocity list or None

One component per axis, each a number or a tensor broadcastable to ndiv, or None if no velocity field is set.

get_void_overlap

get_void_overlap() -> tuple

Get the fractions of grid points in voids and in overlaps.

A void point has no positive level set, an overlap point has more than one positive mobile level set. Points inside immobile domains are not counted as voids.

Returns:

Name Type Description
void_fraction float

Fraction of grid points in voids.

overlap_fraction float

Fraction of grid points in overlaps.

set_advection_scheme

set_advection_scheme(advection_scheme: str) -> None

Set the discretization of the advection term of a prescribed velocity field.

Parameters:

Name Type Description Default
advection_scheme str

'Upwind' (first order), 'ENO2' (second order ENO, Osher and Shu 1991), 'WENO5' (fifth order WENO, Jiang and Peng 2000) or 'WENO5Z' (fifth order WENO with the weights of Borges et al. 2008, which are less dissipative near kinks of the level sets, the default). Case is ignored.

required

Raises:

Type Description
ValueError

If the scheme is not recognized.

set_anisotropy_form

set_anisotropy_form(anisotropy_form: str) -> None

Set how local interface energies enter the evolution equation.

Parameters:

Name Type Description Default
anisotropy_form str

'Heterogeneous' multiplies the curvature term by the local product of mobility and energy. 'Gradient' adds the term -mu grad(gamma).grad(phi) (the 'HetGrad' form of Fausty et al. 2018), which acts where the energy varies, that is near junctions. Neither reproduces the junction angles of unequal energies on its own, use the 'Source' correction with junction weights for that (see get_junction_weights()). 'Stiffness' replaces the energy by the interface stiffness, which accounts for the torque from inclination dependent energies (Herring 1951). In 2D the stiffness is the scalar gamma + d2gamma/dtheta2, where theta is the inclination angle. In 3D it is the tensor gamma P + Hess gamma on the tangent plane, where the Hessian is taken on the unit sphere of normals, and the normal velocity is mu Gamma : K with the curvature tensor K = -P grad(n) P, whose trace is minus the curvature kappa, so that Gamma = gamma P gives -mu gamma kappa. For a smooth energy this is minus the surface divergence of the Cahn-Hoffman vector. The 3D tensor needs seven extra grid fields and is only formed when the energy function reads its normal argument. The case is ignored.

required

set_contact_condition

set_contact_condition(contact_condition: str) -> None

Set the condition where interfaces between mobile domains meet immobile domains.

Parameters:

Name Type Description Default
contact_condition str

'Neumann' extends every mobile level set into the immobile domains, constant along the normal of the immobile surface, which is a homogeneous Neumann condition (zero normal derivative). Interfaces then meet immobile surfaces at 90 degrees, which is the equilibrium angle when both mobile domains have the same interface energy against the immobile domain. 'Pinned' holds the mobile level sets inside the immobile domains at fixed values (a Dirichlet condition), so the lines where interfaces meet immobile surfaces stay in place. The fixed values are those of the fields inside the immobile domains when the condition first acts after set_phi(). To pin interfaces at chosen positions, continue the mobile domains into the immobile domains with the pinned_labels argument of do_sdf(). 'None' applies no condition. The case is ignored.

required

set_correction_method

set_correction_method(method: str) -> None

Set the default interaction correction method.

Parameters:

Name Type Description Default
method str

'MBO' (Merriman, Bence and Osher 1994), 'Losasso' (Losasso et al. 2006), 'Lagrange' (Zhao et al. 1996) or 'Source' (Li and Bernacki 2025). See do_interaction_correction().

required

set_curvature_form

set_curvature_form(curvature_form: str) -> None

Set the discretization of the curvature term.

Parameters:

Name Type Description Default
curvature_form str

'Laplacian' uses mu gamma lap(phi), valid while phi is a signed distance function (Bernacki et al. 2011). 'Full' uses mu gamma |grad phi| div(grad phi/|grad phi|). The case is ignored.

required

set_domain_mobile

set_domain_mobile(domain_id: int, mobile: bool) -> None

Set whether the level set of a domain is evolved or immobile.

Parameters:

Name Type Description Default
domain_id int

Domain ID.

required
mobile bool

True if the level set is evolved, False if it is immobile.

required

Raises:

Type Description
ValueError

If the domain is unknown or if the change would leave a field with both mobile and immobile domains.

set_domain_orientations

set_domain_orientations(orientations: Union[ndarray, Dict[int, Any]], convention: str = 'lab_to_crystal') -> None

Set the crystal orientation of every domain.

In 3D, pyLSET stores orientation matrices g in the convention of texture analysis (Bunge), which transform lab (sample) coordinates into crystal coordinates, v_crystal = g v_lab. The rows of g are the lab axes expressed in crystal coordinates. Matrices of rotations that take the crystal axes into the lab frame, for example as_matrix() of a scipy Rotation built from crystal to lab, are the transposes and are accepted with convention='crystal_to_lab'.

Parameters:

Name Type Description Default
orientations ndarray or dict

An array in the order of get_domain_ids(), with angles (radians) in 2D or rotation matrices of shape (3, 3) in 3D, or a dict mapping domain ID to orientation.

required
convention str

'lab_to_crystal' (default) or 'crystal_to_lab', for 3D matrices.

'lab_to_crystal'

set_domain_source_weights

set_domain_source_weights(weights: Dict[int, float]) -> None

Set per domain weights of the 'Source' interaction correction.

The source term of domain i is -w_i Lambda (sum_j H(phi_j) - 1), with Lambda = source_strength sqrt(mu gamma / dt) (Li and Bernacki 2025, 2026). Unequal weights encode unequal interface energies at junctions. For a T junction with energy ratio R between the two branches, Li and Bernacki found the weight ratio 1/(2R - 1) to reproduce the equilibrium angles. Domains without a given weight keep the weight 1. With an interface energy function, the weights near junctions are by default computed from the local pair energies (junction_weighting, see get_junction_weights()). Weights set here multiply those.

Parameters:

Name Type Description Default
weights dict

Maps domain ID to weight.

required

set_dtime

set_dtime(dtime: Optional[float]) -> None

Set the time step.

Parameters:

Name Type Description Default
dtime float or None

Time step. None selects an automatic time step from the stability limit times the safety factor cfl.

required

Raises:

Type Description
ValueError

If dtime is not positive.

set_field_batch_size

set_field_batch_size(field_batch_size: Union[int, str, None]) -> None

Set the number of level set fields processed together.

do_step_update() evaluates the right hand side for this many fields at a time, which limits the temporary memory to a multiple of the batch size rather than of the total number of fields. The time step needs about 11 grid arrays of temporary memory per field in a batch in 3D (9 in 2D). Larger batches mainly reduce the number of kernel launches, which matters only for small grids.

Parameters:

Name Type Description Default
field_batch_size (int, Auto or None)

Number of fields per batch. 'Auto' takes as many fields as fit in about half a million grid points (at least one), and None processes all fields at once.

required

Raises:

Type Description
ValueError

If the batch size is not positive.

set_field_dependence

set_field_dependence(field: Optional[str], mobility: Optional[Callable] = None, energy: Optional[Callable] = None) -> None

Make the interface mobility and energy depend on a scalar field through factors on the grid.

The mobility and energy set by set_interface_mobility() and set_interface_energy() (numbers, arrays or functions of the domains and the normal) are multiplied at every grid point by mobility(u) and energy(u), where u is the field. For example, an Arrhenius mobility is mobility=lambda T: torch.exp(-Q / (R * T)) times the prefactor given to set_interface_mobility(). The factors are applied again after do_field_update(), do_property_update() and changes of the properties, so the time step follows the largest product of mobility and energy. A factor on the energy also scales the stiffness of the 'Stiffness' form. The factor does not depend on the normal or on the domains, so it leaves the junction weights unchanged. For a dependence that differs between interfaces, give the property function a fourth argument with the field argument of set_interface_mobility() or set_interface_energy().

Parameters:

Name Type Description Default
field str or None

Name of the scalar field (add_scalar_field()), or None to remove the factors.

required
mobility callable

Factor f(u) on the mobility, called with the field tensor on the device. It must return a nonnegative tensor or number.

None
energy callable

Factor f(u) on the energy, called like mobility. It must be positive.

None

set_interface_energy

set_interface_energy(interface_energy: Union[float, ndarray, Callable], on_device: bool = False, field: Optional[str] = None) -> None

Set the interface energy.

Parameters:

Name Type Description Default
interface_energy float, ndarray of shape ndiv or callable

A constant energy, a field of local values, or a function f(domain_a, domain_b, normal) as described in set_interface_mobility(). A dependence on normal gives an inclination dependent energy. For grain boundary energy models that take the orientations of the two grains in the boundary frame, such as GB5DOF, see get_boundary_frames().

required
on_device bool

Call the function with torch tensors on the computing device, see set_interface_mobility().

False
field str

Name of a scalar field whose values at the interface points are passed as a fourth argument, see set_interface_mobility().

None

set_interface_mobility

set_interface_mobility(interface_mobility: Union[float, ndarray, Callable], on_device: bool = False, field: Optional[str] = None) -> None

Set the interface mobility.

Parameters:

Name Type Description Default
interface_mobility float, ndarray of shape ndiv or callable

A constant mobility, a field of local values, or a function f(domain_a, domain_b, normal) that returns the mobility of the interfaces between the domains domain_a and domain_b (integer arrays of length n) with unit normals normal (array of shape (n, ndim), pointing from domain_a into domain_b). The function must be symmetric, f(a, b, n) = f(b, a, -n). With a function, the mobility field is evaluated by do_property_update(). A constant mobility of zero turns off the curvature motion, for example for pure advection by set_velocity_field().

required
on_device bool

Call the function with torch tensors on the computing device (domains as int64, normals in double precision) instead of numpy arrays. It must then return a tensor. This avoids copies to the host for expensive functions, such as batched grain boundary energy models running on a GPU.

False
field str

Name of a scalar field (add_scalar_field()). The function is then called as f(domain_a, domain_b, normal, u) with the field values u at the interface points, and do_property_update() must be called after the field changes. For a factor on the grid, see set_field_dependence().

None

set_phi

set_phi(phi: Union[ndarray, Tensor]) -> None

Set the level set fields.

If no domains have been registered by do_sdf(), each field is taken as one mobile domain with IDs 1, 2, 3 and so on.

Parameters:

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

Level set fields, positive inside.

required

Raises:

Type Description
ValueError

If the shape does not match the grid or the registered domains.

set_reinit_method

set_reinit_method(method: str) -> None

Set the default reinitialization method.

Parameters:

Name Type Description Default
method str

'PDE' (second order reinitialization equation with subcell resolution, du Chéné, Min and Gibou 2008), 'FSM', 'FMM' (requires scikit-fmm) or 'Brute' (2D).

required

set_stored_energy

set_stored_energy(stored_energy: Optional[Dict[int, float]]) -> None

Set the stored energy of every domain, which adds a driving force at interfaces.

A domain grows into a neighbor with a higher stored energy. The normal velocity of the interface of domain a against domain b, positive when a grows, becomes mu (-gamma kappa + E_b - E_a), where kappa is the curvature, positive for a convex domain, so that a convex domain shrinks. Stored energy is energy per volume, in units of interface energy per length. The driving force is evaluated by do_property_update(), which identifies the domains on either side of each interface. The time step is limited by |mu (E_b - E_a)| dt <= cfl h in addition to the curvature limit.

Parameters:

Name Type Description Default
stored_energy dict or None

Maps domain ID to stored energy. Domains that are missing get zero. None removes the driving force. Call again to change values during a run, for example to model recovery. Immobile domains do not move, whatever their stored energy.

required

set_update_scheme

set_update_scheme(update_scheme: str) -> None

Set the explicit time integration scheme.

Parameters:

Name Type Description Default
update_scheme str

'Euler' (forward Euler), 'RK2' or 'RK3' (strong stability preserving Runge–Kutta schemes of Shu and Osher 1988). The case is ignored.

required

set_velocity_field

set_velocity_field(velocity: Union[None, Sequence, Callable]) -> None

Prescribe a velocity field that advects the mobile level set fields.

The fields then follow phi_t + u . grad phi = R, where R holds the curvature, stored energy and correction terms. The advection term is discretized with the scheme set by set_advection_scheme(). All mobile fields are advected by the same velocity, immobile fields are not. With 'Mirror' boundaries the ghost cells are even reflections, which is consistent only where the normal velocity vanishes at the boundary, so interfaces should then stay away from boundaries with inflow or outflow.

Parameters:

Name Type Description Default
velocity (None, sequence or callable)

None removes the velocity field. A sequence holds one component per axis, each a number or an array (or tensor) broadcastable to ndiv. A callable is called as velocity(x, y, t) in 2D or velocity(x, y, z, t) in 3D with the cell center coordinates as torch tensors on the device, shaped to broadcast against each other, and the time t. It returns one component per axis in the same forms as a sequence. Using torch functions keeps the evaluation on the device. It is evaluated at the stage times of the update scheme.

required

Raises:

Type Description
ValueError

If the number of components or their shapes do not fit the grid.

Examples:

>>> sim.set_velocity_field([1.0, 0.0])                                   # uniform translation
>>> sim.set_velocity_field(lambda x, y, t: [-(y - 50.0), x - 50.0])      # rigid rotation