
import matplotlib
matplotlib.use('Agg')  # Force mpl to use a non-GUI backend
import matplotlib.pyplot as plt
import json
import numpy as np
import pandas as pd
import CoolProp.CoolProp as CP

CP.set_config_bool(CP.ENABLE_SUPERANCILLARIES, False)

AS = CP.AbstractState('HEOS', "n-Perfluorohexane")

# Skip pseudo-pure fluids, pure fluids only; pseudo-pure do not have superancillaries
if AS.fluid_param_string("pure") != "true":
    quit()

jEOS = json.loads(CP.get_fluid_param_string("n-Perfluorohexane", "JSON"))[0]['EOS'][0]
if 'SUPERANCILLARY' not in jEOS:
    fig = plt.figure()
    fig.text(0.5, 0.5, 'Superancillary not available')
    plt.savefig('n-Perfluorohexane.png', dpi = 300)
    plt.savefig('n-Perfluorohexane.pdf')
    plt.close()
    quit()
else:
    jSuper = jEOS['SUPERANCILLARY']

superanc = CP.SuperAncillary(json.dumps(jSuper))
RPname = AS.fluid_param_string("REFPROP_name")

# Load extended precision calcs from the release on github. If the current
# release pin doesn't include this fluid yet (e.g. a fluid freshly added or
# updated in a PR before the corresponding fastchebpure tag is cut), emit a
# placeholder plot instead of failing the docs build.
import os as _os
_check_path = '/__w/CoolProp/CoolProp/Web/scripts/fastchebpure-2026.04.18/outputcheck/n-Perfluorohexane_check.json'
if not _os.path.exists(_check_path):
    fig = plt.figure()
    fig.text(0.5, 0.5, 'Check file not in pinned fastchebpure release\\nyet (fluid added/updated in this PR)')
    plt.savefig('n-Perfluorohexane.png', dpi = 300)
    plt.savefig('n-Perfluorohexane.pdf')
    plt.close()
    quit()
chk = json.load(open(_check_path))
df = pd.DataFrame(chk['data'])
# df.info() # uncomment to see what fields are available

Tcrit_num = AS.get_fluid_parameter_double(0, "SUPERANC::Tcrit_num")
T = df['T / K'].to_numpy()
Theta = (Tcrit_num-T)/Tcrit_num

fig, axes = plt.subplots(3, 1, sharex=True, figsize=(3.5,7))


plt.sca(axes[0])
rhoL_anc = np.zeros_like(T)
superanc.eval_sat_many(T, 'D', 0, rhoL_anc)
err = np.abs(df["rho'(mp) / mol/m^3"]/rhoL_anc-1)
plt.plot(Theta, err, 'o', label=r'$\Upsilon$:SA')

errCP = np.abs(df["rho'(mp) / mol/m^3"]/CP.PropsSI('Dmolar', 'T', T, 'Q', 0, f'HEOS::n-Perfluorohexane')-1)
plt.plot(Theta, errCP, '^', label=r'$\Upsilon$:HEOS')

try:
    errRP = np.abs(df["rho'(mp) / mol/m^3"]/CP.PropsSI('Dmolar', 'T', T, 'Q', 0, f'REFPROP::{RPname}')-1)
    plt.plot(Theta, errRP, 'x', label=r'$\Upsilon$:REFPROP')
except BaseException as BE:
    print(BE)

plt.legend(loc='best')
plt.ylabel(r"$|\rho_{\rm \Upsilon}'/\rho_{\rm ep}'-1|$")
plt.yscale('log')



plt.sca(axes[1])
rhoV_anc = np.zeros_like(T)
superanc.eval_sat_many(T, 'D', 1, rhoV_anc)
err = np.abs(df["rho''(mp) / mol/m^3"]/rhoV_anc-1)
plt.plot(Theta, err, 'o', label=r'$\Upsilon$:SA')

errCP = np.abs(df["rho''(mp) / mol/m^3"]/CP.PropsSI('Dmolar', 'T', T, 'Q', 1, f'HEOS::n-Perfluorohexane')-1)
plt.plot(Theta, errCP, '^', label=r'$\Upsilon$:HEOS')

try:
    errRP = np.abs(df["rho''(mp) / mol/m^3"]/CP.PropsSI('Dmolar', 'T', T, 'Q', 1, f'REFPROP::{RPname}')-1)
    plt.plot(Theta, errRP, 'x', label=r'$\Upsilon$:REFPROP')
except BaseException as BE:
    print(BE)

plt.legend(loc='best')
plt.ylabel(r"$|\rho_{\rm \Upsilon}''/\rho_{\rm ep}''-1|$")
plt.yscale('log')



plt.sca(axes[2])
p_anc = np.zeros_like(T)
superanc.eval_sat_many(T, 'P', 1, p_anc)
err = np.abs(df["p(mp) / Pa"]/p_anc-1)
plt.plot(Theta, err, 'o', label=r'$\Upsilon$:SA')

errCP = np.abs(df["p(mp) / Pa"]/CP.PropsSI('P', 'T', T, 'Q', 1, f'HEOS::n-Perfluorohexane')-1)
plt.plot(Theta, errCP, '^', label=r'$\Upsilon$:HEOS')

try:
    errRP = np.abs(df["p(mp) / Pa"]/CP.PropsSI('P', 'T', T, 'Q', 1, f'REFPROP::{RPname}')-1)
    plt.plot(Theta, errRP, 'x', label=r'$\Upsilon$:REFPROP')
except BaseException as BE:
    print(BE)
plt.legend(loc='best')

# print(CP.PropsSI('gas_constant', 'T', T[0], 'Q', 1, f'HEOS::n-Perfluorohexane'))
# print(CP.PropsSI('gas_constant', 'T', T[0], 'Q', 1, f'REFPROP::n-Perfluorohexane'))

plt.ylabel(r"$|p_{\rm \Upsilon}/p_{\rm ep}-1|$")
plt.yscale('log')

plt.sca(axes[2])
plt.xlabel(r'$\Theta=(T_{\rm crit,num}-T)/T_{\rm crit,num}$')
plt.xscale('log')

plt.suptitle('Superancillary v. Extended Precision')
plt.tight_layout(pad=0.2, rect=(0,0,1,0.95))
plt.savefig('n-Perfluorohexane.png', dpi = 300)
plt.savefig('n-Perfluorohexane.pdf')
plt.close()
