Characterization, model parameters, and fitting¶
Heavy-end characterization¶
torch_flash.characterization
¶
Heavy-end characterization independent of thermodynamic model.
CubicFractionProperties
dataclass
¶
CubicFractionProperties(
critical_temperature: Tensor,
critical_pressure: Tensor,
acentric_factor: Tensor,
m: Tensor,
)
Critical properties and acentric factors for cubic-EoS adapters.
Attributes:
| Name | Type | Description |
|---|---|---|
critical_temperature |
Tensor
|
Cut critical temperatures in K. |
critical_pressure |
Tensor
|
Cut critical pressures in Pa. |
acentric_factor |
Tensor
|
Dimensionless cut acentric factors. |
m |
Tensor
|
Dimensionless alpha-function parameter associated with the requested SRK or PR correlation. |
LumpedDistribution
dataclass
¶
LumpedDistribution(
names: tuple[str, ...],
carbon_number_bounds: tuple[tuple[int, int], ...],
mole_fractions: Tensor,
molar_masses: Tensor,
densities: Tensor | None,
properties: dict[str, Tensor],
)
Contiguous pseudo-components produced by a lumping rule.
Attributes:
| Name | Type | Description |
|---|---|---|
names |
tuple[str, ...]
|
Pseudo-component labels in increasing carbon-number order. |
carbon_number_bounds |
tuple[tuple[int, int], ...]
|
Inclusive lower/upper carbon-number bounds for each lump. |
mole_fractions |
Tensor
|
Lump mole fractions. |
molar_masses |
Tensor
|
Mole-averaged lump molar masses in kg/mol. |
densities |
Tensor | None
|
Ideal-volume-preserving lump densities in kg/m3, or |
properties |
dict[str, Tensor]
|
Additional named, mass-weighted property tensors. |
PseudoComponentCut
dataclass
¶
PseudoComponentCut(
name: str,
mole_fraction: float,
normal_boiling_temperature: float,
specific_gravity: float,
molar_mass: float,
)
One measured or estimated heavy-end cut in SI units.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Nonempty pseudo-component identifier. |
mole_fraction |
float
|
Nonnegative fraction of the complete fluid composition. |
normal_boiling_temperature |
float
|
Normal boiling temperature in K. |
specific_gravity |
float
|
Dimensionless liquid specific gravity under the source convention. |
molar_mass |
float
|
Molar mass in kg/mol. |
SCNDistribution
dataclass
¶
SCNDistribution(
carbon_numbers: Tensor,
mole_fractions: Tensor,
molar_masses: Tensor,
densities: Tensor | None = None,
)
Discrete single-carbon-number representation of a plus fraction.
Attributes:
| Name | Type | Description |
|---|---|---|
carbon_numbers |
Tensor
|
Strictly increasing one-dimensional integer-like carbon-number labels. |
mole_fractions |
Tensor
|
Nonnegative cut mole fractions; their sum is the represented plus fraction, not generally one. |
molar_masses |
Tensor
|
Positive cut molar masses in kg/mol. |
densities |
Tensor | None
|
Optional positive cut mass densities in kg/m3. |
total_mole_fraction
property
¶
Return the total feed fraction represented by all SCN cuts.
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar sum of |
average_molar_mass
property
¶
Return the mole-average molar mass.
Returns:
| Type | Description |
|---|---|
Tensor
|
Plus-fraction average in kg/mol. |
bulk_density
property
¶
Return ideal-volume-mixed bulk mass density.
Returns:
| Type | Description |
|---|---|
Tensor or None
|
Density in kg/m3, or |
to
¶
to(
*,
dtype: dtype | None = None,
device: device | str | None = None,
) -> SCNDistribution
Return the distribution on a common dtype and device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
dtype | None
|
Target floating dtype for fractions, masses, and densities. |
None
|
device
|
device | str | None
|
Target device for every tensor. |
None
|
Returns:
| Type | Description |
|---|---|
SCNDistribution
|
New immutable distribution. Carbon numbers retain integer dtype. |
Source code in src/torch_flash/characterization/types.py
pedersen_cubic_properties
¶
pedersen_cubic_properties(
distribution: SCNDistribution,
eos: CubicCharacterization,
parameter_set: ParameterSource = "characterization.pedersen-2024",
) -> CubicFractionProperties
Map characterized SCN cuts to SRK or PR properties.
The default implements Pedersen et al. (2024), Eqs. 5.1-5.5 and Table 5.3. The C200 heavy-aromatic parameter set implements Pedersen, Milter, and Sorensen, SPE Journal 9 (2004), Eqs. 7-14 and Table 4, doi:10.2118/88364-PA. Its alpha parameter follows the published inverse-molar-mass continuation above 1000 g/mol. The correlation coefficients are EoS-specific; the input distribution and density split remain model-neutral.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distribution
|
SCNDistribution
|
SCN distribution with molar masses in kg/mol and densities in kg/m3. |
required |
eos
|
CubicCharacterization
|
|
required |
parameter_set
|
ParameterSource
|
Characterization parameter identifier, YAML path, or explicit record. |
'characterization.pedersen-2024'
|
Returns:
| Type | Description |
|---|---|
CubicFractionProperties
|
Cut properties with the same shape, dtype, and device as the distribution. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the EoS name is invalid, densities are absent, or the fitted acentric-factor inversion has no real solution. |
ParameterDatabaseError
|
If the selected document is not a compatible characterization set. |
Source code in src/torch_flash/characterization/cubic.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
pedersen_density_split
¶
pedersen_density_split(
distribution: SCNDistribution,
plus_density: float | Tensor,
*,
anchor_density: float | Tensor | None = None,
anchor_carbon_number: int | None = None,
parameter_set: ParameterSource = "characterization.pedersen-2024",
) -> SCNDistribution
Assign rho_N = C + D ln(CN) while matching bulk plus density.
Density inputs and results are SI (kg/m3). If no measured anchor is provided, Pedersen's suggested C6 density ratio is applied to the carbon number immediately preceding the plus fraction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distribution
|
SCNDistribution
|
SCN distribution whose moles and molar masses are retained. |
required |
plus_density
|
float | Tensor
|
Positive scalar target bulk density in kg/m3. |
required |
anchor_density
|
float | Tensor | None
|
Optional positive measured density in kg/m3 at
|
None
|
anchor_carbon_number
|
int | None
|
Positive anchor label. By default, the number immediately before the first SCN is used. |
None
|
parameter_set
|
ParameterSource
|
Pedersen characterization parameter source. |
'characterization.pedersen-2024'
|
Returns:
| Type | Description |
|---|---|
SCNDistribution
|
New distribution with per-cut densities matching the bulk ideal-volume balance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If target/anchor values or the anchor label are invalid. |
ConvergenceError
|
If a positive density trend cannot satisfy the volume balance. |
ParameterDatabaseError
|
If the selected document does not define the density rule. |
Source code in src/torch_flash/characterization/distributions.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
pedersen_logarithmic_split
¶
pedersen_logarithmic_split(
plus_mole_fraction: float | Tensor,
plus_molar_mass: float | Tensor,
*,
first_carbon_number: int = 7,
max_carbon_number: int | None = None,
parameter_set: ParameterSource = "characterization.pedersen-2024",
dtype: dtype | None = None,
device: device | str | None = None,
) -> SCNDistribution
Split a plus fraction with Pedersen's logarithmic molar distribution.
The finite distribution satisfies both plus-fraction mole and molar-mass balances (Pedersen et al., 2024, Eqs. 5.10-5.12). Molecular weights use Eq. 5.22. Measured extended compositions should be preferred whenever available, as emphasized by the source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plus_mole_fraction
|
float | Tensor
|
Positive scalar mole fraction represented by the plus cut. |
required |
plus_molar_mass
|
float | Tensor
|
Positive scalar average molar mass in kg/mol. |
required |
first_carbon_number
|
int
|
Inclusive SCN label range. The default maximum comes from the parameter set. |
7
|
max_carbon_number
|
int
|
Inclusive SCN label range. The default maximum comes from the parameter set. |
7
|
parameter_set
|
ParameterSource
|
Pedersen characterization parameter source. |
'characterization.pedersen-2024'
|
dtype
|
dtype | None
|
Output tensor options; omitted values use runtime configuration. |
None
|
device
|
dtype | None
|
Output tensor options; omitted values use runtime configuration. |
None
|
Returns:
| Type | Description |
|---|---|
SCNDistribution
|
Finite distribution preserving total plus moles and average molar mass. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If scalar inputs or carbon bounds are invalid, or the requested mean mass lies outside the finite SCN range. |
ConvergenceError
|
If the moment-constrained solve does not close the mass balance. |
ParameterDatabaseError
|
If the selected parameter document lacks required coefficients. |
Source code in src/torch_flash/characterization/distributions.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
whitson_gamma_split
¶
whitson_gamma_split(
plus_mole_fraction: float | Tensor,
plus_molar_mass: float | Tensor,
*,
first_carbon_number: int = 7,
max_carbon_number: int = 80,
shape: float | Tensor | None = None,
minimum_molar_mass: float | Tensor | None = None,
parameter_set: ParameterSource = "characterization.whitson-2000",
dtype: dtype | None = None,
device: device | str | None = None,
) -> SCNDistribution
Discretize Whitson's shifted gamma distribution into SCN-like bins.
The last requested bin contains the complete tail to infinite molecular
weight, so total moles and average molar mass are preserved exactly apart
from floating-point roundoff. shape=1 gives the exponential special
case discussed by both Whitson and Pedersen.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plus_mole_fraction
|
float | Tensor
|
Positive scalar mole fraction represented by the plus cut. |
required |
plus_molar_mass
|
float | Tensor
|
Positive scalar average molar mass in kg/mol. |
required |
first_carbon_number
|
int
|
Inclusive nominal bin labels. The final bin contains the complete remaining gamma tail. |
7
|
max_carbon_number
|
int
|
Inclusive nominal bin labels. The final bin contains the complete remaining gamma tail. |
7
|
shape
|
float | Tensor | None
|
Positive gamma shape parameter. |
None
|
minimum_molar_mass
|
float | Tensor | None
|
Positive shifted-gamma lower bound in kg/mol, below the average. |
None
|
parameter_set
|
ParameterSource
|
Whitson characterization parameter source. |
'characterization.whitson-2000'
|
dtype
|
dtype | None
|
Output tensor options; omitted values use runtime configuration. |
None
|
device
|
dtype | None
|
Output tensor options; omitted values use runtime configuration. |
None
|
Returns:
| Type | Description |
|---|---|
SCNDistribution
|
Discrete distribution preserving total moles and mean molar mass. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If scalar values, bounds, shape, or minimum mass are invalid. |
ParameterDatabaseError
|
If the selected document lacks required gamma parameters. |
Source code in src/torch_flash/characterization/distributions.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | |
equal_weight_lump
¶
equal_weight_lump(
distribution: SCNDistribution,
groups: int,
*,
properties: Mapping[str, Tensor] | None = None,
) -> LumpedDistribution
Lump contiguous SCN cuts into approximately equal-weight groups.
Critical properties supplied through properties use Pedersen's
weight-average rule (2024, Eqs. 5.29-5.31). Molar mass is mole averaged;
density, when present, preserves ideal mixed volume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distribution
|
SCNDistribution
|
Ordered SCN distribution to combine. |
required |
groups
|
int
|
Number of nonempty contiguous lumps, from one through the SCN count. |
required |
properties
|
Mapping[str, Tensor] | None
|
Optional named per-SCN tensors to aggregate by mass weighting. |
None
|
Returns:
| Type | Description |
|---|---|
LumpedDistribution
|
Contiguous pseudo-components preserving total moles and mass. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/torch_flash/characterization/lumping.py
Interaction and group-contribution parameters¶
torch_flash.parameters
¶
Published thermodynamic parameter sets.
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 |
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 |
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
as_dict
¶
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
CubicInteractionParameters
dataclass
¶
Validated cubic attraction and covolume interaction matrices.
Attributes:
| Name | Type | Description |
|---|---|---|
kij |
Tensor
|
Symmetric dimensionless attraction-interaction matrix. |
lij |
Tensor
|
Symmetric dimensionless cross-covolume-interaction matrix. |
parameter_set |
str
|
Identifier of the parameter set from which the matrices were selected. |
Notes
Both matrices have zero diagonals and axes ordered exactly as the
:class:~torch_flash.components.ComponentSet supplied to the loader.
PPR78GroupContributionParameters
dataclass
¶
PPR78GroupContributionParameters(
group_names: tuple[str, ...],
group_fractions: Tensor,
group_a: Tensor,
group_b: Tensor,
reference_temperature: float,
parameter_set: str,
)
Selected PPR78 or E-PPR78 decompositions and interactions.
Attributes:
| Name | Type | Description |
|---|---|---|
group_names |
tuple[str, ...]
|
Ordered group identifiers. |
group_fractions |
Tensor
|
Normalized component group fractions with shape
|
group_a, group_b |
Symmetric universal interaction matrices in Pa with shape
|
|
reference_temperature |
float
|
Positive interaction reference temperature in K. |
parameter_set |
str
|
Versioned parameter-set identifier. |
available_parameter_sets
¶
Return bundled parameter-set identifiers, optionally filtered by kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_kind
|
str | None
|
Exact model-kind filter, for example |
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
clear_parameter_caches
¶
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
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: |
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
cubic_interaction_parameters
¶
cubic_interaction_parameters(
components: ComponentSet, source: ParameterSource
) -> CubicInteractionParameters
Load general van der Waals one-fluid kij and lij matrices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
ComponentSet
|
Ordered component set defining output matrix axes, dtype, and device. |
required |
source
|
ParameterSource
|
Bundled identifier, YAML path, mapping, or loaded binary-interaction parameter set. |
required |
Returns:
| Type | Description |
|---|---|
CubicInteractionParameters
|
Symmetric matrices on the component set's dtype and device. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the parameter inventory does not support a requested component. |
ParameterDatabaseError
|
If model identity, units, defaults, component order, or pair records are invalid. |
Notes
The YAML payload declares component_order, optional numeric
defaults, and unordered first|second pair records. Missing pair
fields use the declared defaults, which are zero when omitted.
Source code in src/torch_flash/parameters/cubic_interactions.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
ppr78_group_contribution_parameters
¶
ppr78_group_contribution_parameters(
components: ComponentSet,
source: ParameterSource = DEFAULT_PPR78_GROUP_CONTRIBUTION,
*,
group_counts: Mapping[str, Mapping[str, float]]
| Tensor
| None = None,
) -> PPR78GroupContributionParameters
Load PPR78 or E-PPR78 group parameters for components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
ComponentSet
|
Ordered component set defining selected decompositions, dtype, and device. |
required |
source
|
ParameterSource
|
Bundled identifier, custom YAML path, mapping, or loaded parameter set. |
DEFAULT_PPR78_GROUP_CONTRIBUTION
|
group_counts
|
Mapping[str, Mapping[str, float]] | Tensor | None
|
Optional component-by-group counts as a mapping or tensor. Values are normalized into group fractions and override only source component decompositions. |
None
|
Returns:
| Type | Description |
|---|---|
PPR78GroupContributionParameters
|
Selected fractions and universal interaction tensors. Parameter sets
with explicitly unavailable pairs are reduced to the groups active in
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a requested component lacks a decomposition. |
ValueError
|
If explicit counts have invalid shapes or values. |
ParameterDatabaseError
|
If source identity, units, group inventory, interactions, or the availability of an active group pair is invalid. |
Notes
source may be the default 2004 saturated-hydrocarbon PPR78 set,
:data:PPR78_HYDROGEN_WATER_GROUP_CONTRIBUTION, a custom YAML path, or an
in-memory :class:~torch_flash.database.ModelParameterSet. The global
E-PPR78 parameterization is selected with
:data:DEFAULT_EPPR78_GROUP_CONTRIBUTION. The
H2/N2/H2O set is the exact active-group submatrix of the 2013 hydrogen and
water extensions, not a refit. Explicit group_counts override only
the component decompositions; the source still supplies the group
inventory and interaction matrices.
Source code in src/torch_flash/parameters/group_contribution.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
ppr78_mixing
¶
ppr78_mixing(
components: ComponentSet,
source: ParameterSource = DEFAULT_PPR78_GROUP_CONTRIBUTION,
*,
group_counts: Mapping[str, Mapping[str, float]]
| Tensor
| None = None,
trainable: bool = False,
) -> PPR78Mixing
Construct a differentiable PPR78 or E-PPR78 mixing rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
ComponentSet
|
Ordered component set. |
required |
source
|
ParameterSource
|
PPR78 or E-PPR78 parameter source. |
DEFAULT_PPR78_GROUP_CONTRIBUTION
|
group_counts
|
Mapping[str, Mapping[str, float]] | Tensor | None
|
Optional explicit component group counts overriding stored decompositions. Counts are normalized to molecular group fractions. |
None
|
trainable
|
bool
|
Register the independent, active off-diagonal A/B group interactions as PyTorch parameters. |
False
|
Returns:
| Type | Description |
|---|---|
PPR78Mixing
|
Mixing-rule module on the component set's dtype and device. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a requested component lacks a stored decomposition. |
ValueError
|
If explicit group counts or tensor values are invalid. |
ParameterDatabaseError
|
If the source inventory is malformed or an interaction between two active E-PPR78 groups is unavailable. |
Notes
The implemented correlation is Eq. (5) of Jaubert and Mutelet,
Fluid Phase Equilibria 224 (2004) 285--304,
doi:10.1016/j.fluid.2004.06.059. E-PPR78 uses the same equation with the
global interactions in Jaubert, Qian, Lasala, and Privat,
Fluid Phase Equilibria 560 (2022) 113456,
doi:10.1016/j.fluid.2022.113456, Table S4. For a source with unavailable
pairs, only the groups active in components are retained after every
active pair has been validated. All tensors honor the component set's
dtype and device.
Source code in src/torch_flash/parameters/group_contribution.py
binary_interaction
¶
binary_interaction(
components: ComponentSet,
parameter_set: ParameterSource,
eos: PetroleumEOS = "PR",
*,
aggregate_hydrocarbons: Iterable[str] = (),
) -> Tensor
Select a petroleum cubic-EOS binary-interaction matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
ComponentSet
|
Ordered component set defining matrix axes, dtype, and device. |
required |
parameter_set
|
ParameterSource
|
Bundled identifier, YAML path, mapping, or loaded petroleum binary-interaction parameter set. |
required |
eos
|
PetroleumEOS
|
Select the source's Peng--Robinson ( |
'PR'
|
aggregate_hydrocarbons
|
Iterable[str]
|
Component names in |
()
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Symmetric dimensionless |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If a requested component is outside the parameter inventory. |
ParameterDatabaseError
|
If the source model identity or table structure is invalid. |
Source code in src/torch_flash/parameters/petroleum.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
pedersen_binary_interaction
¶
pedersen_binary_interaction(
components: ComponentSet,
eos: PetroleumEOS = "PR",
*,
aggregate_hydrocarbons: Iterable[str] = (),
) -> Tensor
Return Pedersen et al. (2024), Table 4.2, kij values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
ComponentSet
|
Ordered component set defining output axes. |
required |
eos
|
PetroleumEOS
|
Source table, |
'PR'
|
aggregate_hydrocarbons
|
Iterable[str]
|
Explicit names of characterized hydrocarbon cuts that use the published C7+ interaction row. |
()
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Symmetric dimensionless interaction matrix. |
Notes
This is a distinct parameterization from Whitson's Table A-3. The source's aggregate C7+ entries are used for n-heptane through n-decane.
Source code in src/torch_flash/parameters/petroleum.py
whitson_binary_interaction
¶
whitson_binary_interaction(
components: ComponentSet, eos: PetroleumEOS = "PR"
) -> Tensor
Return Whitson and Brule (2000), Table A-3, kij values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
ComponentSet
|
Ordered component set defining output axes. |
required |
eos
|
PetroleumEOS
|
Source table, |
'PR'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Symmetric dimensionless interaction matrix. |
Notes
The source's C7+ values are applied from n-heptane through n-decane. The printed H2S/C7+ value is not silently extrapolated by carbon number.
Source code in src/torch_flash/parameters/petroleum.py
Parameter fitting¶
Calibration utilities preserve PyTorch gradients but do not by themselves establish identifiability or independent validation.
torch_flash.fitting
¶
Autodifferentiable thermodynamic parameter estimation.
FitResult
dataclass
¶
FitResult(
losses: tuple[float, ...],
converged: bool,
iterations: int,
final_loss: float,
stopping_reason: Literal[
"tolerance", "patience", "iteration-limit"
],
)
Optimization history and final convergence diagnostics.
Attributes:
| Name | Type | Description |
|---|---|---|
losses |
tuple[float, ...]
|
Scalar objective at the initial point followed by each accepted optimizer iterate. |
converged |
bool
|
Whether successive objective values met the relative stopping test. |
iterations |
int
|
Number of optimizer iterations executed. |
final_loss |
float
|
Minimum objective value retained in the supplied parameter tensors. |
stopping_reason |
Literal['tolerance', 'patience', 'iteration-limit']
|
|
Notes
Optimizer convergence does not establish parameter identifiability or model validation. Inspect sensitivities, parameter correlations, and independent holdout behavior separately.
CubicInteractionFitSystem
dataclass
¶
CubicInteractionFitSystem(
components: ComponentSet,
component_indices: tuple[int, ...],
states: tuple[PhaseTransitionState, ...],
)
One component subset and transition-state group in a cubic fit.
Attributes:
| Name | Type | Description |
|---|---|---|
components |
ComponentSet
|
Ordered component set used to construct this system's cubic model. |
component_indices |
tuple[int, ...]
|
Indices mapping |
states |
tuple[PhaseTransitionState, ...]
|
Phase-transition states used by the joint fit and sensitivity audit. |
CubicPhaseTransitionFitResult
dataclass
¶
CubicPhaseTransitionFitResult(
parameters: Tensor,
parameter_history: tuple[float, ...],
selected_iteration: int,
selected_loss: float,
optimizer_converged: bool,
iterations: int,
optimizer_stopping_reason: Literal[
"tolerance", "patience", "iteration-limit"
],
seed_evaluations: tuple[
tuple[PhaseTransitionEvaluation, ...], ...
],
sensitivity_matrix: Tensor,
sensitivity_singular_values: Tensor,
sensitivity_rank: int,
sensitivity_condition_number: float,
calibration_objective: CalibrationObjective,
optimizer: OptimizerKind,
sensitivity_kind: Literal[
"log-transition-pressure", "observed-state-fugacity"
],
fitted_states: tuple[
tuple[PhaseTransitionState, ...], ...
],
)
Bounded cubic-interaction fit and local identifiability diagnostics.
Attributes:
| Name | Type | Description |
|---|---|---|
parameters |
Tensor
|
Selected physical interaction vector in the declared pair order. |
parameter_history |
tuple[float, ...]
|
Scalar objective at the initial point followed by each accepted optimizer iterate. |
selected_iteration |
int
|
Zero-based optimizer-step index of the retained minimum-loss point. Zero identifies the initial point. |
selected_loss |
float
|
Loss at |
optimizer_converged |
bool
|
Whether the strict successive-loss stopping test was met. |
iterations |
int
|
Number of Adam iterations executed. |
optimizer_stopping_reason |
Literal['tolerance', 'patience', 'iteration-limit']
|
|
seed_evaluations |
tuple[tuple[PhaseTransitionEvaluation, ...], ...]
|
Source-parameter branch evaluations in system/state order. |
sensitivity_matrix |
Tensor
|
Jacobian of fitted log pressure ratios with respect to physical interaction parameters. Nonfinite rows are excluded. |
sensitivity_singular_values |
Tensor
|
Singular values of |
sensitivity_rank |
int
|
Numerical matrix rank using dtype-aware SVD tolerance. |
sensitivity_condition_number |
float
|
Largest/smallest singular-value ratio, or infinity when rank deficient. |
calibration_objective |
CalibrationObjective
|
Residual formulation minimized during calibration. |
optimizer |
OptimizerKind
|
PyTorch optimizer used for parameter updates. |
sensitivity_kind |
Literal['log-transition-pressure', 'observed-state-fugacity']
|
Scientific meaning of the rows in |
fitted_states |
tuple[tuple[PhaseTransitionState, ...], ...]
|
Phase-transition states in input system/state order with the selected incipient branch compositions installed as explicit initializers. |
build_cubic_interaction_models
¶
build_cubic_interaction_models(
constructor: Callable[..., StateModel],
systems: Sequence[CubicInteractionFitSystem],
parameters: Tensor,
*,
kij_pairs: Sequence[tuple[int, int]],
lij_pairs: Sequence[tuple[int, int]] = (),
) -> tuple[StateModel, ...]
Construct matched cubic systems from one shared interaction vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constructor
|
Callable[..., StateModel]
|
Cubic model constructor accepting |
required |
systems
|
Sequence[CubicInteractionFitSystem]
|
Component subsets and their master-component index mappings. |
required |
parameters
|
Tensor
|
One-dimensional tensor containing all |
required |
kij_pairs
|
Sequence[tuple[int, int]]
|
Unique off-diagonal master-component index pairs. Returned models use symmetric zero-diagonal matrices. |
required |
lij_pairs
|
Sequence[tuple[int, int]]
|
Unique off-diagonal master-component index pairs. Returned models use symmetric zero-diagonal matrices. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
One constructed model per system in input order. Parameter gradients, dtype, and device are preserved. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If parameters, system mappings, or interaction pairs are invalid. |
Source code in src/torch_flash/fitting.py
fit_cubic_phase_transition_interactions
¶
fit_cubic_phase_transition_interactions(
constructor: Callable[..., StateModel],
systems: Sequence[CubicInteractionFitSystem],
initial_parameters: Tensor,
lower_bounds: Tensor,
upper_bounds: Tensor,
*,
kij_pairs: Sequence[tuple[int, int]],
lij_pairs: Sequence[tuple[int, int]] = (),
objective: CalibrationObjective = "transition-pressure",
optimizer: OptimizerKind = "adam",
learning_rate: float = 0.005,
weight_decay: float = 0.0,
momentum: float = 0.0,
max_iterations: int = 30,
stopping_tolerance: float = 1e-09,
no_improvement_patience: int | None = 6,
fugacity_tolerance: float = 1e-07,
solver_iterations: int = 24,
minimum_phase_separation: float = 0.002,
fugacity_penalty: float = 0.05,
phase_merge_penalty: float = 5.0,
parameter_prior_weight: float = 0.0,
) -> CubicPhaseTransitionFitResult
Fit shared conventional-cubic interactions to phase-transition states.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constructor
|
Callable[..., StateModel]
|
Cubic model constructor accepting component, |
required |
systems
|
Sequence[CubicInteractionFitSystem]
|
Component subsets, master-index mappings, and two-phase transition states. Two-phase boundaries and binary three-phase invariants are included in one joint objective. |
required |
initial_parameters
|
Tensor
|
Interior physical interaction vector in |
required |
lower_bounds
|
Tensor
|
Finite physical bounds with the same shape as |
required |
upper_bounds
|
Tensor
|
Finite physical bounds with the same shape as |
required |
kij_pairs
|
Sequence[tuple[int, int]]
|
Shared master-component pair identities. |
required |
lij_pairs
|
Sequence[tuple[int, int]]
|
Shared master-component pair identities. |
required |
objective
|
CalibrationObjective
|
|
'transition-pressure'
|
optimizer
|
OptimizerKind
|
PyTorch optimizer: |
'adam'
|
learning_rate
|
float
|
Optimizer learning rate in unconstrained coordinates. |
0.005
|
weight_decay
|
float
|
Nonnegative optimizer weight decay. Keep zero unless a regularization prior on the transformed variables is scientifically justified. |
0.0
|
momentum
|
float
|
SGD momentum. Ignored by Adam and AdamW. |
0.0
|
max_iterations
|
int
|
Maximum optimizer iterations. |
30
|
stopping_tolerance
|
float
|
Relative successive-loss stopping threshold. |
1e-09
|
no_improvement_patience
|
int | None
|
Stop after this many evaluated losses without a new minimum. |
6
|
fugacity_tolerance
|
float
|
Local transition-pressure solver controls. They apply to the
|
1e-07
|
solver_iterations
|
float
|
Local transition-pressure solver controls. They apply to the
|
1e-07
|
minimum_phase_separation
|
float
|
Minimum selected-component mole-fraction difference. The simultaneous observed-state objective enforces it by construction, rather than allowing the algebraic homogeneous solution. |
0.002
|
fugacity_penalty
|
float
|
Weight on mean squared dimensionless fugacity residual. |
0.05
|
phase_merge_penalty
|
float
|
Weight on squared phase-separation shortfall. |
5.0
|
parameter_prior_weight
|
float
|
Nonnegative quadratic prior weight on the bounded physical interaction
displacement from |
0.0
|
Returns:
| Type | Description |
|---|---|
CubicPhaseTransitionFitResult
|
Minimum-loss bounded parameters, complete optimization history, source-seed branch results, and a local sensitivity SVD. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If bounds, parameters, pair identities, states, objective, optimizer, or numerical controls are invalid, or the selected objective cannot represent a requested state. |
Notes
Branches are identified once at initial_parameters using
:func:torch_flash.envelope.evaluate_phase_transition_state; the selected
or fallback physically separated incipient composition initializes the
same branch during autodiff optimization. The simultaneous observed-state
formulation evaluates every experimental state in every optimizer step,
avoids differentiating through a failed nested pressure solve, and keeps
the latent incipient compositions strictly separated from the parent.
The minimum-loss evaluated iterate is retained even when a later first-order step increases the objective. SVD rank and condition number diagnose only the reported local residual Jacobian; they do not establish a unique global fit.
Source code in src/torch_flash/fitting.py
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 | |
least_squares_loss
¶
least_squares_loss(
prediction: Tensor,
observation: Tensor,
*,
scale: Tensor | float = 1.0,
weights: Tensor | None = None,
) -> Tensor
Return a dimensionless weighted mean-square residual.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction
|
Tensor
|
Broadcast-compatible model predictions and observations in matching physical units. |
required |
observation
|
Tensor
|
Broadcast-compatible model predictions and observations in matching physical units. |
required |
scale
|
Tensor | float
|
Positive residual scale in the same units. Scalar or broadcastable tensor. |
1.0
|
weights
|
Tensor | None
|
Optional nonnegative statistical weights, broadcastable to the residual shape. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar mean of the squared, scaled residuals; weights enter through their square roots. |
Source code in src/torch_flash/fitting.py
phase_equilibrium_residual
¶
phase_equilibrium_residual(
model: StateModel,
temperature: Tensor,
pressure: Tensor,
phase1_composition: Tensor,
phase2_composition: Tensor,
*,
phase_kinds: tuple[PhaseKind, PhaseKind] = (
"liquid",
"vapor",
),
) -> Tensor
Return component log-fugacity equalities for measured phase pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
StateModel
|
Homogeneous-state fugacity model. |
required |
temperature
|
Tensor
|
Scalar or batched temperatures in K and pressures in Pa. |
required |
pressure
|
Tensor
|
Scalar or batched temperatures in K and pressures in Pa. |
required |
phase1_composition
|
Tensor
|
Equally shaped, strictly positive phase mole fractions. |
required |
phase2_composition
|
Tensor
|
Equally shaped, strictly positive phase mole fractions. |
required |
phase_kinds
|
tuple[PhaseKind, PhaseKind]
|
Root request corresponding to each measured phase. |
('liquid', 'vapor')
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Dimensionless component residual
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If phase compositions differ in shape or are nonpositive/nonfinite. |
Notes
Inputs may contain independent batched states. The residual is dimensionless and is zero when every component has equal fugacity in the two requested phases. Strictly positive compositions are required because the thermodynamic equality is evaluated in logarithmic form.
Source code in src/torch_flash/fitting.py
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 | |
fit_parameters
¶
fit_parameters(
parameters: Iterable[Parameter],
closure: Callable[[], Tensor],
*,
optimizer: OptimizerKind = "adam",
learning_rate: float = 0.05,
weight_decay: float = 0.0,
momentum: float = 0.0,
max_iterations: int = 500,
tolerance: float = 1e-10,
no_improvement_patience: int | None = None,
) -> FitResult
Fit arbitrary PyTorch thermodynamic parameters with a PyTorch optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Iterable[Parameter]
|
Trainable tensors passed to the selected optimizer. |
required |
closure
|
Callable[[], Tensor]
|
Zero-argument function that recomputes one finite differentiable scalar loss. |
required |
optimizer
|
OptimizerKind
|
|
'adam'
|
learning_rate
|
float
|
Optimizer learning rate. |
0.05
|
weight_decay
|
float
|
Nonnegative optimizer weight decay. A nonzero value is a regularizer, not a numerical acceleration, and requires a defensible prior. |
0.0
|
momentum
|
float
|
SGD momentum in |
0.0
|
max_iterations
|
int
|
Maximum optimizer steps. |
500
|
tolerance
|
float
|
Relative successive-loss stopping threshold. |
1e-10
|
no_improvement_patience
|
int | None
|
Optional number of consecutive evaluated losses without a new
minimum before stopping. The returned |
None
|
Returns:
| Type | Description |
|---|---|
FitResult
|
Initial and accepted-iterate loss history plus explicit stopping diagnostics. The supplied tensors are restored to the minimum-loss accepted point. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no parameters are supplied or the closure returns a nonfinite or nonscalar loss. |
Notes
The closure must recompute and return a scalar differentiable loss. Bounds can be imposed by parameterizing physical values through sigmoid/softplus transforms in the model.
Source code in src/torch_flash/fitting.py
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 | |