Skip to content

State and result types

The dataclasses below are immutable records. Tensor-valued fields retain the dtype and device of the calculation unless the individual API states otherwise.

torch_flash.types

Typed result containers shared by thermodynamic domains.

ChemicalState dataclass

ChemicalState(
    temperature: Tensor,
    pressure: Tensor,
    composition: Tensor,
)

Specified temperature, pressure, and molar composition.

The state is an immutable input record. Temperature and pressure must be positive. Composition is normalized along its final axis by :func:normalize_composition; tiny negative roundoff is clipped and materially negative or zero-sum rows are rejected.

Attributes:

Name Type Description
temperature Tensor

Absolute temperature in K. Individual calculation APIs document whether scalar or batched temperatures are accepted.

pressure Tensor

Absolute pressure in Pa, with shape compatible with temperature.

composition Tensor

Mole fractions with components on the final axis. The stored tensor is nonnegative and normalized to unit sum.

PhaseIdentification dataclass

PhaseIdentification(
    kind: PhaseIdentityKind,
    method: PhaseIdentificationMethod,
    criterion_value: Tensor | None,
    threshold: Tensor | None,
    ambiguous: bool,
)

Likely physical identity of a homogeneous phase.

kind is deliberately separate from the EoS root requested through :class:PhaseProperties. criterion_value and threshold retain the native quantity used by the selected method: T/Tc and one for Li's pseudo-critical-temperature rule, V/b and normally 1.75 for Pedersen's rule, G(0.5) and zero for Perschke's negative-flash rule, or the relevant temperature derivative and zero for either derivative rule, or the dimensionless Venkatarathnam-Oellrich phase-identification parameter and one. For density ordering, they are the phase molar volume and the geometric-mean separator between the two least-dense phases. The Boolean ambiguous marks values within the configured numerical band around the separator.

Phase identification is a naming diagnostic; it does not change the equilibrium calculation or any thermodynamic property.

Attributes:

Name Type Description
kind PhaseIdentityKind

Likely physical identity: "liquid", "vapor", or "unknown".

method PhaseIdentificationMethod

Diagnostic rule used to assign kind.

criterion_value Tensor | None

Value compared with threshold, or None when unavailable.

threshold Tensor | None

Decision threshold in the same units as criterion_value.

ambiguous bool

Whether the criterion lies within the configured ambiguity band.

PhaseProperties dataclass

PhaseProperties(
    kind: str,
    composition: Tensor,
    compressibility_factor: Tensor,
    molar_volume: Tensor,
    log_fugacity_coefficients: Tensor,
    fugacities: Tensor,
    log_fugacities: Tensor,
    chemical_potentials: Tensor,
    reduced_chemical_potentials: Tensor,
    molar_gibbs_energy: Tensor,
    molar_helmholtz_energy: Tensor,
    reduced_gibbs_energy: Tensor,
    reduced_helmholtz_energy: Tensor,
    reduced_residual_gibbs_energy: Tensor,
    reduced_residual_helmholtz_energy: Tensor,
    residual_enthalpy: Tensor | None = None,
    residual_entropy: Tensor | None = None,
    phase_identification: PhaseIdentification | None = None,
)

Thermodynamic properties of one homogeneous phase.

Fugacities are in Pa and log_fugacities are the dimensionless ln(f_i / p_standard) values. Chemical potentials and molar free energies are in J/mol. reduced_* chemical potentials and energies are dimensionless quantities divided by R*T. Total quantities use the standard-state convention selected by phase_properties; the reduced residual quantities are reference-independent EoS departures.

Attributes:

Name Type Description
kind str

Algebraic root requested from the model: "liquid", "vapor", or "stable".

composition Tensor

Phase mole fractions, normalized on the final component axis.

compressibility_factor Tensor

Dimensionless compressibility factor Z = P*v/(R*T).

molar_volume Tensor

Molar volume in m3/mol.

log_fugacity_coefficients Tensor

Dimensionless ln(phi_i) values.

fugacities Tensor

Component fugacities in Pa.

log_fugacities Tensor

Dimensionless ln(f_i/p_standard), with p_standard = 1 bar.

chemical_potentials Tensor

Component chemical potentials in J/mol under the selected standard state.

reduced_chemical_potentials Tensor

Dimensionless mu_i/(R*T).

molar_gibbs_energy, molar_helmholtz_energy

Total molar free energies in J/mol.

reduced_gibbs_energy, reduced_helmholtz_energy

Dimensionless total molar free energies divided by R*T.

reduced_residual_gibbs_energy, reduced_residual_helmholtz_energy

Reference-independent dimensionless EoS departures.

residual_enthalpy Tensor | None

Residual molar enthalpy in J/mol, or None when caloric evaluation was disabled or unsupported for the state shape.

residual_entropy Tensor | None

Residual molar entropy in J/(mol K), with the same availability as residual_enthalpy.

phase_identification PhaseIdentification | None

Optional physical-identity diagnostic, separate from kind.

fugacity_coefficients property

fugacity_coefficients: Tensor

Return component fugacity coefficients.

Returns:

Type Description
Tensor

Dimensionless phi_i = exp(log(phi_i)).

RachfordRiceResult dataclass

RachfordRiceResult(
    vapor_fraction: Tensor,
    liquid_fraction: Tensor,
    liquid_composition: Tensor,
    vapor_composition: Tensor,
    iterations: int,
    converged: Tensor,
    residual: Tensor,
)

Solution of the two-phase Rachford-Rice material balance.

Attributes:

Name Type Description
vapor_fraction, liquid_fraction

Phase molar fractions. For batched inputs these retain the leading state dimensions.

liquid_composition, vapor_composition

Normalized phase mole fractions with components on the final axis.

iterations int

Maximum iteration count used by the solve.

converged Tensor

Boolean tensor indicating convergence for each state.

residual Tensor

Final scalar Rachford-Rice residual for each state.

BatchedTwoPhaseFlashResult dataclass

BatchedTwoPhaseFlashResult(
    vapor_fraction: Tensor,
    liquid_fraction: Tensor,
    liquid_composition: Tensor,
    vapor_composition: Tensor,
    k_values: Tensor,
    iterations: int,
    converged: Tensor,
    residual_norm: Tensor,
)

Fixed two-phase flash results for a batch of known unstable states.

This record does not imply that phase stability was checked. It is returned by :func:torch_flash.flash.batched_two_phase_flash, whose input contract assumes every state belongs to the requested two-phase branch.

Attributes:

Name Type Description
vapor_fraction, liquid_fraction

Phase fractions with one value per input state.

liquid_composition, vapor_composition

Phase mole fractions with shape batch_shape + (ncomponents,).

k_values Tensor

Final positive equilibrium ratios K_i = y_i/x_i.

iterations int

Number of fixed substitution/Newton iterations performed.

converged Tensor

Boolean tensor with one convergence flag per state.

residual_norm Tensor

Maximum absolute log-fugacity residual for each state.

BatchedStabilityResult dataclass

BatchedStabilityResult(
    stable: Tensor,
    minimum_tpd: Tensor,
    trial_composition: Tensor,
    iterations: int,
    converged: Tensor,
    residual_norm: Tensor,
)

Tangent-plane stability results for independent homogeneous states.

Attributes:

Name Type Description
stable Tensor

Boolean stability decision for each input state.

minimum_tpd Tensor

Lowest dimensionless tangent-plane distance found per state.

trial_composition Tensor

Composition associated with minimum_tpd.

iterations int

Shared number of successive-substitution passes executed.

converged Tensor

Whether the selected stationary-point iteration met its residual tolerance for each state.

residual_norm Tensor

Maximum absolute log trial-mole update at the selected stationary point.

StabilityResult dataclass

StabilityResult(
    stable: bool,
    minimum_tpd: Tensor,
    trial_composition: Tensor,
    iterations: int,
    converged: bool,
)

Result of tangent-plane-distance minimization.

Attributes:

Name Type Description
stable bool

Whether the minimum tangent-plane distance is nonnegative within the solver tolerance.

minimum_tpd Tensor

Smallest dimensionless tangent-plane distance found.

trial_composition Tensor

Normalized trial composition at minimum_tpd.

iterations int

Iterations associated with the selected trial minimization.

converged bool

Whether that minimization met its numerical stopping criterion.

Notes

Stability is only as strong as the explored trial-composition basins. A small residual or equal-fugacity split is not a substitute for this test.

FlashResult dataclass

FlashResult(
    phase_fractions: Tensor,
    phases: tuple[PhaseProperties, ...],
    converged: bool,
    iterations: int,
    residual_norm: Tensor,
    stable: bool,
    diagnostics: dict[
        str, float | int | bool | str
    ] = dict(),
)

Equilibrium phases and numerical diagnostics.

Attributes:

Name Type Description
phase_fractions Tensor

Molar phase fractions in the same order as phases.

phases tuple[PhaseProperties, ...]

Homogeneous properties and compositions for each returned phase.

converged bool

Whether the flash iteration satisfied its numerical criterion.

iterations int

Number of outer flash iterations performed.

residual_norm Tensor

Maximum absolute dimensionless log-fugacity mismatch.

stable bool

Stability status reported by the solver. Its exact meaning depends on whether the selected flash API performed phase-stability analysis.

diagnostics dict[str, float | int | bool | str]

Additional scalar algorithm diagnostics, such as Rachford-Rice or autodiff-Newton iteration counts.

Notes

phase_kinds are post-solve physical-identification diagnostics. They do not alter the equilibrium equations or prove the global phase count.

nphases property

nphases: int

Return the number of phases in the result.

Returns:

Type Description
int

Length of :attr:phases.

phase_identifications property

phase_identifications: tuple[
    PhaseIdentification | None, ...
]

Return physical-identification diagnostics in phase order.

Returns:

Type Description
tuple

One optional :class:PhaseIdentification per phase.

phase_kinds property

phase_kinds: tuple[PhaseIdentityKind, ...]

Return likely physical phase identities.

Returns:

Type Description
tuple

"liquid", "vapor", or "unknown" for each phase.

phase_regime property

phase_regime: str

Return a compact aggregate phase-regime label.

Returns:

Type Description
str

Examples include "vapor", "vapor-liquid", and "3-phase-unknown".

normalize_composition

normalize_composition(
    composition: Tensor, *, atol: float = 1e-14
) -> Tensor

Return a normalized, non-negative mole-fraction tensor.

Parameters:

Name Type Description Default
composition Tensor

Mole amounts or fractions with components on the final axis.

required
atol float

Absolute magnitude below which negative roundoff is clipped to zero.

1e-14

Returns:

Type Description
Tensor

Nonnegative final-axis mole fractions normalized to unit sum.

Raises:

Type Description
ValueError

In eager execution, if the tensor has no component axis, contains nonfinite/materially negative values, or a row has zero total.

Notes

The last axis is interpreted as the component axis. Tiny negative values caused by roundoff are clipped; materially negative or zero-sum compositions are rejected.

Source code in src/torch_flash/types.py
def normalize_composition(
    composition: Tensor,
    *,
    atol: float = 1.0e-14,
) -> Tensor:
    """Return a normalized, non-negative mole-fraction tensor.

    Parameters
    ----------
    composition
        Mole amounts or fractions with components on the final axis.
    atol
        Absolute magnitude below which negative roundoff is clipped to zero.

    Returns
    -------
    Tensor
        Nonnegative final-axis mole fractions normalized to unit sum.

    Raises
    ------
    ValueError
        In eager execution, if the tensor has no component axis, contains
        nonfinite/materially negative values, or a row has zero total.

    Notes
    -----
    The last axis is interpreted as the component axis. Tiny negative values
    caused by roundoff are clipped; materially negative or zero-sum
    compositions are rejected.
    """
    if not torch.is_floating_point(composition):
        composition = composition.to(torch.get_default_dtype())
    # Tensor-to-Python validation branches are intentionally excluded from
    # compiled graphs. Public eager calls retain the strict validation below;
    # compiled kernels assume the same documented input contract. Keeping the
    # numerical normalization in the graph lets torch.compile fuse the small
    # tensor operations that dominate multiparameter and association models.
    if not torch.compiler.is_compiling():
        if composition.ndim < 1:
            raise ValueError("composition must have at least one dimension")
        if not torch.isfinite(composition).all():
            raise ValueError("composition must contain only finite values")
        if bool((composition < -atol).any()):
            raise ValueError("composition cannot contain negative mole fractions")
    clipped = torch.clamp_min(composition, 0.0)
    total = clipped.sum(dim=-1, keepdim=True)
    if not torch.compiler.is_compiling() and bool((total <= 0.0).any()):
        raise ValueError("composition must have a positive sum")
    return clipped / total