Skip to content

Class pypfc_io

pyPFC logo

Bases: setup_pre

I/O operations for Phase Field Crystal simulation data.

This class provides comprehensive file I/O functionality for PFC simulations including:

  • Extended XYZ format for atomic positions and properties
  • VTK output for visualization in ParaView/VisIt
  • Binary pickle serialization for Python objects
  • Structured grid data export for continuous fields
  • Point data export for atomic/particle systems
  • Simulation metadata and setup information files

The class supports both text and binary formats, with optional compression for large datasets. All methods are designed to handle typical PFC simulation outputs including atomic positions, density fields, energy fields and phase field data.

Notes

The extended XYZ format follows the convention used in molecular dynamics and materials simulation communities, allowing storage of arbitrary per-atom properties alongside coordinates. VTK output enables direct visualization in scientific visualization software.

Methods:

__init__

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

Initialize I/O handler with domain parameters and device configuration.

Parameters:

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

Physical size of the simulation domain [Lx, Ly, Lz] in lattice parameter units.

required
ndiv ndarray of int, shape (3,)

Number of grid divisions [nx, ny, nz]. Must be even numbers for FFT compatibility.

required
config dict

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

required

append_to_info_file

append_to_info_file(
    info: Union[str, List[str]],
    filename: str = "pypfc_simulation.txt",
    output_path: Optional[str] = None,
) -> None

Append information to a text file.

Adds new content to an existing text file, useful for logging simulation progress or adding additional information to setup files.

Parameters:

Name Type Description Default
info str or list of str

String or list of strings to append to the file.

required
filename str

Name of the output file.

'pypfc_simulation.txt'
output_path str

Path to the output directory. Uses the current working directory as default.

None

load_hdf5

load_hdf5(filename: str) -> Dict[str, Any]

Load pyPFC data from a single HDF5 file.

Parameters:

Name Type Description Default
filename str

Input filename with or without .h5 extension.

required

Returns:

Name Type Description
data dict

Dictionary containing root_attrs and group dictionaries for meta, simulation, grid, fields, atoms, diagnostics and user (when present). Supported Python None, list/tuple and dtype values written by save_hdf5 are restored to their original types. fields contains field_data (stacked along axis 0) and matching field_labels. Legacy named field datasets are converted to this representation when loaded. atoms contains coords, atom_data and atom_data_labels when present; legacy coord datasets are returned as coords.

load_pickle

load_pickle(filename: str, ndata: int) -> List[Any]

Load data objects from a binary pickle file.

Deserializes Python objects from a pickle file created with save_pickle. Reads a specified number of objects from the binary file.

Parameters:

Name Type Description Default
filename str

Path to input pickle file (without .pickle extension).

required
ndata int

Number of data objects to read from the file.

required

Returns:

Name Type Description
data list

List of Python objects loaded from filename.pickle.

Warning

Only load pickle files from trusted sources, as they can execute arbitrary code during deserialization.

read_extended_xyz

read_extended_xyz(
    filename: str, nfields: int = 0
) -> Tuple[
    np.ndarray, List[float], float, List[np.ndarray]
]

Read PFC data from extended XYZ format file.

Reads atomic positions and associated properties from an extended XYZ file, which may be compressed with gzip. Automatically detects file format and handles both .xyz and .xyz.gz extensions.

Parameters:

Name Type Description Default
filename str

Name of input XYZ file (with or without .xyz/.xyz.gz extension).

required
nfields int

Number of data fields per atom beyond coordinates [x,y,z].

0

Returns:

Name Type Description
coord ndarray of float, shape (natoms, 3)

Atomic coordinates.

domain_size ndarray of float, shape (3,)

Domain size [Lx, Ly, Lz] from file header.

time float

Simulation time from file header.

partDen ndarray of float, shape (natoms,)

Particle density values (if available).

partEne ndarray of float, shape (natoms,)

Particle energy values (if available).

partPf ndarray of float, shape (natoms,)

Particle phase field values (if available).

save_hdf5

save_hdf5(
    filename: str,
    meta: Optional[Dict[str, Any]] = None,
    simulation: Optional[Dict[str, Any]] = None,
    grid: Optional[Dict[str, Any]] = None,
    fields: Optional[Dict[str, Any]] = None,
    atoms: Optional[Dict[str, Any]] = None,
    diagnostics: Optional[Dict[str, Any]] = None,
    user_data: Optional[Dict[str, Any]] = None,
    compression: Optional[str] = "gzip",
    compression_level: int = 4,
    schema_version: str = "1.0.0",
) -> None

Save pyPFC data to a single HDF5 file.

The file uses a structured layout with top-level groups: meta, simulation, grid, fields, atoms, diagnostics and user.

Parameters:

Name Type Description Default
filename str

Output filename with or without .h5 extension.

required
meta dict

Metadata dictionary stored under /meta.

None
simulation dict

Simulation parameters stored under /simulation. Defaults to the configuration used to initialize this simulation.

None
grid dict

Grid data stored under /grid. If None, defaults to current domain_size, ndiv and ddiv.

None
fields dict

Mapping of field labels to equally shaped arrays. The arrays are stacked along a leading axis and stored as /fields/field_data; labels are stored in matching order as /fields/field_labels.

None
atoms dict

Discrete atom data. Recognized keys are coords with shape (n_atoms, 3), atom_data with shape (n_atoms, n_features), and atom_data_labels with length n_features. These are stored under /atoms using the same dataset names.

None
diagnostics dict

Diagnostics stored under /diagnostics.

None
user_data dict

User-defined data stored under /user.

None
compression (gzip, lzf, None)

Dataset compression algorithm for non-scalar arrays.

'gzip'
compression_level int

Compression level for gzip (0-9).

4
schema_version str

HDF5 schema version written as root attribute.

'1.0.0'
Python
required
are
required

save_pickle

save_pickle(filename: str, data: List[Any]) -> None

Save data objects to a binary pickle file.

Serializes a list of Python objects to a binary pickle file for efficient storage and later retrieval. This is useful for saving simulation state, configuration parameters or processed results.

Parameters:

Name Type Description Default
filename str

Path to the output file (without .pickle extension).

required
data list

List of Python objects to serialize and save.

required
Notes

The output file will be named filename.pickle. Pickle files are Python-specific binary format that preserves object structure and types.

Warning

Only load pickle files from trusted sources, as they can execute arbitrary code during deserialization.

write_extended_xyz

write_extended_xyz(
    filename: str,
    coord: ndarray,
    atom_data: List[ndarray],
    atom_data_labels: List[str],
    simulation_time: float = 0.0,
    gz: bool = True,
) -> None

Save PFC atomic data in extended XYZ format.

Writes atomic positions and associated properties to an extended XYZ file, which is a standard format in molecular dynamics and materials simulation. The format includes atomic coordinates plus arbitrary per-atom properties such as density, energy, phase field values, etc.

Parameters:

Name Type Description Default
filename str

Base name of the output XYZ file (without extension).

required
coord ndarray of float, shape (natoms, 3)

Atomic coordinates [x, y, z] for each atom.

required
atom_data list of ndarray

List of arrays containing per-atom data. Each array must have shape (natoms,) and represent a property for each atom.

required
atom_data_labels list of str

Labels for each data array in atom_data. Must have same length as atom_data list.

required
simulation_time float

Simulation time to include in file header.

0.0
gz bool

If True, compress output using gzip.

True
Notes

The output file will be named filename.xyz or filename.xyz.gz if compression is enabled. The extended XYZ format includes a header with the number of atoms, simulation time, and property labels, followed by atomic coordinates and properties.

Examples:

>>> write_extended_xyz('output', coord, [density, energy], 
...                   ['density', 'energy'], simulation_time=100.0)

write_info_file

write_info_file(
    filename: str = "pypfc_simulation.txt",
    output_path: Optional[str] = None,
) -> None

Write simulation setup information to a file.

Creates a text file containing simulation parameters, grid configuration, and other setup information for documentation and reproducibility.

Parameters:

Name Type Description Default
filename str

Name of the output file.

'pypfc_simulation.txt'
output_path str

Path to the output directory. Uses the current working directory as default.

None

write_vtk_points

write_vtk_points(
    filename: str,
    coord: ndarray,
    scalar_data: List[ndarray],
    scalar_data_name: List[str],
    vector_data: Optional[List[ndarray]] = None,
    vector_data_name: Optional[List[str]] = None,
    tensor_data: Optional[List[ndarray]] = None,
    tensor_data_name: Optional[List[str]] = None,
) -> None

Save 3D point data to VTK file for visualization.

Exports atomic positions and associated scalar, vector and tensor data to a VTK (Visualization Toolkit) file in binary XML format. This format is compatible with ParaView, VisIt and other scientific visualization software.

Parameters:

Name Type Description Default
filename str

Output file name (with or without .vtu extension).

required
coord ndarray of float, shape (natoms, 3)

3D coordinates of points/atoms.

required
scalar_data list of ndarray

List of scalar data arrays. Each array should have shape (natoms,).

required
scalar_data_name list of str

Names/labels for each scalar data array. Must match length of scalarData.

required
vector_data list of ndarray

List of vector data arrays. Each array should have shape (natoms, 3).

None
vector_data_name list of str

Names/labels for each vector data array. Required if vectorData is provided.

None
tensor_data list of ndarray

List of tensor data arrays. Each array should have shape (natoms, 3, 3). Tensors are automatically reshaped to VTK format (natoms, 9).

None
tensor_data_name list of str

Names/labels for each tensor data array. Required if tensorData is provided.

None
Notes

Tensor data is reshaped from (3,3) matrices to 9-component vectors following VTK convention:

\[T = \begin{bmatrix} T_{11} & T_{12} & T_{13} \\ T_{21} & T_{22} & T_{23} \\ T_{31} & T_{32} & T_{33} \end{bmatrix}\]

becomes: \([T_{11}, T_{12}, T_{13}, T_{21}, T_{22}, T_{23}, T_{31}, T_{32}, T_{33}]\)

write_vtk_structured_grid

write_vtk_structured_grid(
    filename: str,
    array_data: List[ndarray],
    array_name: List[str],
) -> None

Save 3D field data to VTK structured grid file.

Exports 3D field data (such as density, energy, or phase fields) to a VTK structured grid file in binary XML format. This format is ideal for visualizing continuous field data in ParaView, VisIt and other scientific visualization software.

Parameters:

Name Type Description Default
filename str

Output file name (with or without .vts extension).

required
array_data list of ndarray

List of 3D numpy arrays containing field data. Each array should have shape (nx, ny, nz) matching the simulation grid.

required
array_name list of str

Names/labels for each data array. Must match length of arrayData.

required
Notes

The output file will be named filename.vts and uses VTK's structured grid format with binary encoding for efficient storage. The grid dimensions and spacing are automatically determined from the inherited grid setup.