Skip to content

Core Classes

This section documents the structure, the conventions and the configuration parameters of pyLSET.

Class Structure

The classes form an inheritance chain, from the most basic to the main class.

pylset_grid -> pylset_base -> pylset_pre -> pylset_io -> pylset (main)
File Class Content
pylset_grid.py setup_grid Grid size, spacing and boundary condition along each axis
pylset_base.py setup_base Device and precision handling, finite difference operators
pylset_pre.py setup_pre Label maps, coloring, signed distances from labels and surfaces
pylset_io.py setup_io VTK and HDF5 output, HDF5 input and restarts, surface input
pylset.py setup_simulation Time integration, reinitialization, interaction correction, domain bookkeeping
pylset_field.py setup_field Scalar fields such as temperature, transient diffusion with face conditions
pylset_mesh.py setup_mesh Finite element discretization (planned)

Conventions

Level sets

  • A level set function is denoted phi. It is a signed distance function, positive inside a domain, zero on its boundary and negative outside.
  • With this convention the outward normal is \(n = -\nabla\phi/|\nabla\phi|\) and the mean curvature (sum of principal curvatures, positive for a convex domain) is \(\kappa = \nabla\cdot n\). For a signed distance function \(\kappa = -\Delta\phi\).
  • A boundary moving with outward normal speed \(v\) obeys \(\partial_t\phi = v|\nabla\phi|\). Isotropic curvature flow, \(v = -\mu\gamma\kappa\), becomes \(\partial_t\phi = \mu\gamma\,|\nabla\phi|\,\nabla\cdot(\nabla\phi/|\nabla\phi|)\), which equals \(\mu\gamma\Delta\phi\) for a signed distance function.
  • Some numerical literature uses the opposite sign of \(\phi\). Formulas taken from it must be checked for sign.

Grid and voxel convention

  • The dimensionality (2D or 3D) is set by the length of ndiv.
  • Values are stored at cell centers, \(x_i = (i + 1/2)\,h\). Boundaries taken from pixel or voxel label data lie on the faces between cells with different labels, so a cell next to a boundary normal to a grid axis gets the value \(\pm h/2\).
  • Boundary conditions are set per axis with bc_x, bc_y and bc_z. 'Periodic' wraps around. 'Mirror' reflects the field evenly about the domain face, which is a homogeneous Neumann condition (zero normal derivative).

Domains, fields and coloring

  • Every distinct label in the input to do_sdf() defines a domain, for example a grain, a particle or a free surface region.
  • Without coloring each domain has its own level set field. With coloring (use_coloring=True) domains that are not neighbors share a field, which reduces memory use. Two domains may share a field only if their distance in the neighbor graph exceeds coloring_separation. Domains touching at a corner count as neighbors. Paths through immobile domains are not counted, since every domain along an immobile surface would otherwise be within two steps of all others along it and need its own field. Mobile domains that face each other across an immobile region at less than about a band width, as on the two sides of a thin plate, count as neighbors.
  • During the evolution, topological changes can bring two domains of the same field close to each other. do_recoloring() detects such pairs and moves the smaller domain to another field before the two meet. Call it at regular intervals, for example together with do_reinitialization(). get_domain_map() prints a warning if domains sharing a field have merged.
  • Each domain carries a flag stating whether its level set is evolved (mobile) or immobile (set_domain_mobile()). Immobile and mobile domains never share a field.

Naming

  • Names of variables, functions and methods use snake case.
  • A trailing _d marks a quantity residing on the computing device (CPU or GPU).
  • Private methods and attributes start with a single underscore.

Configuration Parameters

All parameters can be given in a configuration dictionary or as keyword arguments to setup_simulation. Unknown keys are reported and ignored.

Parameter Default Description
dtime None Time step. None gives the explicit stability limit times cfl
cfl 0.5 Safety factor for the automatic time step
bc_x, bc_y, bc_z 'Periodic' Boundary condition per axis, 'Periodic' or 'Mirror'
interface_mobility 1.0 Interface mobility, a scalar, a field or a function of the two domains and the normal. A scalar zero turns off the curvature motion
interface_energy 1.0 Interface energy, a scalar, a field or a function of the two domains and the normal
anisotropy_form 'Heterogeneous' How local energies enter, 'Heterogeneous', 'Gradient' or 'Stiffness'
property_smoothing 2 Neighbor averaging passes applied to property fields after extension
curvature_form 'Full' Discretization of the curvature term, 'Full' or 'Laplacian' (see below)
update_scheme 'RK2' 'Euler', 'RK2' or 'RK3'
sdf_method 'EDT' Method used by do_sdf(), 'EDT', 'FMM', 'FSM' or 'Brute'
reinit_method 'PDE' Method used by do_reinitialization(), 'PDE', 'FSM', 'FMM' or 'Brute'
reinit_iterations None Pseudo time iterations for 'PDE'. None covers the band
use_compile False Evaluate the curvature term, the advection term and the 'PDE' reinitialization iterations with functions compiled by torch.compile (see Numerical Notes)
band_width 6.0 Band half width in grid spacings. Values outside are clamped
correction_method 'MBO' Interaction correction, 'MBO', 'Losasso', 'Lagrange' or 'Source'
source_strength 1.0 Scale of the 'Source' correction relative to \(\sqrt{\mu\gamma/\Delta t}\)
junction_weighting True Weights of the 'Source' correction near junctions from the local pair energies (needs an energy function)
junction_width None Distance in grid spacings from a junction within which the junction weights act. None uses band_width
stored_energy None Stored energy per domain as a dict of domain ID and value, see set_stored_energy()
velocity_field None Prescribed velocity that advects the mobile fields, a list of components or a function of the coordinates and time, see set_velocity_field()
advection_scheme 'WENO5Z' Discretization of the advection term, 'Upwind', 'ENO2', 'WENO5' or 'WENO5Z'
contact_condition 'Neumann' Condition where interfaces meet immobile domains, 'Neumann', 'Pinned' or 'None'
use_coloring False Group domains in shared fields
coloring_separation 2 Graph distance separation for shared fields
field_batch_size 'Auto' Number of fields processed together in a time step. 'Auto' fills about half a million grid points, None takes all at once
block_size None Edge length of the blocks to which the 'PDE' reinitialization is restricted, see Numerical Notes. None reinitializes the whole fields
device_type 'GPU' 'CPU' or 'GPU'
device_number 0 GPU number
dtype_cpu np.double Floating point type of host arrays
dtype_gpu torch.float64 Floating point type of device tensors, torch.float32 or torch.float64
verbose False Print timing and status information
torch_threads number of CPUs CPU threads used by PyTorch
torch_threads_interop number of CPUs Interop threads used by PyTorch

The Curvature Term

Isotropic curvature driven motion is governed by

\[ \partial_t\phi = \mu\gamma\,|\nabla\phi|\,\nabla\cdot\frac{\nabla\phi}{|\nabla\phi|}. \]

The parameter curvature_form selects how the right hand side is evaluated.

  • 'Full' evaluates the expression above with central differences, written as \((|\nabla\phi|^2\Delta\phi - \nabla\phi\cdot H\nabla\phi)/|\nabla\phi|^2\), where \(H\) is the Hessian of \(\phi\). It gives the correct normal velocity \(-\mu\gamma\kappa\) of every level set of \(\phi\) whether or not \(\phi\) is a signed distance function.
  • 'Laplacian' evaluates \(\mu\gamma\Delta\phi\). For a signed distance function, \(|\nabla\phi| = 1\) and the two expressions are equal (Osher and Fedkiw 2003, Bernacki et al. 2011). The Laplacian is cheaper and linear in \(\phi\), which is what semi implicit and spectral schemes need. Between reinitializations \(\phi\) drifts from a signed distance function, and the Laplacian then no longer equals the curvature term. For a shrinking circle of radius 16 grid spacings with 'PDE' reinitialization every 20 steps, the 'Laplacian' form gives an area rate 2.3 percent too high and the 'Full' form 0.2 percent. With the first order 'FSM' reinitialization the two errors are 15 and 3.4 percent.

The Time Loop

A typical loop calls do_step_update() every step and, every 10 to 20 steps, reinitializes, corrects and reinitializes again.

for step in range(1, n_steps + 1):
    sim.do_step_update()
    if step % 20 == 0:
        sim.do_reinitialization()
        sim.do_interaction_correction()
        sim.do_reinitialization()
        sim.do_recoloring()          # with coloring
        sim.do_property_update()     # with property functions or stored energy

With coloring and many domains, calling do_recoloring(reinitialize=False) before the first reinitialization saves the reinitialization of the fields that recoloring changes, since the reinitialization that follows covers all fields.

The reinitialization before the correction matters. Applied to fields that are not signed distance functions, the MBO correction gives wrong junction angles. In a T junction test with equal energies, correcting every step but reinitializing only every 20 steps left the angles near 160 degrees, while reinitializing before each correction brought them close to 120 degrees.

With the 'Source' correction, which acts within each time step, the separate correction and the first reinitialization are not needed.

sim = pylset.setup_simulation(..., correction_method='Source', interface_energy=energy_function)
for step in range(1, n_steps + 1):
    sim.do_step_update()
    if step % 20 == 0:
        sim.do_reinitialization()
        sim.do_recoloring()          # with coloring
        sim.do_property_update()     # also updates the junction weights

Interface Properties

Interface energy and mobility can be constants, fields of local values, or functions f(domain_a, domain_b, normal) of the two domains on either side of an interface and the unit normal pointing from domain_a into domain_b. A function must be symmetric, f(a, b, n) = f(b, a, -n). Domain orientations are set with set_domain_orientations() (angles in 2D, rotation matrices in 3D), and get_misorientation_angle(), get_disorientation(), get_read_shockley_energy() and get_sigmoidal_mobility() help build such functions. get_misorientation_angle() returns the disorientation angle, the smallest rotation angle among all symmetrically equivalent descriptions of the misorientation, with the crystal symmetry of both grains and the switching symmetry (exchange of the grains) taken into account. get_disorientation() also returns the disorientation axis in crystal coordinates, in the fundamental zone \(u \ge v \ge w \ge 0\) for cubic symmetry. Both were checked against a search over all 24 x 24 pairs of symmetry operators, with and without switching. Matrices must be given in the convention described next, or with convention='crystal_to_lab', since the crystal symmetry is otherwise applied on the wrong side and the angles are wrong.

In 3D, orientation matrices follow the convention of texture analysis (Bunge). A matrix \(g\) transforms lab coordinates into crystal coordinates, \(v_\text{crystal} = g\,v_\text{lab}\), so its rows are the lab axes in crystal coordinates. Matrices of rotations that take the crystal axes into the lab frame are the transposes and are accepted with set_domain_orientations(..., convention='crystal_to_lab').

Grain boundary energy models such as GB5DOF (Bulatov, Reed and Kumar 2014) for FCC and uGBE for BCC 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. get_boundary_frames(domain_a, domain_b, normal) returns these matrices at the interface points, \(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. The first row of \(P\) is then the boundary normal in the frame of the first grain. Such a model is hooked on 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')          # a vectorized implementation

sim.set_interface_energy(energy, on_device=True)

With on_device=True the function receives torch tensors on the computing device (domains as int64, normals in double precision) and returns a tensor, so that an implementation on the GPU needs no copies to the host. The function is called with all interface points at once, so it should be vectorized. A model called once per boundary point in Python is far too slow for 3D simulations, which have millions of interface points. With the scalar Python version of GB5DOF, for example, one call takes about 3 ms. In a check against that version, the coherent twin built from pyLSET orientations got the energy 0.062 J/m² for Ni, and the energies of 300 random boundaries were unchanged by a rotation of the lab frame and by swapping the two grains while reversing the normal.

do_property_update() evaluates the functions. It finds, at every grid point near an interface, the domains on either side with the neighbor identification of Hallberg and Bulatov (2019). Among the fields present at a point, the neighbor is the one whose normal is most nearly opposite to the own normal, which works unchanged at triple junctions and quadruple points. The normal passed to the functions 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. The values at the interface points are extended to the whole grid by taking the value of the nearest interface point, followed by property_smoothing passes of neighbor averaging. This is the closest point extension of Malladi, Sethian and Vemuri (1995), which keeps a value nearly constant along the normals (Sethian 1999, Chapter 11). The nearest interface points are found once per call and shared by all properties. On a GPU they are found on the device by jump flooding (Rong and Tan 2006), on a CPU by the exact distance transform of SciPy.

The parameter anisotropy_form selects how a varying energy enters the evolution.

  • 'Heterogeneous' multiplies the curvature term by the local \(\mu\gamma\). It is the simplest form, but it does not reproduce Young's law at junctions with unequal energies (Murgas et al. 2021).

  • 'Gradient' adds \(-\mu\nabla\gamma\cdot\nabla\phi\), the 'HetGrad' form of Fausty et al. (2018), which acts where the energy varies, that is near junctions. The sign is opposite to that of the variation of \(\int\gamma\,\mathrm{d}s\) with a spatially varying \(\gamma\), \(\nabla\cdot(\gamma\nabla\phi/|\nabla\phi|)|\nabla\phi| = \gamma|\nabla\phi|\nabla\cdot(\nabla\phi/|\nabla\phi|) + \nabla\gamma\cdot\nabla\phi\). Murgas et al. (2021) found that it can move boundaries in the wrong direction. With the energy field of pyLSET, which is extended from the nearest interface point, the energetic sign gave worse junction angles than the 'HetGrad' sign.

  • 'Stiffness' replaces \(\gamma\) by the interface stiffness, which gives the weighted curvature flow of inclination dependent energies, including the torque contribution (Herring 1951). In 2D the stiffness is \(\gamma + \gamma''\), where the derivative is taken with respect to the inclination angle. In 3D it is the tensor \(\boldsymbol{\Gamma} = \gamma\mathbf{P} + \nabla_{\mathbf{n}}\nabla_{\mathbf{n}}\gamma\) on the tangent plane, where \(\mathbf{P} = \mathbf{I} - \mathbf{n}\mathbf{n}\) and the Hessian is taken on the unit sphere of normals, and the normal velocity is \(\mu\boldsymbol{\Gamma}:\mathbf{K}\) with the curvature tensor \(\mathbf{K} = -\mathbf{P}(\nabla\mathbf{n})\mathbf{P} = \mathbf{P}\mathbf{H}\mathbf{P}/|\nabla\phi|\), where \(\mathbf{H}\) is the Hessian of \(\phi\). Its trace is \(-\kappa\), so that an isotropic energy, \(\boldsymbol{\Gamma} = \gamma\mathbf{P}\), gives \(-\mu\gamma\kappa\). For a smooth energy \(\boldsymbol{\Gamma}:\mathbf{K}\) equals minus the surface divergence of the Cahn–Hoffman vector \(\boldsymbol{\xi} = \gamma\mathbf{n} + \nabla_{\mathbf{n}}\gamma\) (Hoffman and Cahn 1972). The Hessian is found at the interface points by central differences of the energy function along great circles through the normal, which takes eight extra evaluations, and the six tensor components are extended to the grid like the energy. The level set equation becomes \(\phi_t = \mu\boldsymbol{\Gamma}:(\mathbf{P}\mathbf{H}\mathbf{P})\), with the Hessian \(\mathbf{H}\) of \(\phi\) and the projection \(\mathbf{P}\) evaluated from the current \(\phi\) at every step (get_stiffness_flow_term()). The tensor is formed only when the energy function reads its normal argument, and it needs seven extra grid fields, the six components and the largest eigenvalue, which sets the time step. In both 2D and 3D, stiffness values below \(0.05\gamma\), where the problem is ill posed, are reported and raised to \(0.05\gamma\).

The 3D form was checked with the cubic energy \(\gamma = 1 + \varepsilon(n_x^4 + n_y^4 + n_z^4)\) and the mobility \(\mu = \gamma\), for which a Wulff shape of size \(r\) shrinks self-similarly with \(r^2 = r_0^2 - 4t\) (its weighted mean curvature is \(2/r\) and its support function \(r\gamma\)). On a \(96^3\) grid with \(\varepsilon = 0.2\) and \(r_0 = 28\), the slope of \(r^2\) from the volume was \(-4.01\) and the support function \((\mathbf{x} - \mathbf{c})\cdot\mathbf{n}/\gamma(\mathbf{n})\) varied by 0.03 to 0.05 percent over the surface down to \(r = 14\), both with the cubic axes along the grid axes and rotated away from them. With the 'Heterogeneous' form the shape drifted 4 percent from the Wulff shape. The stiffness lowers the explicit time step, here by the ratio of the largest \(\mu\gamma\) to the largest \(\mu\lambda_{\max}\), which is 0.80, 0.69 and 0.63 for \(\varepsilon = 0.1\), 0.2 and 0.3 (the stiffness stays positive for \(\varepsilon < 1/3\)).

Junctions with unequal energies

A level set field only sees the energies of its own interfaces, so with the 'Heterogeneous' form the field of a grain at a junction does not know the energy of the opposite boundary. The MBO and Losasso projections and the 'Lagrange' correction then give angles close to those of equal energies. With the 'Source' correction, junction_weighting=True (the default) and an interface energy function, get_junction_weights() gives each of the three domains a, b and c at a junction the weight \(w_a = \bar e/e_a\), with the domain energies \(e_a = (\gamma_{ab} + \gamma_{ac} - \gamma_{bc})/2\) (Zhao et al. 1996) and their mean \(\bar e\). For a T junction this is the weight ratio \(1/(2R - 1)\) of Li and Bernacki (2025). The weights act within junction_width grid spacings (by default the band width) of the third domain and are blended to 1 further away.

The traveling T junction of Hallberg and Bulatov (2019, Fig. 4) has the analytical solution of Garcke et al. (1999). The vertical boundary has the energy \(\gamma_v\) and the two curved boundaries \(R\gamma_v\), which gives the dihedral angle \(\chi = 2\arccos(1/(2R))\) and the speed \(v = \mu R\gamma_v(\pi - \chi)/L\) for the width \(L\). The table gives, with junction weights, the angle between the boundary tangents extrapolated to the junction and the angle \(\chi_v = \pi - vL/(\mu R\gamma_v)\) from the measured junction speed, for widths of 64 grid points (example 02) and 128 grid points.

\(R\) exact \(\chi\) tangents, L = 64 \(\chi_v\), L = 64 \(\chi_v\), L = 128
0.6 67.1 61.4 61.7 58.2
0.75 96.4 94.6 94.8 94.7
1 120.0 119.8 119.7 119.8
1.5 141.1 140.7 140.6 140.6
2 151.0 150.5 150.4 150.3
3 160.8 160.2 160.1 160.1
5 168.5 168.2 168.2 168.0

Without junction weights, the 'Heterogeneous' form gave about 120 degrees for all \(R\) with either the MBO or the 'Source' correction, and speeds wrong by the corresponding factor (0.55 for \(R = 0.6\), 3.1 for \(R = 3\)). The 'Gradient' form with MBO gave 97.6 degrees for \(R = 0.6\) and 149.7 degrees for \(R = 2\) at L = 64, but for larger \(R\) it overshoots. The junction moved at 64 percent of the exact speed for \(R = 3\) and stopped for \(R = 5\).

The same test in 3D, extruded along a periodic z axis and with the energies set through Read–Shockley functions of the misorientations between grain orientations, gave \(\chi_v\) = 140.9, 150.7 and 160.4 degrees for \(R\) = 1.5, 2 and 3 at L = 64 (exact 141.1, 151.0 and 160.8), with junction speeds within 0.3, 1.2 and 2.2 percent of the exact values. Spheres shrinking with Read–Shockley energies of 0.52, 0.87 and 1 followed \(R^2 = R_0^2 - 4\mu\gamma t\) to within 0.13 percent. With junction weights, the deviations do not decrease with resolution. They are within 2 degrees for \(R \ge 0.75\) and grow close to wetting (\(R \to 1/2\)). For \(R = 0.6\), doubling source_strength brought the junction speed from 5 to 2 percent above the exact value, while four times the default destabilized the junction. Within a grid spacing or two of a junction the level sets do not form a sharp corner, and the junction point lies a fraction of a grid spacing (0.1 to 0.9 grid spacings in the test) from the intersection of the boundary tangents. Angles measured on a small circle around the junction point found from the level sets are therefore biased by an amount that decreases with the radius of the circle. Example 02 measures the angle from the boundary tangents extrapolated to the junction instead.

Two further tests use junctions that are not straight lines. A lens shaped grain C between grains A and B, with \(\gamma_{AB} = 0.52\) and \(\gamma_{AC} = \gamma_{BC} = 1\), has the angle \(2\arccos(\gamma_{AB}/2) = 149.9\) degrees inside the lens at its rim. The lens starts with an angle of 120 degrees and shrinks. The angle was measured from boundary tangents fitted 3 to 12 grid spacings from the junction and extrapolated to it, in 8 planes through the lens axis in 3D. After the initial transient, the angle was 148.1 to 148.4 degrees on a \(256^3\) grid while the lens volume fell from 700000 to 270000 grid cells, and at most 144.7 degrees on a \(128^3\) grid. In 2D the lens gave 147.8 degrees on a \(256^2\) grid and about 145 degrees on a \(128^2\) grid. With all energies equal the same measurement gave 118.5 degrees at \(128^3\) and 118.6 degrees at \(128^2\) in place of 120, so part of the deviation comes from the measurement. Without junction weights the 2D lens gave 118 degrees. When the lens becomes small compared with the measurement window, the measured angle decreases, to 145.3 degrees at \(256^3\) when 5 percent of the volume remained.

In a polycrystal with two grain types A and B, boundaries between grains of the same type have the energy 0.6 and boundaries between types the energy 1. Young's law then gives 145.1 degrees in the odd grain at AAB and ABB triple lines, 107.5 degrees in the other two grains and 120 degrees at AAA and BBB lines. With 300 grains on a \(96^3\) grid, the angles were measured at \(t = 40\) (295 grains left, mean grain diameter about 18 grid spacings) in the plane normal to each triple line. For each line point, the boundary points within a slab one grid spacing thick on either side of that plane and 2 to 9 grid spacings from the line were fitted by a parabola for each of the three boundaries, and the tangents of the parabolas at the line give the angles, as in example 02. Points within 4 grid spacings of quadruple points were left out. On the 3D lens above at \(128^3\), this measurement gave 146.4 degrees in a window of 2 to 9 grid spacings and 144.7 degrees in a window of 3 to 12 grid spacings, the same as the slices through the axis. The table gives the median angles in degrees, with about 1500 to 6500 values in each group and quartiles 4 to 6 degrees from the medians.

energies and weights AAA and BBB (exact 120) odd grain (exact 145.1) other two grains (exact 107.5)
all equal, with weights 119.8 120.5 119.8
0.6 and 1, with weights 120.0 142.6 108.8
0.6 and 1, without weights 120.0 120.8 119.6

Without junction weights the unequal energies do not change the angles. With weights the median angles come within 2.5 degrees of Young's law, about 90 percent of the way from 120 degrees, at a resolution where the lens deviated by 5 degrees. A window of 3 to 12 grid spacings gave 140.4 degrees in the odd grain with quartiles twice as far apart, since it reaches two thirds of the grain diameter. The mean directions of the boundary points 2 to 6 grid spacings from the line, without a fit, gave 137.3 degrees in the polycrystal and 137 degrees on the lens, so such a measurement reads about 8 degrees low at these junctions while it gives 120 degrees with equal energies.

Stored energy

A difference in stored energy across an interface, for example from dislocations in deformed grains, adds a driving force. With stored energies \(E\) set per domain by set_stored_energy() (a dict of domain ID and value), the normal velocity of the interface of domain a against domain b, positive when a grows, is

\[V = \mu\left(-\gamma\kappa + E_b - E_a\right),\]

where \(\kappa\) is the curvature defined above, positive for a convex domain, so that a convex domain shrinks. A domain thus grows into neighbors with a higher stored energy. Stored energy is energy per volume, in units of interface energy per length. Each mobile field gets the term \(V_E|\nabla\phi|\) with the stored energy part \(V_E = \mu(E_b - E_a)\), discretized with Godunov upwinding (Osher and Fedkiw 2003, Section 6.2). The automatic time step adds the rate \(\max|V_E|/h\) to the curvature limit.

do_property_update() finds the two domains at each interface point with the neighbor identification above and extends the difference \(E_b - E_a\) and the field of b to the grid by the nearest interface point. The field that holds the domain at a point then moves with \(\mu(E_b - E_a)\) and the field across the interface with the opposite value. Fields that are neither, near junctions, move with \(\mu(E - E_k)\), where \(E\) is the stored energy of the domain at the point and \(E_k\) that of the field, if the field holds a single domain. Interfaces against immobile domains do not get a stored energy force. Call set_stored_energy() again to change values during a run.

In tests against exact solutions, a flat boundary moves at the speed \(\mu\Delta E\) to within 0.1 percent with both the MBO and the 'Source' correction. A circle of radius \(R\) follows \(\mathrm{d}R/\mathrm{d}t = \mu(\Delta E - \gamma/R)\) to within 0.25 grid spacings, growing above the critical radius \(\gamma/\Delta E\) and shrinking below it.

Advection by a Prescribed Velocity

A velocity field \(\mathbf{u}(\mathbf{x},t)\) set by set_velocity_field() (or the config key velocity_field) carries all mobile fields, which then follow

\[\phi_t + \mathbf{u}\cdot\nabla\phi = R,\]

where \(R\) holds the curvature, stored energy and correction terms. Immobile fields are not moved. The velocity is a list of components, each a number or an array that broadcasts to the grid, or a function u(x, y, t) (u(x, y, z, t) in 3D) of the time and of the cell center coordinates, which it receives as torch tensors on the device that broadcast against each other. A function is evaluated at the stage times of the update scheme, and its values are kept for the stages of a step. With interface_mobility=0 the interfaces only move with the flow, and the curvature term is skipped.

The term \(\mathbf{u}\cdot\nabla\phi\) is discretized along each axis with the one sided difference on the upwind side of the local velocity component (Osher and Fedkiw 2003, Chapter 3). advection_scheme selects first order differences ('Upwind'), second order ENO ('ENO2', Osher and Shu 1991) or fifth order WENO with the weights of Jiang and Peng (2000) ('WENO5') or of Borges et al. (2008) ('WENO5Z', the default). The 'WENO5Z' weights, used for Hamilton–Jacobi equations by Kim, Ri and Han (2025), add the stencil weights \(d_k(1 + \tau/(\epsilon + \beta_k))\) with \(\tau = |\beta_0 - \beta_2|\) in place of \(d_k/(\epsilon + \beta_k)^2\), which leans less on the smoothest stencil near kinks and is less dissipative everywhere. The advection term then costs 8 to 13 percent more without compilation and the same with it, while 'WENO5' needs a grid about 1.45 times finer for the same shape error of the Zalesak disc. Each one sided difference is written as a central difference minus a correction, \(u\,\partial_x\phi \approx u\,C - |u|\,\Phi\), so that the backward and forward differences share their arithmetic and only \(\Phi\) depends on the sign of \(u\). The ghost cells follow the boundary conditions. Mirror boundaries reflect the fields, which is consistent only where the normal velocity vanishes at the boundary, so interfaces should otherwise stay away from mirror boundaries. The automatic time step adds the rate \(\sum_k \max|u_k|/h_k\) at the current time. On smooth fields the errors of the schemes decrease at close to first, second and fifth order with the grid spacing, and the error of 'WENO5Z' is about 3 times smaller than that of 'WENO5'.

Example 03 and the tests reproduce the standard advection tests, measured as in Enright et al. (2002) by the change of the area (volume in 3D) and by the shape error \(E = L^{-1}\int|H(\phi_\text{exact}) - H(\phi)|\,\mathrm{d}A\), with \(L\) the length (area) of the exact interface. The runs use 'RK3' and a Courant number of 0.5. The last column gives the values of Enright et al. for WENO5 with reinitialization after every step.

Test Grid Scheme Reinitialization Area change \(E\) Enright et al.
Zalesak disc, one revolution 100^2 'WENO5' never -0.9 % 0.13 +5.3 %, 0.61
100^2 'WENO5Z' never -1.0 % 0.086
100^2 'WENO5' every 20 steps +1.7 % 0.27
100^2 'WENO5' every step +0.4 % 0.87
200^2 'WENO5' never -0.02 % 0.033
200^2 'WENO5Z' never +0.02 % 0.018
200^2 'WENO5' every 5 steps -0.3 % 0.09 -0.5 %, 0.08
200^2 'WENO5' every step -0.7 % 0.25
400^2 'WENO5' never +0.02 % 0.011
400^2 'WENO5Z' never 0.00 % 0.0059
800^2 'WENO5' never +0.005 % 0.0034
800^2 'WENO5Z' never +0.001 % 0.0018
Single vortex, T = 8 128^2 'WENO5' never -32 % 0.024 -40 %
128^2 'WENO5Z' never -17 % 0.013
128^2 'WENO5' every 20 steps -37 % 0.028
128^2 'WENO5Z' every 20 steps -25 % 0.019
256^2 'WENO5' every 20 steps -5.6 % 0.0043 -10 %, 0.008
256^2 'WENO5Z' every 20 steps -4.1 % 0.0031
3D deformation, T = 3 100^3 'WENO5' never -35 % 0.017 -80 %
100^3 'WENO5' every 20 steps -37 % 0.019
200^3 'WENO5' never -15 % 0.0074
200^3 'WENO5' every 20 steps -10 % 0.0052

Without reinitialization, the shape error of the Zalesak disc falls by a factor of about 3 per refinement of the grid, and the slot corners are sharp to within about two grid spacings on every grid. 'WENO5Z' roughly halves the shape error at the same cost. Each reinitialization rounds sharp corners a little, so in a rigid motion, where the fields stay signed distance functions, it is best left out or done rarely. In flows that stretch the fields, such as the vortex, an occasional reinitialization keeps the gradients bounded. The losses in the vortex and the deformation tests come from filaments thinner than the grid spacing, which a level set cannot hold. Methods that conserve the area, such as particle level sets (Enright et al. 2002), are not part of pyLSET, since grain volumes are not conserved in grain growth.

Scalar Fields

A scalar field, such as a temperature or a concentration, lives on the same grid as the level sets. add_scalar_field() creates a setup_field object (module pylset_field), which follows

\[c\,\frac{\partial u}{\partial t} = \nabla\cdot(k\nabla u) + Q,\]

with the capacity \(c\), the conductivity \(k\) and the volumetric source \(Q\). Each can be a number or an array on the grid. The capacity and the conductivity can also be functions of the field, f(u), evaluated at the start of each update, and the source a function of the coordinates and the time, f(x, y, t) or f(x, y, z, t). A field keeps its own time, and do_field_update() advances every field in one step to the time of the level sets, so it can be called every step or every few steps. A 'Steady' field is also solved at the first call, at the start of a run.

T = sim.add_scalar_field('T', value=1.0, conductivity=50.0)
T.set_bc('x-', 'Dirichlet', 1.2)                  # fixed temperature
T.set_bc('x+', 'Robin', 1.0, coefficient=0.5)     # convection to a fluid at 1.0
while sim.get_time() < t_end:
    sim.do_step_update()
    if sim.get_step() % 20 == 0:
        sim.do_reinitialization()
        sim.do_field_update()

The equation is discretized by finite volumes on the cell centered grid. The conductivity at a face between two cells is the harmonic mean of the cell values, which keeps the flux continuous where \(k\) jumps, so a layered slab gives the exact piecewise linear profile. Each face of the domain ('x-', 'x+', 'y-', 'y+', 'z-', 'z+') has its own condition, set with set_bc(). Axes that are periodic for the level sets are periodic for the field, and the faces of the other axes are insulated until set otherwise.

  • 'Dirichlet' fixes the field on the face. The flux into the boundary cell is \(2k(g - u_0)/h\) across the half cell.
  • 'Neumann' prescribes the flux into the domain, zero for an insulated face.
  • 'Robin' gives the flux \(\alpha(g - u_\mathrm{b})\) into the domain, with the transfer coefficient \(\alpha\) and the face value \(u_\mathrm{b}\), for example convection to a fluid at the temperature \(g\). In series with the half cell this is the flux \((g - u_0)/(1/\alpha + h/(2k))\).
  • 'Radiation' gives the flux \(s(g^4 - u_\mathrm{b}^4)\) into the domain, radiation exchange with surroundings at the temperature \(g\), where the coefficient \(s\) is the emissivity times the Stefan–Boltzmann constant in the units of the field. The field must then be an absolute temperature, with \(u_\mathrm{b} \ge 0\).

Values and coefficients can be numbers, arrays over the face or functions of the time.

The 'Radiation' condition is nonlinear. In each solve, the face value \(u_\mathrm{b}\) that balances the radiation and the conduction across the half cell, \(2k(u_0 - u_\mathrm{b})/h = s(u_\mathrm{b}^4 - g^4)\), is found per face cell by Newton iterations, which converge from \(\max(u_0, g)\) since the residual is convex and increasing. The radiation is then linearized at \(u_\mathrm{b}\) as a 'Robin' condition with the coefficient \(\alpha = 4su_\mathrm{b}^3\) and the value \((g^4 + 3u_\mathrm{b}^4)/(4u_\mathrm{b}^3)\), which keeps the matrix symmetric and positive definite, and the linear solve is repeated from the new field until the largest change is below ten times tolerance relative to the largest value. These are Newton iterations for the whole system, which converged in 3 to 5 solves per step in the tests and in about 8 solves for a 'Steady' field from a uniform zero start. With 'Crank-Nicolson', the old half of the step uses the exact radiation flux of the old field. 'Explicit' takes the exact flux of each substep, with the stability limit of the start of the step. get_solver_info() reports the number of solves as 'newton_iterations'.

Besides the volumetric source \(Q\) of add_scalar_field(), which may also read the field as f(x, y, t, u) (taken at the start of each step), add_source() places localized sources at rest or moving, for example a laser or electron beam.

path = [[0.0, 10.0, 32.0], [50.0, 118.0, 32.0]]      # rows (t, x, y), interpolated linearly
T.add_source(power=2.0, radius=4.0, path=path, profile='Gaussian', time=(0.0, 50.0))

The total power (a number or a function of time) is distributed as \(Q \propto \exp(-2r^2/w^2)\) with the 1/e\(^2\) radius \(w\), as is usual for beams, or uniformly over a disc or sphere of radius \(w\) with an edge smoothed over one grid spacing ('Uniform'). The discrete profile is normalized so that the deposited power is exact on any grid, and the part of a source outside a nonperiodic face is lost. In each update a source is averaged over the step, with the center sampled along the path at intervals of at most \(w/2\), so a source that moves many grid spacings in one step leaves a continuous track rather than separate spots. The sources are evaluated in a box around their path in the step. A path is either an array of rows \((t, x, y)\) or \((t, x, y, z)\), constant before the first and after the last row, or a function of time, and time gives the interval in which the source is active.

The deposited energy matched the integral of the power to rounding with all time schemes, for a source at rest and a moving source with a power that changed in time and an active interval. A source crossing 32 grid spacings in one step without conduction left 75.0 percent of its energy in the central 24 grid spacings of its track, as for a uniform track. A continuous Gaussian source with \(w = 8\) grid spacings in 3D raised the center value to within 0.5 percent of \(P/(c(2\pi)^{3/2}D)\,(1/\sigma - (\sigma^2 + 2Dt)^{-1/2})\), with \(\sigma = w/2\) and the diffusivity \(D = k/c\).

Immobile domains can take part in the field problem in two ways, set per domain with set_domain_condition().

T.set_domain_condition(5, 'Material', conductivity=40.0, capacity=2.0)   # an inclusion with its own properties
T.set_domain_condition(6, 'Dirichlet', 1.2)                              # a surface held at 1.2
T.set_domain_condition(7, 'Robin', 1.0, coefficient=0.5)                 # a surface exchanging heat with 1.0
T.set_domain_condition(8, 'Radiation', 1.0, coefficient=0.1)             # a free surface radiating to 1.0
  • 'Material' keeps the domain in the problem with its own capacity, conductivity and source. They are blended with the surrounding values by the smoothed Heaviside function of the domain over one grid spacing, and the harmonic face conductivity then keeps the flux continuous across the surface. A circular inclusion with four times the conductivity of its surroundings carried a gradient 3.1 percent above the exact \(2/(1 + 4)\) of the applied gradient on a \(128^2\) grid and 2.2 percent above on a \(256^2\) grid, partly from the finite domain, and a source and capacity in an inclusion kept the energy balance.
  • 'Dirichlet', 'Neumann', 'Robin' and 'Radiation' remove the domain from the problem and act on its surface, the zero contour of its level set, with a value or flux that can depend on time. The faces between remaining and removed cells are cut. For 'Dirichlet', the surface value enters through the distance \(\theta h\) from the remaining cell center to the surface, found from the level set, as the conductance \(k/(\theta h^2)\) (Gibou et al. 2002), which keeps the matrix symmetric and gives second order accuracy. \(\theta\) is kept above 0.01. For 'Robin', the transfer coefficient acts in series with the same distance, 'Radiation' is linearized as described for the faces, with the conductance \(k/(\theta h)\) from the cell center to the surface, and for 'Neumann' the flux enters the remaining cell. For these three, each cut face along axis \(a\) is weighted by the normal component \(|n_a|\) of the surface, so that the cut faces sum to the true surface area, \(\sum_a n_a^2 = 1\). The removed cells of 'Dirichlet' domains are set to the surface value, and those of the other removed domains to the value of the nearest remaining cell after each update, so that functions of the field, such as an Arrhenius mobility, stay finite there. In an annulus between a disc held at 1 and an outer region held at 2, the error of \(u = 1 + B\ln(r/R_1)\) was \(1.1\cdot 10^{-3}\), \(3.1\cdot 10^{-4}\) and \(1.0\cdot 10^{-4}\) on grids of \(64^2\), \(128^2\) and \(256^2\), and with a 'Robin' outer region it decreased at first order, from \(3.1\cdot 10^{-3}\) to \(7.8\cdot 10^{-4}\). The energy given by a 'Neumann' surface of a disc was within 0.9 and 0.6 percent of the exact value on \(128^2\) and \(256^2\) grids. A uniform source in a periodic box, removed by a disc of radius \(R\) radiating to 1, gave a steady field within 0.24 and 0.09 percent of the temperature \(T_\mathrm{s}\) of the energy balance \(2\pi R\, s(T_\mathrm{s}^4 - 1) = Q(1 - \pi R^2)\) on \(64^2\) and \(128^2\) grids, with a conductivity high enough for the field to be nearly uniform. The level sets must be signed distance functions near the surfaces, since a level set built from voxel labels has its zero contour on the cell faces and reduces the accuracy to first order. With such a level set, the energy given by the 'Neumann' disc was 5.2 and 5.3 percent too high on \(128^2\) and \(256^2\) grids. do_surface_sdf() gives the signed distance to a surface read from a file, see Geometry from Surface Files. The multigrid preconditioner needed 13 to 21 iterations in these tests.

time_scheme selects the integration. 'Implicit' (backward Euler, the default) and 'Crank-Nicolson' solve \(c(u^{n+1} - u^n)/\Delta t = \theta(Lu^{n+1} + b^{n+1}) + (1 - \theta)(Lu^n + b^n)\) with \(\theta = 1\) or \(1/2\), where \(L\) is the discrete operator and \(b\) holds the source and the boundary values, evaluated at \(t + \theta\Delta t\). The matrix is symmetric and positive definite and is never formed. It is solved by preconditioned conjugate gradients (Saad 2003, Chapter 9), from the previous field, to the relative residual tolerance. 'Explicit' takes forward Euler substeps within the stability limit \(\Delta t \le\) cfl \(\min(c)/\max(d)\), where \(d\) is the diagonal of \(-L\), and 'Steady' solves \(Lu + b = 0\), which needs at least one 'Dirichlet', 'Robin' or 'Radiation' face or removed domain.

The default preconditioner='Multigrid' applies one geometric multigrid V-cycle per iteration (Trottenberg, Oosterlee and Schüller 2001). The grid is halved along every axis with an even number of cells of at least 4, until the coarsest grid has at most 512 cells, which is solved by a Cholesky factorization, or no axis can be halved further, in which case 40 Jacobi sweeps replace the coarse solve. The coarse operators are discretized again on each grid, with the face conductances averaged over the fine faces of a coarse face, the capacity term and the cell conductivities averaged over the fine cells, and the boundary conductances evaluated with the coarse spacing. Corrections are interpolated linearly between cell centers, with the weights ¾ and ¼ along each axis, and residuals are restricted with the transpose of the interpolation divided by \(2^d\). Two weighted Jacobi sweeps with the weight \(2d/(2d + 1)\) before and after the coarse correction keep the V-cycle symmetric, as conjugate gradients require. preconditioner='Jacobi' uses the diagonal alone, which needs no extra memory but takes a number of iterations that grows roughly with \(\sqrt{k\Delta t/(ch^2)}\). The grid sizes should have a factor \(2^m\) with \(m \ge 3\) along every axis for the V-cycle to work well.

On slabs, linear profiles were exact to rounding with every kind of face condition, the steady profile with a uniform source converged at second order, and a decaying sine mode gave first order errors in time with 'Implicit' and much smaller errors with 'Crank-Nicolson'. A Gaussian pulse in a periodic box kept its integral and its variance grew as \(2kt/c\) per axis. A steady slab between a fixed value and a 'Radiation' face gave the exact linear profile, and a slab cooling by radiation from both faces with a high conductivity followed \(u = (u_0^{-3} + 3sAt/(cV))^{-1/3}\) with first order errors in time for 'Implicit' and second order errors for 'Crank-Nicolson'. The table gives one implicit step on a \(256^3\) grid on a GPU, with a 'Dirichlet' and a 'Robin' face, a tolerance of \(10^{-8}\) in double precision and \(10^{-5}\) in single precision, and either a uniform conductivity or 200 grains with conductivities spread by a factor 10.

\(k\Delta t/(ch^2)\) Multigrid, uniform \(k\), double Multigrid, uniform \(k\), single Multigrid, grains, double Jacobi, grains, double
10 7 iterations, 0.8 s 4 iterations, 0.2 s 8 iterations, 0.8 s 134 iterations, 2.5 s
100 11 iterations, 1.1 s 6 iterations, 0.3 s 13 iterations, 1.3 s 412 iterations, 7.6 s
1000 14 iterations, 1.4 s 10 iterations, 0.5 s 19 iterations, 1.9 s 1090 iterations, 20 s

The peak memory was 1.9 GiB in double precision with either preconditioner, about 15 fields of the grid size, since the coarse grids add about a seventh of the fine grid.

Interface properties that depend on a field

The interface mobility and energy can depend on a scalar field in two ways.

set_field_dependence(field, mobility=f, energy=g) multiplies the mobility and the energy set by set_interface_mobility() and set_interface_energy(), whether numbers, arrays or functions of the domains and the normal, by the factors \(f(u)\) and \(g(u)\) at every grid point. The factors are functions of the field tensor on the device, for example an Arrhenius mobility,

T = sim.add_scalar_field('T', value=0.9, conductivity=50.0)
sim.set_interface_mobility(lambda a, b, n: mobility_prefactor(a, b))
sim.set_field_dependence('T', mobility=lambda T: torch.exp(-Q_act / T))

with the activation energy Q_act divided by the gas constant, in the units of the field. pyLSET keeps the properties without the factors and applies the factors again after do_field_update(), after do_property_update() and when a property is set, so the automatic time step follows the largest product of mobility and energy. A factor on the energy also scales the stiffness of the 'Stiffness' form. Since the factors do not depend on the domains or on the normal, they cancel in the junction weights.

For a dependence that differs between interfaces, for example a temperature dependent anisotropy, a property function can take the field values at the interface points as a fourth argument, set_interface_energy(lambda a, b, n, T: ..., field='T'). The function is then evaluated at every interface point, also when it does not read the normal, and do_property_update() has to be called after the field changes.

Three tests check the coupling. With a field rising as \(u = 1 + 0.02t\) and the mobility factor \(u\), a circle followed \(R^2 = R_0^2 - 2\gamma(t + 0.01t^2)\), with the fitted coefficients within 0.2 percent of the exact values, and the time step fell as \(1/u\). An energy factor and an energy function of the field both gave the shrinkage rate of the corresponding constant energy within 0.2 percent. A flat boundary driven by stored energy in the steady field \(u = 1 + x/32\), with the mobility factor \(u\), moved as \(\mathrm{d}x/\mathrm{d}t = \mu\Delta E(1 + x/32)\).

Interaction Corrections

  • 'MBO' and 'Losasso' are projections applied by do_interaction_correction(). They give the same zero contours.
  • 'Lagrange' adds \(-\mu\lambda(\sum_j H(\phi_j) - 1)\) to the evolution of every field, with one global multiplier \(\lambda\) evaluated from the previous step (Zhao et al. 1996, Hallberg and Bulatov 2019). A single multiplier leaves small voids at junctions.
  • 'Source' adds \(-w_i\Lambda(\sum_j H(\phi_j) - 1)\) with \(\Lambda\) = source_strength \(\sqrt{\mu\gamma/\Delta t}\) (Li and Bernacki 2025, 2026). The weights \(w_i\) are 1 by default. Per domain weights can be set with set_domain_source_weights(). With junction_weighting=True and an interface energy function, the weights near junctions follow from the local pair energies, see below. Both kinds of weights multiply.

With 'Lagrange' and 'Source', do_interaction_correction() only reports voids and overlaps.

Immobile Domains and Contact

Domains given with immobile_ids in do_sdf(), or flagged with set_domain_mobile(), keep their level sets unchanged. With contact_condition='Neumann', every mobile level set is extended into the immobile domains constant along the normal of the immobile surface before each time step. This is a homogeneous Neumann condition, \(\partial\phi/\partial n = 0\) at the immobile surface. 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. A grain boundary inclined at 59 degrees to an immobile substrate turned to 89 degrees at the contact in a test, against 79 degrees without the condition.

With contact_condition='Pinned', the mobile level sets inside immobile domains are held at fixed values, which is a Dirichlet condition, so the lines where interfaces meet immobile surfaces do not move. This is the boundary condition of the triangular triple junction test of Fausty et al. (2018) and Murgas et al. (2021), and it gives a minimum energy state for any interface energies. The fixed values are taken from the fields when the condition first acts after set_phi(). To pin interfaces at chosen positions, continue the mobile domains into the immobile domains with pinned_labels in do_sdf(), for example

grains = ...                                    # partition of the whole grid into mobile domains
labels = np.where(wall, 99, grains)             # the wall is an immobile domain
sim = setup_simulation(..., contact_condition='Pinned')
sim.set_phi(sim.do_sdf(labels, immobile_ids=[99], pinned_labels=grains))

The time step leaves the pinned values unchanged, and do_reinitialization() and do_interaction_correction() restore them. In tests, a curved boundary pinned at two walls relaxed to the straight segment between its ends within 0.06 grid spacings, and a straight boundary inclined to the walls stayed in place, where the 'Neumann' condition turned it to 90 degrees.

Geometry from Surface Files

A domain given by voxel labels has its boundary on the cell faces. For immobile domains with a condition of a scalar field on their surface, and for comparisons with a known shape, the level set should instead be the signed distance to the true surface. load_surface() reads a surface as line segments in 2D or triangles in 3D, and do_surface_sdf() computes the signed distance to it on the grid. The result is given to do_sdf() through exact_sdf, together with labels that agree with its sign.

V, C = sim.load_surface('part.step', scale=0.1, offset=[32.0, 32.0, 10.0])   # millimeters to grid units
sdf = sim.do_surface_sdf(V, C)
labels = np.where(sdf > 0, 99, grains)
sim.set_phi(sim.do_sdf(labels, immobile_ids=[99], exact_sdf={99: sdf}))

load_surface() reads STL files (3D only), VTK polygon data (.vtp) and Gmsh meshes (.msh) directly. Gmsh geometry and CAD files (.geo, .step, .stp, .iges, .igs, .brep) are first meshed by Gmsh, by default with elements the size of a grid spacing. The physical groups of Gmsh files are selected with group, so that one file can define several domains. Analytic distances, for example of a disc or a cylinder, can also be given to exact_sdf.

do_surface_sdf() first splits the cells until no edge is longer than the smallest grid spacing, segments evenly and triangles at their longest edge. For each piece, the exact distance to the segment or triangle is computed at all grid points in a box around it that reaches the band width, and the smallest value is kept at each grid point. Beyond the band the value is clamped. The inside follows from the crossings of the surface with the grid lines along each axis, as the stretches between the first and second crossing, the third and fourth and so on. In 3D the lines are moved by about \(10^{-7}\) grid spacings, so that they never pass exactly through an edge or a vertex, and in 2D a crossing at a shared end point is counted once. The orientation of the cells is therefore not used. The inside is the majority over the axes, and a surface that is not closed gives a warning. Periodic axes wrap the surface around.

The distance is exact to rounding for a surface of flat pieces, for example \(10^{-15}\) for a cube whose edges lie on grid lines. For a curved surface it differs from the true distance by the distance between the surface and its segments or triangles. A sphere of radius 45 meshed by Gmsh as 60 thousand triangles took 13 s on four CPU threads on a \(128^3\) grid with the default band of 6 grid spacings, and a sphere of 240 thousand triangles took 3.6 s on a GPU on a \(256^3\) grid. For the disc with a 'Neumann' surface of the section on scalar fields, the energy was 0.86 and 0.61 percent too high on \(128^2\) and \(256^2\) grids with the distance from do_surface_sdf(), the same as with the analytic distance, and 5.2 and 5.3 percent too high with the level set built from labels.

VTK Output

  • write_vtk_image() writes grid data as VTK image data (.vti). This format stores only the origin, spacing and dimensions of the grid, not the coordinates of every point, which makes it the most compact VTK format for uniform Cartesian grids. Values are written at the cell centers. Files are compressed with zlib.
  • write_vtk_interfaces() writes the zero contours of all level set fields as polylines (2D) or triangulated surfaces (3D) in VTK polydata format (.vtp), with the field index and domain ID of each element. This is the way to show interfaces in ParaView. The maximum over all fields (get_phi_max()) is positive almost everywhere and only touches zero at interfaces, so contouring it at zero does not work.
  • mesh_domain() meshes the interior of one, several or all domains with triangles (2D) or tetrahedra (3D) by Gmsh (optional extra mesh). The boundary of each domain is its zero contour from marching squares or cubes, and the elements grow from the boundary towards the inside of the domain (size_growth, size_max). Every element carries its domain ID. Domains are meshed separately, so small gaps remain where zero contours do not meet, mainly at junctions, and domains are closed by the grid boundary. surface_step samples the fields every few grid points for a coarser mesh of large 3D data, and n_workers meshes domains in parallel processes. write_vtk_mesh() writes the mesh as a VTK unstructured grid (.vtu) with the cell arrays 'domain_id' and 'mobile'. In ParaView, a Threshold filter on 'domain_id' shows a selected set of domains.
mesh = sim.mesh_domain(surface_step=2, n_workers=8)   # all domains
sim.write_vtk_mesh('grains', mesh)

For smooth surfaces in images, keep surface_step=1 and let ParaView compute point normals of the extracted surface (Extract Surface followed by Surface Normals, with a feature angle of about 50 degrees so that edges at junction lines stay sharp). With surface_step=2 and flat shading, the facets of the marching cubes surface show. In 2D, the mesh boundaries are the zero contours and can be drawn as thin lines between domains of similar color.

In tests, the area of a meshed disc of radius 15 grid spacings was within 0.5 percent of the exact value, and the volumes of meshed 3D Voronoi grains were within 5 percent of their voxel counts, with gaps of less than 3 percent of the volume.

  • write_vtk_collection() writes a ParaView collection file (.pvd) that groups VTK files of several output times into a time series.
  • get_domain_map() gives -1 at points where no level set is positive (voids).

HDF5 Files and Restarts

save_hdf5() writes the state of a simulation to an HDF5 file (format version 1.1.0), with the groups /meta (format version and time stamp), /simulation (configuration, time, step and the multiplier of the 'Lagrange' correction), /grid (domain size, grid points, spacing and boundary conditions), /domains (domain IDs, field of each domain, mobile flags, the initial domain map domain_map0, the domain map found last domain_map_last and, if set, the stored energies, orientations and source weights of the domains), /state (level set fields), /scalar_fields (value, time and time scheme of each scalar field), /fields (additional arrays given as fields) and /user (numbers, strings and arrays given as user_data). Arrays are compressed with gzip by default. domain_map_last is the reference that get_domain_map() and do_recoloring() use to tell apart the domains that share a field. save_hdf5() does not compute a new domain map, since that would change this reference and make a run with checkpoints differ from one without, so a current domain map for post-processing is best saved in fields.

load_hdf5() returns the content of a file as a nested dictionary and leaves the simulation unchanged, so any simulation object can read any file. With restore=True, the state is restored into the simulation, which must have the grid of the file, and the run can be continued.

sim = make_simulation()                                  # grid, configuration and property functions
sim.load_hdf5('checkpoint_00400.h5', restore=True)       # domains, level sets, time, step, orientations ...
while sim.get_step() < 1200:
    sim.do_step_update()

Settings given as functions are code and are not saved: property functions, velocity fields, field dependences and the properties, conditions and sources of scalar fields. The continuing script sets them again, before or after the restore. Scalar fields that exist in the simulation get the values and times of the file, and a field that does not exist is created with default properties and insulated faces.

The restored simulation evaluates the interface properties at its first step. A run continued from a checkpoint written directly after do_property_update() is therefore identical to the uninterrupted run, which was verified to the last bit for a colored polycrystal with an orientation dependent energy, stored energies and a scalar field with a source (test_hdf5_restart), and in ex05_hdf5.ipynb. From a checkpoint between two property updates, 34 of 16384 grid points of the domain map differed after 110 further steps, with a median difference of the level sets of 0.0065 near the interfaces, as expected from evaluating the properties at a different step. A run that never calls do_property_update() keeps the properties of its first step, while a restored run evaluates them at the checkpoint. The files hold host arrays, so a run can be continued on another device or in another precision, with results that then agree to rounding.

Files of format version 1.0.0 (pyLSET 0.0.1) can be read. They hold no domain maps and no per domain data, and they can be restored only when every level set field holds one domain.

Numerical Notes

  • Reinitialization moves the interface slightly. An explicit time step moves an interface by only about \(\Delta t\,\mu\gamma\kappa \approx 0.1\,h^2\kappa\), so even a small shift per reinitialization changes the effective mobility if the fields are reinitialized every step. The 'PDE' method is second order with subcell resolution (du Chéné, Min and Gibou 2008). It moves the zero contour of a circle of radius 16 grid spacings by about \(10^{-4}h\) per call. Reinitializing every step then gives a shrinking circle area rate within 2 percent of the exact value, and reinitializing every 20 steps within 0.2 percent.

  • Interaction correction needs signed distance functions. The MBO correction gives the correct 120 degree junctions only if all fields are signed distance functions when it is applied (Esedoglu, Ruuth and Tsai 2010).

  • First order distance methods. 'FSM' and 'FMM' build the first band next to the interface by linear interpolation, which limits their accuracy near the interface.

  • Cost of the 'PDE' reinitialization. Each call iterates until the band is covered, 28 pseudo time steps in 2D and 40 in 3D with the default band. The early stop rarely triggers in a running simulation, because the clamped values at the edge of the band are smoothed by the time steps and have to be rebuilt. The iteration works on a copy of the fields with two ghost layers per side, so that neighbor values are views, and keeps the subcell interface distances only at the grid links that the interface crosses. Fields are reinitialized together in groups of at most about 4 million grid points, which needs about 10 grid arrays of transient memory per field in the group. With use_compile=True, each iteration runs as one compiled function. For the fields of a Voronoi polycrystal in double precision, one do_reinitialization() call took 0.72, 0.26 and 0.07 seconds before these changes, after them and with compilation (2D, 512 x 512, 13 fields, GPU), and 25, 9.0 and 3.0 seconds (3D, 128^3, 37 fields, GPU). The first compiled call takes 10 to 40 seconds to compile, and a C++ compiler is needed on a CPU. Every grid shape, grid spacing and advection scheme gets its own compiled version, so pyLSET raises the limit of torch on the number of versions of a function from 8 to 64. Beyond the limit torch would run the function uncompiled without notice.

  • Cost and memory of a time step. The curvature term is evaluated from one copy of the fields padded by one ghost layer, so that the neighbor values, including the diagonal ones of the mixed derivatives, are views. It is computed in slabs of about 260 000 grid points along the first axis, and the Runge–Kutta stages are formed in place. A time step then needs about 4 grid arrays of temporary memory per field in a batch in 3D and 5 in 2D, and field_batch_size='Auto' keeps batches to about half a million grid points. The slabs also made a step 25 to 30 percent faster on a GPU (128^3 and 256^3) and 25 percent faster on a CPU (96^3) than without them, when the term needed 11 grid arrays in 3D and 9 in 2D. With use_compile=True, the curvature term is a compiled function that needs about 2 grid arrays per field. For a 3D polycrystal at 128^3 with 37 fields on a GPU in double precision, a time step took 0.49 seconds with 144 grid arrays of temporary memory before these changes, 0.39 seconds with 11 arrays after them, and 0.075 seconds with 3 arrays with compilation.

  • Cost and memory of the advection term. The term is evaluated from one copy of the fields padded by the ghost width of the scheme (1, 2 or 3 layers). Without compilation it is computed one axis at a time in slabs along another axis, with in place operations. With use_compile=True it is one compiled function. Both need about 2 grid arrays of temporary memory per field in a batch. On a GPU at 256^3, 'WENO5' took about 2.5 times as long as the curvature term without compilation and about as long with it.

  • Cost and memory of the property update. The neighbor identification treats one field at a time, so its memory grows with the number of interface points and not with the number of fields, and it samples the domain map on the device. The nearest interface points are found by jump flooding with steps \(2^m, \ldots, 2, 1\) taken along one axis at a time, followed by one pass over all neighbors at distance one. Periodic axes wrap exactly. Against the exact transform, the chosen point was farther away than the nearest one at 0.2 percent of the points or fewer, by at most 0.3 grid spacings. Most remaining differences to the CPU result are ties between points at the same distance. For a 3D polycrystal at 256^3 with 40 fields in single precision on a GPU, do_property_update() with energy, mobility and stored energy took 5.6 seconds and 1.1 GB of device memory on top of the fields, against 18.8 seconds and 6.1 GB before these changes.

  • Interface functions. An energy or mobility function that never reads its normal argument (checked in its bytecode) is evaluated once for each pair of domains and not at every point near an interface, which matters for functions of the misorientation.

  • Reinitialization restricted to blocks. With block_size set (for example 8), do_reinitialization() with the 'PDE' method splits the fields into blocks and iterates only the blocks within two grid points of a value inside the band, as one batch whose ghost cells are filled from the neighboring blocks after every iteration. Blocks elsewhere hold the clamped values and do not change. Inside the band, more than two grid points from its edge, the result equals that of the whole fields to rounding. On a GPU in single precision at 256^3 with 40 fields, one call took 3.7 seconds on the whole fields, 5.3 seconds with blocks when 32 percent of them were active (grains of about 20 grid points) and 2.4 seconds when 13 percent were active (grains of about 40 grid points). When more than a fifth of the blocks are active, the whole fields are therefore iterated instead. On a CPU the blocks were not faster.