Skip to content

Class pypfc

pyPFC logo

Bases: setup_io

This is the primary class for conducting PFC simulations, providing complete functionality for time evolution, energy evaluation, and phase field analysis. It combines all inherited capabilities from the class hierarchy:

  • Grid setup and domain discretization (pypfc_grid)
  • Mathematical operations and device management (pypfc_base)
  • Density field generation and crystal structures (pypfc_pre)
  • File I/O operations and data export (pypfc_io)

The class uses a configuration-driven approach where all simulation parameters are managed through a DEFAULTS dictionary. User configurations merge with defaults, to provide parameter handling with fallback values.

Notes

All grid divisions (ndiv) must be even numbers for FFT compatibility. The class automatically validates configuration parameters and provides informative error messages for invalid inputs.

Functions

__init__

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

Initialize PFC simulation with domain parameters and configuration.

Sets up the complete simulation environment including grid discretization, device configuration, and all numerical parameters needed for PFC evolution.

Parameters:

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

Physical size of simulation domain [Lx, Ly, Lz] in lattice parameter units. This defines the spatial extent of the simulation box.

required
ndiv array_like of int, shape (3,)

Number of grid divisions [nx, ny, nz]. All values must be even numbers for FFT compatibility. If not provided, automatically calculated as domain_size / alat * 8 (8 points per lattice spacing).

None
config dict

Configuration parameters as key-value pairs. See the pyPFC overview for a complete list of the configuration parameters.

None
**kwargs dict

Individual configuration parameters passed as keyword arguments. These will override any corresponding values in the config dictionary.

{}

Raises:

Type Description
ValueError

If any element in ndiv is not an even number.

Examples:

>>> # Basic simulation setup
>>> sim = setup_simulation([10.0, 10.0, 10.0])
>>> # Custom grid and parameters using config dictionary
>>> config = {'dtime': 5e-5, 'struct': 'BCC', 'verbose': True}
>>> sim = setup_simulation([8.0, 8.0, 8.0], ndiv=[64, 64, 64], config=config)
>>> # Using individual keyword arguments
>>> sim = setup_simulation([8.0, 8.0, 8.0], pf_iso_level=0.5, dtime=1e-4, verbose=True)
>>> # Mixing config dictionary and keyword arguments (kwargs take precedence)
>>> sim = setup_simulation([8.0, 8.0, 8.0], config=config, pf_iso_level=0.3)

cleanup

cleanup() -> None

Clean up allocated tensors and free device memory.

Explicitly deletes PyTorch tensors to free GPU/CPU memory. This is particularly important for GPU simulations to prevent memory leaks and ensure proper resource management.

Notes

This method should be called at the end of simulations, especially when running multiple simulations sequentially or when GPU memory is limited. The method automatically detects which tensors exist based on the update scheme and cleans up accordingly.

do_step_update

do_step_update() -> None

Update the PFC density field using the selected time integration scheme.

Performs one time step of the PFC evolution equation using the time integration method specified by _update_scheme. The method operates in Fourier space for computational efficiency and automatically handles the FFT/iFFT transformations.

Returns:

Name Type Description
f_den_d Tensor

Updated density field in Fourier space. The real-space density field is automatically updated in self._den_d via inverse FFT.

Raises:

Type Description
ValueError

If the specified update_scheme is not supported.

Notes

This method uses precomputed linear terms for efficiency. The appropriate update method is selected based on self._update_scheme and called with the corresponding precomputed Fourier-space operators.

evaluate_energy

evaluate_energy() -> float

Evaluate the PFC energy.

Computes the total free energy of the system using the phase field crystal energy functional.

Returns:

Name Type Description
ene Tensor

Energy field with shape [nx, ny, nz].

eneAv float

Average free energy density.

Notes

Energy is computed in Fourier space for efficiency and transformed back to real space for local energy density visualization.

get_C2_d

get_C2_d() -> torch.Tensor

Get the current two-point correlation function.

Returns:

Type Description
Tensor

Two-point correlation function in Fourier space.

get_alat

get_alat() -> float

Get the current lattice parameter.

Returns:

Type Description
float

Current lattice parameter value.

get_alpha

get_alpha() -> np.ndarray

Get the current alpha parameters.

Returns:

Type Description
float

Current alpha parameter values.

get_density

get_density() -> np.ndarray

Get the PFC density field and its mean value.

Returns the current density field and its spatial average, transferring data from GPU to CPU if necessary.

Returns:

Name Type Description
den ndarray of float, shape (nx,ny,nz)

Density field on CPU.

mean_den float

Spatially averaged density.

get_dtime

get_dtime() -> float

Get the current time step size.

Returns:

Type Description
float

Current time step size for integration.

get_energy

get_energy() -> np.ndarray

Get the PFC energy field and its mean value.

Computes the local energy density field and its spatial average using the current density field configuration.

Returns:

Name Type Description
ene ndarray of float, shape (nx,ny,nz)

Local energy density field on CPU.

mean_ene float

Spatially averaged energy density.

get_phase_field

get_phase_field() -> Union[np.ndarray, List[np.ndarray]]

Evaluate phase field using wavelet filtering.

Computes the phase field by applying wavelet convolution followed by Gaussian smoothing. The phase field identifies crystalline regions and their orientations within the PFC density field.

Returns:

Name Type Description
pf ndarray of float, shape (nx,ny,nz) or list of such arrays

Phase field(s) on CPU. Returns a single array for isotropic kernels or a list of arrays for directional analysis with multiple kernels.

Notes

The method automatically handles both single and multiple wavelet kernels for comprehensive grain orientation analysis.

get_update_scheme

get_update_scheme() -> str

Establish the PFC time integration scheme and return method handle.

Configures the selected time integration scheme and returns a function handle to the appropriate update method. This method sets up scheme-specific parameters and precomputed terms for efficient time stepping.

Returns:

Name Type Description
update_density callable

Function handle to the selected time integration method.

Raises:

Type Description
ValueError

If alpha, beta, gamma parameters are not provided for '2nd_order' scheme.

ValueError

If f_denOld_d is not provided for '2nd_order' scheme.

ValueError

If the specified update_scheme is not supported.

Notes

The method automatically precomputes linear terms in Fourier space to optimize performance during time stepping. Different schemes require different numbers of precomputed terms and have varying stability properties and computational costs.

get_update_scheme_params

get_update_scheme_params() -> np.ndarray

Get the current integration scheme parameters.

Returns:

Type Description
array_like

Current parameters for the time integration scheme.

set_C2_d

set_C2_d(C2_d: Tensor) -> None

Set the two-point correlation function in Fourier space.

Parameters:

Name Type Description Default
C2_d Tensor

Two-point correlation function tensor in Fourier space. Must match the grid dimensions and be on the correct device.

required

set_H2

set_H2(H0: float, Rot: ndarray) -> None

Set the directional correlation kernel for extended PFC models.

Configures the H2 kernel used in extended phase field crystal models to introduce directional correlations.

Parameters:

Name Type Description Default
H0 float

Amplitude of the directional correlation kernel.

required
Rot array_like or None

Rotation matrix for orienting the kernel. If None, uses identity orientation.

required

set_alat

set_alat(alat: float) -> None

Set the lattice parameter.

Parameters:

Name Type Description Default
alat float

Lattice parameter.

required

set_alpha

set_alpha(alpha: Union[List[float], ndarray]) -> None

Set the alpha parameters, controlling the widths of the Gaussian peaks of the pair correlation function.

Parameters:

Name Type Description Default
alpha float

Pair correlation peak widths.

required

set_density

set_density(density: ndarray) -> None

Set the PFC density field.

Updates the density field and automatically computes its Fourier transform for subsequent calculations.

Parameters:

Name Type Description Default
density ndarray of float, shape (nx,ny,nz)

New density field configuration.

required

set_dtime

set_dtime(dtime: float) -> None

Set the time step.

Parameters:

Name Type Description Default
dtime float

Time step size. Must be positive and small enough for stability.

required

set_phase_field_kernel

set_phase_field_kernel(
    H0: float = 1.0,
    Rot: Optional[Union[ndarray, List[ndarray]]] = None,
) -> None

Set phase field kernel for directional analysis.

Configures the correlation kernel used for phase field evaluation, allowing for directional filtering or isotropic analysis.

Parameters:

Name Type Description Default
H0 float

Kernel amplitude.

1.0
Rot ndarray of float, shape (3,3)

Rotation matrix for directional kernel. If None, uses isotropic two-point correlation function.

None

set_phase_field_smoothing_kernel

set_phase_field_smoothing_kernel(
    pf_gauss_var: Optional[float] = None,
) -> None

Set phase field smoothing kernel.

Configures Gaussian smoothing parameters for phase field calculations.

Parameters:

Name Type Description Default
pf_gauss_var float

Gaussian variance for smoothing kernel. If None, uses current value.

None

set_update_scheme

set_update_scheme(update_scheme: str) -> None

Set the time integration scheme for density evolution.

Parameters:

Name Type Description Default
update_scheme str

Time integration method. Options: '1st_order', '2nd_order', 'exponential'.

required

set_update_scheme_params

set_update_scheme_params(
    params: Union[List[float], ndarray],
) -> None

Set parameters for the time integration scheme.

Parameters:

Name Type Description Default
params array_like

Parameters specific to the chosen integration scheme. Format depends on the selected scheme type.

required