From 13cdeef9b97f8de5fa5662d6ae48e5218b42d34d Mon Sep 17 00:00:00 2001 From: Jorrit Wronski Date: Thu, 12 Nov 2026 12:08:44 +0000 Subject: [PATCH 1/2] Release 1.5.2: cubic interpolation of the envelope crossings Where an isoline of a mixture crosses the phase envelope and CoolProp's saturation flash does not converge, the crossing was interpolated on a straight line between two envelope points. Near the critical point, where the points are up to 4 K apart and the dome bends, that is off by up to 2e-3 in pressure. Whether the flash converges there differs between platforms: on macOS the bubble flash of R32/R125 converges at 340 K and gives the exact state, which failed test_blend_lines_meet_the_dome_near_the_critical_point against its straight-line reference (conda-forge staged-recipes build). - the crossing is a cubic through the four envelope points around it, with the isoline quantity as the variable; a straight line where that quantity turns over the four points, where the steps are uneven by more than 100 to 1, or where the cubic strays from the straight line - the envelope's repeated points (CoolProp repeats some where its pieces join, sometimes differing in the last digits) are taken once - against the exact flash, over isotherms and isobars of R32/R125, R32/R1234yf and R32/R1234ze(E): pressure within 1.2e-6 (R32/R125) and 1.1e-4 (R32/R1234yf, at the top of the dome) instead of 2.6e-3, enthalpy within 4e-4 instead of 1.5e-3; worse than before in 2 of 2542 values, by at most 1.1e-4, at the top of the dome - the test compares with a cubic reference below the top of the envelope; a new test checks a crossing against the exact flash at 339 K. Both fail with the straight line. CoolProp's C++ port of these numerics (envelope_crossings in src/CoolPropPlot.cpp) still interpolates linearly and needs the same change to give the same points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013bsHH7N2gNABwvNHsDaKn9 --- CHANGELOG.md | 19 +++++++ src/coolplot/__version__.py | 2 +- src/coolplot/thermo/isolines.py | 92 ++++++++++++++++++++++++++++----- tests/test_numerics.py | 41 +++++++++++++-- 4 files changed, 137 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b75b7e..a1eabae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,25 @@ guide in the documentation says what to change in your code. ## [Unreleased] +## [1.5.2] - 2026-11-12 + +### Fixed +- Where an isoline of a mixture crosses the phase envelope and + CoolProp's saturation flash does not converge (near the critical + point), the crossing is interpolated on the envelope with a cubic + through the four points around it instead of a straight line between + two. For R32/R125 the pressure there is now within about 1e-6 of the + exact saturation state instead of up to 2e-3, the enthalpy within + 4e-4 instead of 1.5e-3. CoolProp repeats some points of its envelope + where its pieces join; they are taken once. Where the cubic cannot be + trusted (the isoline quantity turns over the four points, or the + cubic strays from the straight line) the crossing stays a straight + line interpolation. A line therefore gets nearly the same crossing + whether the flash converges or not, which differs between platforms: + `test_blend_lines_meet_the_dome_near_the_critical_point` failed on + macOS, where the bubble flash of R32/R125 converges at 340 K, against + a straight-line reference that was itself off by 2e-4. + ## [1.5.1] - 2026-11-11 ### Fixed diff --git a/src/coolplot/__version__.py b/src/coolplot/__version__.py index b3ab551..b37111f 100644 --- a/src/coolplot/__version__.py +++ b/src/coolplot/__version__.py @@ -1,4 +1,4 @@ # CoolPlot version information -VERSION = (1, 5, 1, '') +VERSION = (1, 5, 2, '') __version__ = '.'.join(map(str, VERSION[:3])) + ''.join(VERSION[3:]) diff --git a/src/coolplot/thermo/isolines.py b/src/coolplot/thermo/isolines.py index e5fdc53..1ea8a4b 100644 --- a/src/coolplot/thermo/isolines.py +++ b/src/coolplot/thermo/isolines.py @@ -488,7 +488,7 @@ def _merge(self, crossings): """Insert saturation states by their value of the stepped quantity. A crossing interpolated on the phase envelope is accurate to about - 1e-5 of the property, a hundredth of a line width; where the + 1e-6 of the property (see :func:`_envelope_crossings`); where the saturation solver answers it is refined to the exact state between the two neighbouring points of the line. """ @@ -619,18 +619,29 @@ def result(w, found): def _envelope_crossings(envelope, diagram, iso_key, value_SI, sweep_key, metric, sweep_range=None): """Where an isoline crosses the phase envelope of a mixture. - The envelope has about 300 closely spaced points. Between two - neighbours where the isoline quantity passes ``value_SI`` the crossing - is interpolated linearly, which is accurate to well below the line - width. Returns (sweep value, quality, Sample) triples; with - ``sweep_range`` only crossings inside that range of the stepped - quantity. + The envelope has about 300 points. Between two neighbours where the + isoline quantity passes ``value_SI`` the crossing is interpolated with + a cubic through the four points around it, with the isoline quantity + as the variable (:func:`_cubic_through`). That is close to the exact + saturation state (about 1e-6 relative for the pressure of R32/R125 + at 340 K, 4 K below its critical point, where a straight line between + the two points is off by 2e-4), so a line gets the same crossing + whether CoolProp's saturation flash still converges there or not. + Where the isoline quantity does not run one way over the four points + (around the top of the dome) the crossing is interpolated linearly. + Returns (sweep value, quality, Sample) triples; with ``sweep_range`` + only crossings inside that range of the stepped quantity. """ - k = envelope.values(iso_key) - columns = [envelope.values(key) for key in (sweep_key, diagram.x, diagram.y, "T", "p", "rho")] + # CoolProp's envelope repeats some points where its pieces join; each + # point is taken once, so that the cubic gets four different neighbours + distinct = _distinct_points(envelope.values("T"), envelope.values("p")) + k = envelope.values(iso_key)[distinct] + columns = [envelope.values(key)[distinct] for key in (sweep_key, diagram.x, diagram.y, "T", "p", "rho")] + Q = envelope.Q[distinct] found = [] f = k - value_SI - for i in range(len(f) - 1): + n = len(f) + for i in range(n - 1): a, b = f[i], f[i + 1] if not (np.isfinite(a) and np.isfinite(b)): continue @@ -641,17 +652,74 @@ def _envelope_crossings(envelope, diagram, iso_key, value_SI, sweep_key, metric, if sb == 0 and i + 1 < len(f) - 1: continue # an exact hit on a point is counted once, by the next pair t = a / (a - b) - w, x, y, T_K, p_Pa, rho = [v[i] + t * (v[i + 1] - v[i]) for v in columns] + # The four points around the crossing: i - 1 to i + 2, moved inwards at the ends + j = min(max(i - 1, 0), n - 4) + stencil = slice(j, j + 4) + straight = [v[i] + t * (v[i + 1] - v[i]) for v in columns] + w, x, y, T_K, p_Pa, rho = straight + if j >= 0 and _spaced_one_way(k[stencil]) and all(np.all(np.isfinite(v[stencil])) for v in columns): + cubic = [_cubic_through(k[stencil], v[stencil], value_SI) for v in columns] + # A cubic further from the straight line than the step between + # the two points is not following the dome: keep the straight line + if all(abs(c - s) <= abs(v[i + 1] - v[i]) for c, s, v in zip(cubic, straight, columns)): + w, x, y, T_K, p_Pa, rho = cubic if not all(np.isfinite((w, x, y, T_K, p_Pa, rho))): continue if sweep_range is not None and not sweep_range[0] <= w <= sweep_range[1]: continue - quality = envelope.Q[i] if t < 0.5 else envelope.Q[i + 1] + quality = Q[i] if t < 0.5 else Q[i + 1] found.append((w, quality, Sample(x, y, _inside(metric, x, y), None, (w, T_K, p_Pa, quality, rho, "envelope")))) return found +def _distinct_points(T_K, p_Pa) -> np.ndarray: + """Indices of the envelope points, leaving out each point that repeats the one before it. + + A repeat has the same temperature and pressure to 1e-9 relative. + """ + keep = [0] + for m in range(1, len(T_K)): + last = keep[-1] + same_T = abs(T_K[m] - T_K[last]) <= 1e-9 * abs(T_K[last]) + same_p = abs(p_Pa[m] - p_Pa[last]) <= 1e-9 * abs(p_Pa[last]) + if not (same_T and same_p): + keep.append(m) + return np.array(keep, dtype=int) + + +def _spaced_one_way(k) -> bool: + """Whether the values can serve as the variable of a cubic through them. + + They have to rise or fall throughout, with no step below a hundredth + of the largest: CoolProp's envelope repeats some points, sometimes + with a difference in the last digits, and the cubic through two + nearly equal values swings far off the dome. + """ + if not np.all(np.isfinite(k)): + return False + steps = np.diff(k) + if not (np.all(steps > 0.0) or np.all(steps < 0.0)): + return False + return bool(np.min(np.abs(steps)) >= 0.01 * np.max(np.abs(steps))) + + +def _cubic_through(k, v, k0: float) -> float: + """The value at ``k0`` of the cubic through the four points (k, v), in the Lagrange form. + + Each point contributes its value times a weight that is 1 at its own + k and 0 at the other three, so the cubic passes through all four. + """ + total = 0.0 + for m in range(4): + weight = 1.0 + for other in range(4): + if other != m: + weight *= (k0 - k[other]) / (k[m] - k[other]) + total += weight * v[m] + return float(total) + + # --------------------------------------------------------------------------- # Lines of constant quality # --------------------------------------------------------------------------- diff --git a/tests/test_numerics.py b/tests/test_numerics.py index 1a37711..18273b0 100644 --- a/tests/test_numerics.py +++ b/tests/test_numerics.py @@ -149,18 +149,51 @@ def test_blend_lines_meet_the_dome_near_the_critical_point(blend): assert isochore.n_inserted == 1 isotherm = compute_isoline(blend, PH, "T", 340.0, box, points=40) assert isotherm.n_inserted == 2 - # The two inserted states of the isotherm sit at 340 K on the envelope + # The two inserted states of the isotherm sit at 340 K on the envelope. + # The reference is a cubic fitted to the envelope points around 340 K, + # which follows the curved dome: a straight line between two points is + # off by 2e-4 here. On some platforms the bubble flash still converges + # at 340 K and gives the exact state; both pass. envelope = blend.phase_envelope() T_env, p_env = envelope.values("T"), envelope.values("p") + below_top = p_env < envelope.top("p") # past its top the envelope runs back to 340 K at about 10 MPa for quality in (0.0, 1.0): - branch = (envelope.Q > 0.5) == (quality > 0.5) # Q is 0 or 1: pick the branch by side + branch = ((envelope.Q > 0.5) == (quality > 0.5)) & below_top # Q is 0 or 1: pick the branch by side + # Sorted by temperature, each point once: CoolProp's envelope repeats + # some, with differences in the last digits only order = np.argsort(T_env[branch]) - p_sat = np.interp(340.0, T_env[branch][order], p_env[branch][order]) - assert np.min(np.abs(isotherm.y - p_sat)) < 1e-4 * p_sat + T_K, p_Pa = T_env[branch][order], p_env[branch][order] + new = np.concatenate(([True], np.diff(T_K) > 1e-6)) + T_K, p_Pa = T_K[new], p_Pa[new] + near = np.argsort(np.abs(T_K - 340.0))[:4] + p_sat = np.polyval(np.polyfit(T_K[near] - 340.0, p_Pa[near], 3), 0.0) + assert np.min(np.abs(isotherm.y - p_sat)) < 1e-5 * p_sat assert envelope is not None and len(envelope) > 100 assert np.all(np.isfinite(envelope.values("h"))) +def test_envelope_crossings_follow_the_curved_dome(blend): + """Interpolated on the envelope, a crossing agrees with the exact flash where the flash converges. + + At 339 K, 5 K below the critical point of R32/R125, the bubble flash + still works; a straight line between two envelope points would be off + by 7e-4 there. + """ + from coolplot.thermo.isolines import _envelope_crossings + from coolplot.thermo.stepping import Metric + envelope = blend.phase_envelope() + metric = Metric((0.0, 1.0), (0.0, 1.0)) + crossings = _envelope_crossings(envelope, PH, "T", 339.0, "h", metric) + bubble = [sample for _, quality, sample in crossings if quality < 0.5] + assert len(bubble) == 1 + state = CoolProp.AbstractState("HEOS", "R32&R125") + state.set_mole_fractions([0.7, 0.3]) + state.update(CoolProp.QT_INPUTS, 0.0, 339.0) + assert bubble[0].y == pytest.approx(state.p(), rel=1e-5) + # The enthalpy bends more steeply near the critical point: about 4e-4 here, 1.4e-3 on a straight line + assert bubble[0].x == pytest.approx(state.hmass(), rel=1e-3) + + def test_pure_fluids_have_no_envelope(r290): assert r290.phase_envelope() is None From 53ac3ba6d743b4ee47774c76bd2a4bf35ab6e13b Mon Sep 17 00:00:00 2001 From: Jorrit Wronski Date: Thu, 12 Nov 2026 12:53:13 +0000 Subject: [PATCH 2/2] Release 1.6.0 instead of 1.5.2 The release adds a path kind ("isochoric"), a change of the public API, so it is a minor release. The upgrade guide gets a section from 1.5 to 1.6. Notes that still said the features of 1.5.0 came with 1.6 (dome labels, the saturation scale, the marked points, the versions line) say 1.5, as the rest of the code and the changelog do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013bsHH8qQUqPxK3TzHzpc72 --- CHANGELOG.md | 2 +- cpp/include/coolplot/layout.h | 2 +- cpp/include/coolplot/spec.h | 6 +++--- cpp/src/compose.cpp | 10 +++++----- cpp/src/layout.cpp | 2 +- docs/upgrade.md | 16 ++++++++++++++++ src/coolplot/__version__.py | 2 +- src/coolplot/compose/layout.py | 2 +- tests/test_branding.py | 2 +- tests/test_dome_labels.py | 2 +- tests/test_marked_points.py | 2 +- tests/test_saturation_scale.py | 2 +- 12 files changed, 33 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6930200..8353bb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ guide in the documentation says what to change in your code. ## [Unreleased] -## [1.5.2] - 2026-11-12 +## [1.6.0] - 2026-11-12 ### Fixed - Where an isoline of a mixture crosses the phase envelope and diff --git a/cpp/include/coolplot/layout.h b/cpp/include/coolplot/layout.h index 694500b..c785fe5 100644 --- a/cpp/include/coolplot/layout.h +++ b/cpp/include/coolplot/layout.h @@ -122,7 +122,7 @@ struct DomeEnds double xb, yb, xd, yd; }; -/// Two more labels for each request with ends, inside the dome next to the bubble and dew lines (LabelSettings.dome, 1.6): +/// Two more labels for each request with ends, inside the dome next to the bubble and dew lines (LabelSettings.dome, 1.5): /// on the chord between the ends, DOME_GAP_PT from each end, upright; left out where they do not fit, leave the frame, /// come near a cycle or overlap a placed label (``labels``), a box of ``occupied`` or an earlier dome label. std::vector place_dome_labels(const std::vector& requests, const std::map& ends, const Frame& frame, diff --git a/cpp/include/coolplot/spec.h b/cpp/include/coolplot/spec.h index 2474eaf..83358db 100644 --- a/cpp/include/coolplot/spec.h +++ b/cpp/include/coolplot/spec.h @@ -28,7 +28,7 @@ struct LabelSettings int tick_digits = 6; /// "unicode" (rho, deg C and m3 with their own characters) or "ascii"; a labels record without it is "ascii" std::string symbols = "unicode"; - /// Label the lines of the dome family once more inside the dome, next to the bubble and dew lines (since 1.6) + /// Label the lines of the dome family once more inside the dome, next to the bubble and dew lines (since 1.5) bool dome = false; /// The edges set for a family, or the family's own. @@ -143,9 +143,9 @@ struct DiagramSpec bool has_y_view = false; Range y_view_SI; std::string title; - /// The special states marked with a dot: "critical" and or "triple", in that order (since 1.6) + /// The special states marked with a dot: "critical" and or "triple", in that order (since 1.5) std::vector marked_points; - /// A scale of saturation states right of the vertical axis (since 1.6): T_sat next to a pressure axis, + /// A scale of saturation states right of the vertical axis (since 1.5): T_sat next to a pressure axis, /// p_sat next to a temperature axis; its ticks come with the domain bool has_saturation_scale = false; double saturation_scale_Q = 1.0; ///< vapour quality of the saturation states the scale shows diff --git a/cpp/src/compose.cpp b/cpp/src/compose.cpp index d91c420..d408dc0 100644 --- a/cpp/src/compose.cpp +++ b/cpp/src/compose.cpp @@ -44,16 +44,16 @@ struct Domain { std::map ranges_SI; double tp_box[4] = {0.0, 0.0, 0.0, 0.0}; ///< T_min, T_max, p_min, p_max (read when points are marked) - /// States of the marked points by name: "critical", "triple_liquid", "triple_vapour" (since 1.6) + /// States of the marked points by name: "critical", "triple_liquid", "triple_vapour" (since 1.5) std::map> points; - /// Ticks of the saturation scale: (saturation value, value on the vertical axis) in SI units (since 1.6) + /// Ticks of the saturation scale: (saturation value, value on the vertical axis) in SI units (since 1.5) std::vector> scale; struct DomeLine { double value_SI; std::map bubble, dew; }; - /// Where the labelled lines of the dome family meet the bubble and dew lines (since 1.6) + /// Where the labelled lines of the dome family meet the bubble and dew lines (since 1.5) std::vector dome; Range range_SI(const std::string& key) const { @@ -789,7 +789,7 @@ std::vector cycle_items(const DiagramSpec& spec, const Theme& theme, const return items; } -// The marked critical and triple points (since 1.6) ---------------------------- +// The marked critical and triple points (since 1.5) ---------------------------- /// The marker of the critical and triple points: a dot in the colour of the saturation curve, with its casing as edge. MarkerStyle marked_point_style(const DiagramSpec& spec, const Theme& theme) { @@ -849,7 +849,7 @@ std::vector marked_point_items(const DiagramSpec& spec, const Theme& theme return items; } -// The saturation scale (since 1.6) ---------------------------------------------- +// The saturation scale (since 1.5) ---------------------------------------------- const double SCALE_INSET_PT = 10.0; ///< distance of the scale from the left edge of the plot area const double SCALE_GAP_PT = 2.0; ///< gap between a tick of the scale and its label diff --git a/cpp/src/layout.cpp b/cpp/src/layout.cpp index b051608..49628b8 100644 --- a/cpp/src/layout.cpp +++ b/cpp/src/layout.cpp @@ -1205,7 +1205,7 @@ std::vector place_state_numbers(const std::vector& numbers, const Fr return out; } -// Labels inside the dome (LabelSettings.dome, 1.6) ----------------------------- +// Labels inside the dome (LabelSettings.dome, 1.5) ----------------------------- namespace { diff --git a/docs/upgrade.md b/docs/upgrade.md index 310a3ef..4a05001 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -35,6 +35,22 @@ starting with an underscore, the helpers in `coolplot.core`, `coolplot.testing`, the scene item ids, and the exact coordinates of a chart (better numerics may move points). +## From 1.5 to 1.6 + +Nothing to change in your code. Two things are new or look different: + +**Cycle paths bend exactly on the dome.** Every path between two states +of a cycle gets the state where it meets the bubble or dew line, so the +line has a sharp corner there instead of a rounded one. A cycle line +therefore has one or two more points than in 1.5 where it crosses the +dome. Before, only isobars had them. + +**`"isochoric"` is a path kind.** Two states of equal density are joined +by an isochore with `"auto"`, as a state given with +`"via": "isochoric"` is. In 1.5 that line was a polytropic path that cut +across the dome. It can also be set by hand with +`paths={(1, 2): "isochoric"}`. + ## From 1.4 to 1.5 Nothing to change in your code, but new charts look different in two diff --git a/src/coolplot/__version__.py b/src/coolplot/__version__.py index b37111f..c96b74f 100644 --- a/src/coolplot/__version__.py +++ b/src/coolplot/__version__.py @@ -1,4 +1,4 @@ # CoolPlot version information -VERSION = (1, 5, 2, '') +VERSION = (1, 6, 0, '') __version__ = '.'.join(map(str, VERSION[:3])) + ''.join(VERSION[3:]) diff --git a/src/coolplot/compose/layout.py b/src/coolplot/compose/layout.py index 3b31ee8..8eddf4a 100644 --- a/src/coolplot/compose/layout.py +++ b/src/coolplot/compose/layout.py @@ -498,7 +498,7 @@ def _text(request: LabelRequest, frame: Frame, box: Box, direction_pt) -> Text: # --------------------------------------------------------------------------- -# Labels inside the dome (LabelSettings.dome, 1.6) +# Labels inside the dome (LabelSettings.dome, 1.5) # --------------------------------------------------------------------------- #: Distance of a dome label from the bubble or dew line, in points DOME_GAP_PT = 3.0 diff --git a/tests/test_branding.py b/tests/test_branding.py index 0e62b90..6230f1f 100644 --- a/tests/test_branding.py +++ b/tests/test_branding.py @@ -69,7 +69,7 @@ def test_other_files_are_refused(tmp_path): def test_branding_settings_validate_and_round_trip(logo_files): assert BrandingSettings().has_badge and BrandingSettings().references == "short" # the default since 1.5 assert not BrandingSettings(references="none", versions=False).has_badge - assert BrandingSettings(references="none").has_badge # the versions line alone (the default since 1.6) + assert BrandingSettings(references="none").has_badge # the versions line alone (the default since 1.5) with pytest.raises(ValueError, match="badge location"): BrandingSettings(location="middle") with pytest.raises(ValueError, match="references style"): diff --git a/tests/test_dome_labels.py b/tests/test_dome_labels.py index 81f02d8..8285b41 100644 --- a/tests/test_dome_labels.py +++ b/tests/test_dome_labels.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -"""Labels inside the dome, next to the bubble and dew lines (LabelSettings.dome, 1.6).""" +"""Labels inside the dome, next to the bubble and dew lines (LabelSettings.dome, 1.5).""" import json import math diff --git a/tests/test_marked_points.py b/tests/test_marked_points.py index 9f62c22..6ae0741 100644 --- a/tests/test_marked_points.py +++ b/tests/test_marked_points.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -"""The critical and triple points marked with a dot (DiagramSpec.marked_points, 1.6).""" +"""The critical and triple points marked with a dot (DiagramSpec.marked_points, 1.5).""" import json import pytest diff --git a/tests/test_saturation_scale.py b/tests/test_saturation_scale.py index 7fca5f9..00fb600 100644 --- a/tests/test_saturation_scale.py +++ b/tests/test_saturation_scale.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -"""The saturation scale next to the vertical axis (DiagramSpec.saturation_scale, 1.6).""" +"""The saturation scale next to the vertical axis (DiagramSpec.saturation_scale, 1.5).""" import json import pytest