Skip to content

Runtime, components, and databases

Physical constants

torch_flash.constants

Physical constants used throughout :mod:torch_flash.

R module-attribute

R = 8.31446261815324

Exact molar gas constant in J/(mol K), CODATA 2018.

STANDARD_PRESSURE module-attribute

STANDARD_PRESSURE = 100000.0

Package standard pressure in Pa (1 bar).

Runtime configuration

torch_flash.config

Process-wide runtime configuration for native torch-flash models.

The configuration is intentionally read when model or data tensors are constructed, not inside thermodynamic kernels. Existing model instances are therefore unaffected by later configuration changes and hot-path calls do not pay for repeated policy lookups.

RuntimeConfig dataclass

RuntimeConfig(
    device: device,
    dtype: dtype,
    num_threads: int,
    num_interop_threads: int,
    deterministic: bool,
    deterministic_warn_only: bool,
)

Immutable snapshot of torch-flash's tensor and execution policy.

Parameters:

Name Type Description Default
device device

Device used by named model, component, standard-state, and characterization factories when no explicit device is supplied.

required
dtype dtype

Floating-point dtype used by those factories. Float64 is the scientific default; float32 is available for explicit lower-precision studies.

required
num_threads int

Current PyTorch CPU intra-operation thread count.

required
num_interop_threads int

Current PyTorch CPU inter-operation thread count.

required
deterministic bool

Whether PyTorch deterministic algorithms are enabled.

required
deterministic_warn_only bool

Whether unavailable deterministic algorithms warn instead of raising.

required

accelerated property

accelerated: bool

Report whether the configured default device is an accelerator.

Returns:

Type Description
bool

True for CUDA, XPU, or MPS devices and False for CPU.

tensor_options property

tensor_options: dict[str, dtype | device]

Return configured tensor-factory keyword arguments.

Returns:

Type Description
dict

Mapping containing dtype and device.

tensor

tensor(
    data: Any,
    *,
    dtype: dtype | None = None,
    device: device | str | None = None,
    requires_grad: bool = False,
) -> Tensor

Construct a copied tensor using this runtime policy.

Parameters:

Name Type Description Default
data Any

Any value accepted by :func:torch.tensor.

required
dtype dtype | None

Per-call overrides for configured defaults.

None
device dtype | None

Per-call overrides for configured defaults.

None
requires_grad bool

Whether autograd records operations on the new tensor.

False

Returns:

Type Description
Tensor

Newly allocated tensor.

Source code in src/torch_flash/config.py
def tensor(
    self,
    data: Any,
    *,
    dtype: torch.dtype | None = None,
    device: torch.device | str | None = None,
    requires_grad: bool = False,
) -> Tensor:
    """Construct a copied tensor using this runtime policy.

    Parameters
    ----------
    data
        Any value accepted by :func:`torch.tensor`.
    dtype, device
        Per-call overrides for configured defaults.
    requires_grad
        Whether autograd records operations on the new tensor.

    Returns
    -------
    Tensor
        Newly allocated tensor.
    """
    return torch.tensor(
        data,
        dtype=self.dtype if dtype is None else dtype,
        device=self.device if device is None else device,
        requires_grad=requires_grad,
    )

as_tensor

as_tensor(
    data: Any,
    *,
    dtype: dtype | None = None,
    device: device | str | None = None,
) -> Tensor

Convert data using this runtime policy without unnecessary copies.

Parameters:

Name Type Description Default
data Any

Any value accepted by :func:torch.as_tensor.

required
dtype dtype | None

Per-call overrides for configured defaults.

None
device dtype | None

Per-call overrides for configured defaults.

None

Returns:

Type Description
Tensor

Converted tensor, sharing storage when PyTorch permits.

Source code in src/torch_flash/config.py
def as_tensor(
    self,
    data: Any,
    *,
    dtype: torch.dtype | None = None,
    device: torch.device | str | None = None,
) -> Tensor:
    """Convert data using this runtime policy without unnecessary copies.

    Parameters
    ----------
    data
        Any value accepted by :func:`torch.as_tensor`.
    dtype, device
        Per-call overrides for configured defaults.

    Returns
    -------
    Tensor
        Converted tensor, sharing storage when PyTorch permits.
    """
    return torch.as_tensor(
        data,
        dtype=self.dtype if dtype is None else dtype,
        device=self.device if device is None else device,
    )

get_config

get_config() -> RuntimeConfig

Return a current immutable runtime-policy snapshot.

Returns:

Type Description
RuntimeConfig

Configured device/dtype plus live PyTorch thread and deterministic settings. Mutating process-wide PyTorch settings outside torch-flash is reflected in the returned snapshot.

Source code in src/torch_flash/config.py
def get_config() -> RuntimeConfig:
    """Return a current immutable runtime-policy snapshot.

    Returns
    -------
    RuntimeConfig
        Configured device/dtype plus live PyTorch thread and deterministic
        settings. Mutating process-wide PyTorch settings outside torch-flash
        is reflected in the returned snapshot.
    """
    with _CONFIG_LOCK:
        return replace(
            _CONFIG,
            num_threads=torch.get_num_threads(),
            num_interop_threads=torch.get_num_interop_threads(),
            deterministic=torch.are_deterministic_algorithms_enabled(),
            deterministic_warn_only=torch.is_deterministic_algorithms_warn_only_enabled(),
        )

configure

configure(
    *,
    device: device | str | None = None,
    dtype: dtype | None = None,
    num_threads: int | None = None,
    num_interop_threads: int | None = None,
    deterministic: bool | None = None,
    deterministic_warn_only: bool | None = None,
) -> RuntimeConfig

Set the process-wide torch-flash runtime policy before model creation.

device="auto" selects the first available CUDA, XPU, or MPS device that supports the requested dtype, falling back to CPU. device="gpu" performs the same search but raises if no accelerator supports the dtype.

The dtype becomes PyTorch's default floating dtype. The selected device is applied only by torch-flash factories and :class:RuntimeConfig tensor helpers; this function deliberately does not call :func:torch.set_default_device, which adds overhead to every Python-level PyTorch API call.

PyTorch thread counts and deterministic-algorithm flags are inherently process-wide. In particular, num_interop_threads can be changed only once and before inter-operation parallel work starts; PyTorch's failure is reported with an actionable error.

Parameters:

Name Type Description Default
device device | str | None

Explicit PyTorch device, "auto" for accelerator-then-CPU selection, "gpu" to require an accelerator, or None to retain the current setting.

None
dtype dtype | None

torch.float64 or torch.float32. None retains the current dtype.

None
num_threads int | None

Positive CPU intra-operation thread count.

None
num_interop_threads int | None

Positive CPU inter-operation thread count. PyTorch permits changing it only once before parallel work begins.

None
deterministic bool | None

Enable or disable PyTorch deterministic algorithms.

None
deterministic_warn_only bool | None

Warn instead of raising when a deterministic implementation is unavailable. Requires deterministic=True.

None

Returns:

Type Description
RuntimeConfig

New immutable runtime-policy snapshot.

Raises:

Type Description
ValueError

If a dtype, device type, thread count, or deterministic option is invalid.

RuntimeError

If the requested device/dtype is unavailable or PyTorch can no longer change inter-operation threads.

Source code in src/torch_flash/config.py
def configure(
    *,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
    num_threads: int | None = None,
    num_interop_threads: int | None = None,
    deterministic: bool | None = None,
    deterministic_warn_only: bool | None = None,
) -> RuntimeConfig:
    """Set the process-wide torch-flash runtime policy before model creation.

    ``device="auto"`` selects the first available CUDA, XPU, or MPS device
    that supports the requested dtype, falling back to CPU. ``device="gpu"``
    performs the same search but raises if no accelerator supports the dtype.

    The dtype becomes PyTorch's default floating dtype. The selected device is
    applied only by torch-flash factories and :class:`RuntimeConfig` tensor
    helpers; this function deliberately does not call
    :func:`torch.set_default_device`, which adds overhead to every Python-level
    PyTorch API call.

    PyTorch thread counts and deterministic-algorithm flags are inherently
    process-wide. In particular, ``num_interop_threads`` can be changed only
    once and before inter-operation parallel work starts; PyTorch's failure is
    reported with an actionable error.

    Parameters
    ----------
    device:
        Explicit PyTorch device, ``"auto"`` for accelerator-then-CPU
        selection, ``"gpu"`` to require an accelerator, or ``None`` to retain
        the current setting.
    dtype:
        ``torch.float64`` or ``torch.float32``. ``None`` retains the current
        dtype.
    num_threads:
        Positive CPU intra-operation thread count.
    num_interop_threads:
        Positive CPU inter-operation thread count. PyTorch permits changing
        it only once before parallel work begins.
    deterministic:
        Enable or disable PyTorch deterministic algorithms.
    deterministic_warn_only:
        Warn instead of raising when a deterministic implementation is
        unavailable. Requires ``deterministic=True``.

    Returns
    -------
    RuntimeConfig
        New immutable runtime-policy snapshot.

    Raises
    ------
    ValueError
        If a dtype, device type, thread count, or deterministic option is
        invalid.
    RuntimeError
        If the requested device/dtype is unavailable or PyTorch can no longer
        change inter-operation threads.
    """
    global _CONFIG

    with _CONFIG_LOCK:
        current = get_config()
        selected_dtype = current.dtype if dtype is None else dtype
        if selected_dtype not in _SUPPORTED_DTYPES:
            raise ValueError("torch-flash runtime dtype must be torch.float32 or torch.float64")
        selected_device = _resolve_device(device, selected_dtype, current.device)
        selected_threads = _positive_thread_count(
            num_threads,
            "num_threads",
            current.num_threads,
        )
        selected_interop_threads = _positive_thread_count(
            num_interop_threads,
            "num_interop_threads",
            current.num_interop_threads,
        )
        selected_deterministic = current.deterministic if deterministic is None else deterministic
        if not isinstance(selected_deterministic, bool):
            raise ValueError("deterministic must be a boolean")
        if deterministic is False and deterministic_warn_only is None:
            selected_warn_only = False
        else:
            selected_warn_only = (
                current.deterministic_warn_only
                if deterministic_warn_only is None
                else deterministic_warn_only
            )
        if not isinstance(selected_warn_only, bool):
            raise ValueError("deterministic_warn_only must be a boolean")
        if selected_warn_only and not selected_deterministic:
            raise ValueError("deterministic_warn_only requires deterministic=True")

        if selected_interop_threads != current.num_interop_threads:
            try:
                torch.set_num_interop_threads(selected_interop_threads)
            except RuntimeError as exc:
                raise RuntimeError(
                    "PyTorch inter-operation threads must be configured once, before "
                    "inter-operation parallel work starts"
                ) from exc
        if selected_threads != current.num_threads:
            torch.set_num_threads(selected_threads)
        if (
            selected_deterministic != current.deterministic
            or selected_warn_only != current.deterministic_warn_only
        ):
            torch.use_deterministic_algorithms(
                selected_deterministic,
                warn_only=selected_warn_only,
            )
        if selected_dtype != torch.get_default_dtype():
            torch.set_default_dtype(selected_dtype)

        _CONFIG = RuntimeConfig(
            selected_device,
            selected_dtype,
            torch.get_num_threads(),
            torch.get_num_interop_threads(),
            torch.are_deterministic_algorithms_enabled(),
            torch.is_deterministic_algorithms_warn_only_enabled(),
        )
        return _CONFIG

resolve_tensor_options

resolve_tensor_options(
    dtype: dtype | None, device: device | str | None
) -> tuple[dtype, device | str]

Resolve optional tensor options against current runtime configuration.

Parameters:

Name Type Description Default
dtype dtype | None

Explicit options or None to use configured defaults.

required
device dtype | None

Explicit options or None to use configured defaults.

required

Returns:

Type Description
tuple

Resolved dtype and device suitable for PyTorch tensor factories.

Source code in src/torch_flash/config.py
def resolve_tensor_options(
    dtype: torch.dtype | None,
    device: torch.device | str | None,
) -> tuple[torch.dtype, torch.device | str]:
    """Resolve optional tensor options against current runtime configuration.

    Parameters
    ----------
    dtype, device
        Explicit options or ``None`` to use configured defaults.

    Returns
    -------
    tuple
        Resolved dtype and device suitable for PyTorch tensor factories.
    """
    current = get_config()
    return (
        current.dtype if dtype is None else dtype,
        current.device if device is None else device,
    )

Components

torch_flash.components

Canonical component names and shared SI property databases.

DEFAULT_COMPONENT_DATABASE module-attribute

DEFAULT_COMPONENT_DATABASE = load_component_database()

Validated bundled component database used by default constructors.

COMPONENTS module-attribute

COMPONENTS: dict[str, Component] = {}

Canonical-name and alias lookup mapping for bundled component records.

Component dataclass

Component(
    name: str,
    critical_temperature: float,
    critical_pressure: float,
    acentric_factor: float | None,
    molar_mass: float,
    critical_volume: float | None = None,
    aliases: tuple[str, ...] = (),
    critical_density: float | None = None,
)

Shared pure-component properties in SI units.

acentric_factor may be unavailable for components whose bundled use is restricted to a model-specific multiparameter equation. Such a record can be resolved by name but cannot be used to construct a cubic EoS until the user supplies a complete custom component database or :class:ComponentSet.

Attributes:

Name Type Description
name str

Canonical lowercase snake-case component identifier.

critical_temperature float

Critical temperature in K.

critical_pressure float

Critical pressure in Pa.

acentric_factor float | None

Dimensionless acentric factor, or None when unavailable.

molar_mass float

Molar mass in kg/mol.

critical_volume float | None

Critical molar volume in m3/mol, or None when unavailable.

aliases tuple[str, ...]

Accepted alternative names, normalized only at API lookup boundaries.

critical_density float | None

Critical molar density in mol/m3, or None when unavailable.

ComponentDatabase dataclass

ComponentDatabase(
    identifier: str,
    revision: str,
    components: tuple[Component, ...],
    units: Mapping[str, str],
    references: tuple[Mapping[str, str], ...] = (),
    source: str = "<api>",
)

Validated immutable canonical component database.

Attributes:

Name Type Description
identifier str

Stable database identifier.

revision str

Database revision string.

components tuple[Component, ...]

Pure-component records in database order.

units Mapping[str, str]

Read-only mapping of property names to declared SI units.

references tuple[Mapping[str, str], ...]

Read-only source records applying to the database.

source str

Bundled resource label, custom YAML path, or "<api>".

Raises:

Type Description
ParameterDatabaseError

If identifiers, units, records, aliases, or required positive properties are invalid.

names property

names: tuple[str, ...]

Return canonical component names in database order.

Returns:

Type Description
tuple

Immutable sequence of canonical identifiers.

lookup

lookup(name: str) -> Component

Resolve a canonical name or alias.

Parameters:

Name Type Description Default
name str

Name or alias; matching is case-insensitive and treats spaces and hyphens as underscores.

required

Returns:

Type Description
Component

Matching immutable component record.

Raises:

Type Description
KeyError

If no component or alias matches.

Source code in src/torch_flash/components.py
def lookup(self, name: str) -> Component:
    """Resolve a canonical name or alias.

    Parameters
    ----------
    name:
        Name or alias; matching is case-insensitive and treats spaces and
        hyphens as underscores.

    Returns
    -------
    Component
        Matching immutable component record.

    Raises
    ------
    KeyError
        If no component or alias matches.
    """
    normalized = _normalize_name(name)
    aliases: dict[str, Component] = {}
    for record in self.components:
        aliases[_normalize_name(record.name)] = record
        for alias in record.aliases:
            aliases[_normalize_name(alias)] = record
    try:
        return aliases[normalized]
    except KeyError as exc:
        available = ", ".join(sorted(self.names))
        raise KeyError(f"unknown component {name!r}; available: {available}") from exc

ComponentSet dataclass

ComponentSet(
    names: tuple[str, ...],
    critical_temperature: Tensor,
    critical_pressure: Tensor,
    acentric_factor: Tensor,
    molar_mass: Tensor,
    critical_volume: Tensor | None = None,
    critical_density: Tensor | None = None,
)

Vectorized component constants used by native PyTorch models.

All tensor fields have shape (ncomponents,) and share a dtype/device. Component order defines the final axis of every associated composition tensor.

Attributes:

Name Type Description
names tuple[str, ...]

Canonical component names in tensor order.

critical_temperature Tensor

Critical temperatures in K.

critical_pressure Tensor

Critical pressures in Pa.

acentric_factor Tensor

Dimensionless acentric factors.

molar_mass Tensor

Molar masses in kg/mol.

critical_volume Tensor | None

Critical molar volumes in m3/mol, or None.

critical_density Tensor | None

Critical molar densities in mol/m3, or None.

ncomponents property

ncomponents: int

Return the component-axis length.

Returns:

Type Description
int

Number of entries in :attr:names.

to

to(
    *,
    dtype: dtype | None = None,
    device: device | str | None = None,
) -> ComponentSet

Return a component set with all tensors converted together.

Parameters:

Name Type Description Default
dtype dtype | None

Target floating dtype. None preserves the current dtype.

None
device device | str | None

Target PyTorch device. None preserves the current device.

None

Returns:

Type Description
ComponentSet

New immutable record; the original is unchanged.

Source code in src/torch_flash/components.py
def to(
    self,
    *,
    dtype: torch.dtype | None = None,
    device: torch.device | str | None = None,
) -> ComponentSet:
    """Return a component set with all tensors converted together.

    Parameters
    ----------
    dtype:
        Target floating dtype. ``None`` preserves the current dtype.
    device:
        Target PyTorch device. ``None`` preserves the current device.

    Returns
    -------
    ComponentSet
        New immutable record; the original is unchanged.
    """
    return ComponentSet(
        self.names,
        self.critical_temperature.to(dtype=dtype, device=device),
        self.critical_pressure.to(dtype=dtype, device=device),
        self.acentric_factor.to(dtype=dtype, device=device),
        self.molar_mass.to(dtype=dtype, device=device),
        (
            None
            if self.critical_volume is None
            else self.critical_volume.to(dtype=dtype, device=device)
        ),
        (
            None
            if self.critical_density is None
            else self.critical_density.to(dtype=dtype, device=device)
        ),
    )

load_component_database

load_component_database(
    source: str | Path | ComponentDatabase | None = None,
) -> ComponentDatabase

Load and validate a bundled, custom, or explicit component database.

Parameters:

Name Type Description Default
source str | Path | ComponentDatabase | None

None, "default", or "components.default" selects the bundled database. A path reads a custom torch-flash component YAML document. An existing :class:ComponentDatabase is returned unchanged.

None

Returns:

Type Description
ComponentDatabase

Immutable validated database. Parsed files are cached by resolved path.

Raises:

Type Description
FileNotFoundError

If a custom path does not exist.

ParameterDatabaseError

If the YAML schema, unit declarations, or component records are invalid.

Source code in src/torch_flash/components.py
def load_component_database(
    source: str | Path | ComponentDatabase | None = None,
) -> ComponentDatabase:
    """Load and validate a bundled, custom, or explicit component database.

    Parameters
    ----------
    source:
        ``None``, ``"default"``, or ``"components.default"`` selects the
        bundled database. A path reads a custom torch-flash component YAML
        document. An existing :class:`ComponentDatabase` is returned unchanged.

    Returns
    -------
    ComponentDatabase
        Immutable validated database. Parsed files are cached by resolved path.

    Raises
    ------
    FileNotFoundError
        If a custom path does not exist.
    ParameterDatabaseError
        If the YAML schema, unit declarations, or component records are invalid.
    """
    if source is None or source in ("default", "components.default"):
        return _default_component_database()
    if isinstance(source, ComponentDatabase):
        return source
    return _component_database_from_path(str(Path(source).expanduser().absolute()))

clear_component_caches

clear_component_caches() -> None

Clear cached bundled and custom component YAML documents.

Use this after intentionally modifying a custom database in a long-running process. Existing :class:ComponentSet and model instances are unaffected.

Returns:

Type Description
None

The next database load reparses its source.

Source code in src/torch_flash/components.py
def clear_component_caches() -> None:
    """Clear cached bundled and custom component YAML documents.

    Use this after intentionally modifying a custom database in a long-running
    process. Existing :class:`ComponentSet` and model instances are unaffected.

    Returns
    -------
    None
        The next database load reparses its source.
    """
    _default_component_database.cache_clear()
    _component_database_from_path.cache_clear()

canonical_component_name

canonical_component_name(
    name: str,
    *,
    database: str | Path | ComponentDatabase | None = None,
    strict: bool = True,
) -> str

Resolve a component name or alias to the canonical identifier.

Parameters:

Name Type Description Default
name str

Canonical name or declared alias.

required
database str | Path | ComponentDatabase | None

Bundled/custom database selection accepted by :func:load_component_database.

None
strict bool

If True, unknown names raise. If False, an unknown name is normalized to lowercase snake case without asserting database presence.

True

Returns:

Type Description
str

Canonical database name or, in non-strict mode, normalized input.

Raises:

Type Description
KeyError

If name is unknown and strict=True.

Source code in src/torch_flash/components.py
def canonical_component_name(
    name: str,
    *,
    database: str | Path | ComponentDatabase | None = None,
    strict: bool = True,
) -> str:
    """Resolve a component name or alias to the canonical identifier.

    Parameters
    ----------
    name:
        Canonical name or declared alias.
    database:
        Bundled/custom database selection accepted by
        :func:`load_component_database`.
    strict:
        If ``True``, unknown names raise. If ``False``, an unknown name is
        normalized to lowercase snake case without asserting database presence.

    Returns
    -------
    str
        Canonical database name or, in non-strict mode, normalized input.

    Raises
    ------
    KeyError
        If ``name`` is unknown and ``strict=True``.
    """
    selected = load_component_database(database)
    try:
        return selected.lookup(name).name
    except KeyError:
        if strict:
            raise
        return _normalize_name(name)

component

component(
    name: str,
    *,
    database: str | Path | ComponentDatabase | None = None,
) -> Component

Look up one pure-component record by canonical name or alias.

Parameters:

Name Type Description Default
name str

Canonical name or alias to resolve.

required
database str | Path | ComponentDatabase | None

Bundled/custom database selection.

None

Returns:

Type Description
Component

Immutable record from the selected database.

Raises:

Type Description
KeyError

If the component is absent from the selected database.

Source code in src/torch_flash/components.py
def component(
    name: str,
    *,
    database: str | Path | ComponentDatabase | None = None,
) -> Component:
    """Look up one pure-component record by canonical name or alias.

    Parameters
    ----------
    name:
        Canonical name or alias to resolve.
    database:
        Bundled/custom database selection.

    Returns
    -------
    Component
        Immutable record from the selected database.

    Raises
    ------
    KeyError
        If the component is absent from the selected database.
    """
    return load_component_database(database).lookup(name)

component_set

component_set(
    names: Iterable[str],
    *,
    dtype: dtype | None = None,
    device: device | str | None = None,
    database: str | Path | ComponentDatabase | None = None,
) -> ComponentSet

Build vectorized cubic-EoS constants from a component database.

Omitted tensor options follow the process-wide :mod:torch_flash.config policy. Explicit dtype or device arguments override that policy.

Parameters:

Name Type Description Default
names Iterable[str]

Nonempty iterable of canonical names or aliases. Order is preserved.

required
dtype dtype | None

Tensor options. Omitted values use the configured runtime policy.

None
device dtype | None

Tensor options. Omitted values use the configured runtime policy.

None
database str | Path | ComponentDatabase | None

Bundled/custom database selection.

None

Returns:

Type Description
ComponentSet

Vectorized SI constants in the requested order.

Raises:

Type Description
ValueError

If no components are requested.

KeyError

If a name is unknown.

ParameterDatabaseError

If a requested component lacks the acentric factor required by cubic EoS construction.

Source code in src/torch_flash/components.py
def component_set(
    names: Iterable[str],
    *,
    dtype: torch.dtype | None = None,
    device: torch.device | str | None = None,
    database: str | Path | ComponentDatabase | None = None,
) -> ComponentSet:
    """Build vectorized cubic-EoS constants from a component database.

    Omitted tensor options follow the process-wide :mod:`torch_flash.config`
    policy. Explicit dtype or device arguments override that policy.

    Parameters
    ----------
    names:
        Nonempty iterable of canonical names or aliases. Order is preserved.
    dtype, device:
        Tensor options. Omitted values use the configured runtime policy.
    database:
        Bundled/custom database selection.

    Returns
    -------
    ComponentSet
        Vectorized SI constants in the requested order.

    Raises
    ------
    ValueError
        If no components are requested.
    KeyError
        If a name is unknown.
    ParameterDatabaseError
        If a requested component lacks the acentric factor required by cubic
        EoS construction.
    """
    dtype, device = resolve_tensor_options(dtype, device)
    items = tuple(component(name, database=database) for name in names)
    if not items:
        raise ValueError("at least one component is required")
    unavailable = tuple(item.name for item in items if item.acentric_factor is None)
    if unavailable:
        joined = ", ".join(unavailable)
        raise ParameterDatabaseError(
            f"cubic-EoS acentric factors are unavailable for: {joined}; "
            "supply a custom component database or ComponentSet"
        )

    def tensor(values: list[float]) -> Tensor:
        return torch.tensor(values, dtype=dtype, device=device)

    critical_volumes = [
        float("nan") if item.critical_volume is None else item.critical_volume for item in items
    ]
    critical_densities = [
        float("nan") if item.critical_density is None else item.critical_density for item in items
    ]
    return ComponentSet(
        tuple(item.name for item in items),
        tensor([item.critical_temperature for item in items]),
        tensor([item.critical_pressure for item in items]),
        tensor([cast(float, item.acentric_factor) for item in items]),
        tensor([item.molar_mass for item in items]),
        tensor(critical_volumes),
        tensor(critical_densities),
    )

Model parameter documents

torch_flash.database

Versioned YAML parameter-database loading.

Bundled model parameter sets are immutable scientific inputs. YAML documents are parsed and validated once per process, while model constructors copy their values into independent PyTorch tensors with the requested dtype, device, and trainability.

ModelParameterSet dataclass

ModelParameterSet(
    identifier: str,
    model_kind: str,
    model: str,
    version: str,
    parameters: ParameterDocument,
    units: ParameterDocument = dict(),
    references: tuple[ParameterDocument, ...] = (),
    description: str = "",
    source: str = "<api>",
)

Validated model parameter set independent of tensor dtype and device.

Parameters can be supplied directly through this dataclass, read from a custom YAML path, or selected from the bundled database by identifier. The stored mappings are recursively read-only. Use :meth:as_dict when a mutable deep copy is needed.

Attributes:

Name Type Description
identifier str

Stable lowercase parameter-set identifier.

model_kind str

Scientific domain such as "cubic", "activity", or "multiparameter".

model str

Model/form name declared by the document.

version str

Parameter-set version or revision.

parameters ParameterDocument

Recursively read-only numerical/scientific payload.

units ParameterDocument

Recursively read-only units mapping.

references tuple[ParameterDocument, ...]

Source records for equations, coefficients, or fits.

description str

Human-readable parameter-set scope.

source str

Bundled resource label, custom path, or "<api>".

from_document classmethod

from_document(
    document: Mapping[str, Any], *, source: str = "<api>"
) -> ModelParameterSet

Validate a model-parameter YAML document represented as a mapping.

Parameters:

Name Type Description Default
document Mapping[str, Any]

Parsed YAML mapping following the torch-flash model-parameter schema.

required
source str

Label used in diagnostics and stored provenance.

'<api>'

Returns:

Type Description
ModelParameterSet

Immutable validated parameter document.

Raises:

Type Description
ParameterDatabaseError

If required headers, identifiers, mappings, units, or references are invalid.

Source code in src/torch_flash/database.py
@classmethod
def from_document(
    cls,
    document: Mapping[str, Any],
    *,
    source: str = "<api>",
) -> ModelParameterSet:
    """Validate a model-parameter YAML document represented as a mapping.

    Parameters
    ----------
    document:
        Parsed YAML mapping following the torch-flash model-parameter
        schema.
    source:
        Label used in diagnostics and stored provenance.

    Returns
    -------
    ModelParameterSet
        Immutable validated parameter document.

    Raises
    ------
    ParameterDatabaseError
        If required headers, identifiers, mappings, units, or references
        are invalid.
    """
    _validate_header(document, _MODEL_FORMAT, source)
    parameters = document.get("parameters")
    if not isinstance(parameters, Mapping):
        raise ParameterDatabaseError(f"{source} requires a 'parameters' mapping")
    units = document.get("units", {})
    references = document.get("references", [])
    if not isinstance(units, Mapping):
        raise ParameterDatabaseError(f"{source} requires 'units' to be a mapping")
    if not isinstance(references, list):
        raise ParameterDatabaseError(f"{source} requires 'references' to be a list")
    description = document.get("description", "")
    if not isinstance(description, str):
        raise ParameterDatabaseError(f"{source} requires 'description' to be a string")
    return cls(
        identifier=_require_string(document, "id", source),
        model_kind=_require_string(document, "model_kind", source),
        model=_require_string(document, "model", source),
        version=_require_string(document, "version", source),
        parameters=parameters,
        units=units,
        references=tuple(cast(list[ParameterDocument], references)),
        description=description,
        source=source,
    )

as_dict

as_dict() -> dict[str, Any]

Return a mutable deep copy of the numerical parameter payload.

Returns:

Type Description
dict

Deeply mutable copy. Mutating it cannot alter the cached parameter set or any existing model tensors.

Source code in src/torch_flash/database.py
def as_dict(self) -> dict[str, Any]:
    """Return a mutable deep copy of the numerical parameter payload.

    Returns
    -------
    dict
        Deeply mutable copy. Mutating it cannot alter the cached parameter
        set or any existing model tensors.
    """
    return cast(dict[str, Any], _thaw(self.parameters))

load_model_parameters

load_model_parameters(
    source: ParameterSource,
) -> ModelParameterSet

Load a bundled identifier, custom YAML path, or explicit parameter set.

Parsed bundled and custom files are cached by identifier or resolved path. Call :func:clear_parameter_caches after intentionally modifying a custom file in a long-running process.

Parameters:

Name Type Description Default
source ParameterSource

Bundled identifier or alias, custom YAML path, or an explicit :class:ModelParameterSet.

required

Returns:

Type Description
ModelParameterSet

Immutable validated parameter set.

Raises:

Type Description
KeyError

If a string is neither a bundled identifier/alias nor a YAML path.

FileNotFoundError

If a custom YAML path does not exist.

ParameterDatabaseError

If the document does not satisfy the schema.

Source code in src/torch_flash/database.py
def load_model_parameters(source: ParameterSource) -> ModelParameterSet:
    """Load a bundled identifier, custom YAML path, or explicit parameter set.

    Parsed bundled and custom files are cached by identifier or resolved path.
    Call :func:`clear_parameter_caches` after intentionally modifying a custom
    file in a long-running process.

    Parameters
    ----------
    source:
        Bundled identifier or alias, custom YAML path, or an explicit
        :class:`ModelParameterSet`.

    Returns
    -------
    ModelParameterSet
        Immutable validated parameter set.

    Raises
    ------
    KeyError
        If a string is neither a bundled identifier/alias nor a YAML path.
    FileNotFoundError
        If a custom YAML path does not exist.
    ParameterDatabaseError
        If the document does not satisfy the schema.
    """
    if isinstance(source, ModelParameterSet):
        return source
    if isinstance(source, Path):
        return _load_path(str(source.expanduser().absolute()))
    _, aliases = _index()
    normalized = source.strip().lower()
    if normalized in aliases:
        if normalized.startswith("multifluid."):
            warnings.warn(
                "the 'multifluid.' parameter prefix is deprecated; use 'multiparameter.'",
                DeprecationWarning,
                stacklevel=2,
            )
        return _load_builtin(aliases[normalized])
    candidate = Path(source).expanduser()
    if candidate.suffix.lower() in (".yaml", ".yml"):
        return _load_path(str(candidate.absolute()))
    available = ", ".join(available_parameter_sets())
    raise KeyError(f"unknown model parameter set {source!r}; available: {available}")

available_parameter_sets

available_parameter_sets(
    *, model_kind: str | None = None
) -> tuple[str, ...]

Return bundled parameter-set identifiers, optionally filtered by kind.

Parameters:

Name Type Description Default
model_kind str | None

Exact model-kind filter, for example "cubic" or "activity". None returns every bundled identifier.

None

Returns:

Type Description
tuple[str, ...]

Sorted immutable tuple of matching identifiers. An unknown kind yields an empty tuple.

Source code in src/torch_flash/database.py
def available_parameter_sets(*, model_kind: str | None = None) -> tuple[str, ...]:
    """Return bundled parameter-set identifiers, optionally filtered by kind.

    Parameters
    ----------
    model_kind:
        Exact model-kind filter, for example ``"cubic"`` or ``"activity"``.
        ``None`` returns every bundled identifier.

    Returns
    -------
    tuple[str, ...]
        Sorted immutable tuple of matching identifiers. An unknown kind yields
        an empty tuple.
    """
    entries, _ = _index()
    identifiers = tuple(sorted(entries))
    if model_kind is None:
        return identifiers
    if model_kind == "multifluid":
        warnings.warn(
            "model_kind='multifluid' is deprecated; use 'multiparameter'",
            DeprecationWarning,
            stacklevel=2,
        )
        model_kind = "multiparameter"
    return tuple(
        identifier
        for identifier in identifiers
        if _load_builtin(identifier).model_kind == model_kind
    )

clear_parameter_caches

clear_parameter_caches() -> None

Clear parsed model-parameter YAML caches.

Use this after intentionally modifying a custom file in a long-running process. Existing model instances and tensors are unaffected.

Returns:

Type Description
None

The next parameter load reparses its source.

Source code in src/torch_flash/database.py
def clear_parameter_caches() -> None:
    """Clear parsed model-parameter YAML caches.

    Use this after intentionally modifying a custom file in a long-running
    process. Existing model instances and tensors are unaffected.

    Returns
    -------
    None
        The next parameter load reparses its source.
    """
    _load_builtin.cache_clear()
    _load_path.cache_clear()
    _index.cache_clear()

Exceptions and warnings

torch_flash.exceptions

Package-specific exceptions and warnings.

TorchFlashError

Bases: Exception

Base class for torch-flash domain-specific errors.

Catch this type when an application wants to handle all package-defined calculation and parameter errors without intercepting unrelated Python exceptions.

InvalidStateError

Bases: TorchFlashError, ValueError

Indicate that a thermodynamic state is outside a model's domain.

Typical causes include nonpositive temperature or pressure, inadmissible volume, and mechanically unstable response functions.

ConvergenceError

Bases: TorchFlashError, RuntimeError

Indicate that an iterative thermodynamic calculation failed.

The originating API should include a physically meaningful residual or iteration context in the exception message.

ModelCapabilityError

Bases: TorchFlashError, NotImplementedError

Indicate that a model or optional backend lacks a requested operation.

This is distinct from numerical non-convergence of an implemented capability.

ParameterDatabaseError

Bases: TorchFlashError, ValueError

Indicate an invalid component or model parameter document.

Examples include schema, unit, model-identity, provenance, and coefficient consistency failures.

ConvergenceWarning

Bases: RuntimeWarning

Warn that a returned iterative result did not meet its tolerance.

APIs emitting this warning also mark the associated result non-converged; callers must not silently treat it as a valid solution.

ExperimentalModelWarning

Bases: UserWarning

Warn that an implemented model path has limited validation scope.

The warning concerns scientific maturity or automated phase discovery, not necessarily numerical failure at the requested state.