def get_critical_point(state):
    crit_state = PyCriticalState() 
    crit_state.T = np.nan
    crit_state.p = np.nan
    crit_state.rhomolar = np.nan
    crit_state.stable = False
    try:
        crit_state.T = state.T_critical()
        crit_state.p = state.p_critical()
        crit_state.rhomolar = state.rhomolar_critical()
        crit_state.stable = True
    except:
        try:
            for crit_state_tmp in state.all_critical_points():
                if crit_state_tmp.stable and (crit_state_tmp.T > crit_state.T or not np.isfinite(crit_state.T)):
                    crit_state.T = crit_state_tmp.T
                    crit_state.p = crit_state_tmp.p
                    crit_state.rhomolar = crit_state_tmp.rhomolar
                    crit_state.stable = crit_state_tmp.stable
        except:
            raise ValueError("Could not calculate the critical point data.")    
    new_state = AbstractState(state.backend_name(), '&'.join(state.fluid_names()))
    masses = state.get_mass_fractions()
    if len(masses)>1: 
        new_state.set_mass_fractions(masses) # Uses mass fraction to work with incompressibles
        #try: new_state.build_phase_envelope("dummy")
        #except: pass
    if np.isfinite(crit_state.p) and np.isfinite(crit_state.T):
        try: new_state.specify_phase(CoolProp.iphase_critical_point)
        except: pass 
        new_state.update(CoolProp.PT_INPUTS, crit_state.p, crit_state.T)
        #new_state.update(CoolProp.DmolarT_INPUTS, crit_state.rhomolar, crit_state.T)
        return new_state
    raise ValueError("Could not calculate the critical point data.")
Exemple #2
0
def get_critical_point(state):
    crit_state = PyCriticalState() 
    crit_state.T = np.nan
    crit_state.p = np.nan
    crit_state.rhomolar = np.nan
    crit_state.rhomolar = np.nan
    crit_state.stable = False
    try:
        crit_state.T = state.T_critical()
        crit_state.p = state.p_critical()
        crit_state.rhomolar = state.rhomolar_critical()
        crit_state.stable = True
    except:
        try:
            for crit_state_tmp in state.all_critical_points():
                if crit_state_tmp.stable and (crit_state_tmp.T > crit_state.T or not np.isfinite(crit_state.T)):
                    crit_state.T = crit_state_tmp.T
                    crit_state.p = crit_state_tmp.p
                    crit_state.rhomolar = crit_state_tmp.rhomolar
                    crit_state.stable = crit_state_tmp.stable
        except:
            raise ValueError("Could not calculate the critical point data.")    
    new_state = AbstractState(state.backend_name(), '&'.join(state.fluid_names()))
    masses = state.get_mass_fractions()
    if len(masses)>1: 
        new_state.set_mass_fractions(masses) # Uses mass fraction to work with incompressibles
        #try: new_state.build_phase_envelope("dummy")
        #except: pass
    msg = ""
    if np.isfinite(crit_state.p) and np.isfinite(crit_state.T):
        try: 
            new_state.specify_phase(CoolProp.iphase_critical_point)
            new_state.update(CoolProp.PT_INPUTS, crit_state.p, crit_state.T)
            return new_state
        except Exception as e:
            msg += str(e)+" - "
            pass
        try:
            new_state.update(CoolProp.PT_INPUTS, crit_state.p, crit_state.T)
            return new_state
        except Exception as e:
            msg += str(e)+" - "
            pass 
    if np.isfinite(crit_state.rhomolar) and np.isfinite(crit_state.T):
        try:
            new_state.specify_phase(CoolProp.iphase_critical_point)
            new_state.update(CoolProp.DmolarT_INPUTS, crit_state.rhomolar, crit_state.T)
            return new_state
        except Exception as e:
            msg += str(e)+" - "
            pass
        try:
            new_state.update(CoolProp.DmolarT_INPUTS, crit_state.rhomolar, crit_state.T)
            return new_state
        except Exception as e:
            msg += str(e)+" - "
            pass
    raise ValueError("Could not calculate the critical point data. "+msg)
Exemple #3
0
class Fluid:
    """Represents a fluid."""
    def __init__(self, name: str, eos: str = 'HEOS'):
        """Initiate a Fluid instance.

        :param ID: id of fluid
        """

        self.name = name
        self.eos = eos.upper()
        self.state = AbstractState(self.eos, self.name)

        if self.state.name() not in ["NitrousOxide"]:
            raise NotImplementedError(
                f'{self.state.name()} is not supported currently')
        self.Tmax = 309.5  # self.state.Tmax()
        self.Tmin = 182.23  # self.state.Tmin()
        self.pmax = self.state.pmax()
        self.pmin = 0

    def copy(self):
        fluid = Fluid(self.name, self.eos)
        fluid.set_state(P=self.state.p(), T=self.state.T())
        return fluid

    def set_state(self,
                  D: float = None,
                  P: float = None,
                  T: float = None,
                  Q: float = None,
                  H: float = None,
                  S: float = None,
                  U: float = None):

        args_present = {
            'D': D is not None,
            'P': P is not None,
            'T': T is not None,
            'Q': Q is not None,
            'H': H is not None,
            'S': S is not None,
            'U': U is not None
        }

        if sum(args_present.values()) != 2:
            raise ValueError(
                f'Must have exactly 2 arguments: {sum(args_present.values())} provided'
            )
        args = []
        if args_present['D']:
            if args_present['P']:
                args = CP.DmassP_INPUTS, D, P
            elif args_present['T']:
                args = CP.DmassT_INPUTS, D, T
            elif args_present['Q']:
                args = CP.DmassQ_INPUTS, D, Q
            elif args_present['H']:
                args = CP.DmassHmass_INPUTS, D, H
            elif args_present['S']:
                args = CP.DmassSmass_INPUTS, D, S
            elif args_present['U']:
                args = CP.DmassUmass_INPUTS, D, U
        elif args_present['P']:
            if args_present['T']:
                args = CP.PT_INPUTS, P, T
            elif args_present['Q']:
                args = CP.PQ_INPUTS, P, Q
            elif args_present['H']:
                args = CP.HmassP_INPUTS, H, P
            elif args_present['S']:
                args = CP.PSmass_INPUTS, P, S
            elif args_present['U']:
                args = CP.PUmass_INPUTS, P, U
        elif args_present['T']:
            if args_present['Q']:
                args = CP.QT_INPUTS, Q, T
            elif args_present['H']:
                args = CP.HmassT_INPUTS, H, T
            elif args_present['S']:
                args = CP.SmassT_INPUTS, S, T
            elif args_present['U']:
                args = CP.TUmass_INPUTS, T, U
        elif args_present['Q']:
            if args_present['H']:
                args = CP.HmassQ_INPUTS, H, Q
            elif args_present['S']:
                args = CP.QSmass_INPUTS, Q, S
            elif args_present['U']:
                raise ValueError('Invalid combination: Q and U')
        elif args_present['H']:
            if args_present['S']:
                args = CP.HmassSmass_INPUTS, H, S
            elif args_present['U']:
                raise ValueError('Invalid combination: H and U')
        elif args_present['S'] and args_present['U']:
            args = CP.SmassUmass_INPUTS, S, U
        else:
            raise ValueError('Invalid combination')

        try:
            self.state.update(*args)
        except ValueError:
            pass

    def Vf(self, S: float):
        x = self.chi()
        return 1 / (1 /
                    (1 + S * ((1 - x) / x) * self.rhog([self.state.T()])[0] /
                     self.rhol([self.state.T()])[0]))

    def chi(self):
        x = self.state.Q()
        if x >= 0:
            return x
        if self.state.rhomass() > self.rhol([self.state.T()])[0]:
            return 0
        else:
            return 1

    def viscosityl(self, T):
        b1 = 1.6089
        b2 = 2.0439
        b3 = 5.24
        b4 = 0.0293423
        theta = (self.state.T_critical() - b3) / (T - b3)
        return b4 * np.exp(b1 * (theta - 1)**(1 / 3) + b2 *
                           (theta - 1)**(4 / 3))

    def viscosityg(self, T):
        b1 = 3.3281
        b2 = -1.18237
        b3 = -0.055155
        Tr = T / self.state.T_critical()
        return 0.001 * np.exp(b1 + b2 * (1 / Tr - 1)**(1 / 3) + b3 *
                              (1 / Tr - 1)**(4 / 3)) if (
                                  self.Tmin < T < self.Tmax) else None

    def viscosity(self):
        T = self.state.T()
        mug = self.viscosityg(T)
        mul = self.viscosityl(T)
        x = self.chi()
        rho = self.state.rhomass()
        rhol = self.rhol([T])[0]
        rhog = self.rhog([T])[0]
        return mug * x * rho / rhog + mul * (1 - x) * rho / rhol

    def dvg_dP_saturation(self):
        dP = 0.002
        rho1 = PropsSI('D', 'P', self.state.p() + dP / 2, 'Q', 1, self.name)
        rho0 = PropsSI('D', 'P', self.state.p() - dP / 2, 'Q', 1, self.name)
        dvg = 1 / rho1 - 1 / rho0
        return dvg / dP

    def rhol(self, T: Iterable):
        return [
            PropsSI('D', 'T', t, 'Q', 0, self.eos + "::" + self.name)
            for t in T
        ]

    def rhog(self, T: Iterable):
        return [
            PropsSI('D', 'T', t, 'Q', 1, self.eos + "::" + self.name)
            for t in T
        ]

    def psat(self, T: Iterable):
        return [
            PropsSI('P', 'Q', 0.5, 'T', t, self.eos + "::" + self.name) if
            (self.Tmin < t < self.Tmax) else None for t in T
        ]

    def tsat(self, P: Iterable):
        return [
            PropsSI('T', 'P', P, 'Q', 0.5, self.eos + "::" + self.name) if
            (self.pmin < p < self.pmax) else None for p in P
        ]

    def hl(self, T: Iterable):
        return [
            PropsSI('H', 'T', t, 'Q', 0, self.eos + "::" + self.name) if
            (self.Tmin < t < self.Tmax) else None for t in T
        ]

    def hg(self, T: Iterable):
        return [
            PropsSI('H', 'T', t, 'Q', 1, self.eos + "::" + self.name) if
            (self.Tmin < t < self.Tmax) else None for t in T
        ]

    def sl(self, T: Iterable):
        return [
            PropsSI('S', 'T', t, 'Q', 0, self.eos + "::" + self.name) if
            (self.Tmin < t < self.Tmax) else None for t in T
        ]

    def sg(self, T: Iterable):
        return [
            PropsSI('S', 'T', t, 'Q', 1, self.eos + "::" + self.name) if
            (self.Tmin < t < self.Tmax) else None for t in T
        ]

    def __repr__(self):
        return f'Fluid({self.name}: p={self.state.p() / 100000:.1f}bar, t={self.state.T():.1f}K)'
Exemple #4
0
    def __init__(self, symbol="N2", T=530.0, P=1000.0, child=1):
        '''Init generic Fluid'''

        self.symbol = symbol.upper()

        # http://www.coolprop.org/_static/doxygen/html/class_cool_prop_1_1_abstract_state.html
        AS = AbstractState("HEOS", self.symbol)
        self.AS = AS

        self.name = AS.name()
        self.T = T
        self.P = P
        self.child = child

        Tsi = TSI_fromEng(T)
        Psi = PSI_fromEng(P)
        AS.update(CP.PT_INPUTS, Psi, Tsi)

        self.WtMol = AS.molar_mass() * 1000.0
        self.Tc = Teng_fromSI(AS.T_critical())
        self.Pc = Peng_fromSI(AS.p_critical())
        self.Dc = Deng_fromSI(AS.rhomass_critical())
        self.Ttriple = Teng_fromSI(AS.Ttriple())
        try:
            self.Tfreeze = Teng_fromSI(AS.T_freeze())
        except:
            self.Tfreeze = self.Ttriple

        self.Tmin = Teng_fromSI(AS.Tmin())
        self.Tmax = Teng_fromSI(AS.Tmax())
        #self.Pmin = Peng_fromSI( AS.pmin() ) # missing from AbstractState
        self.Pmax = Peng_fromSI(AS.pmax())

        dcIdeal = self.Pc * self.WtMol / self.Tc / 10.729
        self.Zc = dcIdeal / self.Dc

        try:
            TnbpSI = PropsSI("T", "P", 101325, "Q", Q_LIQUID, self.symbol)
            self.good_nbp = True
            self.Tnbp = Teng_fromSI(TnbpSI)
        except:
            #print('WARNING... "%s" failed Normal Boiling Point Calculation.'%self.symbol)
            Ttriple = PropsSI(self.symbol, 'Ttriple')
            #print('    Using Triple Point = %g degK as Tref'%Ttriple)
            self.good_nbp = False
            self.Tnbp = 'N/A'

        if self.good_nbp:
            if self.Tnbp < 536.67:
                self.Tref = self.Tnbp  # if NBP is low, use NBP as ref
            else:
                self.Tref = 536.67  # 536.67R = (SATP, Standard Ambient T P) = 77F, 25C
        else:
            self.Tref = Teng_fromSI(Ttriple) + 0.1
        self.Pref = 14.7

        #print( 'About to call setTP #1 with Tref, Pref=',self.Tref,self.Pref )
        self.setTP(self.Tref, self.Pref)
        #print( 'Back from call setTP')
        self.Href = self.H
        #print( 'About to call setTP #2')
        self.setTP(T, P)
        #print( 'Back from call setTP')

        if child == 1:
            self.dup = EC_Fluid(symbol=self.symbol,
                                T=self.T,
                                P=self.P,
                                child=0)

        self.calcdFreezePt = 0
Exemple #5
0
import CoolProp.CoolProp as CoolProp
from CoolProp.HumidAirProp import HAPropsSI
from math import sin
print("**************** INFORMATION ***************")
print("This example was auto-generated by the language-agnostic dev/scripts/example_generator.py script written by Ian Bell")
print("CoolProp version:", get_global_param_string("version"))
print("CoolProp gitrevision:", get_global_param_string("gitrevision"))
print("CoolProp Fluids:", get_global_param_string("FluidsList"))
# See http://www.coolprop.org/coolprop/HighLevelAPI.html#table-of-string-inputs-to-propssi-function for a list of inputs to high-level interface
print("*********** HIGH LEVEL INTERFACE *****************")
print("Critical temperature of water:", PropsSI("Water", "Tcrit"), "K")
print("Boiling temperature of water at 101325 Pa:", PropsSI("T", "P", 101325, "Q", 0, "Water"), "K")
print("Phase of water at 101325 Pa and 300 K:", PhaseSI("P", 101325, "Q", 0, "Water"))
print("c_p of water at 101325 Pa and 300 K:", PropsSI("C", "P", 101325, "T", 300, "Water"), "J/kg/K")
print("c_p of water (using derivatives) at 101325 Pa and 300 K:", PropsSI("d(H)/d(T)|P", "P", 101325, "T", 300, "Water"), "J/kg/K")
print("*********** HUMID AIR PROPERTIES *****************")
print("Humidity ratio of 50% rel. hum. air at 300 K, 101325 Pa:", HAPropsSI("W", "T", 300, "P", 101325, "R", 0.5), "kg_w/kg_da")
print("Relative humidity from last calculation:", HAPropsSI("R", "T", 300, "P", 101325, "W", HAPropsSI("W", "T", 300, "P", 101325, "R", 0.5)), "(fractional)")
print("*********** INCOMPRESSIBLE FLUID AND BRINES *****************")
print("Density of 50% (mass) ethylene glycol/water at 300 K, 101325 Pa:", PropsSI("D", "T", 300, "P", 101325, "INCOMP::MEG-50%"), "kg/m^3")
print("Viscosity of Therminol D12 at 350 K, 101325 Pa:", PropsSI("V", "T", 350, "P", 101325, "INCOMP::TD12"), "Pa-s")
print("*********** LOW-LEVEL INTERFACE *****************")
AS = AbstractState("HEOS", "Water&Ethanol")
z = [0.5, 0.5]
AS.set_mole_fractions(z)
AS.update(CoolProp.PQ_INPUTS, 101325, 1)
print("Normal boiling point temperature of water and ethanol:", AS.T(), "K")
print("*********** TABULAR BACKENDS *****************")
TAB = AbstractState("BICUBIC&HEOS", "R245fa")
TAB.update(CoolProp.PT_INPUTS, 101325, 300)
print("Mass density of refrigerant R245fa at 300 K, 101325 Pa:", TAB.rhomass(), "kg/m^3")
Exemple #6
0
import CoolProp.State
from math import sin

# P, h -> T ([Pa], [J/kg] -> [degC])
# result = CP.CoolProp.PropsSI("T", "P", 20e6, 'H', 995164, 'CO2') - 273.15

# P, T -> h ([Pa], [K] -> [J/kg])
# result = CP.CoolProp.PropsSI("H", "P", 20e6, 'T', 715 + 273.15, 'CO2')

# P, T -> mu (local viscosity)([Pa], [K] -> [mu])
# result = CP.CoolProp.PropsSI("V", "P", 3616780, 'T', 700 + 273.15, 'CO2')

# result = CP.CoolProp.PropsSI("H", "P", 8e6, 'T', 15 + 273.15, 'CO2')

# print("result=" + str(result))

# result = CP.CoolProp.PropsSI("H", "P", 20e6, 'T', 15 + 273.15, 'CO2')

# print("result=" + str(result))

# result = CP.CoolProp.PropsSI("H", "P", 8e6, 'T', 700 + 273.15, 'CO2')

# print("result=" + str(result))

# result = CP.CoolProp.PropsSI("H", "P", 20e6, 'T', 700 + 273.15, 'CO2')

# print("result=" + str(result))

AS_SAT = AbstractState("HEOS", "CO2")
AS_SAT.update(CoolProp.PT_INPUTS, 20e6, 273.15 + 700)
print("First saturation derivative:", AS_SAT.hmass(), "Pa/K")