Optional backends and numerical solvers¶
External backends are optional homogeneous-state references. They are not silently substituted for native models and are not required by normal tests.
Optional backends¶
torch_flash.backends
¶
Optional validation backends.
BackendCapabilities
dataclass
¶
Capabilities declared by an optional validation backend.
Attributes:
| Name | Type | Description |
|---|---|---|
autodiff |
bool
|
Whether backend outputs participate in PyTorch automatic differentiation. |
gpu |
bool
|
Whether the backend can execute on accelerator tensors. |
fugacity_coefficients |
bool
|
Whether component fugacity coefficients are exposed. |
exact_model |
str
|
Model identity implemented by the backend, for matched-input verification rather than name-only comparison. |
CoolPropBackend
¶
CoolProp AbstractState wrapper.
This backend is intended for independent validation and frozen baselines.
It is CPU-only and not differentiable. HEOS uses multifluid mixture
machinery with GERG-style reducing/departure functions but is not labeled
as the published GERG-2008 coefficient set. Exact GERG through REFPROP
requires a licensed REFPROP installation configured by the user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
tuple[str, ...]
|
Canonical component names in composition-axis order. |
required |
backend
|
Literal['HEOS', 'REFPROP']
|
CoolProp |
'HEOS'
|
Notes
Inputs are copied through CPU scalars/lists. Returned tensors match the caller's dtype/device but are detached from PyTorch autograd.
Source code in src/torch_flash/backends/coolprop.py
select_z
¶
select_z(
temperature: Tensor,
pressure: Tensor,
composition: Tensor,
phase: PhaseKind = "stable",
) -> Tensor
Return CoolProp compressibility factor.
Source code in src/torch_flash/backends/coolprop.py
molar_volume
¶
molar_volume(
temperature: Tensor,
pressure: Tensor,
composition: Tensor,
phase: PhaseKind = "stable",
) -> Tensor
Return CoolProp molar volume.
Source code in src/torch_flash/backends/coolprop.py
log_fugacity_coefficients
¶
log_fugacity_coefficients(
temperature: Tensor,
pressure: Tensor,
composition: Tensor,
phase: PhaseKind = "stable",
) -> Tensor
Return CoolProp log fugacity coefficients.
Source code in src/torch_flash/backends/coolprop.py
TeqpBackend
¶
Wrap a teqp residual model as a homogeneous-state model.
teqp is deliberately optional and all values cross a CPU/NumPy boundary, so this adapter is for validation rather than differentiable production calculations. The GERG constructor uses the published hard-coded GERG-2008 residual coefficient set shipped by teqp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
tuple[str, ...]
|
Canonical component names in composition-axis order. |
required |
model
|
Any
|
Constructed teqp residual model object. |
required |
exact_model
|
str
|
Explicit coefficient/model identity reported through capabilities. |
required |
Notes
Inputs cross a CPU/NumPy boundary. Returned tensors match the caller's dtype/device but are not differentiable.
Source code in src/torch_flash/backends/teqp.py
canonical_peng_robinson
classmethod
¶
canonical_peng_robinson(
components: ComponentSet,
) -> TeqpBackend
Construct teqp's canonical Peng-Robinson model.
Source code in src/torch_flash/backends/teqp.py
gerg2008
classmethod
¶
gerg2008(names: tuple[str, ...]) -> TeqpBackend
Construct teqp's exact GERG-2008 residual model.
Source code in src/torch_flash/backends/teqp.py
eoscg_2015
classmethod
¶
eoscg_2015(names: tuple[str, ...]) -> TeqpBackend
Construct the complete 2015 EOS-CG multiparameter mixture model.
The six-component scope is CO2, water, nitrogen, oxygen, argon, and carbon monoxide. teqp loads the pure-fluid Helmholtz equations plus the Gernert--Span binary reducing and departure parameters through its multifluid model factory and versioned CoolProp-format data files.
Source code in src/torch_flash/backends/teqp.py
molar_volume
¶
molar_volume(
temperature: Tensor,
pressure: Tensor,
composition: Tensor,
phase: PhaseKind = "stable",
) -> Tensor
Return a teqp molar-volume root in m3/mol.
Source code in src/torch_flash/backends/teqp.py
pressure
¶
Return pressure at a prescribed homogeneous density.
Source code in src/torch_flash/backends/teqp.py
select_z
¶
select_z(
temperature: Tensor,
pressure: Tensor,
composition: Tensor,
phase: PhaseKind = "stable",
) -> Tensor
Return compressibility factor.
Source code in src/torch_flash/backends/teqp.py
log_fugacity_coefficients
¶
log_fugacity_coefficients(
temperature: Tensor,
pressure: Tensor,
composition: Tensor,
phase: PhaseKind = "stable",
) -> Tensor
Return teqp residual-model fugacity coefficients.
Source code in src/torch_flash/backends/teqp.py
Numerical solvers¶
torch_flash.solvers
¶
Reusable autodifferentiable nonlinear solvers.
BatchedNewtonResult
dataclass
¶
BatchedNewtonResult(
solution: Tensor,
residual: Tensor,
residual_norm: Tensor,
iterations: Tensor,
converged: Tensor,
)
Solutions and diagnostics from :func:batched_damped_newton.
Attributes:
| Name | Type | Description |
|---|---|---|
solution |
Tensor
|
Final variables with shape |
residual |
Tensor
|
Residual vectors evaluated at |
residual_norm |
Tensor
|
Per-system infinity norms with shape |
iterations |
Tensor
|
Per-system outer iteration counts with shape |
converged |
Tensor
|
Per-system convergence flags with shape |
NewtonResult
dataclass
¶
NewtonResult(
solution: Tensor,
residual: Tensor,
residual_norm: Tensor,
iterations: int,
converged: bool,
)
Solution and diagnostics from :func:damped_newton.
Attributes:
| Name | Type | Description |
|---|---|---|
solution |
Tensor
|
Final iterate. |
residual |
Tensor
|
Residual vector evaluated at |
residual_norm |
Tensor
|
Maximum absolute residual component. |
iterations |
int
|
Number of outer Newton iterations executed. |
converged |
bool
|
Whether |
BatchedTrustRegionResult
dataclass
¶
BatchedTrustRegionResult(
solution: Tensor,
objective: Tensor,
gradient_norm: Tensor,
minimum_hessian_eigenvalue: Tensor,
iterations: Tensor,
converged: Tensor,
accepted_steps: Tensor,
rejected_steps: Tensor,
trust_radius: Tensor,
)
Independent dense trust-region minimizations executed in one batch.
Attributes:
| Name | Type | Description |
|---|---|---|
solution |
Tensor
|
Final variables with shape |
objective |
Tensor
|
Final scalar objective per independent state with shape |
gradient_norm |
Tensor
|
Final infinity-norm objective gradient per state. |
minimum_hessian_eigenvalue |
Tensor
|
Smallest eigenvalue of each final symmetrized Hessian. |
iterations |
Tensor
|
Outer trust-region iterations performed per state. |
converged |
Tensor
|
Per-state flags requiring the gradient and local-curvature gates. |
accepted_steps, rejected_steps |
Per-state counts based on actual versus quadratic-model reduction. |
|
trust_radius |
Tensor
|
Final Euclidean trust-region radius per state. |
TrustRegionResult
dataclass
¶
TrustRegionResult(
solution: Tensor,
objective: Tensor,
gradient_norm: Tensor,
minimum_hessian_eigenvalue: Tensor,
iterations: int,
converged: bool,
accepted_steps: int,
rejected_steps: int,
trust_radius: Tensor,
)
Result and convergence diagnostics from dense trust-region minimization.
Attributes:
| Name | Type | Description |
|---|---|---|
solution |
Tensor
|
Final variable vector. Its dtype, device, and autodiff graph follow
|
objective |
Tensor
|
Scalar objective evaluated at |
gradient_norm |
Tensor
|
Infinity norm of the final objective gradient. |
minimum_hessian_eigenvalue |
Tensor
|
Smallest eigenvalue of the final symmetrized Hessian. A converged local minimum requires it to be nonnegative within dtype-aware roundoff. |
iterations |
int
|
Number of outer trust-region iterations. |
converged |
bool
|
Whether |
accepted_steps, rejected_steps |
Counts based on agreement between the exact objective reduction and its local quadratic model. |
|
trust_radius |
Tensor
|
Final Euclidean trust-region radius. |
batched_damped_newton
¶
batched_damped_newton(
residual_function: Callable[..., Tensor],
initial: Tensor,
*residual_arguments: Tensor,
tolerance: float = 1e-08,
max_iterations: int = 50,
max_line_search: int = 16,
lower_bound: Tensor | None = None,
upper_bound: Tensor | None = None,
) -> BatchedNewtonResult
Solve independent small nonlinear systems in one PyTorch batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residual_function
|
Callable[..., Tensor]
|
Batched mapping. Its first argument is the complete variable tensor;
subsequent arguments are the complete tensors in
|
required |
initial
|
Tensor
|
Initial variables with shape |
required |
*residual_arguments
|
Tensor
|
Tensors whose leading dimension equals |
()
|
tolerance
|
float
|
Absolute per-system infinity-norm convergence threshold. |
1e-08
|
max_iterations
|
int
|
Maximum damped-Newton iterations. |
50
|
max_line_search
|
int
|
Maximum residual-decreasing backtracking trials per iteration. |
16
|
lower_bound
|
Tensor | None
|
Optional bounds broadcastable to |
None
|
upper_bound
|
Tensor | None
|
Optional bounds broadcastable to |
None
|
Returns:
| Type | Description |
|---|---|
BatchedNewtonResult
|
Per-system solutions, residuals, iteration counts, and convergence. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes or numerical controls are invalid. |
Notes
Exact per-system Jacobian blocks come from
:func:torch.func.jacrev of each residual component summed across the
independent batch. This evaluates only the block diagonal implied by
independent systems rather than constructing and discarding cross-batch
zero blocks. Gradients through model parameters and accepted Newton
iterates are preserved. A singular direct solve falls back to a batched
least-squares step. Failed systems remain explicit in the returned
diagnostics.
Source code in src/torch_flash/solvers/newton.py
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 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 | |
damped_newton
¶
damped_newton(
residual_function: Callable[[Tensor], Tensor],
initial: Tensor,
*,
tolerance: float = 1e-08,
max_iterations: int = 50,
max_line_search: int = 16,
lower_bound: Tensor | None = None,
upper_bound: Tensor | None = None,
jacobian_refresh_interval: int = 1,
) -> NewtonResult
Solve a square nonlinear system with autodiff and backtracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residual_function
|
Callable[[Tensor], Tensor]
|
Differentiable mapping from the variable tensor to an equally sized residual tensor. |
required |
initial
|
Tensor
|
Initial variable tensor; dtype and device are preserved. |
required |
tolerance
|
float
|
Absolute infinity-norm convergence threshold. |
1e-08
|
max_iterations
|
int
|
Maximum Newton iterations. |
50
|
max_line_search
|
int
|
Maximum residual-decreasing backtracking trials per iteration. |
16
|
lower_bound
|
Tensor | None
|
Optional elementwise projection bounds broadcastable to |
None
|
upper_bound
|
Tensor | None
|
Optional elementwise projection bounds broadcastable to |
None
|
jacobian_refresh_interval
|
int
|
Recompute the exact autodiff Jacobian after this many accepted iterations. Values above one use rank-one Broyden updates between refreshes; the default preserves full Newton behavior. |
1
|
Returns:
| Type | Description |
|---|---|
NewtonResult
|
Final iterate and explicit convergence diagnostics. |
Notes
A singular square solve falls back to a least-squares step. Failure to converge is reported in the result and is never silently converted into a successful solve.
Source code in src/torch_flash/solvers/newton.py
248 249 250 251 252 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 359 360 361 362 | |
minimize_batched_dense_trust_region
¶
minimize_batched_dense_trust_region(
objective: Callable[..., Tensor],
initial: Tensor,
*objective_arguments: Tensor,
is_feasible: Callable[[Tensor], Tensor] | None = None,
initial_radius: float | Tensor = 0.5,
maximum_radius: float | Tensor = 5.0,
gradient_tolerance: float = 1e-09,
max_iterations: int = 100,
acceptance_threshold: float = 0.0,
subproblem_tolerance: float = 1e-08,
max_subproblem_iterations: int = 80,
) -> BatchedTrustRegionResult
Minimize independent small dense objectives in one PyTorch batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
Callable[..., Tensor]
|
Mapping from the complete variable tensor and optional complete
|
required |
initial
|
Tensor
|
Finite initial variables with shape |
required |
*objective_arguments
|
Tensor
|
Tensors sharing the leading batch size. |
()
|
is_feasible
|
Callable[[Tensor], Tensor] | None
|
Optional predicate returning one Boolean per batch row. Infeasible trial rows are rejected without evaluating their objective. Every initial row must be feasible. |
None
|
initial_radius
|
float | Tensor
|
Positive scalars or per-state tensors with shape |
0.5
|
maximum_radius
|
float | Tensor
|
Positive scalars or per-state tensors with shape |
0.5
|
gradient_tolerance
|
float
|
|
1e-09
|
max_iterations
|
float
|
|
1e-09
|
acceptance_threshold
|
float
|
|
1e-09
|
subproblem_tolerance
|
float
|
Controls with the same meaning as
:func: |
1e-08
|
max_subproblem_iterations
|
float
|
Controls with the same meaning as
:func: |
1e-08
|
Returns:
| Type | Description |
|---|---|
BatchedTrustRegionResult
|
Per-state solutions and convergence, curvature, iteration, step, and radius diagnostics. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If batch shapes, radii, controls, or objective values are invalid. |
Notes
PyTorch evaluates the objective, gradients, and exact block-diagonal Hessians over the complete state batch. Only the tiny Moré-Sorensen spectral subproblem is dispatched row by row. This avoids coupling independent phase states while keeping the thermodynamic kernels vectorized on CPU or accelerator devices.
Source code in src/torch_flash/solvers/trust_region.py
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 | |
minimize_dense_trust_region
¶
minimize_dense_trust_region(
objective: Callable[[Tensor], Tensor],
initial: Tensor,
*,
is_feasible: Callable[[Tensor], bool] | None = None,
initial_radius: float | Tensor | None = None,
maximum_radius: float | Tensor | None = None,
gradient_tolerance: float = 1e-09,
max_iterations: int = 100,
acceptance_threshold: float = 0.0,
subproblem_tolerance: float = 1e-08,
max_subproblem_iterations: int = 80,
) -> TrustRegionResult
Minimize a scalar objective with an exact small dense trust region.
This operation implements the restricted-step formulation used for phase stability and multiphase Gibbs minimization by M. Petitfrere and D. V. Nichita, "Robust and efficient Trust-Region based stability analysis and multiphase flash calculations", Fluid Phase Equilibria 362 (2014), 51-68, sections 3.1-3.4, doi:10.1016/j.fluid.2013.08.039. The dense quadratic subproblem follows the Moré-Sorensen eigenvalue-shift conditions. It is intended for the small systems typical of compositional phase calculations, not large sparse optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
Callable[[Tensor], Tensor]
|
Differentiable mapping from one variable vector to one finite scalar. Gradients and exact Hessians are assembled with PyTorch autodiff. |
required |
initial
|
Tensor
|
One-dimensional starting vector. |
required |
is_feasible
|
Callable[[Tensor], bool] | None
|
Optional predicate for hard variable bounds. Infeasible trial steps
are rejected without evaluating |
None
|
initial_radius
|
float | Tensor | None
|
Positive initial Euclidean radius. The paper's flash choice
|
None
|
maximum_radius
|
float | Tensor | None
|
Positive maximum radius. Ten times the initial radius is used when omitted. |
None
|
gradient_tolerance
|
float
|
Convergence threshold for the infinity norm of the objective gradient. |
1e-09
|
max_iterations
|
int
|
Maximum accepted-or-rejected outer iterations. |
100
|
acceptance_threshold
|
float
|
Minimum actual-to-predicted reduction ratio for accepting a step. Zero matches the phase-equilibrium algorithm in section 3.4. |
0.0
|
subproblem_tolerance
|
float
|
Relative radius tolerance for the shifted-Hessian subproblem. |
1e-08
|
max_subproblem_iterations
|
int
|
Maximum safeguarded scalar shift iterations. |
80
|
Returns:
| Type | Description |
|---|---|
TrustRegionResult
|
Final variables, objective and gradient diagnostics, iteration and step counts, and the final trust radius. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the initial tensor is not a finite vector, controls are invalid, or the objective is not a finite scalar. |
Notes
The method is a local minimizer. It does not prove that a tangent-plane or Gibbs minimum is global; phase calculations still require multiple starts, material-balance checks, and stability tests. A negative or poorly predicted step is rejected rather than returned as convergence.
Source code in src/torch_flash/solvers/trust_region.py
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 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 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 | |