Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions REGISTER.md
Original file line number Diff line number Diff line change
Expand Up @@ -29636,3 +29636,45 @@ tabulate (the table model clamps outside its range, so only in-range points coun
- **Status:** decided (2026-11-12). Open: the 6-9e-4 offset from Eimerl's indices;
Chen et al.'s tabulation and Zhang et al. (2000) would settle it, and neither is in
the library.

## TC-1096 CoolProp without superancillaries: the same densities, a seventh of the load (2026-11-16)

- **Where:** `optmat.gas.eos` (`_coolprop`, `_quiet_stdout`, `_update_gas`,
`EVALUATION_VERSION`), `tests/test_coolprop_loading.py`,
`tests/data/golden_models.json`.
- **Claim:** CoolProp 8.0.0 builds the superancillaries of all of its fluids (about 120)
when it first loads, which is 0.43 s of its 0.46 s load (measured on an Apple M-series
laptop; `COOLPROP_DISABLE_SUPERANCILLARIES_ENTIRELY`, read in `FluidLibrary.h` as the
fluids are parsed, skips them: 0.067 s). optmat sets that variable for its import of
CoolProp, unless it is already set, removes it again so that child processes do not
take it for the user's, and hides CoolProp's notice of it on standard output. Without
superancillaries CoolProp finds a pressure-temperature state's phase with a
saturation solve that refuses pressures under its triple point's, which the phase
domain reaches just above the triple point (every gas's
`test_the_inverse_round_trips_across_the_domain` failed there); below the critical
temperature, where every caller has already checked that the state is the vapour,
optmat now tells CoolProp so (`iphase_gas`).
- **Checked:** against optmat 0.9.1 (superancillaries, phase found by CoolProp).
- Densities: every gas with an equation, 12 temperatures from its triple point to
600 K and a fixed grid of 40 pressures from 100 Pa to 200 bar within the domain
(5924 states): every density bitwise the same; the imposed phase alone changes
nothing.
- The critical temperature: CoolProp reports the equation's stated critical
temperature instead of the critical point of its superancillary, which is where
the equation's coexistence actually ends. Oxygen's moves from 154.599 K to the
published 154.581 K (1.2e-4), hydrogen's by 2.0e-5, the others' by at most 2.1e-6.
Oxygen between the two is now supercritical: its domain there ends at the
equation's 800 bar, not at the vapour pressure (about 50 bar).
- Saturation pressures, and so the domain's top: 300 temperatures per gas, denser
towards the critical point. More than 1 K below it they move by at most 7.1e-11
(oxygen's at its triple point, 146 Pa, by 2.0e-9); within 1 K by at most 6.5e-8
(hydrogen, 0.7 mK below it), the tolerance of CoolProp's saturation solve, which
they now come from. Within 60 µK of helium's critical point and 4.4 µK of SF6's the
solve is worse than 1e-6 (helium's 1 % at 2 µK, SF6's 2.2e-4) or, for helium within
40 µK, raises CoolProp's own `ValueError` rather than a `StateError`.
- **Decided:** `EVALUATION_VERSION` of `optmat.gas.eos` is raised to 2 (the maintainer,
2026-11-17): the critical temperature is a field of every equation's identity, so the
identities change anyway, and the domain moves near the critical points. 57 golden
identities were re-recorded (equations of state, their mixtures, transport and air
models); no golden value changed.
- **Status:** decided (2026-11-17).
9 changes: 9 additions & 0 deletions changelog.d/coolprop-no-superancillaries.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CoolProp is loaded without the superancillaries it builds for all of its fluids, unless
`COOLPROP_DISABLE_SUPERANCILLARIES_ENTIRELY` is already set or CoolProp was imported
first: the first real-gas density takes 0.07 s instead of 0.46 s. No density at a given
state changed and no recommended value moved, but the identity of every equation of
state, and of the mixture, transport and air models built on one, changes: the
equation-of-state `EVALUATION_VERSION` is now 2. A gas's critical temperature is now its
equation's stated value (oxygen 154.581 K instead of 154.599 K; others within 2e-5), and
saturation pressures, so where a gas's domain ends, move by at most 7e-11 more than 1 K
below the critical point and by up to 7e-8 within it (TC-1096).
11 changes: 11 additions & 0 deletions docs/conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ it with its identity (CoolProp's version, the fluid and the equation's reference
CODATA's $k_B$, not the equation's mass density, which carries the gas constant of its
publication (argon's, 5.7 ppm from CODATA's).

**Loading CoolProp.** optmat imports CoolProp on the first real-gas density, without the
superancillaries CoolProp would otherwise build for every one of its fluids: they are
most of its load time (0.46 s against 0.07 s), and no density at a given state changes
without them. A gas's critical temperature is then its equation's stated value (oxygen's
154.581 K, not the 154.599 K where its coexistence ends), and saturation pressures, so
where a gas's domain ends, come from CoolProp's saturation solve: within 7 × 10⁻¹¹ of the
superancillaries' more than 1 K below the critical point, and to 7 × 10⁻⁸ within it, but
not within some tens of microkelvin of it (TC-1096). Set
`COOLPROP_DISABLE_SUPERANCILLARIES_ENTIRELY` yourself, or import CoolProp before optmat
does, to choose otherwise; the variable is read once, when CoolProp loads.

**The molar mass.** `molar_mass` is the molar mass the backend's equation uses, kg/mol:
the one its mass density and its speed of sound are formed with, for a propagation
code's mass terms. The number densities do not use it. For the pseudo-pure dry air of
Expand Down
115 changes: 109 additions & 6 deletions src/optmat/gas/eos.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
quantity, which needs the number density the author actually meant.

Real-gas densities come from CoolProp's Helmholtz-energy equations of state, imported
lazily because CoolProp takes about a second to load. :func:`equation_of_state` returns
lazily, and without its superancillaries unless they were asked for (TC-1096): building
them for every one of its fluids is most of CoolProp's load time (0.43 s of 0.46 s), and
no density optmat reads changes without them; the critical temperature is the
equation's stated one, and saturation pressures agree to rounding except close to it.
Set ``COOLPROP_DISABLE_SUPERANCILLARIES_ENTIRELY`` yourself, or import
CoolProp before optmat loads it, to decide otherwise. :func:`equation_of_state` returns
a gas's equation as an object with an identity: its forward law
``N = p / (Z k_B T)``, its inverse (the pressure at a number density and temperature),
its speed of sound, its molar mass and its phase domain (OEP 1, section 4.2).
Expand All @@ -33,8 +38,14 @@
"""

import atexit
import contextlib
import ctypes
import functools
import os
import sys
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any, ClassVar, Final

import numpy as np
Expand All @@ -60,7 +71,7 @@
"pressure",
]

EVALUATION_VERSION: Final = 1
EVALUATION_VERSION: Final = 2
"""The version of this module's evaluation code, in the identity of every model that
evaluates through it; raised whenever the code changes its output (OEP 1, section 4.8).
"""
Expand Down Expand Up @@ -106,9 +117,55 @@ def ideal_number_density(state: State) -> float:
return state.pressure / (K_B * state.temperature)


_NO_SUPERANCILLARIES: Final = "COOLPROP_DISABLE_SUPERANCILLARIES_ENTIRELY"
"""CoolProp's switch, read once as it loads its fluids, that skips superancillaries."""


@contextlib.contextmanager
def _quiet_stdout() -> Iterator[None]:
"""Send what native code writes to standard output nowhere for the block.

CoolProp announces on standard output that superancillaries are disabled. The
file descriptor itself is redirected, since the line comes from C++. C's buffers are
flushed before it is redirected, so that earlier output still reaches it, and again
before it is restored. Without a usable descriptor 1 the block runs as it is.

- Yields: nothing.
"""
try:
sys.stdout.flush()
_flush_c_streams()
saved = os.dup(1)
Comment on lines +136 to +138

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Flush native output before redirecting stdout

When stdout is redirected to a pipe or file, native libraries can have buffered output pending before the first real-gas call. sys.stdout.flush() only flushes Python's stream, so that native output remains buffered until _flush_c_streams() runs while descriptor 1 points to /dev/null, silently discarding the caller's output along with CoolProp's notice. This is reproducible by calling libc printf before entering _quiet_stdout(). Flush the native streams before redirecting descriptor 1 as well as before restoring it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7043d9b: _quiet_stdout now flushes C's buffers before redirecting descriptor 1 as well as before restoring it. test_native_output_written_before_the_block_is_kept checks it with libc printf; it fails without the fix.

except (AttributeError, OSError, ValueError):
yield
return
try:
with Path(os.devnull).open("wb") as sink:
os.dup2(sink.fileno(), 1)
try:
yield
finally:
_flush_c_streams()
finally:
os.dup2(saved, 1)
os.close(saved)


def _flush_c_streams() -> None:
"""Flush C's output buffers (``fflush(NULL)``), where the C library can be found."""
with contextlib.suppress(AttributeError, OSError):
library = ctypes.CDLL(None) if os.name == "posix" else ctypes.cdll.ucrtbase
library.fflush(None)


@functools.cache
def _coolprop() -> Any:
"""Return CoolProp's module, imported on first use.
"""Return CoolProp's module, imported on first use, without superancillaries.

Unless :data:`_NO_SUPERANCILLARIES` is already set, it is set for the import alone,
which loads CoolProp's fluids, and CoolProp's notice of it is not printed; it is
removed again so that child processes do not inherit it. CoolProp imported earlier
keeps the fluids it loaded.

Returns
-------
Expand All @@ -120,14 +177,30 @@ def _coolprop() -> Any:
ImportError
Without the ``gas`` extra.
"""
asked = _NO_SUPERANCILLARIES in os.environ
try:
import CoolProp.CoolProp as coolprop # noqa: N813, PLC0415 - import cost
with contextlib.nullcontext() if asked else _without_superancillaries():
import CoolProp.CoolProp as coolprop # noqa: N813, PLC0415 - import cost
except ImportError as exc:
msg = "real-gas densities need CoolProp: install optmat[gas]"
raise ImportError(msg) from exc
return coolprop


@contextlib.contextmanager
def _without_superancillaries() -> Iterator[None]:
"""Set :data:`_NO_SUPERANCILLARIES` for the block, with standard output quiet.

- Yields: nothing.
"""
os.environ[_NO_SUPERANCILLARIES] = "1"
try:
with _quiet_stdout():
yield
finally:
del os.environ[_NO_SUPERANCILLARIES]


@functools.cache
def _abstract_state(fluid: str) -> Any:
"""Return CoolProp's Helmholtz-energy state of a fluid (one per fluid, reused).
Expand Down Expand Up @@ -158,6 +231,36 @@ def _release() -> None:
atexit.register(_release)


def _update_gas(backend: Any, pressure: float, temperature: float) -> None:
"""Set a CoolProp state to a pressure and temperature of the gas.

Below the critical temperature the state is the vapour: every caller has checked it
against the phase domain, or keeps within it. CoolProp is told so, rather than
finding the phase itself; without superancillaries it would find it with a
saturation solve that refuses pressures under its triple point's, which the domain
reaches just above the triple point (TC-1096). Above the critical temperature there
is no saturation to find, and CoolProp solves as it always has.

Parameters
----------
backend : CoolProp.AbstractState
The fluid's state, updated in place.
pressure : float
Pa.
temperature : float
K.
"""
coolprop = _coolprop()
if temperature >= backend.T_critical():
backend.update(coolprop.PT_INPUTS, pressure, temperature)
return
backend.specify_phase(coolprop.iphase_gas)
try:
backend.update(coolprop.PT_INPUTS, pressure, temperature)
finally:
backend.unspecify_phase()


@functools.cache
def _compressibility(fluid: str, pressure: float, temperature: float) -> float:
"""Return the compressibility factor at a state, unchecked (cached).
Expand All @@ -178,7 +281,7 @@ def _compressibility(fluid: str, pressure: float, temperature: float) -> float:
"""
backend = _abstract_state(fluid)
try:
backend.update(_coolprop().PT_INPUTS, pressure, temperature)
_update_gas(backend, pressure, temperature)
except ValueError as exc:
msg = (
f"no equation-of-state solution for {fluid} at {pressure} Pa and "
Expand Down Expand Up @@ -476,7 +579,7 @@ def speed_of_sound(self, state: State) -> float:
"""
self._check(state)
backend = _abstract_state(self.fluid)
backend.update(_coolprop().PT_INPUTS, state.pressure, state.temperature)
_update_gas(backend, state.pressure, state.temperature)
return float(backend.speed_sound())

def _density_at(self, pressure_value: float, temperature: float) -> float:
Expand Down
Loading
Loading