Skip to content

API reference

Everything listed here is importable from the top-level package (import nanofoams), except where a module path is shown.

Generating foams

generate

generate(params: FoamParameters | None = None, *, backend: str = DEFAULT_BACKEND, backend_options: dict | None = None, **kwargs) -> Foam

Build the lattice, evaluate the random field and classify every atom.

Pass either a FoamParameters or its fields as keyword arguments::

foam = generate(lattice="bcc", lattice_parameter=3.303, cells=100,
                solid_fraction=0.3, h2=54, seed=42)

With ligament_diameter=... instead of h2, H^2 is chosen as in FoamParameters.from_ligament_diameter.

All backends give the same result up to floating-point rounding; see nanofoams.backends for their cost. backend_options are passed to the backend (e.g. {"batch_size": 4096}).

FoamParameters dataclass

FoamParameters(lattice: LatticeKind, lattice_parameter: float, cells: int, solid_fraction: float, h2: int, n_waves: int = 10000, seed: int | None = None, period_cells: int | None = None)

Everything needed to generate one foam, reproducibly.

The simulation box is a cube of cells unit cells per side. The random field is periodic with period period_cells unit cells (by default the whole box), which must divide cells so the box itself is periodic.

Parameters:

Name Type Description Default
lattice LatticeKind

Crystal lattice, "sc", "bcc" or "fcc".

required
lattice_parameter float

Lattice constant (any length unit, used consistently).

required
cells int

Unit cells per box side.

required
solid_fraction float

Target solid volume fraction phi_B in (0, 1).

required
h2 int

Squared norm H^2 = h^2 + k^2 + l^2 of the Miller indices of the wave vectors; sets the length scale (q0 = 2 pi H / period).

required
n_waves int

Requested number of waves N. It is rounded down to a multiple of the number of directions (as in the legacy code).

10000
seed int | None

Seed for the random phases. If None, a fresh seed is drawn and stored, so the result can always be reproduced from the parameters.

None
period_cells int | None

Period of the field in unit cells (default: cells).

None

period property

period: float

Period a of the random field (the constant a of the thesis).

effective_n_waves property

effective_n_waves: int

Number of waves actually summed (n_waves rounded down).

xi property

xi: float

Level-cut threshold, xi = sqrt(2) erfinv(2 phi_B - 1).

q0 property

q0: float

Wave number |q| = 2 pi H / a.

ligament_diameter property

ligament_diameter: float

Predicted mean ligament diameter (Soyarslan fit).

from_ligament_diameter classmethod

from_ligament_diameter(ligament_diameter: float, *, lattice: LatticeKind, lattice_parameter: float, cells: int, solid_fraction: float, n_waves: int = 10000, seed: int | None = None, period_cells: int | None = None, min_directions: int = 48, h2_max: int | None = None) -> FoamParameters

Choose h2 from a target mean ligament diameter (legacy workflow).

The achieved diameter is available as ligament_diameter.

Foam dataclass

Foam(params: FoamParameters, field: GaussianRandomField, positions: ndarray, f: ndarray, types: ndarray)

A generated sample: every lattice site, its field value and its phase.

solid_positions property

solid_positions: ndarray

Positions of the solid atoms only (what is simulated in MD).

morphology property

morphology: Morphology

Analytical predictions for these parameters (see morphology).

write_lammps_data

write_lammps_data(path: str | PathLike, *, solid_only: bool = True, masses: Sequence[float] | None = None, precision: int = 6) -> None

LAMMPS read_data file. By default only the solid atoms, as type 1.

With solid_only=False every site is written with type 1 (solid) or 2 (pore); masses then needs two entries.

write_lammps_dump

write_lammps_dump(path: str | PathLike, *, solid_only: bool = False, precision: int = 6) -> None

Legacy-style dump (id type x y z f); all atoms by default.

Random field

GaussianRandomField dataclass

GaussianRandomField(directions: ndarray, phases: ndarray, period: float)

f(x) = sqrt(2/N) sum_i cos(q_i . x + phi_i) with periodic q_i.

Parameters:

Name Type Description Default
directions ndarray

(n_dir, 3) integer Miller indices (h, k, l).

required
phases ndarray

(n_dir, waves_per_direction) phases; phases[d, k] goes with directions[d]. N = phases.size.

required
period float

Period a; wave vectors are 2 pi / a * (h, k, l).

required

from_parameters classmethod

from_parameters(params: FoamParameters) -> GaussianRandomField

Deterministic directions for params.h2 and phases drawn from numpy.random.default_rng(params.seed), uniform in [-pi, pi).

__call__

__call__(points: ndarray, *, backend: str = 'direct', **options) -> np.ndarray

Evaluate f at points (shape (n, 3)).

on_lattice

on_lattice(kind: LatticeKind, lattice_parameter: float, cells: int, *, backend: str = DEFAULT_BACKEND, **options) -> np.ndarray

Evaluate f on every site of nanofoams.lattice_points.

Same order as lattice_points(kind, lattice_parameter, cells). Backends with an evaluate_lattice (fft, cupy) use the exact FFT path; others evaluate point by point.

classify

classify(f: ndarray, xi: float) -> np.ndarray

Solid (SOLID) where f < xi, pore (PORE) otherwise.

SOLID module-attribute

SOLID = 1

PORE module-attribute

PORE = 2

Directions and length scale

miller_indices

miller_indices(h2: int) -> np.ndarray

All integer vectors with h^2 + k^2 + l^2 == h2, one per {q, -q} pair.

Returns a read-only (n_directions, 3) int array in a fixed order.

Raises:

Type Description
ValueError

if h2 is not a positive integer or is not a sum of three squares (h2 = 4^a (8b + 7), Legendre's three-square theorem).

n_directions

n_directions(h2: int) -> int

Number of independent directions for h2 (0 if none exist).

valid_h2

valid_h2(h2_max: int, min_directions: int = 1) -> np.ndarray

All H^2 in [1, h2_max] with at least min_directions directions.

This replaces the legacy H2_database.txt file.

suggest_h2

suggest_h2(ligament_diameter: float, period: float, solid_fraction: float, *, min_directions: int = 48, h2_max: int | None = None) -> int

H^2 whose predicted ligament diameter is closest to the requested one.

Candidates are restricted to H^2 with at least min_directions directions (fewer directions give visibly anisotropic structures; see thesis Sec. 4.4). The legacy code used min_directions=48 and h2_max=500.

ligament_diameter

ligament_diameter(period: float, h2: int, solid_fraction: float) -> float

Mean ligament diameter predicted by the Soyarslan fit.

Lattices

lattice_points

lattice_points(kind: LatticeKind, lattice_parameter: float, cells: int) -> np.ndarray

Positions of a cells^3 block of unit cells, shape (n_atoms, 3).

All coordinates lie in [0, cells * lattice_parameter), so the block tiles the periodic box without overlaps or gaps.

Morphology

predict

predict(params: FoamParameters) -> Morphology

Analytical morphology for a set of parameters.

Morphology dataclass

Morphology(solid_fraction: float, xi: float, q0: float, ligament_diameter: float, ligament_spacing: float, surface_density: float, solid_surface_density: float, mean_curvature: float, gaussian_curvature: float, genus_density: float, scaled_genus_density: float, reduced_genus_density: float, genus_per_ligament_volume: float)

Predicted morphology. Lengths use the units of the lattice parameter.

PERCOLATION_THRESHOLD module-attribute

PERCOLATION_THRESHOLD = 0.159

measure

measure(field: GaussianRandomField, xi: float, *, resolution: int = 96) -> MeasuredMorphology

Measure the solid fraction and interface area of the level cut f = xi.

Choose resolution so that one wavelength 2 pi / q0 spans at least ~10 grid points, i.e. resolution >= 10 * sqrt(h2).

MeasuredMorphology dataclass

MeasuredMorphology(solid_fraction: float, surface_density: float, resolution: int)

Diagnostics and configuration

check

check(params: FoamParameters, *, target_ligament_diameter: float | None = None) -> list[Diagnostic]

Return the warnings that apply to params (empty if none).

Diagnostic dataclass

Diagnostic(code: str, message: str)

load_config

load_config(path: str | PathLike) -> FoamConfig

Read a .toml config or a .json run log.

FoamConfig dataclass

FoamConfig(params: FoamParameters, target_ligament_diameter: float | None = None)

convert_legacy

convert_legacy(path: str | PathLike) -> tuple[dict[str, Any], list[str]]

Translate a legacy positional input file into a config mapping.

Returns the mapping and a list of notes on approximations made. The H^2 selection reproduces the legacy database (min_directions=48, h2_max=499).

LAMMPS files

lammps

LAMMPS file formats.

  • data file (read_data): the input for an MD simulation. By default only the solid atoms are written, as a single atom type.
  • dump file (ITEM: format): what the legacy scripts wrote, with every atom, its phase as the type and the field value f. OVITO reads it directly.

Both assume an orthogonal box [0, L)^3 with periodic boundaries.

write_data

write_data(path: PathLike, positions: ndarray, box_length: float, *, types: ndarray | None = None, masses: Sequence[float] | None = None, comment: str = '', precision: int = 6) -> None

Write a LAMMPS data file with atom_style atomic.

Parameters:

Name Type Description Default
types ndarray | None

Per-atom types (1-based). Defaults to all 1.

None
masses Sequence[float] | None

Optional mass per type, written in a Masses section.

None

write_dump

write_dump(path: PathLike, positions: ndarray, box_length: float, *, types: ndarray, f: ndarray | None = None, timestep: int = 0, precision: int = 6) -> None

Write a LAMMPS text dump (id type x y z [f]), legacy-compatible.

read_data

read_data(path: PathLike) -> dict[str, np.ndarray | float | int]

Minimal reader for data files written by write_data.

read_dump

read_dump(path: PathLike) -> dict[str, np.ndarray | float]

Read a single-frame text dump written by write_dump or the legacy scripts. Returns the columns by name plus box_length.

Backends

backends

Interchangeable evaluators of the random field.

Every backend exposes evaluate(points, wavevectors, phases, **options) and returns f at each point as a float64 NumPy array. Backends that can exploit lattice structure also expose evaluate_lattice(directions, phases, basis, period_cells, cells).

============= ====== =================================== ================= name device algorithm cost ============= ====== =================================== ================= direct CPU thesis formula, term by term atoms * N collapsed CPU exact phase collapse atoms * n_dir fft CPU inverse FFT on the lattice p^3 log p cupy GPU collapse / FFT on CUDA via CuPy as above ============= ====== =================================== =================

BACKENDS module-attribute

BACKENDS: dict[str, str] = {'direct': '.numpy_direct', 'collapsed': '.numpy_collapsed', 'fft': '.numpy_fft', 'cupy': '.cupy_gpu'}

DEFAULT_BACKEND module-attribute

DEFAULT_BACKEND = 'fft'

get_backend

get_backend(name: str) -> ModuleType