From 56ccdbc4ac44e34a1dbe36040fbcc667d6cbc410 Mon Sep 17 00:00:00 2001 From: Ian bell Date: Thu, 15 May 2014 22:19:53 +0200 Subject: [PATCH] Renamed python wrapper files for now to CoolProp5 - python wrapper is coming together. Dropped xdress and building it manually. Signed-off-by: Ian bell --- wrappers/Python/CoolProp/CoolProp.pxd | 475 ------ wrappers/Python/CoolProp/CoolProp.pyx | 1321 ----------------- wrappers/Python/CoolProp/oldState.pyx | 365 ----- wrappers/Python/CoolProp/param_constants.pyx | 88 -- .../CoolProp/param_constants_header.pxd | 89 -- wrappers/Python/CoolProp/phase_constants.pyx | 8 - .../CoolProp/phase_constants_header.pxd | 9 - .../CoolProp/unit_systems_constants.pyx | 8 - .../unit_systems_constants_header.pxd | 9 - wrappers/Python/CoolProp5/AbstractState.pxd | 24 + wrappers/Python/CoolProp5/AbstractState.pyx | 49 + wrappers/Python/CoolProp5/CoolProp.pxd | 126 ++ wrappers/Python/CoolProp5/CoolProp.pyx | 802 ++++++++++ .../{CoolProp => CoolProp5}/CyState.pxd | 0 .../{CoolProp => CoolProp5}/CyState.pyx | 0 .../GUI/CoolPropGUI.py | 0 .../GUI/PsychScript.py | 0 .../{CoolProp => CoolProp5}/GUI/__init__.py | 0 .../{CoolProp => CoolProp5}/HumidAirProp.py | 0 .../{CoolProp => CoolProp5}/HumidAirProp.pyx | 0 .../{CoolProp => CoolProp5}/Plots/Common.py | 0 .../{CoolProp => CoolProp5}/Plots/Plots.py | 0 .../Plots/PsychChart.py | 0 .../Plots/PsychScript.py | 0 .../Plots/SimpleCycles.py | 0 .../{CoolProp => CoolProp5}/Plots/Tests.py | 0 .../{CoolProp => CoolProp5}/Plots/__init__.py | 0 .../Python/{CoolProp => CoolProp5}/State.pxd | 0 .../Python/{CoolProp => CoolProp5}/State.py | 0 wrappers/Python/CoolProp5/__init__.py | 59 + wrappers/Python/CoolProp5/cAbstractState.pxd | 38 + wrappers/Python/CoolProp5/constants.pyx | 97 ++ .../Python/CoolProp5/constants_header.pxd | 100 ++ .../{CoolProp => CoolProp5}/tests/__init__.py | 0 .../{CoolProp => CoolProp5}/tests/runner.py | 0 .../tests/test_CoolPropState.py | 0 .../tests/test_HAProps.py | 0 .../tests/test_Props.py | 0 .../tests/test_Props1.py | 0 .../tests/test_Saturation.py | 0 .../tests/test_Units_CPState.py | 0 .../tests/test_consistency.py | 0 .../tests/test_param_getters.py | 0 .../tests/test_plots.py | 0 wrappers/Python/setup2.py | 172 +++ 45 files changed, 1467 insertions(+), 2372 deletions(-) delete mode 100644 wrappers/Python/CoolProp/CoolProp.pxd delete mode 100644 wrappers/Python/CoolProp/CoolProp.pyx delete mode 100644 wrappers/Python/CoolProp/oldState.pyx delete mode 100644 wrappers/Python/CoolProp/param_constants.pyx delete mode 100644 wrappers/Python/CoolProp/param_constants_header.pxd delete mode 100644 wrappers/Python/CoolProp/phase_constants.pyx delete mode 100644 wrappers/Python/CoolProp/phase_constants_header.pxd delete mode 100644 wrappers/Python/CoolProp/unit_systems_constants.pyx delete mode 100644 wrappers/Python/CoolProp/unit_systems_constants_header.pxd create mode 100644 wrappers/Python/CoolProp5/AbstractState.pxd create mode 100644 wrappers/Python/CoolProp5/AbstractState.pyx create mode 100644 wrappers/Python/CoolProp5/CoolProp.pxd create mode 100644 wrappers/Python/CoolProp5/CoolProp.pyx rename wrappers/Python/{CoolProp => CoolProp5}/CyState.pxd (100%) rename wrappers/Python/{CoolProp => CoolProp5}/CyState.pyx (100%) rename wrappers/Python/{CoolProp => CoolProp5}/GUI/CoolPropGUI.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/GUI/PsychScript.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/GUI/__init__.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/HumidAirProp.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/HumidAirProp.pyx (100%) rename wrappers/Python/{CoolProp => CoolProp5}/Plots/Common.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/Plots/Plots.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/Plots/PsychChart.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/Plots/PsychScript.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/Plots/SimpleCycles.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/Plots/Tests.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/Plots/__init__.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/State.pxd (100%) rename wrappers/Python/{CoolProp => CoolProp5}/State.py (100%) create mode 100644 wrappers/Python/CoolProp5/__init__.py create mode 100644 wrappers/Python/CoolProp5/cAbstractState.pxd create mode 100644 wrappers/Python/CoolProp5/constants.pyx create mode 100644 wrappers/Python/CoolProp5/constants_header.pxd rename wrappers/Python/{CoolProp => CoolProp5}/tests/__init__.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/runner.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_CoolPropState.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_HAProps.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_Props.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_Props1.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_Saturation.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_Units_CPState.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_consistency.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_param_getters.py (100%) rename wrappers/Python/{CoolProp => CoolProp5}/tests/test_plots.py (100%) create mode 100644 wrappers/Python/setup2.py diff --git a/wrappers/Python/CoolProp/CoolProp.pxd b/wrappers/Python/CoolProp/CoolProp.pxd deleted file mode 100644 index 878f52ad..00000000 --- a/wrappers/Python/CoolProp/CoolProp.pxd +++ /dev/null @@ -1,475 +0,0 @@ -from libcpp.string cimport string -import cython -cimport cython - -# Default string in Python 3.x is a unicode string (type str) -# Default string in Python 2.x is a byte string(type bytes) -# -# Create a fused type that allows for either unicode string or bytestring -# We encode unicode strings using the ASCII encoding since we know they are all -# ASCII strings -ctypedef fused string_like: - cython.bytes - cython.unicode - -cdef extern from "CPState.h": - cdef cppclass CoolPropStateClass: - - bint flag_SinglePhase, flag_TwoPhase - - ## Bulk values - double _rho,_T,_p,_Q,_h,_s, tau, delta - - ## Phase flags - bint TwoPhase, SinglePhase - - ## Nullary Constructor - CoolPropStateClass() except + - - ## Constructor with fluid name - CoolPropStateClass(string FluidName) except + - - ## Property updater - ## Uses the indices in CoolProp for the input parameters - void update(long iInput1, double Value1, long iInput2, double Value2) except +ValueError - - ## Property accessors for saturation parameters directly - ## These all must be calculated every time if the state is saturated or two-phase - double rhoL() except + - double rhoV() except + - double pL() except + - double pV() except + - double TL() except + - double TV() except + - ## Derived parameters for the saturation states - double hL() except + - double hV() except + - double sL() except + - double sV() except + - - ## Bulk properties accessors - temperature and density are directly calculated every time - ## All other parameters are calculated on an as-needed basis - ## If single-phase, just plug into the EOS, otherwise need to do two-phase analysis - double T() except + - double rho() except + - double p() except + - double h() except + - double s() except + - double cp() except + - double cv() except + - double speed_sound() except + - double keyed_output(long iOutput) except + - long phase() except + - - ## ---------------------------------------- - ## TTSE LUT things - ## ---------------------------------------- - - ## Enable the TTSE - void enable_TTSE_LUT() except + - ## Check if TTSE is enabled - bint isenabled_TTSE_LUT() except + - ## Disable the TTSE - void disable_TTSE_LUT() except + - ## Interpolate within the TTSE LUT - double interpolate_in_TTSE_LUT(long iParam, long iInput1, double Input1, long iInput2, double Input2) except + - - ## ---------------------------------------- - ## Derivatives of properties - ## ---------------------------------------- - - double dvdp_constT() except + - double dvdT_constp() except + - - double drhodT_constp() except + - double drhodh_constp() except + - double drhodp_consth() except + - double drhodp_constT() except + - double d2rhodp2_constT() except + - double d2rhodTdp() except + - double d2rhodhdQ() except + - double d2rhodpdQ() except + - double d2rhodhdp() except + - double d2rhodh2_constp() except + - double d2rhodT2_constp() except + - - double dpdrho_constT() except + - double dpdrho_consth() except + - double dpdT_constrho() except + - double dpdT_consth() except + - double d2pdrho2_constT() except + - double d2pdrhodT() except + - double d2pdT2_constrho() except + - - double dhdrho_constT() except + - double dhdrho_constp() except + - double dhdT_constrho() except + - double dhdT_constp() except + - double dhdp_constT() except + - double d2hdrho2_constT() except + - double d2hdrhodT() except + - double d2hdT2_constrho() except + - double d2hdT2_constp() except + - double d2hdp2_constT() except + - double d2hdTdp() except + - - double dsdrho_constT() except + - double dsdT_constrho() except + - double dsdrho_constp() except + - double dsdT_constp() except + - double dsdp_constT() except + - double d2sdrho2_constT() except + - double d2sdrhodT() except + - double d2sdT2_constrho() except + - double d2sdT2_constp() except + - double d2sdp2_constT() except + - double d2sdTdp() except + - - ## ---------------------------------------- - ## Derivatives along the saturation curve - ## ---------------------------------------- - - ## Derivative of temperature w.r.t. pressure along saturation curve - double dTdp_along_sat() except +ValueError - ## Second derivative of temperature w.r.t. pressure along saturation curve - double d2Tdp2_along_sat() except +ValueError - ## Partial derivative w.r.t. pressure of dTdp along saturation curve - double ddp_dTdp_along_sat() except +ValueError - ## Partial derivative w.r.t. temperature of dTdp along saturation curve - double ddT_dTdp_along_sat() except +ValueError - - double dhdp_along_sat_vapor() except +ValueError - double dhdp_along_sat_liquid() except +ValueError - double d2hdp2_along_sat_vapor() except +ValueError - double d2hdp2_along_sat_liquid() except +ValueError - - double dsdp_along_sat_vapor() except +ValueError - double dsdp_along_sat_liquid() except +ValueError - double d2sdp2_along_sat_vapor() except +ValueError - double d2sdp2_along_sat_liquid() except +ValueError - - double drhodp_along_sat_vapor() except +ValueError - double drhodp_along_sat_liquid() except +ValueError - double d2rhodp2_along_sat_vapor() except +ValueError - double d2rhodp2_along_sat_liquid() except +ValueError - - double drhodT_along_sat_vapor() except +ValueError - double drhodT_along_sat_liquid() except +ValueError - - ## Clear out all the cached values - void clear_cache() - - ## ---------------------------------------- - ## Helmholtz Energy Derivatives - ## ---------------------------------------- - - double phi0(double tau, double delta) - double dphi0_dDelta(double tau, double delta) - double dphi0_dTau(double tau, double delta) - double d2phi0_dDelta2(double tau, double delta) - double d2phi0_dDelta_dTau(double tau, double delta) - double d2phi0_dTau2(double tau, double delta) - double d3phi0_dDelta3(double tau, double delta) - double d3phi0_dDelta2_dTau(double tau, double delta) - double d3phi0_dDelta_dTau2(double tau, double delta) - double d3phi0_dTau3(double tau, double delta) - - double phir(double tau, double delta) - double dphir_dDelta(double tau, double delta) - double dphir_dTau(double tau, double delta) - double d2phir_dDelta2(double tau, double delta) - double d2phir_dDelta_dTau(double tau, double delta) - double d2phir_dTau2(double tau, double delta) - double d3phir_dDelta3(double tau, double delta) - double d3phir_dDelta2_dTau(double tau, double delta) - double d3phir_dDelta_dTau2(double tau, double delta) - double d3phir_dTau3(double tau, double delta) - - cdef cppclass CoolPropStateClassSI: - - bint flag_SinglePhase, flag_TwoPhase - - ## Bulk values - double _rho,_T,_p,_Q,_h,_s, tau, delta - - ## Phase flags - bint TwoPhase, SinglePhase - - ## Nullary Constructor - CoolPropStateClassSI() except + - - ## Constructor with fluid name - CoolPropStateClassSI(string FluidName) except + - - ## Property updater - ## Uses the indices in CoolProp for the input parameters - void update(long iInput1, double Value1, long iInput2, double Value2) except +ValueError - - ## Property accessors for saturation parameters directly - ## These all must be calculated every time if the state is saturated or two-phase - double rhoL() except + - double rhoV() except + - double pL() except + - double pV() except + - double TL() except + - double TV() except + - ## Derived parameters for the saturation states - double hL() except + - double hV() except + - double sL() except + - double sV() except + - - ## Bulk properties accessors - temperature and density are directly calculated every time - ## All other parameters are calculated on an as-needed basis - ## If single-phase, just plug into the EOS, otherwise need to do two-phase analysis - double T() except + - double rho() except + - double p() except + - double h() except + - double s() except + - double cp() except + - double cv() except + - double speed_sound() except + - double keyed_output(long iOutput) except + - long phase() except + - - ## ---------------------------------------- - ## TTSE LUT things - ## ---------------------------------------- - - ## Enable the TTSE - void enable_TTSE_LUT() except + - ## Check if TTSE is enabled - bint isenabled_TTSE_LUT() except + - ## Disable the TTSE - void disable_TTSE_LUT() except + - ## Interpolate within the TTSE LUT - double interpolate_in_TTSE_LUT(long iParam, long iInput1, double Input1, long iInput2, double Input2) except + - - ## ---------------------------------------- - ## Derivatives of properties - ## ---------------------------------------- - - double dvdp_constT() except + - double dvdT_constp() except + - - double drhodT_constp() except + - double drhodh_constp() except + - double drhodp_consth() except + - double drhodp_constT() except + - double d2rhodp2_constT() except + - double d2rhodTdp() except + - double d2rhodhdQ() except + - double d2rhodpdQ() except + - double d2rhodhdp() except + - double d2rhodh2_constp() except + - double d2rhodT2_constp() except + - - double dpdrho_constT() except + - double dpdrho_consth() except + - double dpdT_constrho() except + - double dpdT_consth() except + - double d2pdrho2_constT() except + - double d2pdrhodT() except + - double d2pdT2_constrho() except + - - double dhdrho_constT() except + - double dhdrho_constp() except + - double dhdT_constrho() except + - double dhdT_constp() except + - double dhdp_constT() except + - double d2hdrho2_constT() except + - double d2hdrhodT() except + - double d2hdT2_constrho() except + - double d2hdT2_constp() except + - double d2hdp2_constT() except + - double d2hdTdp() except + - - double dsdrho_constT() except + - double dsdT_constrho() except + - double dsdrho_constp() except + - double dsdT_constp() except + - double dsdp_constT() except + - double d2sdrho2_constT() except + - double d2sdrhodT() except + - double d2sdT2_constrho() except + - double d2sdT2_constp() except + - double d2sdp2_constT() except + - double d2sdTdp() except + - - ## ---------------------------------------- - ## Derivatives along the saturation curve - ## ---------------------------------------- - - ## Derivative of temperature w.r.t. pressure along saturation curve - double dTdp_along_sat() except +ValueError - ## Second derivative of temperature w.r.t. pressure along saturation curve - double d2Tdp2_along_sat() except +ValueError - ## Partial derivative w.r.t. pressure of dTdp along saturation curve - double ddp_dTdp_along_sat() except +ValueError - ## Partial derivative w.r.t. temperature of dTdp along saturation curve - double ddT_dTdp_along_sat() except +ValueError - - double dhdp_along_sat_vapor() except +ValueError - double dhdp_along_sat_liquid() except +ValueError - double d2hdp2_along_sat_vapor() except +ValueError - double d2hdp2_along_sat_liquid() except +ValueError - - double dsdp_along_sat_vapor() except +ValueError - double dsdp_along_sat_liquid() except +ValueError - double d2sdp2_along_sat_vapor() except +ValueError - double d2sdp2_along_sat_liquid() except +ValueError - - double drhodp_along_sat_vapor() except +ValueError - double drhodp_along_sat_liquid() except +ValueError - double d2rhodp2_along_sat_vapor() except +ValueError - double d2rhodp2_along_sat_liquid() except +ValueError - - double drhodT_along_sat_vapor() except +ValueError - double drhodT_along_sat_liquid() except +ValueError - - ## Clear out all the cached values - void clear_cache() - - ## ---------------------------------------- - ## Helmholtz Energy Derivatives - ## ---------------------------------------- - - double phi0(double tau, double delta) - double dphi0_dDelta(double tau, double delta) - double dphi0_dTau(double tau, double delta) - double d2phi0_dDelta2(double tau, double delta) - double d2phi0_dDelta_dTau(double tau, double delta) - double d2phi0_dTau2(double tau, double delta) - double d3phi0_dDelta3(double tau, double delta) - double d3phi0_dDelta2_dTau(double tau, double delta) - double d3phi0_dDelta_dTau2(double tau, double delta) - double d3phi0_dTau3(double tau, double delta) - - double phir(double tau, double delta) - double dphir_dDelta(double tau, double delta) - double dphir_dTau(double tau, double delta) - double d2phir_dDelta2(double tau, double delta) - double d2phir_dDelta_dTau(double tau, double delta) - double d2phir_dTau2(double tau, double delta) - double d3phir_dDelta3(double tau, double delta) - double d3phir_dDelta2_dTau(double tau, double delta) - double d3phir_dDelta_dTau2(double tau, double delta) - double d3phir_dTau3(double tau, double delta) - -cdef extern from "CoolPropDLL.h": - int _set_reference_stateS "set_reference_stateS"(char *, char *) - int _set_reference_stateD "set_reference_stateD"(char *, double T, double rho, double h0, double s0) - int _get_standard_unit_system "get_standard_unit_system"() - -cdef extern from "CoolPropTools.h": - bint _ValidNumber "ValidNumber"(double) - -cdef extern from "Units.h": - double _fromSIints "convert_from_SI_to_unit_system"(long input, double value, int new_system) - double _toSIints "convert_from_unit_system_to_SI"(long input, double value, int old_system) - double _fromSI "convert_from_SI_to_unit_system"(string input, double value, string new_system) - double _toSI "convert_from_unit_system_to_SI"(string input, double value, string old_system) - -cdef extern from "CoolProp.h": - void _set_standard_unit_system "set_standard_unit_system"(int unit_system) - - double _PropsSI "PropsSI"(string Output, string Name1, double Prop1, string Name2, double Prop2, string Ref) - double _Props1SI "Props1SI"(string Ref, string Output) - - double _IProps "IProps"(long Output, long Name1, double Prop1, long Name2, double Prop2, long Ref) - - double _Props "Props"(string Output, string Name1, double Prop1, string Name2, double Prop2, string Ref) - double _Props1 "Props1"(string Ref, string Output) - - string _Phase "Phase"(char *Fluid, double T, double p) - string _Phase_Tp "Phase_Tp"(string Fluid, double T, double p) - string _Phase_Trho "Phase_Trho"(string Fluid, double T, double rho) - double _DerivTerms "DerivTerms"(char* Term, double T, double rho, char* Ref) - - # Conversion functions - double _F2K "F2K"(double T_F) - double _K2F "K2F"(double T) - - string _get_global_param_string "get_global_param_string"(string ParamName) - string _get_fluid_param_string "get_fluid_param_string"(string ParamName, string FluidName) - - long _set_phase "set_phase" (string phase) - long _get_Fluid_index "get_Fluid_index" (string Fluid) - long _get_param_index "get_param_index" (string param) - - string _get_TTSE_mode "get_TTSE_mode"(string Fluid) - int _set_TTSE_mode "set_TTSE_mode"(char* Fluid, char* Value) - - string _add_REFPROP_fluid "add_REFPROP_fluid"(string FluidName) except + - - int _get_debug_level "get_debug_level"() - void _set_debug_level "set_debug_level"(int level) - - string _get_BibTeXKey "get_BibTeXKey"(string Ref, string key) - - # Convenience functions - int _IsFluidType "IsFluidType"(char* Ref, char* Type) - - # Enable the TTSE - bint _enable_TTSE_LUT "enable_TTSE_LUT"(char *FluidName) - # Check if TTSE is enabled - bint _isenabled_TTSE_LUT "isenabled_TTSE_LUT"(char *FluidName) - # Disable the TTSE - bint _disable_TTSE_LUT "disable_TTSE_LUT"(char *FluidName) - - # Enable the writing of TTSE tables to file for this fluid - bint _enable_TTSE_LUT_writing "enable_TTSE_LUT_writing"(char *FluidName) - # Check if the writing of TTSE tables to file is enabled - bint _isenabled_TTSE_LUT_writing "isenabled_TTSE_LUT_writing"(char *FluidName) - # Disable the writing of TTSE tables to file for this fluid - bint _disable_TTSE_LUT_writing "disable_TTSE_LUT_writing"(char *FluidName) - - # Over-ride the default size of both of the saturation LUT - bint _set_TTSESat_LUT_size "set_TTSESat_LUT_size"(char *FluidName, int) - # Over-ride the default size of the single-phase LUT - bint _set_TTSESinglePhase_LUT_size "set_TTSESinglePhase_LUT_size"(char *FluidName, int Np, int Nh) - # Over-ride the default range of the single-phase LUT - bint _set_TTSESinglePhase_LUT_range "set_TTSESinglePhase_LUT_range"(char *FluidName, double hmin, double hmax, double pmin, double pmax) - # Get the current range of the single-phase LUT - bint _get_TTSESinglePhase_LUT_range "get_TTSESinglePhase_LUT_range"(char *FluidName, double *hmin, double *hmax, double *pmin, double *pmax) - -cdef extern from "HumidAirProp.h": - double _HAProps "HAProps"(char *OutputName, char *Input1Name, double Input1, char *Input2Name, double Input2, char *Input3Name, double Input3) - double _HAProps_Aux "HAProps_Aux"(char* Name,double T, double p, double W, char *units) - double _cair_sat "cair_sat"(double T) - -cdef class State: - cdef CoolPropStateClassSI CPS - cdef readonly string Fluid, phase - cdef int iFluid,iParam1,iParam2,iOutput - cdef double T_, rho_, p_ - cdef readonly bint is_CPFluid - - cpdef set_Fluid(self, string_like Fluid) - cpdef speed_test(self, int N) - cpdef update(self, dict params) - cpdef update_ph(self, double p, double h) - cpdef update_Trho(self, double T, double rho) - cpdef State copy(self) - cpdef double Props(self, long iOutput) except * - cpdef long Phase(self) except * - - cpdef double get_Q(self) except * - cpdef double get_T(self) except * - cpdef double get_p(self) except * - cpdef double get_h(self) except * - cpdef double get_rho(self) except * - cpdef double get_s(self) except * - cpdef double get_u(self) except * - cpdef double get_visc(self) except * - cpdef double get_cond(self) except * - cpdef double get_cp(self) except * - cpdef double get_cp0(self) except * - cpdef double get_cv(self) except * - cpdef double get_MM(self) except * - cpdef double get_dpdT(self) except * - cpdef double get_speed_sound(self) except * - cpdef get_Tsat(self, double Q = *) - cpdef get_subcooling(self) - cpdef get_superheat(self) diff --git a/wrappers/Python/CoolProp/CoolProp.pyx b/wrappers/Python/CoolProp/CoolProp.pyx deleted file mode 100644 index 9c10b380..00000000 --- a/wrappers/Python/CoolProp/CoolProp.pyx +++ /dev/null @@ -1,1321 +0,0 @@ -#cython: embedsignature = True, c_string_type=str, c_string_encoding=ascii -from __future__ import division -# -# This file provides wrapper functions of all the CoolProp functions -# -# Each of the functions from the CoolProp header are renamed in cython code to -# an underscored name so that the same name can be used in the exposed functions below - -#Check for the existence of numpy -cdef bint _numpy_supported -try: - import numpy as np - _numpy_supported = True -except ImportError: - _numpy_supported = False - -import math -import warnings - -from param_constants import * -from param_constants_header cimport * - -from phase_constants import * -from phase_constants_header cimport * - -cpdef bint iterable(object a): - if _numpy_supported: - return isinstance(a,(list,tuple, np.ndarray)) - else: - return isinstance(a,(list,tuple)) - -include "HumidAirProp.pyx" - -def set_reference_state(string_like FluidName, *args): - """ - Accepts one of two signatures: - - Type #1: - - set_reference_state(FluidName,reference_state) - - FluidName The name of the fluid - param reference_state The reference state to use, one of - - ========== =========================================== - ``IIR`` (h=200 kJ/kg, s=1 kJ/kg/K at 0C sat. liq.) - ``ASHRAE`` (h=0,s=0 @ -40C sat liq) - ``NBP`` (h=0,s=0 @ 1.0 bar sat liq.) - ========== =========================================== - - Type #2: - - set_reference_state(FluidName,T0,rho0,h0,s0) - - ``FluidName`` The name of the fluid - - ``T0`` The temperature at the reference point [K] - - ``rho0`` The density at the reference point [kg/m^3] - - ``h0`` The enthalpy at the reference point [J/kg] - - ``s0`` The entropy at the reference point [J/kg] - """ - - cdef bytes _param - cdef int retval - - if len(args) == 1: - _param = args[0].encode('ascii') - retval = _set_reference_stateS(FluidName, _param) - elif len(args) == 4: - retval = _set_reference_stateD(FluidName, args[0], args[1], args[2], args[3]) - else: - raise ValueError('Invalid number of inputs') - - if retval < 0: - raise ValueError('Unable to set reference state') - -cpdef add_REFPROP_fluid(string_like FluidName): - """ - Add a REFPROP fluid to CoolProp internal structure - - example:: - - add_REFPROP_fluid("REFPROP-PROPANE") - - """ - _add_REFPROP_fluid(FluidName) - -cpdef long get_Fluid_index(string_like Fluid): - """ - Gets the integer index of the given CoolProp fluid (primarily for use in ``IProps`` function) - """ - return _get_Fluid_index(Fluid) - -cpdef double IProps(long iOutput, long iInput1, double Input1, long iInput2, double Input2, long iFluid) except *: - """ - This is a more computationally efficient version of the Props() function as it uses integer keys for the input and output codes as well as the fluid index for the fluid. It can only be used with CoolProp fluids. An example of how it should be used:: - - # These should be run once in the header of your file - from CoolProp.CoolProp import IProps, get_Fluid_index - from CoolProp import param_constants - iPropane = get_Fluid_index('Propane') - - # This should be run using the cached values - much faster ! - IProps(param_constants.iP,param_constants.iT,0.8*Tc,param_constants.iQ,1,iPropane) - - The reason that this function is significantly faster than Props is that it skips all the string comparisons which slows down the Props function quite a lot. At the C++ level, IProps doesn't use any strings and operates on integers and floating point values - """ - cdef double val = _IProps(iOutput, iInput1, Input1, iInput2, Input2, iFluid) - - if math.isinf(val) or math.isnan(val): - err_string = _get_global_param_string('errstring') - if not len(err_string) == 0: - raise ValueError("{err:s} :: inputs were :{iin1:d},{in1:g},{iin2:d},{in2:g},{iFluid:d}".format(err= err_string,iin1=iInput1,in1=Input1,iin2=iInput2,in2=Input2,iFluid = iFluid)) - else: - raise ValueError("IProps failed ungracefully with inputs:\"{in1:g}\",\"{in2:g}\"; please file a ticket at https://sourceforge.net/p/coolprop/tickets/".format(in1=Input1,in2=Input2)) - else: - return val - -cpdef get_global_param_string(string_like param): - return _get_global_param_string(param) - -cpdef get_fluid_param_string(string_like fluid, string_like param): - return _get_fluid_param_string(fluid, param) - -def isConstant(what): - """Get the boolean telling you if - the given key matches with a fluid constant. - """ - altFactors = { - "Tcrit" : 1. ,#Critical temperature [K] - "pcrit" : 1./1000.,#Critical pressure [kPa] - "Psat" : 1./1000.,#Saturation pressure [kPa] - "rhocrit" : 1. ,#Critical density [kg/m3] - "molemass" : 1./1000.,#Molecular mass [kg/kmol] - "Ttriple" : 1. ,#Triple-point temperature [K] - "Tmin" : 1. ,#Minimum temperature [K] - "Tmax" : 1. ,#Maximum temperature [K] - "Tfreeze" : 1. ,#Freezing temperature [K] - "ptriple" : 1./1000.,#Triple-point pressure [kPa] - "accentric" : 1. ,#Accentric factor [-] - "GWP100" : 1. ,#Global Warming Potential 100 yr - "ODP" : 1. #Ozone Depletion Potential - } - if what in altFactors: - return True - else: - return False - #msg = 'Your input '+str(what)+' does not match any of the stored keys '+str(list(factors.keys()))+'.' - #print msg - #raise ValueError(msg) - -def PropsU(in1, in2, in3 = None, in4 = None, in5 = None, in6 = None, in7 = None): - """Make the Props function handle different kinds of unit sets. Use - kSI or SI to identify your desired unit system. Both input and output - values have to be from the same unit set. - """ - # Check for reduced inputs - if ( in4 == None - and in5 == None - and in6 == None - and in7 == None):# Only three arguments given - in7 = in3 - - if in7 is None or in7 == 'kSI': # Nothing has to be done - return Props(in1, in2, in3, in4, in5, in6) - elif in7 == 'SI': - if isConstant(in2): - return toSI(in2,Props(in1, in2, in3, in4, in5, in6), 'kSI') - else: - in3kSI = fromSI(in2, in3, 'kSI') - in5kSI = fromSI(in4, in5, 'kSI') - return toSI(in1,Props(in1, in2, in3kSI, in4, in5kSI, in6), 'kSI') - else: - msg = 'Your requested unit set '+str(in7)+' is not supported, valid unit definitions are kSI and SI only.' - #print msg - raise ValueError(msg) - -cpdef fromSI(str in1, in2=None, str in3 = 'kSI'): - """ - Call fromSI(Property, Value, Units) to convert from SI units to a given set of units. - At the moment, only kSI is supported. This convenience function is used inside both the - PropsU and DerivTermsU functions. - """ - if isinstance(in2, (int, long, float, complex)): #is not iterable - return _fromSI(in1, in2, in3) - else: # iterable or error - result = [_fromSI(in1, inV, in3) for inV in in2] - if _numpy_supported: - return np.array(result) - else: - return result - -cpdef toSI(str in1, in2=None, str in3='kSI'): - """ - Call toSI(Property, Value, Units) to convert from a given set of units to SI units. - At the moment, only kSI is supported. This convenience function is used inside both the - PropsU and DerivTermsU functions. - """ - if isinstance(in2, (int, long, float, complex)): #is not iterable - return _toSI(in1, in2, in3) - else: # iterable or error - result = [_toSI(in1, inV, in3) for inV in in2] - if _numpy_supported: - return np.array(result) - else: - return result - -cpdef ndarray_or_iterable(object input): - if _numpy_supported: - return np.array(input) - else: - return input - -cpdef __Props_err1(in1,in2,errstr): - if not len(errstr) == 0: - raise ValueError("{err:s} :: inputs were :\"{in1:s}\",\"{in2:s}\"".format(err= errstr,in1=in1,in2=in2)) - else: - raise ValueError("Props failed ungracefully with inputs:\"{in1:s}\",\"{in2:s}\"; please file a ticket at https://github.com/ibell/coolprop/issues".format(in1=in1,in2=in2)) - -cpdef __Props_err2(in1, in2, in3, in4, in5, in6, errstr): - if not len(errstr) == 0: - raise ValueError("{err:s} :: inputs were:\"{in1:s}\",\"{in2:s}\",{in3:0.16e},\"{in4:s}\",{in5:0.16e},\"{in6:s}\"".format(err=errstr,in1=in1,in2=in2,in3=in3,in4=in4,in5=in5,in6=in6)) - else: - raise ValueError("Props failed ungracefully :: inputs were:\"{in1:s}\",\"{in2:s}\",{in3:0.16e},\"{in4:s}\",{in5:0.16e},\"{in6:s}\"; please file a ticket at https://github.com/ibell/coolprop/issues".format(in1=in1,in2=in2,in3=in3,in4=in4,in5=in5,in6=in6)) - -cpdef Props(in1, in2, in3 = None, in4 = None, in5 = None, in6 = None, in7 = None): - """ - Call Type #1:: - - Props(Fluid,PropName) --> float - - Where ``Fluid`` is a string with a valid CoolProp fluid name, and ``PropName`` is one of the following strings: - - ============= ============================ - ``Tcrit`` Critical temperature [K] - ``Treduce`` Reducing temperature [K] - ``pcrit`` Critical pressure [kPa] - ``rhocrit`` Critical density [kg/m3] - ``rhoreduce`` Reducing density [kg/m3] - ``molemass`` Molecular mass [kg/kmol] - ``Ttriple`` Triple-point temperature [K] - ``Tmin`` Minimum temperature [K] - ``ptriple`` Triple-point pressure [kPa] - ``accentric`` Accentric factor [-] - ``GWP100`` Global Warming Potential 100 yr - ``ODP`` Ozone Depletion Potential - ============= ============================ - - This type of call is used to get fluid-specific parameters that are not - dependent on the state - - Call Type #2: - - Alternatively, Props can be called in the form:: - - Props(OutputName,InputName1,InputProp1,InputName2,InputProp2,Fluid) --> float - - where ``Fluid`` is a string with a valid CoolProp fluid name. The value - ``OutputName`` is either a single-character or a string alias. This list - shows the possible values - - ============================ ====================================================== - ``OutputName`` Description - ============================ ====================================================== - ``Q`` Quality [-] - ``T`` Temperature [K] - ``P`` Pressure [kPa] - ``D`` Density [kg/m3] - ``C0`` Ideal-gas specific heat at constant pressure [kJ/kg/K] - ``C`` Specific heat at constant pressure [kJ/kg/K] - ``O`` Specific heat at constant volume [kJ/kg/K] - ``U`` Internal energy [kJ/kg] - ``H`` Enthalpy [kJ/kg] - ``S`` Entropy [kJ/kg/K] - ``A`` Speed of sound [m/s] - ``G`` Gibbs function [kJ/kg] - ``V`` Dynamic viscosity [Pa-s] - ``L`` Thermal conductivity [kW/m/K] - ``I`` or ``SurfaceTension`` Surface Tension [N/m] - ``w`` or ``accentric`` Accentric Factor [-] - ============================ ====================================================== - - The following sets of input values are valid (order doesn't matter): - - ========================= ====================================== - ``InputName1`` ``InputName2`` - ========================= ====================================== - ``T`` ``P`` - ``T`` ``D`` - ``P`` ``D`` - ``T`` ``Q`` - ``P`` ``Q`` - ``H`` ``P`` - ``S`` ``P`` - ``S`` ``H`` - ``T`` ``S`` - ========================= ====================================== - - **Python Only** : InputProp1 and InputProp2 can be lists or numpy arrays. If both are iterables, they must be the same size. - - If `InputName1` is `T` and `OutputName` is ``I`` or ``SurfaceTension``, the second input is neglected - since surface tension is only a function of temperature - """ - cdef double _in3 - - if (in4 is None and in6 is None and in7 is None): - val = _Props1(in1.encode('ascii'), in2.encode('ascii')) - if not _ValidNumber(val): - __Props_err1(in1,in2,_get_global_param_string('errstring')) - else: - return val - else: - if not iterable(in3) and not iterable(in5): - val = _Props(in1, in2, in3, in4, in5, in6) - if not _ValidNumber(val): - __Props_err2(in1,in2,in3,in4,in5,in6,_get_global_param_string('errstring')) - else: - return val - elif iterable(in3) and iterable(in5): - if len(in3) != len(in5) : raise TypeError('Lengths of iterables must be the same') - vals = [] - for _in3, _in5 in zip(in3,in5): - val = _PropsS(in1, in2, _in3, in4, _in5, in6) - if not _ValidNumber(val): - __Props_err2(in1,in2,_in3,in4,_in5,in6,_get_global_param_string('errstring')) - vals.append(val) - return ndarray_or_iterable(vals) - else: - if iterable(in5) and not iterable(in3): - in3, in5 = in5, in3 # swap 3 and 5 so 3 is the iterable - in2, in4 = in4, in2 # swap their keys too - vals = [] - for _in3 in in3: - val = _Props(in1, in2, _in3, in4, in5, in6) - if not _ValidNumber(val): - __Props_err2(in1,in2,_in3,in4,in5,in6,_get_global_param_string('errstring')) - vals.append(val) - return ndarray_or_iterable(vals) - -cpdef __PropSIs_err1(in1,in2,errstr): - if not len(errstr) == 0: - raise ValueError("{err:s} :: inputs were :\"{in1:s}\",\"{in2:s}\"".format(err= errstr,in1=in1,in2=in2)) - else: - raise ValueError("PropsSI failed ungracefully with inputs:\"{in1:s}\",\"{in2:s}\"; please file a ticket at https://github.com/ibell/coolprop/issues".format(in1=in1,in2=in2)) - -cpdef __PropsSI_err2(in1, in2, in3, in4, in5, in6, errstr): - if not len(errstr) == 0: - raise ValueError("{err:s} :: inputs were:\"{in1:s}\",\"{in2:s}\",{in3:0.16e},\"{in4:s}\",{in5:0.16e},\"{in6:s}\"".format(err=errstr,in1=in1,in2=in2,in3=in3,in4=in4,in5=in5,in6=in6)) - else: - raise ValueError("PropsSI failed ungracefully :: inputs were:\"{in1:s}\",\"{in2:s}\",{in3:0.16e},\"{in4:s}\",{in5:0.16e},\"{in6:s}\"; please file a ticket at https://github.com/ibell/coolprop/issues".format(in1=in1,in2=in2,in3=in3,in4=in4,in5=in5,in6=in6)) - -cpdef PropsSI(in1, in2, in3 = None, in4 = None, in5 = None, in6 = None, in7 = None): - """ - Just like Props(), but this function ALWAYS takes in and returns SI units (K, kg, J/kg, Pa, N/m, etc.) - - Call Type #1:: - - Props(Fluid,PropName) --> float - - Where ``Fluid`` is a string with a valid CoolProp fluid name, and ``PropName`` is one of the following strings: - - ============= ============================ - ``Tcrit`` Critical temperature [K] - ``Treduce`` Reducing temperature [K] - ``pcrit`` Critical pressure [Pa] - ``rhocrit`` Critical density [kg/m3] - ``rhoreduce`` Reducing density [kg/m3] - ``molemass`` Molecular mass [kg/kmol] - ``Ttriple`` Triple-point temperature [K] - ``Tmin`` Minimum temperature [K] - ``ptriple`` Triple-point pressure [Pa] - ``accentric`` Accentric factor [-] - ``GWP100`` Global Warming Potential 100 yr - ``ODP`` Ozone Depletion Potential - ============= ============================ - - This type of call is used to get fluid-specific parameters that are not - dependent on the state - - Call Type #2: - - Alternatively, Props can be called in the form:: - - Props(OutputName,InputName1,InputProp1,InputName2,InputProp2,Fluid) --> float - - where ``Fluid`` is a string with a valid CoolProp fluid name. The value - ``OutputName`` is either a single-character or a string alias. This list - shows the possible values - - ============================ ====================================================== - ``OutputName`` Description - ============================ ====================================================== - ``Q`` Quality [-] - ``T`` Temperature [K] - ``P`` Pressure [Pa] - ``D`` Density [kg/m3] - ``C0`` Ideal-gas specific heat at constant pressure [J/kg] - ``C`` Specific heat at constant pressure [J/kg] - ``O`` Specific heat at constant volume [J/kg] - ``U`` Internal energy [J/kg] - ``H`` Enthalpy [J/kg] - ``S`` Entropy [J/kg/K] - ``A`` Speed of sound [m/s] - ``G`` Gibbs function [J/kg] - ``V`` Dynamic viscosity [Pa-s] - ``L`` Thermal conductivity [W/m/K] - ``I`` or ``SurfaceTension`` Surface Tension [N/m] - ``w`` or ``accentric`` Accentric Factor [-] - ============================ ====================================================== - - The following sets of input values are valid (order doesn't matter): - - ========================= ====================================== - ``InputName1`` ``InputName2`` - ========================= ====================================== - ``T`` ``P`` - ``T`` ``D`` - ``P`` ``D`` - ``T`` ``Q`` - ``P`` ``Q`` - ``H`` ``P`` - ``S`` ``P`` - ``S`` ``H`` - ========================= ====================================== - - **Python Only** : InputProp1 and InputProp2 can be lists or numpy arrays. If both are iterables, they must be the same size. - - - If `InputName1` is `T` and `OutputName` is ``I`` or ``SurfaceTension``, the second input is neglected - since surface tension is only a function of temperature - - """ - cdef double _in3 - if (in4 is None and in6 is None and in7 is None): - val = _Props1SI(in1.encode('ascii'), in2.encode('ascii')) - if not _ValidNumber(val): - __Props_err1(in1,in2,_get_global_param_string('errstring')) - else: - return val - else: - if not iterable(in3) and not iterable(in5): - val = _PropsSI(in1, in2, in3, in4, in5, in6) - if not _ValidNumber(val): - __PropsSI_err2(in1,in2,in3,in4,in5,in6,_get_global_param_string('errstring')) - else: - return val - elif iterable(in3) and iterable(in5): - if len(in3) != len(in5) : raise TypeError('Lengths of iterables must be the same') - vals = [] - for _in3, _in5 in zip(in3,in5): - val = _PropsSI(in1, in2, _in3, in4, _in5, in6) - if not _ValidNumber(val): - __PropsSI_err2(in1,in2,_in3,in4,_in5,in6,_get_global_param_string('errstring')) - vals.append(val) - return ndarray_or_iterable(vals) - else: - if iterable(in5) and not iterable(in3): - in3, in5 = in5, in3 # swap 3 and 5 so 3 is the iterable - in2, in4 = in4, in2 # swap their keys too - vals = [] - for _in3 in in3: - val = _PropsSI(in1, in2, _in3, in4, in5, in6) - if not _ValidNumber(val): - __PropsSI_err2(in1,in2,_in3,in4,in5,in6,_get_global_param_string('errstring')) - vals.append(val) - return ndarray_or_iterable(vals) - -def DerivTermsU(in1, T, rho, fluid, units = None): - """Make the DerivTerms function handle different kinds of unit sets. Use - kSI or SI to identify your desired unit system. Both input and output - values have to be from the same unit set. - """ - if units is None or units == 'kSI': - return DerivTerms(in1, T, rho, fluid) - elif units == 'SI': - return toSI(in1,DerivTerms(in1, T, rho, fluid), 'kSI') - else: - msg = 'Your requested unit set '+str(units)+' is not supported, valid unit definitions are kSI and SI only.' - #print msg - raise ValueError(msg) - -cpdef double DerivTerms(str Output, double T, double rho, str Fluid) except +: - """ - - .. |cubed| replace:: \ :sup:`3`\ - .. |squared| replace:: \ :sup:`2`\ - .. |IC| replace:: ``IsothermalCompressibility`` - - Call signature:: - - DerivTerms(OutputName, T, rho, Fluid) --> float - - where ``Fluid`` is a string with a valid CoolProp fluid name, and ``T`` and ``rho`` are the temperature in K and density in kg/m |cubed| . The value - ``OutputName`` is one of the strings in the table below: - - ======================== ===================================================================================================================================== - OutputName Description - ======================== ===================================================================================================================================== - ``dpdT`` Derivative of pressure with respect to temperature at constant density [kPa/K] - ``dpdrho`` Derivative of pressure with respect to density at constant temperature [kPa/(kg/m\ |cubed|\ )] - ``Z`` Compressibility factor [-] - ``dZ_dDelta`` Derivative of Z with respect to reduced density [-] - ``dZ_dTau`` Derivative of Z with respect to inverse reduced temperature [-] - ``VB`` Second virial coefficient [m\ |cubed|\ /kg] - ``dBdT`` Derivative of second virial coefficient with respect to temperature [m\ |cubed|\ /kg/K] - ``VC`` Third virial coefficient [m\ :sup:`6`\ /kg\ |squared|\ ] - ``dCdT`` Derivative of third virial coefficient with respect to temperature [m\ :sup:`6`\ /kg\ |squared|\ /K] - ``phir`` Residual non-dimensionalized Helmholtz energy [-] - ``dphir_dTau`` Partial of residual non-dimensionalized Helmholtz energy with respect to inverse reduced temperature [-] - ``d2phir_dTau2`` Second partial of residual non-dimensionalized Helmholtz energy with respect to inverse reduced temperature [-] - ``dphir_dDelta`` Partial of residual non-dimensionalized Helmholtz energy with respect to reduced density [-] - ``d2phir_dDelta2`` Second partial of residual non-dimensionalized Helmholtz energy with respect to reduced density [-] - ``d2phir_dDelta_dTau`` First cross-partial of residual non-dimensionalized Helmholtz energy [-] - ``d3phir_dDelta2_dTau`` Second cross-partial of residual non-dimensionalized Helmholtz energy [-] - ``phi0`` Ideal-gas non-dimensionalized Helmholtz energy [-] - ``dphi0_dTau`` Partial of ideal-gas non-dimensionalized Helmholtz energy with respect to inverse reduced temperature [-] - ``d2phi0_dTau2`` Second partial of ideal-gas non-dimensionalized Helmholtz energy with respect to inverse reduced temperature [-] - ``dphi0_dDelta`` Partial of ideal-gas non-dimensionalized Helmholtz energy with respect to reduced density [-] - ``d2phi0_dDelta2`` Second partial of ideal-gas non-dimensionalized Helmholtz energy with respect to reduced density [-] - |IC| Isothermal compressibility [1/kPa] - ======================== ===================================================================================================================================== - """ - cdef bytes _Fluid = Fluid.encode('ascii') - cdef bytes _Output = Output.encode('ascii') - return _DerivTerms(_Output,T,rho,_Fluid) - -cpdef string Phase_Tp(str Fluid, double T, double p): - cdef bytes _Fluid = Fluid.encode('ascii') - return _Phase_Tp(_Fluid,T,p) - -cpdef string Phase_Trho(str Fluid, double T, double rho): - cdef bytes _Fluid = Fluid.encode('ascii') - return _Phase_Trho(_Fluid,T,rho) - -cpdef string Phase(str Fluid, double T, double p): - """ - Given a set of temperature and pressure, returns one of the following strings - - * Gas - * Liquid - * Supercritical - * Two-Phase - - Phase diagram:: - - | | - | | Supercritical - | | - p | Liquid (b)------------ - | / - | / - | / Gas - | / - | (a) - | / - |------------------------ - - T - - a: triple point - b: critical point - a-b: Saturation line - """ - cdef bytes _Fluid = Fluid.encode('ascii') - return _Phase(_Fluid,T,p) - -cpdef double F2K(double T_F): - """ - Convert temperature in degrees Fahrenheit to Kelvin - """ - return _F2K(T_F) - -cpdef double K2F(double T_K): - """ - Convert temperature in Kelvin to degrees Fahrenheit - """ - return _K2F(T_K) - -cpdef list FluidsList(): - """ - Return a list of strings of all fluid names - - Returns - ------- - FluidsList : list of strings of fluid names - All the fluids that are included in CoolProp - - Notes - ----- - - Here is an example:: - - In [0]: from CoolProp.CoolProp import FluidsList - - In [1]: FluidsList() - - """ - return _get_global_param_string("FluidsList").split(',') - -cpdef get_aliases(str Fluid): - """ - Return a comma separated string of aliases for the given fluid - """ - cdef bytes _Fluid = Fluid.encode('ascii') - return [F.encode('ascii') for F in (_get_fluid_param_string(_Fluid,'aliases').encode('ascii')).decode('ascii').split(',')] - -cpdef get_ASHRAE34(str Fluid): - """ - Return the safety code for the fluid from ASHRAE34 if it is in ASHRAE34 - """ - cdef bytes _Fluid = Fluid.encode('ascii') - return _get_fluid_param_string(_Fluid,"ASHRAE34") - -cpdef string get_REFPROPname(str Fluid): - """ - Return the REFPROP compatible name for the fluid (only useful on windows) - - Some fluids do not use the REFPROP name. For instance, - ammonia is R717, and propane is R290. You can still can still call CoolProp - using the name ammonia or R717, but REFPROP requires that you use a limited - subset of names. Therefore, this function that returns the REFPROP compatible - name. To then use this to call REFPROP, you would do something like:: - - In [0]: from CoolProp.CoolProp import get_REFPROPname, Props - - In [1]: Fluid = 'REFPROP-' + get_REFPROPname('R290') - - In [2]: Props('D', 'T', 300, 'P', 300, Fluid) - """ - cdef bytes _Fluid = Fluid.encode('ascii') - return _get_fluid_param_string(_Fluid,'REFPROP_name') - -cpdef string get_BibTeXKey(str Fluid, str key): - """ - Return the BibTeX key for the given fluid. - - The possible keys are - - * ``EOS`` - * ``CP0`` - * ``VISCOSITY`` - * ``CONDUCTIVITY`` - * ``ECS_LENNARD_JONES`` - * ``ECS_FITS`` - * ``SURFACE_TENSION`` - - BibTeX keys refer to the BibTeX file in the trunk/CoolProp folder - - Returns - ------- - key, string - empty string if Fluid not in CoolProp, "Bad key" if key is invalid - """ - return _get_BibTeXKey(Fluid.encode('ascii'), key.encode('ascii')) - -cpdef string get_errstr(): - """ - Return the current error string - """ - return _get_global_param_string("errstring") - -cpdef set_debug_level(int level): - """ - Set the current debug level as integer in the range [0,10] - - Parameters - ---------- - level : int - If level is 0, no output will be written to screen, if >0, - some output will be written to screen. The larger level is, - the more verbose the output will be - """ - _set_debug_level(level) - -cpdef get_debug_level(): - """ - Return the current debug level as integer - - Returns - ------- - level : int - If level is 0, no output will be written to screen, if >0, - some output will be written to screen. The larger level is, - the more verbose the output will be - """ - return _get_debug_level() - -cpdef string get_CAS_code(string Fluid): - """ - Return a string with the CAS number for the given fluid - """ - return _get_fluid_param_string(Fluid,"CAS") - -cpdef bint IsFluidType(string Fluid, string Type): - """ - Check if a fluid is of a given type - - Valid types are: - - * ``Brine`` - * ``PseudoPure`` (or equivalently ``PseudoPureFluid``) - * ``PureFluid`` - """ - cdef bytes _Fluid = Fluid.encode('ascii') - cdef bytes _Type = Type.encode('ascii') - if _IsFluidType(_Fluid,_Type): - return True - else: - return False - -cpdef bint set_TTSE_mode(char* FluidName, char* Value): - """ Set the mode of the TTSE table, one of ``"TTSE"`` or ``"BICUBIC"`` - """ - return _set_TTSE_mode(FluidName, Value) - -cpdef str get_TTSE_mode(string fluid): - """ Get the mode of the TTSE table, one of ``"TTSE"`` or ``"BICUBIC"`` - """ - return _get_fluid_param_string(fluid,'TTSE_mode').encode('ascii') - -#: Enable the TTSE -cpdef bint enable_TTSE_LUT(char *FluidName): return _enable_TTSE_LUT(FluidName) -#: Check if TTSE is enabled -cpdef bint isenabled_TTSE_LUT(char *FluidName): return _isenabled_TTSE_LUT(FluidName) -#: Disable the TTSE -cpdef bint disable_TTSE_LUT(char *FluidName): return _disable_TTSE_LUT(FluidName) - -#: Enable the TTSE -cpdef bint enable_TTSE_LUT_writing(char *FluidName): return _enable_TTSE_LUT_writing(FluidName) -#: Check if TTSE is enabled -cpdef bint isenabled_TTSE_LUT_writing(char *FluidName): return _isenabled_TTSE_LUT_writing(FluidName) -#: Disable the TTSE -cpdef bint disable_TTSE_LUT_writing(char *FluidName): return _disable_TTSE_LUT_writing(FluidName) - -#: Over-ride the default size of both of the saturation LUT -cpdef bint set_TTSESat_LUT_size(char *FluidName, int N): return _set_TTSESat_LUT_size(FluidName, N) -#: Over-ride the default size of the single-phase LUT -cpdef bint set_TTSESinglePhase_LUT_size(char *FluidName, int Np, int Nh): return _set_TTSESinglePhase_LUT_size(FluidName, Np, Nh) -#: Over-ride the default range of the single-phase LUT -cpdef bint set_TTSESinglePhase_LUT_range(char *FluidName, double hmin, double hmax, double pmin, double pmax): return _set_TTSESinglePhase_LUT_range(FluidName, hmin, hmax, pmin, pmax) - -cpdef tuple get_TTSESinglePhase_LUT_range(char *FluidName): - """ - Get the current range of the single-phase LUT - - Returns - ------- - tuple of hmin,hmax,pmin,pmax - - """ - cdef double hmin = 0, hmax = 0, pmin = 0, pmax = 0 - #In cython, hmin[0] to get pointer rather than &hmin - cdef bint valsok = _get_TTSESinglePhase_LUT_range(FluidName, &hmin, &hmax, &pmin, &pmax) - if valsok: - return (hmin, hmax, pmin, pmax) - else: - raise ValueError("Either your FluidName was invalid or LUT bounds not available since no call has been made to tables") - -cpdef set_standard_unit_system(int unit_system): - _set_standard_unit_system(unit_system) - -cpdef int get_standard_unit_system(): - return _get_standard_unit_system() - -from math import pow as pow_ - -#A dictionary mapping parameter index to string for use with non-CoolProp fluids -cdef dict paras = {iD : 'D', - iQ : 'Q', - iMM : 'M', - iT : 'T', - iH : 'H', - iP : 'P', - iC : 'C', - iC0 : 'C0', - iO : 'O', - iV : 'V', - iL : 'L', - iS : 'S', - iU : 'U', - iDpdT : 'dpdT'} - -cdef dict paras_inverse = {v:k for k,v in paras.iteritems()} - -cdef class State: - """ - A class that contains all the code that represents a thermodynamic state - - The motivation for this class is that it is useful to be able to define the - state once using whatever state inputs you like and then be able to calculate - other thermodynamic properties with the minimum of computational work. - - Let's suppose that you have inputs of pressure and temperature and you want - to calculate the enthalpy and pressure. Since the Equations of State are - all explicit in temperature and density, each time you call something like:: - - h = Props('H','T',T','P',P,Fluid) - s = Props('S','T',T','P',P,Fluid) - - the solver is used to carry out the T-P flash calculation. And if you wanted - entropy as well you could either intermediately calculate ``T``, ``rho`` and then use - ``T``, ``rho`` in the EOS in a manner like:: - - rho = Props('D','T',T','P',P,Fluid) - h = Props('H','T',T','D',rho,Fluid) - s = Props('S','T',T','D',rho,Fluid) - - Instead in this class all that is handled internally. So the call to update - sets the internal variables in the most computationally efficient way possible - """ - - def __init__(self, object Fluid, dict StateDict, object phase = None): - """ - Parameters - ---------- - Fluid, string - StateDict, dictionary - The state of the fluid - passed to the update function - phase, string - The phase of the fluid, it it is known. One of ``Gas``,``Liquid``,``Supercritical``,``TwoPhase`` - """ - cdef string _Fluid = Fluid - - if _Fluid == 'none': - return - else: - self.set_Fluid(Fluid) - - if phase is None: - _phase = b'' - elif isinstance(phase,str): - _phase = phase.encode('ascii') - elif isinstance(phase,bytes): - _phase = phase - else: - raise TypeError() - - self.phase = _phase - #Parse the inputs provided - self.update(StateDict) - #Set the phase flag - if self.phase == 'Gas' or self.phase == 'Liquid' or self.phase == 'Supercritical': - if self.is_CPFluid and (self.phase == 'Gas' or self.phase == 'Liquid'): - self.CPS.flag_SinglePhase = True - elif not self.is_CPFluid and phase is not None: - _set_phase(self.phase) - - def __reduce__(self): - d={} - d['Fluid']=self.Fluid - d['T']=self.T_ - d['rho']=self.rho_ - d['phase'] = self.phase - return rebuildState,(d,) - - cpdef set_Fluid(self, string_like Fluid): - self.Fluid = Fluid.encode('ascii') - - if self.Fluid.startswith('REFPROP-'): - _add_REFPROP_fluid(self.Fluid) - self.iFluid = _get_Fluid_index(self.Fluid) - - # Try to get the fluid from CoolProp - if self.iFluid >= 0: - # It is a CoolProp Fluid so we can use the faster integer passing function - self.is_CPFluid = True - # Instantiate the C++ State class - self.CPS = CoolPropStateClassSI(self.Fluid) - else: - raise ValueError('Invalid fluid name [{n:s}]'.format(n = self.Fluid)) - - cpdef update_ph(self, double p, double h): - """ - Use the pressure and enthalpy directly - - Parameters - ---------- - p: float - Pressure (absolute) [kPa] - h: float - Enthalpy [kJ/kg] - - """ - p = _toSIints(iP, p, _get_standard_unit_system()); - h = _toSIints(iH, h, _get_standard_unit_system()); - self.p_ = p - cdef double T - - if self.is_CPFluid: - self.CPS.update(iP, p, iH, h) - self.T_ = self.CPS.T() - self.rho_ = self.CPS.rho() - else: - T = _PropsSI('T','P',p,'H',h,self.Fluid) - if abs(T)<1e90: - self.T_=T - else: - errstr = _get_global_param_string('errstring') - raise ValueError(errstr) - self.rho_ = _Props('D','P',p,'H',h,self.Fluid) - - cpdef update_Trho(self, double T, double rho): - """ - Just use the temperature and density directly for speed - - Parameters - ---------- - T: float - Temperature [K] - rho: float - Density [kg/m^3] - - """ - cdef double p - self.T_ = T - self.rho_ = rho - - if self.is_CPFluid: - self.CPS.update(iT,T,iD,rho) - p = self.CPS.p() - else: - p = _Props('P','T',T,'D',rho,self.Fluid) - - p = _fromSIints(iP, p, _get_standard_unit_system()); - - if _ValidNumber(p): - self.p_ = p - else: - errstr = _get_global_param_string('errstring') - raise ValueError(errstr+' for T,rho = '+str(T)+','+str(rho)+' '+str(p)+' '+str(_ValidNumber(p))) - - cpdef update(self, dict params): - """ - Parameters - params, dictionary - A dictionary of terms to be updated, with keys equal to single-char inputs to the Props function, - for instance ``dict(T=298, P = 101.325)`` would be one standard atmosphere - """ - - cdef double p, val1, val2 - cdef long iInput1, iInput2 - cdef bytes errstr - - if self.is_CPFluid: - items = list(params.items()) - iInput1 = paras_inverse[items[0][0]] - iInput2 = paras_inverse[items[1][0]] - # Convert to SI units - val1 = _toSIints(iInput1, items[0][1], _get_standard_unit_system()); - val2 = _toSIints(iInput2, items[1][1], _get_standard_unit_system()); - try: - self.CPS.update(iInput1, val1, iInput2, val2) - except: - raise - self.T_ = self.CPS.T() - self.p_ = _fromSIints(iP, self.CPS.p(), _get_standard_unit_system()); - self.rho_ = self.CPS.rho() - - if not _ValidNumber(self.T_) or not _ValidNumber(self.p_) or not _ValidNumber(self.rho_): - raise ValueError(str(params)) - return - - #Get the density if T,P provided, or pressure if T,rho provided - if 'P' in params: - self.p_=params['P'] - rho = _Props('D','T',self.T_,'P',self.p_,self.Fluid) - - if abs(rho) < 1e90: - self.rho_=rho - else: - errstr = _get_global_param_string('errstring') - raise ValueError(errstr) - elif 'D' in params: - self.rho_=params['D'] - p = _Props('P','T',self.T_,'D',self.rho_,self.Fluid) - - if abs(p)<1e90: - self.p_=p - else: - errstr = _get_global_param_string('errstring') - raise ValueError(errstr+str(params)) - elif 'Q' in params: - p = _Props('P','T',self.T_,'Q',params['Q'],self.Fluid) - self.rho_ = _Props('D','T',self.T_,'Q',params['Q'],self.Fluid) - - if abs(self.rho_)<1e90: - pass - else: - errstr = _get_global_param_string('errstring') - raise ValueError(errstr+str(params)) - else: - raise KeyError("Dictionary must contain the key 'T' and one of 'P' or 'D'") - - cpdef long Phase(self) except *: - """ - Returns an integer flag for the phase of the fluid, where the flag value - is one of iLiquid, iSupercritical, iGas, iTwoPhase - - These constants are defined in the phase_constants module, and are imported - into this module - """ - - if self.is_CPFluid: - return self.CPS.phase() - else: - raise NotImplementedError("Phase not defined for fluids other than CoolProp fluids") - - cpdef double Props(self, long iOutput) except *: - if iOutput<0: - raise ValueError('Your output is invalid') - - if self.is_CPFluid: - val = self.CPS.keyed_output(iOutput) - return _fromSIints(iOutput,val,_get_standard_unit_system()); - else: - return _Props(paras[iOutput],'T',self.T_,'D',self.rho_,self.Fluid) - - cpdef double get_Q(self) except *: - """ Get the quality [-] """ - return self.Props(iQ) - property Q: - """ The quality [-] """ - def __get__(self): - return self.get_Q() - - cpdef double get_MM(self) except *: - """ Get the mole mass [kg/kmol] or [g/mol] """ - return self.Props(iMM) - - cpdef double get_rho(self) except *: - """ Get the density [kg/m^3] """ - return self.Props(iD) - property rho: - """ The density [kg/m^3] """ - def __get__(self): - return self.Props(iD) - - cpdef double get_p(self) except *: - """ Get the pressure [kPa] """ - return self.Props(iP) - property p: - """ The pressure [kPa] """ - def __get__(self): - return self.get_p() - - cpdef double get_T(self) except *: - """ Get the temperature [K] """ - return self.Props(iT) - property T: - """ The temperature [K] """ - def __get__(self): - return self.get_T() - - cpdef double get_h(self) except *: - """ Get the specific enthalpy [kJ/kg] """ - return self.Props(iH) - property h: - """ The specific enthalpy [kJ/kg] """ - def __get__(self): - return self.get_h() - - cpdef double get_u(self) except *: - """ Get the specific internal energy [kJ/kg] """ - return self.Props(iU) - property u: - """ The internal energy [kJ/kg] """ - def __get__(self): - return self.get_u() - - cpdef double get_s(self) except *: - """ Get the specific enthalpy [kJ/kg/K] """ - return self.Props(iS) - property s: - """ The specific enthalpy [kJ/kg/K] """ - def __get__(self): - return self.get_s() - - cpdef double get_cp0(self) except *: - """ Get the specific heat at constant pressure for the ideal gas [kJ/kg/K] """ - return self.Props(iC0) - - cpdef double get_cp(self) except *: - """ Get the specific heat at constant pressure [kJ/kg/K] """ - return self.Props(iC) - property cp: - """ The specific heat at constant pressure [kJ/kg/K] """ - def __get__(self): - return self.get_cp() - - cpdef double get_cv(self) except *: - """ Get the specific heat at constant volume [kJ/kg/K] """ - return self.Props(iO) - property cv: - """ The specific heat at constant volume [kJ/kg/K] """ - def __get__(self): - return self.get_cv() - - cpdef double get_speed_sound(self) except *: - """ Get the speed of sound [m/s] """ - return self.Props(iA) - - cpdef double get_visc(self) except *: - """ Get the viscosity, in [Pa-s]""" - return self.Props(iV) - property visc: - """ The viscosity, in [Pa-s]""" - def __get__(self): - return self.get_visc() - - cpdef double get_cond(self) except *: - """ Get the thermal conductivity, in [kW/m/K]""" - return self.Props(iL) - property k: - """ The thermal conductivity, in [kW/m/K]""" - def __get__(self): - return self.get_cond() - - cpdef get_Tsat(self, double Q = 1): - """ - Get the saturation temperature, in [K] - - Returns ``None`` if pressure is not within the two-phase pressure range - """ - if self.p_ > _Props1(self.Fluid,'pcrit') or self.p_ < _Props1(self.Fluid,'ptriple'): - return None - else: - return _Props('T', 'P', self.p_, 'Q', Q, self.Fluid) - property Tsat: - """ The saturation temperature (dew) for the given pressure, in [K]""" - def __get__(self): - return self.get_Tsat(1.0) - - cpdef get_superheat(self): - """ - Get the amount of superheat above the saturation temperature corresponding to the pressure, in [K] - - Returns ``None`` if pressure is not within the two-phase pressure range - """ - - Tsat = self.get_Tsat(1) #dewpoint temp - - if Tsat is not None: - return self.T_-Tsat - else: - return None - property superheat: - """ - The amount of superheat above the saturation temperature corresponding to the pressure, in [K] - - Returns ``None`` if pressure is not within the two-phase pressure range - """ - def __get__(self): - return self.get_superheat() - - cpdef get_subcooling(self): - """ - Get the amount of subcooling below the saturation temperature corresponding to the pressure, in [K] - - Returns ``None`` if pressure is not within the two-phase pressure range - """ - - Tsat = self.get_Tsat(0) #bubblepoint temp - - if Tsat is not None: - return Tsat - self.T_ - else: - return None - property subcooling: - """ - The amount of subcooling below the saturation temperature corresponding to the pressure, in [K] - - Returns ``None`` if pressure is not within the two-phase pressure range - """ - def __get__(self): - return self.get_subcooling() - - property Prandtl: - """ The Prandtl number (cp*mu/k) [-] """ - def __get__(self): - return self.cp * self.visc / self.k - - cpdef double get_dpdT(self) except *: - if self.is_CPFluid: - return _fromSIints(iDERdp_dT__rho, self.CPS.dpdT_constrho(), _get_standard_unit_system()); - else: - raise ValueError("get_dpdT not supported for fluids that are not in CoolProp") - property dpdT: - def __get__(self): - return self.get_dpdT() - - cpdef speed_test(self, int N): - from time import clock - cdef int i - cdef char * k - cdef long ikey - cdef string Fluid = self.Fluid - cdef long IT = 'T' - cdef long ID = 'D' - import CoolProp as CP - - print 'Call to the Python call layer (CoolProp.CoolProp.Props)' - print "'M' involves basically no computational effort and is a good measure of the function call overhead" - keys = ['H','P','S','U','C','O','V','L','M','C0','dpdT'] - for key in keys: - t1=clock() - for i in range(N): - CP.Props(key,'T',self.T_,'D',self.rho_,Fluid) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,key,(t2-t1)/N*1e6) - - print 'Direct c++ call to CoolProp without the Python call layer (_Props function)' - print "'M' involves basically no computational effort and is a good measure of the function call overhead" - keys = ['H','P','S','U','C','O','V','L','M','C0','dpdT'] - for key in keys: - t1=clock() - for i in range(N): - _Props(key,'T',self.T_,'D',self.rho_,Fluid) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,key,(t2-t1)/N*1e6) - - print 'Call to the c++ layer through IProps' - keys = [iH,iP,iS,iU,iC,iO,iV,iL,iMM,iC0,iDpdT] - for key in keys: - t1=clock() - for i in range(N): - _IProps(key,iT,self.T_,iD,self.rho_,self.iFluid) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[key],(t2-t1)/N*1e6) - - print 'Call to the c++ layer using integers' - keys = [iH,iP,iS,iU,iC,iO,iV,iL,iMM,iC0,iDpdT] - for key in keys: - t1=clock() - for i in range(N): - self.CPS.update(iT,self.T_,iD,self.rho_) - self.CPS.keyed_output(key) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[key],(t2-t1)/N*1e6) - - keys = [iH,iP,iS,iU,iC,iO,iV,iL,iMM,iC0,iDpdT] - isenabled = _isenabled_TTSE_LUT(Fluid) - _enable_TTSE_LUT(Fluid) - _IProps(iH,iT,self.T_,iD,self.rho_,self.iFluid) - - print 'Call using TTSE with T,rho' - print "'M' involves basically no computational effort and is a good measure of the function call overhead" - for ikey in keys: - t1=clock() - self.CPS.update(iT,self.T_,iD,self.rho_) - for i in range(N): - self.CPS.keyed_output(ikey) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[ikey],(t2-t1)/N*1e6) - - print 'Call using TTSE with p,h' - print "'M' involves basically no computational effort and is a good measure of the function call overhead" - cdef double hh = self.h - for ikey in keys: - t1=clock() - self.CPS.update(iP,self.p_,iH,hh) - for i in range(N): - self.CPS.keyed_output(ikey) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[ikey],(t2-t1)/N*1e6) - - print 'Using CoolPropStateClass with T,rho with LUT' - keys = [iH,iP,iC,iO,iDpdT] - t1=clock() - for i in range(N): - self.CPS.update(iT,self.T_,iD,self.rho_) - for ikey in keys: - self.CPS.keyed_output(ikey) - t2=clock() - print 'Elapsed time for {0:d} calls of iH,iP,iC,iO,iDpdT takes {1:g} us/call'.format(N,(t2-t1)/N*1e6) - - if not isenabled: - _disable_TTSE_LUT(Fluid) - - def __str__(self): - """ - Return a string representation of the state - """ - units={'T': 'K', - 'p': 'kPa', - 'rho': 'kg/m^3', - 'Q':'kg/kg', - 'h':'kJ/kg', - 'u':'kJ/kg', - 's':'kJ/kg/K', - 'visc':'Pa-s', - 'k':'kW/m/K', - 'cp':'kJ/kg/K', - 'cv':'kJ/kg/K', - 'dpdT':'kPa/K', - 'Tsat':'K', - 'superheat':'K', - 'subcooling':'K', - } - s='phase = '+self.phase+'\n' - for k in ['T','p','rho','Q','h','u','s','visc','k','cp','cv','dpdT','Prandtl','superheat','subcooling']: - if k in units: - s+=k+' = '+str(getattr(self,k))+' '+units[k]+'\n' - else: - s+=k+' = '+str(getattr(self,k))+' NO UNITS'+'\n' - return s.rstrip() - - cpdef State copy(self): - """ - Make a copy of this State class - """ - cdef State S = State(self.Fluid,dict(T=self.T_,D=self.rho_)) - S.phase = self.phase - return S - -def rebuildState(d): - S=State(d['Fluid'],{'T':d['T'],'D':d['rho']},phase=d['phase']) - return S - diff --git a/wrappers/Python/CoolProp/oldState.pyx b/wrappers/Python/CoolProp/oldState.pyx deleted file mode 100644 index 809991a8..00000000 --- a/wrappers/Python/CoolProp/oldState.pyx +++ /dev/null @@ -1,365 +0,0 @@ -#cython: embedsignature = True - -cdef extern from "CoolProp.h": - double _Props "Props" (char* ,char,double,char,double,char*) - double _Props1 "Props" (char*,char*) - void UseSinglePhaseLUT(bool) - double DerivTerms(char *, double, double, char*) - char * get_errstringc() - void get_errstring(char*) - void _debug "debug" (int) - double _IProps "IProps" (long,long,double,long,double,long) - long _get_param_index "get_param_index" (string param) - long _get_Fluid_index "get_Fluid_index" (string param) - void _set_phase "set_phase"(string Phase_str) - -from libc.math cimport pow, sin, cos, exp -from math import pow as pow_ -cdef bint _LUT_Enabled -import CoolProp as CP -cimport cython - -## Variables for each of the possible variables -cdef long iMM = _get_param_index('M') -cdef long iT = _get_param_index('T') -cdef long iD = _get_param_index('D') -cdef long iH = _get_param_index('H') -cdef long iP = _get_param_index('P') -cdef long iC = _get_param_index('C') -cdef long iC0 = _get_param_index('C0') -cdef long iO = _get_param_index('O') -cdef long iV = _get_param_index('V') -cdef long iL = _get_param_index('L') -cdef long iS = _get_param_index('S') -cdef long iU = _get_param_index('U') -cdef long iDpdT = _get_param_index('dpdT') - -#A dictionary mapping parameter index to string for use with non-CoolProp fluids -cdef dict paras = {iMM : 'M', - iT : 'T', - iH : 'H', - iP : 'P', - iC : 'C', - iC0 : 'C0', - iO : 'O', - iV : 'V', - iL : 'L', - iS : 'S', - iU : 'U', - iDpdT : 'dpdT'} - -cpdef int debug(int level): - """ - Sets the debug level - - Parameters - ---------- - level : int - Flag indicating how verbose the debugging should be. - 0 : no debugging output - ... - ... - 10 : very annoying debugging output - every function call debugged - """ - _debug(level) - -cpdef int LUT(bint LUTval): - """ - - LUTval : boolean - If ``True``, turn on the use of lookup table. Parameters must have - already been set through the use of set_1phase_LUT_params - - """ - if LUTval: - _LUT_Enabled = True - print 'Turning on singlephase LUT' - UseSinglePhaseLUT(True) - else: - _LUT_Enabled = False - UseSinglePhaseLUT(False) - -cpdef double Props(bytes Parameter, bytes param1, float value1, bytes param2, float value2, bytes Fluid): - """ - Expose the Props() function. Uses the same call signature as the Props() function in CoolProp.CoolProp - """ - cdef char _param1 = param1[0] - cdef char _param2 = param2[0] - return _Props(Parameter, _param1, value1, _param2, value2, Fluid) - -@cython.final -cdef class State: - """ - A class that contains all the code that represents a thermodynamic state - """ - - def __init__(self,bytes Fluid, dict StateDict, double xL=-1.0, bytes Liquid=str(''), phase = str('Gas')): - self.Fluid = Fluid - self.iFluid = _get_Fluid_index(Fluid) - #Try to get the fluid from CoolProp - if self.iFluid >= 0: - #It is a CoolProp Fluid so we can use the faster integer passing function - self.is_CPFluid = True - else: - self.is_CPFluid = False - self.xL = xL - self.Liquid = Liquid - self.phase = phase - #Parse the inputs provided - self.update(StateDict) - #Set the phase flag - if self.phase == str('Gas') or self.phase == str('Liquid') or self.phase == str('Supercritical'): - _set_phase(self.phase) - - def __reduce__(self): - d={} - d['xL']=self.xL - d['Liquid']=self.Liquid - d['Fluid']=self.Fluid - d['T']=self.T_ - d['rho']=self.rho_ - return rebuildState,(d,) - - - cpdef update_Trho(self, double T, double rho): - """ - Just use the temperature and density directly - """ - self.T_ = T - self.rho_ = rho - cdef double p - - if self.is_CPFluid: - p = _IProps(iP,iT,T,iD,rho,self.iFluid) - else: - p = _Props('P','T',T,'D',rho,self.Fluid) - - if abs(p)<1e90: - self.p_=p - else: - errstr = get_errstringc() - raise ValueError(errstr) - - cpdef update(self,dict params, double xL=-1.0): - """ - *params* is a list(or tuple) of strings that represent the parameters - that have been updated and will be used to fix the rest of the state. - ['T','P'] for temperature and pressure for instance - """ - - cdef double p - cdef bytes errstr - - # If no value for xL is provided, it will have a value of -1 which is - # impossible, so don't update xL - if xL > 0: - #There is liquid - self.xL=xL - self.hasLiquid=True - else: - #There's no liquid - self.xL=0.0 - self.hasLiquid=False - - #You passed in a dictionary, use the values to update the state - if 'T' not in params: - raise AttributeError('T must be provided in params dict in State.update') - - #Consume the 'T' key since it is required (TODO?) - self.T_=float(params.pop('T')) - - #Given temperature and pressure, determine density of gas - # (or gas and oil if xL is provided) - if abs(self.xL)<=1e-15: - #Get the density if T,P provided, or pressure if T,rho provided - if 'P' in params: - self.p_=params['P'] - - if self.is_CPFluid: - rho = _IProps(iD,iT,self.T_,iP,self.p_,self.iFluid) - else: - rho = _Props('D','T',self.T_,'P',self.p_,self.Fluid) - - if abs(rho)<1e90: - self.rho_=rho - else: - errstr = get_errstringc() - raise ValueError(errstr) - elif 'D' in params: - - self.rho_=params['D'] - - if self.is_CPFluid: - p = _IProps(iP,iT,self.T_,iD,self.rho_,self.iFluid) - else: - p = _Props('P','T',self.T_,'D',self.rho_,self.Fluid) - - if abs(p)<1e90: - self.p_=p - else: - errstr = get_errstringc() - raise ValueError(errstr+str(params)) - else: - raise KeyError("Dictionary must contain the key 'T' and one of 'P' or 'D'") - - elif self.xL>0 and self.xL<=1: - raise ValueError('xL is out of range - value for xL is [0,1]') - else: - raise ValueError('xL must be between 0 and 1') - - cpdef double Props(self, long iOutput): - if iOutput<0: - raise ValueError('Your output is invalid') - - if self.is_CPFluid: - return _IProps(iOutput,iT,self.T_,iD,self.rho_,self.iFluid) - else: - return _Props(paras[iOutput],'T',self.T_,'D',self.rho_,self.Fluid) - - cpdef double get_MM(self): - return _Props1(self.Fluid,'molemass') - - cpdef double get_rho(self): - return self.rho_ - property rho: - def __get__(self): - return self.rho_ - - cpdef double get_p(self): - return self.p_ - property p: - def __get__(self): - return self.p_ - - cpdef double get_T(self): - return self.T_ - property T: - def __get__(self): - return self.T_ - - cpdef double get_h(self): - return self.Props(iH) - property h: - def __get__(self): - return self.get_h() - - cpdef double get_u(self): - return self.Props(iU) - property u: - def __get__(self): - return self.get_u() - - cpdef double get_s(self): - return self.Props(iS) - property s: - def __get__(self): - return self.get_s() - - cpdef double get_cp0(self): - return self.Props(iC0) - - cpdef double get_cp(self): - return self.Props(iC) - property cp: - def __get__(self): - return self.get_cp() - - cpdef double get_cv(self): - return self.Props(iO) - property cv: - def __get__(self): - return self.get_cv() - - cpdef double get_visc(self): - return self.Props(iV) - property visc: - def __get__(self): - return self.get_visc() - - cpdef double get_cond(self): - return self.Props(iL) - property k: - def __get__(self): - return self.get_cond() - - property Prandtl: - def __get__(self): - return self.cp * self.visc / self.k - - cpdef double get_dpdT(self): - return self.Props(iDpdT) - property dpdT: - def __get__(self): - return self.get_dpdT() - - cpdef speed_test(self, int N): - from time import clock - cdef int i - cdef char * k - cdef char * Fluid = self.Fluid - cdef long IT = 'T' - cdef long ID = 'D' - - print 'Direct c++ call to CoolProp without the Python call layer' - print "'M' involves basically no computational effort and is a good measure of the function call overhead" - keys = ['H','P','S','U','C','O','V','L','M','C0'] - for key in keys: - t1=clock() - for i in range(N): - _Props(key,'T',self.T_,'D',self.rho_,Fluid) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,key,(t2-t1)/N*1e6) - - print 'Call to the c++ layer using integers' - keys = [iH,iP,iS,iU,iC,iO,iV,iL,iMM,iC0] - for key in keys: - t1=clock() - for i in range(N): - _IProps(key,iT,self.T_,iD,self.rho_,self.iFluid) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[key],(t2-t1)/N*1e6) - - print 'Call to the Python call layer' - print "'M' involves basically no computational effort and is a good measure of the function call overhead" - keys = ['H','P','S','U','C','O','V','L','M','C0'] - for key in keys: - t1=clock() - for i in range(N): - CP.Props(key,'T',self.T_,'D',self.rho_,Fluid) - t2=clock() - print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,key,(t2-t1)/N*1e6) - - def __str__(self): - """ - Return a string representation of the state - """ - units={'T': 'K', - 'p': 'kPa', - 'rho': 'kg/m^3', - 'h':'kJ/kg', - 'u':'kJ/kg', - 's':'kJ/kg/K', - 'visc':'Pa-s', - 'k':'kW/m/K', - 'cp':'kJ/kg/K', - 'cv':'kJ/kg/K', - 'dpdT':'kPa/K'} - s='' - for k in ['T','p','rho','h','u','s','visc','k','cp','cv','dpdT','Prandtl']: - if k in units: - s+=k+' = '+str(getattr(self,k))+' '+units[k]+'\n' - else: - s+=k+' = '+str(getattr(self,k))+' NO UNITS'+'\n' - return s.rstrip() - - cpdef copy(self): - cdef double T = self.T_*(1.0+1e-20) - cdef double rho = self.rho_*(1.0+1e-20) - ST=State(self.Fluid,{'T':T,'D':rho}) - return ST - -def rebuildState(d): - S=State(d['Fluid'],{'T':d['T'],'D':d['rho']}) - S.xL = d['xL'] - S.Liquid=d['Liquid'] - return S diff --git a/wrappers/Python/CoolProp/param_constants.pyx b/wrappers/Python/CoolProp/param_constants.pyx deleted file mode 100644 index 5db1bd64..00000000 --- a/wrappers/Python/CoolProp/param_constants.pyx +++ /dev/null @@ -1,88 +0,0 @@ -#This file is automatically generated by the generate_constants_module.py script in dev/scripts. -#DO NOT MODIFY THE CONTENTS OF THIS FILE! -cimport param_constants_header - -iB = param_constants_header.iB -iT = param_constants_header.iT -iP = param_constants_header.iP -iD = param_constants_header.iD -iC = param_constants_header.iC -iC0 = param_constants_header.iC0 -iO = param_constants_header.iO -iU = param_constants_header.iU -iH = param_constants_header.iH -iS = param_constants_header.iS -iA = param_constants_header.iA -iG = param_constants_header.iG -iQ = param_constants_header.iQ -iV = param_constants_header.iV -iL = param_constants_header.iL -iTfreeze = param_constants_header.iTfreeze -iPsat = param_constants_header.iPsat -iI = param_constants_header.iI -iDpdT = param_constants_header.iDpdT -iDrhodT_p = param_constants_header.iDrhodT_p -iCritSplineT = param_constants_header.iCritSplineT -iPrandtl = param_constants_header.iPrandtl -iMM = param_constants_header.iMM -iTmax = param_constants_header.iTmax -iTmin = param_constants_header.iTmin -iAccentric = param_constants_header.iAccentric -iDipole = param_constants_header.iDipole -iODP = param_constants_header.iODP -iGWP20 = param_constants_header.iGWP20 -iGWP100 = param_constants_header.iGWP100 -iGWP500 = param_constants_header.iGWP500 -iRhoreduce = param_constants_header.iRhoreduce -iTreduce = param_constants_header.iTreduce -iPtriple = param_constants_header.iPtriple -iTtriple = param_constants_header.iTtriple -iHcrit = param_constants_header.iHcrit -iPcrit = param_constants_header.iPcrit -iRhocrit = param_constants_header.iRhocrit -iScrit = param_constants_header.iScrit -iTcrit = param_constants_header.iTcrit -iPhase = param_constants_header.iPhase -iPHASE_LIQUID = param_constants_header.iPHASE_LIQUID -iPHASE_GAS = param_constants_header.iPHASE_GAS -iPHASE_SUPERCRITICAL = param_constants_header.iPHASE_SUPERCRITICAL -iPHASE_TWOPHASE = param_constants_header.iPHASE_TWOPHASE -iDERdh_dp__rho = param_constants_header.iDERdh_dp__rho -iDERdh_dp__v = param_constants_header.iDERdh_dp__v -iDERZ = param_constants_header.iDERZ -iDERdZ_dDelta = param_constants_header.iDERdZ_dDelta -iDERdZ_dTau = param_constants_header.iDERdZ_dTau -iDERB = param_constants_header.iDERB -iDERdB_dT = param_constants_header.iDERdB_dT -iDERC = param_constants_header.iDERC -iDERdC_dT = param_constants_header.iDERdC_dT -iDERphir = param_constants_header.iDERphir -iDERdphir_dTau = param_constants_header.iDERdphir_dTau -iDERdphir_dDelta = param_constants_header.iDERdphir_dDelta -iDERd2phir_dTau2 = param_constants_header.iDERd2phir_dTau2 -iDERd2phir_dDelta2 = param_constants_header.iDERd2phir_dDelta2 -iDERd2phir_dDelta_dTau = param_constants_header.iDERd2phir_dDelta_dTau -iDERd3phir_dDelta3 = param_constants_header.iDERd3phir_dDelta3 -iDERd3phir_dDelta2_dTau = param_constants_header.iDERd3phir_dDelta2_dTau -iDERd3phir_dDelta_dTau2 = param_constants_header.iDERd3phir_dDelta_dTau2 -iDERd3phir_dTau3 = param_constants_header.iDERd3phir_dTau3 -iDERphi0 = param_constants_header.iDERphi0 -iDERdphi0_dTau = param_constants_header.iDERdphi0_dTau -iDERd2phi0_dTau2 = param_constants_header.iDERd2phi0_dTau2 -iDERdphi0_dDelta = param_constants_header.iDERdphi0_dDelta -iDERd2phi0_dDelta2 = param_constants_header.iDERd2phi0_dDelta2 -iDERd2phi0_dDelta_dTau = param_constants_header.iDERd2phi0_dDelta_dTau -iDERd3phi0_dTau3 = param_constants_header.iDERd3phi0_dTau3 -iDERdp_dT__rho = param_constants_header.iDERdp_dT__rho -iDERdp_drho__T = param_constants_header.iDERdp_drho__T -iDERdh_dT__rho = param_constants_header.iDERdh_dT__rho -iDERdh_drho__T = param_constants_header.iDERdh_drho__T -iDERdrho_dT__p = param_constants_header.iDERdrho_dT__p -iDERdrho_dh__p = param_constants_header.iDERdrho_dh__p -iDERdrho_dp__h = param_constants_header.iDERdrho_dp__h -iDERrho_smoothed = param_constants_header.iDERrho_smoothed -iDERdrho_smoothed_dh = param_constants_header.iDERdrho_smoothed_dh -iDERdrho_smoothed_dp = param_constants_header.iDERdrho_smoothed_dp -iDERdrhodh_constp_smoothed = param_constants_header.iDERdrhodh_constp_smoothed -iDERdrhodp_consth_smoothed = param_constants_header.iDERdrhodp_consth_smoothed -iDERIsothermalCompressibility = param_constants_header.iDERIsothermalCompressibility diff --git a/wrappers/Python/CoolProp/param_constants_header.pxd b/wrappers/Python/CoolProp/param_constants_header.pxd deleted file mode 100644 index 6fd96997..00000000 --- a/wrappers/Python/CoolProp/param_constants_header.pxd +++ /dev/null @@ -1,89 +0,0 @@ -#This file is automatically generated by the generate_constants_module.py script in dev/scripts. -#DO NOT MODIFY THE CONTENTS OF THIS FILE! - -cdef extern from "CoolProp.h": - enum params: - iB - iT - iP - iD - iC - iC0 - iO - iU - iH - iS - iA - iG - iQ - iV - iL - iTfreeze - iPsat - iI - iDpdT - iDrhodT_p - iCritSplineT - iPrandtl - iMM - iTmax - iTmin - iAccentric - iDipole - iODP - iGWP20 - iGWP100 - iGWP500 - iRhoreduce - iTreduce - iPtriple - iTtriple - iHcrit - iPcrit - iRhocrit - iScrit - iTcrit - iPhase - iPHASE_LIQUID - iPHASE_GAS - iPHASE_SUPERCRITICAL - iPHASE_TWOPHASE - iDERdh_dp__rho - iDERdh_dp__v - iDERZ - iDERdZ_dDelta - iDERdZ_dTau - iDERB - iDERdB_dT - iDERC - iDERdC_dT - iDERphir - iDERdphir_dTau - iDERdphir_dDelta - iDERd2phir_dTau2 - iDERd2phir_dDelta2 - iDERd2phir_dDelta_dTau - iDERd3phir_dDelta3 - iDERd3phir_dDelta2_dTau - iDERd3phir_dDelta_dTau2 - iDERd3phir_dTau3 - iDERphi0 - iDERdphi0_dTau - iDERd2phi0_dTau2 - iDERdphi0_dDelta - iDERd2phi0_dDelta2 - iDERd2phi0_dDelta_dTau - iDERd3phi0_dTau3 - iDERdp_dT__rho - iDERdp_drho__T - iDERdh_dT__rho - iDERdh_drho__T - iDERdrho_dT__p - iDERdrho_dh__p - iDERdrho_dp__h - iDERrho_smoothed - iDERdrho_smoothed_dh - iDERdrho_smoothed_dp - iDERdrhodh_constp_smoothed - iDERdrhodp_consth_smoothed - iDERIsothermalCompressibility diff --git a/wrappers/Python/CoolProp/phase_constants.pyx b/wrappers/Python/CoolProp/phase_constants.pyx deleted file mode 100644 index d743e6b0..00000000 --- a/wrappers/Python/CoolProp/phase_constants.pyx +++ /dev/null @@ -1,8 +0,0 @@ -#This file is automatically generated by the generate_constants_module.py script in dev/scripts. -#DO NOT MODIFY THE CONTENTS OF THIS FILE! -cimport phase_constants_header - -iLiquid = phase_constants_header.iLiquid -iSupercritical = phase_constants_header.iSupercritical -iGas = phase_constants_header.iGas -iTwoPhase = phase_constants_header.iTwoPhase diff --git a/wrappers/Python/CoolProp/phase_constants_header.pxd b/wrappers/Python/CoolProp/phase_constants_header.pxd deleted file mode 100644 index fbfe0108..00000000 --- a/wrappers/Python/CoolProp/phase_constants_header.pxd +++ /dev/null @@ -1,9 +0,0 @@ -#This file is automatically generated by the generate_constants_module.py script in dev/scripts. -#DO NOT MODIFY THE CONTENTS OF THIS FILE! - -cdef extern from "CoolProp.h": - enum phase: - iLiquid - iSupercritical - iGas - iTwoPhase diff --git a/wrappers/Python/CoolProp/unit_systems_constants.pyx b/wrappers/Python/CoolProp/unit_systems_constants.pyx deleted file mode 100644 index 79769237..00000000 --- a/wrappers/Python/CoolProp/unit_systems_constants.pyx +++ /dev/null @@ -1,8 +0,0 @@ -#This file is automatically generated by the generate_constants_module.py script in dev/scripts. -#DO NOT MODIFY THE CONTENTS OF THIS FILE! -cimport unit_systems_constants_header - -UNIT_SYSTEM_SI = unit_systems_constants_header.UNIT_SYSTEM_SI -UNIT_SYSTEM_KSI = unit_systems_constants_header.UNIT_SYSTEM_KSI -UNIT_SYSTEM_KSI_MOLAR = unit_systems_constants_header.UNIT_SYSTEM_KSI_MOLAR -UNIT_SYSTEM_SI_MOLAR = unit_systems_constants_header.UNIT_SYSTEM_SI_MOLAR diff --git a/wrappers/Python/CoolProp/unit_systems_constants_header.pxd b/wrappers/Python/CoolProp/unit_systems_constants_header.pxd deleted file mode 100644 index c1fa189e..00000000 --- a/wrappers/Python/CoolProp/unit_systems_constants_header.pxd +++ /dev/null @@ -1,9 +0,0 @@ -#This file is automatically generated by the generate_constants_module.py script in dev/scripts. -#DO NOT MODIFY THE CONTENTS OF THIS FILE! - -cdef extern from "CoolProp.h": - enum unit_systems: - UNIT_SYSTEM_SI - UNIT_SYSTEM_KSI - UNIT_SYSTEM_KSI_MOLAR - UNIT_SYSTEM_SI_MOLAR diff --git a/wrappers/Python/CoolProp5/AbstractState.pxd b/wrappers/Python/CoolProp5/AbstractState.pxd new file mode 100644 index 00000000..f132b0c2 --- /dev/null +++ b/wrappers/Python/CoolProp5/AbstractState.pxd @@ -0,0 +1,24 @@ +from libcpp cimport bool +from libcpp.string cimport string + +# A header defining the AbstractState class +cimport cAbstractState + +cdef class AbstractState: + cdef cAbstractState.AbstractState *thisptr # hold a C++ instance which we're wrapping + cpdef update(self, long iInput1, double Value1, double Value2) + + ## ---------------------------------------- + ## Fluid property accessors + ## ---------------------------------------- + + cpdef double T(self) + cpdef double p(self) + cpdef double rhomolar(self) + cpdef double hmolar(self) + cpdef double smolar(self) + cpdef double cpmolar(self) + cpdef double cvmolar(self) + cpdef double speed_sound(self) + + cpdef double keyed_output(self, long) \ No newline at end of file diff --git a/wrappers/Python/CoolProp5/AbstractState.pyx b/wrappers/Python/CoolProp5/AbstractState.pyx new file mode 100644 index 00000000..48b52f6a --- /dev/null +++ b/wrappers/Python/CoolProp5/AbstractState.pyx @@ -0,0 +1,49 @@ +#cython: embedsignature = True, c_string_type=str, c_string_encoding=ascii +from __future__ import division + +cdef class AbstractState: + + def __cinit__(self, string backend, string fluid): + self.thisptr = cAbstractState.factory(backend, fluid) + + def __dealloc__(self): + del self.thisptr + + cpdef update(self, long ipair, double Value1, double Value2): + self.thisptr.update(ipair, Value1, Value2) + + ## ---------------------------------------- + ## Fluid property accessors + ## ---------------------------------------- + + cpdef double keyed_output(self, long iOutput) except *: + return self.thisptr.keyed_output(iOutput) + + cpdef double T(self) except *: + return self.thisptr.T() + cpdef double p(self) except *: + return self.thisptr.p() + cpdef double rhomolar(self) except *: + return self.thisptr.rhomolar() +# cpdef double rhomass(self) except *: +# return self.thisptr.rhomass() + cpdef double hmolar(self) except *: + return self.thisptr.hmolar() + cpdef double smolar(self) except *: + return self.thisptr.smolar() + cpdef double cpmolar(self) except *: + return self.thisptr.cpmolar() + cpdef double cvmolar(self) except *: + return self.thisptr.cvmolar() +# cpdef double hmass(self) except *: +# return self.thisptr.hmass() +# cpdef double smass(self) except *: +# return self.thisptr.smass() +# cpdef double cpmass(self) except *: +# return self.thisptr.cpmass() +# cpdef double cvmass(self) except *: +# return self.thisptr.cvmass() + cpdef double speed_sound(self) except *: + return self.thisptr.speed_sound() + + \ No newline at end of file diff --git a/wrappers/Python/CoolProp5/CoolProp.pxd b/wrappers/Python/CoolProp5/CoolProp.pxd new file mode 100644 index 00000000..d9e24b57 --- /dev/null +++ b/wrappers/Python/CoolProp5/CoolProp.pxd @@ -0,0 +1,126 @@ +from libcpp.string cimport string +import cython +cimport cython + +from libcpp.vector cimport vector + +cimport AbstractState + +# Default string in Python 3.x is a unicode string (type str) +# Default string in Python 2.x is a byte string(type bytes) +# +# Create a fused type that allows for either unicode string or bytestring +# We encode unicode strings using the ASCII encoding since we know they are all +# ASCII strings +ctypedef fused string_like: + cython.bytes + cython.unicode + +# cdef extern from "CoolPropDLL.h": +# int _set_reference_stateS "set_reference_stateS"(char *, char *) +# int _set_reference_stateD "set_reference_stateD"(char *, double T, double rho, double h0, double s0) +# int _get_standard_unit_system "get_standard_unit_system"() + +cdef extern from "CoolPropTools.h" namespace "CoolProp": + bint _ValidNumber "ValidNumber"(double) + +cdef extern from "CoolProp.h" namespace "CoolProp": + double _PropsSI "CoolProp::PropsSI"(string Output, string Name1, double Prop1, string Name2, double Prop2, string FluidName) + vector[double] _PropsSI "CoolProp::PropsSI"(string Output, string Name1, vector[double] Prop1, string Name2, vector[double] Prop2, string FluidName, vector[double] fractions) + string _get_global_param_string "CoolProp::get_global_param_string"(string ParamName) + +# double _Props1SI "Props1SI"(string Ref, string Output) + +# double _IProps "IProps"(long Output, long Name1, double Prop1, long Name2, double Prop2, long Ref) + +# double _Props "Props"(string Output, string Name1, double Prop1, string Name2, double Prop2, string Ref) +# double _Props1 "Props1"(string Ref, string Output) + +# string _get_fluid_param_string "get_fluid_param_string"(string ParamName, string FluidName) + +# long _set_phase "set_phase" (string phase) +# long _get_Fluid_index "get_Fluid_index" (string Fluid) + long _get_parameter_index "get_parameter_index" (string param) +# +# string _add_REFPROP_fluid "add_REFPROP_fluid"(string FluidName) except + +# +# int _get_debug_level "get_debug_level"() +# void _set_debug_level "set_debug_level"(int level) +# +# string _get_BibTeXKey "get_BibTeXKey"(string Ref, string key) + + # Convenience functions +# int _IsFluidType "IsFluidType"(char* Ref, char* Type) + +# cdef extern from "HumidAirProp.h": +# double _HAProps "HAProps"(char *OutputName, char *Input1Name, double Input1, char *Input2Name, double Input2, char *Input3Name, double Input3) +# double _HAProps_Aux "HAProps_Aux"(char* Name,double T, double p, double W, char *units) +# double _cair_sat "cair_sat"(double T) + +cdef class State: + cdef AbstractState.AbstractState pAS + cdef readonly string Fluid, phase + cdef int iFluid,iParam1,iParam2,iOutput + cdef double T_, rho_, p_ + cdef readonly bint is_CPFluid + + cpdef set_Fluid(self, string Fluid, string backend) +# cpdef speed_test(self, int N) +# cpdef update(self, dict params) +# cpdef update_ph(self, double p, double h) + cpdef update_Trho(self, double T, double rho) +# cpdef State copy(self) +# cpdef double Props(self, long iOutput) except * +# cpdef long Phase(self) except * + +# cpdef double get_Q(self) except * +# cpdef double get_T(self) except * +# cpdef double get_p(self) except * +# cpdef double get_h(self) except * +# cpdef double get_rho(self) except * +# cpdef double get_s(self) except * +# cpdef double get_u(self) except * +# cpdef double get_visc(self) except * +# cpdef double get_cond(self) except * +# cpdef double get_cp(self) except * +# cpdef double get_cp0(self) except * +# cpdef double get_cv(self) except * +# cpdef double get_MM(self) except * +# cpdef double get_dpdT(self) except * +# cpdef double get_speed_sound(self) except * +# cpdef get_Tsat(self, double Q = *) +# cpdef get_subcooling(self) +# cpdef get_superheat(self)cdef class State: +# cdef CoolPropStateClassSI CPS +# cdef readonly string Fluid, phase +# cdef int iFluid,iParam1,iParam2,iOutput +# cdef double T_, rho_, p_ +# cdef readonly bint is_CPFluid +# +# cpdef set_Fluid(self, string_like Fluid) + cpdef speed_test(self, int N) +# cpdef update(self, dict params) +# cpdef update_ph(self, double p, double h) +# cpdef update_Trho(self, double T, double rho) +# cpdef State copy(self) +# cpdef double Props(self, long iOutput) except * +# cpdef long Phase(self) except * +# +# cpdef double get_Q(self) except * +# cpdef double get_T(self) except * +# cpdef double get_p(self) except * +# cpdef double get_h(self) except * +# cpdef double get_rho(self) except * +# cpdef double get_s(self) except * +# cpdef double get_u(self) except * +# cpdef double get_visc(self) except * +# cpdef double get_cond(self) except * +# cpdef double get_cp(self) except * +# cpdef double get_cp0(self) except * +# cpdef double get_cv(self) except * +# cpdef double get_MM(self) except * +# cpdef double get_dpdT(self) except * +# cpdef double get_speed_sound(self) except * +# cpdef get_Tsat(self, double Q = *) +# cpdef get_subcooling(self) +# cpdef get_superheat(self) diff --git a/wrappers/Python/CoolProp5/CoolProp.pyx b/wrappers/Python/CoolProp5/CoolProp.pyx new file mode 100644 index 00000000..401c9c60 --- /dev/null +++ b/wrappers/Python/CoolProp5/CoolProp.pyx @@ -0,0 +1,802 @@ +#cython: embedsignature = True, c_string_type=str, c_string_encoding=ascii +from __future__ import division +# +# This file provides wrapper functions of all the CoolProp functions +# +# Each of the functions from the CoolProp header are renamed in cython code to +# an underscored name so that the same name can be used in the exposed functions below + +import math +import warnings + +from constants import * +from constants_header cimport * + +cpdef bint iterable(object a): + if _numpy_supported: + return isinstance(a,(list,tuple, np.ndarray)) + else: + return isinstance(a,(list,tuple)) + +cpdef ndarray_or_iterable(object input): + if _numpy_supported: + return np.array(input) + else: + return input + +#include "HumidAirProp.pyx" + +# def set_reference_state(string_like FluidName, *args): +# """ +# Accepts one of two signatures: +# +# Type #1: +# +# set_reference_state(FluidName,reference_state) +# +# FluidName The name of the fluid +# param reference_state The reference state to use, one of +# +# ========== =========================================== +# ``IIR`` (h=200 kJ/kg, s=1 kJ/kg/K at 0C sat. liq.) +# ``ASHRAE`` (h=0,s=0 @ -40C sat liq) +# ``NBP`` (h=0,s=0 @ 1.0 bar sat liq.) +# ========== =========================================== +# +# Type #2: +# +# set_reference_state(FluidName,T0,rho0,h0,s0) +# +# ``FluidName`` The name of the fluid +# +# ``T0`` The temperature at the reference point [K] +# +# ``rho0`` The density at the reference point [kg/m^3] +# +# ``h0`` The enthalpy at the reference point [J/kg] +# +# ``s0`` The entropy at the reference point [J/kg] +# """ +# +# cdef bytes _param +# cdef int retval +# +# if len(args) == 1: +# _param = args[0].encode('ascii') +# retval = _set_reference_stateS(FluidName, _param) +# elif len(args) == 4: +# retval = _set_reference_stateD(FluidName, args[0], args[1], args[2], args[3]) +# else: +# raise ValueError('Invalid number of inputs') +# +# if retval < 0: +# raise ValueError('Unable to set reference state') +# +# cpdef add_REFPROP_fluid(string_like FluidName): +# """ +# Add a REFPROP fluid to CoolProp internal structure +# +# example:: +# +# add_REFPROP_fluid("REFPROP-PROPANE") +# +# """ +# _add_REFPROP_fluid(FluidName) +# +# cpdef long get_Fluid_index(string_like Fluid): +# """ +# Gets the integer index of the given CoolProp fluid (primarily for use in ``IProps`` function) +# """ +# return _get_Fluid_index(Fluid) +# +# cpdef double IProps(long iOutput, long iInput1, double Input1, long iInput2, double Input2, long iFluid) except *: +# """ +# This is a more computationally efficient version of the Props() function as it uses integer keys for the input and output codes as well as the fluid index for the fluid. It can only be used with CoolProp fluids. An example of how it should be used:: +# +# # These should be run once in the header of your file +# from CoolProp.CoolProp import IProps, get_Fluid_index +# from CoolProp import param_constants +# iPropane = get_Fluid_index('Propane') +# +# # This should be run using the cached values - much faster ! +# IProps(param_constants.iP,param_constants.iT,0.8*Tc,param_constants.iQ,1,iPropane) +# +# The reason that this function is significantly faster than Props is that it skips all the string comparisons which slows down the Props function quite a lot. At the C++ level, IProps doesn't use any strings and operates on integers and floating point values +# """ +# cdef double val = _IProps(iOutput, iInput1, Input1, iInput2, Input2, iFluid) +# +# if math.isinf(val) or math.isnan(val): +# err_string = _get_global_param_string('errstring') +# if not len(err_string) == 0: +# raise ValueError("{err:s} :: inputs were :{iin1:d},{in1:g},{iin2:d},{in2:g},{iFluid:d}".format(err= err_string,iin1=iInput1,in1=Input1,iin2=iInput2,in2=Input2,iFluid = iFluid)) +# else: +# raise ValueError("IProps failed ungracefully with inputs:\"{in1:g}\",\"{in2:g}\"; please file a ticket at https://sourceforge.net/p/coolprop/tickets/".format(in1=Input1,in2=Input2)) +# else: +# return val + +cpdef get_global_param_string(string param): + return _get_global_param_string(param) +# +# cpdef get_fluid_param_string(string_like fluid, string_like param): +# return _get_fluid_param_string(fluid, param) +# +# cpdef __Props_err1(in1,in2,errstr): +# if not len(errstr) == 0: +# raise ValueError("{err:s} :: inputs were :\"{in1:s}\",\"{in2:s}\"".format(err= errstr,in1=in1,in2=in2)) +# else: +# raise ValueError("Props failed ungracefully with inputs:\"{in1:s}\",\"{in2:s}\"; please file a ticket at https://github.com/ibell/coolprop/issues".format(in1=in1,in2=in2)) +# +cpdef __Props_err2(in1, in2, in3, in4, in5, in6): + errstr = get_global_param_string('errstring') + if not len(errstr) == 0: + raise ValueError("{err:s} :: inputs were:\"{in1:s}\",\"{in2:s}\",{in3:0.16e},\"{in4:s}\",{in5:0.16e},\"{in6:s}\"".format(err=errstr,in1=in1,in2=in2,in3=in3,in4=in4,in5=in5,in6=in6)) + else: + raise ValueError("Props failed ungracefully :: inputs were:\"{in1:s}\",\"{in2:s}\",{in3:0.16e},\"{in4:s}\",{in5:0.16e},\"{in6:s}\"; please file a ticket at https://github.com/ibell/coolprop/issues".format(in1=in1,in2=in2,in3=in3,in4=in4,in5=in5,in6=in6)) + +# cpdef Props(in1, in2, in3, in4, in5, in6, in7 = None): +# """ +# $$Props$$ +# """ +# if in7 is None: +# return _Props(in1, in2, in3, in4, in5, in6) +# else: +# return _Props(in1, in2, in3, in4, in5, in6, in7) +cpdef PropsSI(in1, in2, in3, in4, in5, in6, in7 = None): + """ + $$PropsSI$$ + """ + cdef double val + if in7 is None: + val = _PropsSI(in1, in2, in3, in4, in5, in6) + if not _ValidNumber(val): + __Props_err2(in1, in2, in3, in4, in5, in6) + else: + return val + else: + return _PropsSI(in1, in2, in3, in4, in5, in6, in7) + +# cpdef list FluidsList(): +# """ +# Return a list of strings of all fluid names +# +# Returns +# ------- +# FluidsList : list of strings of fluid names +# All the fluids that are included in CoolProp +# +# Notes +# ----- +# +# Here is an example:: +# +# In [0]: from CoolProp.CoolProp import FluidsList +# +# In [1]: FluidsList() +# +# """ +# return _get_global_param_string("FluidsList").split(',') + +# cpdef get_aliases(str Fluid): +# """ +# Return a comma separated string of aliases for the given fluid +# """ +# cdef bytes _Fluid = Fluid.encode('ascii') +# return [F.encode('ascii') for F in (_get_fluid_param_string(_Fluid,'aliases').encode('ascii')).decode('ascii').split(',')] + +# +# cpdef string get_REFPROPname(str Fluid): +# """ +# Return the REFPROP compatible name for the fluid (only useful on windows) +# +# Some fluids do not use the REFPROP name. For instance, +# ammonia is R717, and propane is R290. You can still can still call CoolProp +# using the name ammonia or R717, but REFPROP requires that you use a limited +# subset of names. Therefore, this function that returns the REFPROP compatible +# name. To then use this to call REFPROP, you would do something like:: +# +# In [0]: from CoolProp.CoolProp import get_REFPROPname, Props +# +# In [1]: Fluid = 'REFPROP-' + get_REFPROPname('R290') +# +# In [2]: Props('D', 'T', 300, 'P', 300, Fluid) +# """ +# cdef bytes _Fluid = Fluid.encode('ascii') +# return _get_fluid_param_string(_Fluid,'REFPROP_name') + +# cpdef string get_BibTeXKey(str Fluid, str key): +# """ +# Return the BibTeX key for the given fluid. +# +# The possible keys are +# +# * ``EOS`` +# * ``CP0`` +# * ``VISCOSITY`` +# * ``CONDUCTIVITY`` +# * ``ECS_LENNARD_JONES`` +# * ``ECS_FITS`` +# * ``SURFACE_TENSION`` +# +# BibTeX keys refer to the BibTeX file in the trunk/CoolProp folder +# +# Returns +# ------- +# key, string +# empty string if Fluid not in CoolProp, "Bad key" if key is invalid +# """ +# return _get_BibTeXKey(Fluid.encode('ascii'), key.encode('ascii')) +# cpdef string get_errstr(): +# """ +# Return the current error string +# """ +# return _get_global_param_string("errstring") +# cpdef set_debug_level(int level): +# """ +# Set the current debug level as integer in the range [0,10] +# +# Parameters +# ---------- +# level : int +# If level is 0, no output will be written to screen, if >0, +# some output will be written to screen. The larger level is, +# the more verbose the output will be +# """ +# _set_debug_level(level) + +# cpdef get_debug_level(): +# """ +# Return the current debug level as integer +# +# Returns +# ------- +# level : int +# If level is 0, no output will be written to screen, if >0, +# some output will be written to screen. The larger level is, +# the more verbose the output will be +# """ +# return _get_debug_level() +# +# cpdef bint IsFluidType(string Fluid, string Type): +# """ +# Check if a fluid is of a given type +# +# Valid types are: +# +# * ``Brine`` +# * ``PseudoPure`` (or equivalently ``PseudoPureFluid``) +# * ``PureFluid`` +# """ +# cdef bytes _Fluid = Fluid.encode('ascii') +# cdef bytes _Type = Type.encode('ascii') +# if _IsFluidType(_Fluid,_Type): +# return True +# else: +# return False +# + +# from math import pow as pow_ + +#A dictionary mapping parameter index to string for use with non-CoolProp fluids +cdef dict paras = {iDmass : 'D', + iQ : 'Q', + imolar_mass : 'M', + iT : 'T', + iHmass : 'H', + iP : 'P', + iCpmass : 'C', +# iC0 : 'C0', + iCvmass : 'O', +# iV : 'V', +# iL : 'L', + iSmass : 'S', + iUmass : 'U', +# iDpdT : 'dpdT' +} + +# cdef dict paras_inverse = {v:k for k,v in paras.iteritems()} + +cdef class State: + """ + A class that contains all the code that represents a thermodynamic state + + The motivation for this class is that it is useful to be able to define the + state once using whatever state inputs you like and then be able to calculate + other thermodynamic properties with the minimum of computational work. + + Let's suppose that you have inputs of pressure and temperature and you want + to calculate the enthalpy and pressure. Since the Equations of State are + all explicit in temperature and density, each time you call something like:: + + h = Props('H','T',T','P',P,Fluid) + s = Props('S','T',T','P',P,Fluid) + + the solver is used to carry out the T-P flash calculation. And if you wanted + entropy as well you could either intermediately calculate ``T``, ``rho`` and then use + ``T``, ``rho`` in the EOS in a manner like:: + + rho = Props('D','T',T','P',P,Fluid) + h = Props('H','T',T','D',rho,Fluid) + s = Props('S','T',T','D',rho,Fluid) + + Instead in this class all that is handled internally. So the call to update + sets the internal variables in the most computationally efficient way possible + """ + + def __init__(self, object Fluid, dict StateDict, object phase = None, backend = None): + """ + Parameters + ---------- + Fluid : string + StateDict : dictionary + The state of the fluid - passed to the update function + phase : string + DEPRECATED : this input is ignored + backend : string + The CoolProp backend that should be used + """ + cdef string _Fluid = Fluid + + if _Fluid == 'none': + return + else: + if backend is None: + backend = '?' + self.set_Fluid(Fluid, backend) +# +# self.phase = _phase +# #Parse the inputs provided +# self.update(StateDict) +# #Set the phase flag +# if self.phase == 'Gas' or self.phase == 'Liquid' or self.phase == 'Supercritical': +# if self.is_CPFluid and (self.phase == 'Gas' or self.phase == 'Liquid'): +# self.CPS.flag_SinglePhase = True +# elif not self.is_CPFluid and phase is not None: +# _set_phase(self.phase) + +# def __reduce__(self): +# d={} +# d['Fluid']=self.Fluid +# d['T']=self.T_ +# d['rho']=self.rho_ +# d['phase'] = self.phase +# return rebuildState,(d,) + + cpdef set_Fluid(self, string Fluid, string backend): + self.pAS = AbstractState.AbstractState(backend, Fluid) + +# cpdef update_ph(self, double p, double h): +# """ +# Use the pressure and enthalpy directly +# +# Parameters +# ---------- +# p: float +# Pressure (absolute) [kPa] +# h: float +# Enthalpy [kJ/kg] +# +# """ +# p = _toSIints(iP, p, _get_standard_unit_system()); +# h = _toSIints(iH, h, _get_standard_unit_system()); +# self.p_ = p +# cdef double T +# +# if self.is_CPFluid: +# self.CPS.update(iP, p, iH, h) +# self.T_ = self.CPS.T() +# self.rho_ = self.CPS.rho() +# else: +# T = _PropsSI('T','P',p,'H',h,self.Fluid) +# if abs(T)<1e90: +# self.T_=T +# else: +# errstr = _get_global_param_string('errstring') +# raise ValueError(errstr) +# self.rho_ = _Props('D','P',p,'H',h,self.Fluid) + + cpdef update_Trho(self, double T, double rho): + """ + Just use the temperature and density directly for speed + + Parameters + ---------- + T: float + Temperature [K] + rho: float + Density [kg/m^3] + + """ + self.T_ = T + self.rho_ = rho + + self.pAS.update(DmassT_INPUTS, rho, T) + +# cpdef update(self, dict params): +# """ +# Parameters +# params, dictionary +# A dictionary of terms to be updated, with keys equal to single-char inputs to the Props function, +# for instance ``dict(T=298, P = 101.325)`` would be one standard atmosphere +# """ +# +# # Convert to integer_pair input +# +# cdef double p, val1, val2 +# cdef long iInput1, iInput2 +# cdef bytes errstr +# +# if self.is_CPFluid: +# items = list(params.items()) +# iInput1 = paras_inverse[items[0][0]] +# iInput2 = paras_inverse[items[1][0]] +# # Convert to SI units +# val1 = _toSIints(iInput1, items[0][1], _get_standard_unit_system()); +# val2 = _toSIints(iInput2, items[1][1], _get_standard_unit_system()); +# try: +# self.CPS.update(iInput1, val1, iInput2, val2) +# except: +# raise +# self.T_ = self.CPS.T() +# self.p_ = _fromSIints(iP, self.CPS.p(), _get_standard_unit_system()); +# self.rho_ = self.CPS.rho() +# +# if not _ValidNumber(self.T_) or not _ValidNumber(self.p_) or not _ValidNumber(self.rho_): +# raise ValueError(str(params)) +# return +# +# #Get the density if T,P provided, or pressure if T,rho provided +# if 'P' in params: +# self.p_=params['P'] +# rho = _Props('D','T',self.T_,'P',self.p_,self.Fluid) +# +# if abs(rho) < 1e90: +# self.rho_=rho +# else: +# errstr = _get_global_param_string('errstring') +# raise ValueError(errstr) +# elif 'D' in params: +# self.rho_=params['D'] +# p = _Props('P','T',self.T_,'D',self.rho_,self.Fluid) +# +# if abs(p)<1e90: +# self.p_=p +# else: +# errstr = _get_global_param_string('errstring') +# raise ValueError(errstr+str(params)) +# elif 'Q' in params: +# p = _Props('P','T',self.T_,'Q',params['Q'],self.Fluid) +# self.rho_ = _Props('D','T',self.T_,'Q',params['Q'],self.Fluid) +# +# if abs(self.rho_)<1e90: +# pass +# else: +# errstr = _get_global_param_string('errstring') +# raise ValueError(errstr+str(params)) +# else: +# raise KeyError("Dictionary must contain the key 'T' and one of 'P' or 'D'") + +# cpdef long Phase(self) except *: +# """ +# Returns an integer flag for the phase of the fluid, where the flag value +# is one of iLiquid, iSupercritical, iGas, iTwoPhase +# +# These constants are defined in the phase_constants module, and are imported +# into this module +# """ +# +# if self.is_CPFluid: +# return self.CPS.phase() +# else: +# raise NotImplementedError("Phase not defined for fluids other than CoolProp fluids") + +# cpdef double Props(self, long iOutput) except *: +# if iOutput<0: +# raise ValueError('Your output is invalid') +# +# if self.is_CPFluid: +# val = self.CPS.keyed_output(iOutput) +# return _fromSIints(iOutput,val,_get_standard_unit_system()); +# else: +# return _Props(paras[iOutput],'T',self.T_,'D',self.rho_,self.Fluid) +# +# cpdef double get_Q(self) except *: +# """ Get the quality [-] """ +# return self.Props(iQ) +# property Q: +# """ The quality [-] """ +# def __get__(self): +# return self.get_Q() +# +# cpdef double get_MM(self) except *: +# """ Get the mole mass [kg/kmol] or [g/mol] """ +# return self.Props(iMM) +# +# cpdef double get_rho(self) except *: +# """ Get the density [kg/m^3] """ +# return self.Props(iD) +# property rho: +# """ The density [kg/m^3] """ +# def __get__(self): +# return self.Props(iD) +# +# cpdef double get_p(self) except *: +# """ Get the pressure [kPa] """ +# return self.Props(iP) +# property p: +# """ The pressure [kPa] """ +# def __get__(self): +# return self.get_p() +# +# cpdef double get_T(self) except *: +# """ Get the temperature [K] """ +# return self.Props(iT) +# property T: +# """ The temperature [K] """ +# def __get__(self): +# return self.get_T() +# +# cpdef double get_h(self) except *: +# """ Get the specific enthalpy [kJ/kg] """ +# return self.Props(iH) +# property h: +# """ The specific enthalpy [kJ/kg] """ +# def __get__(self): +# return self.get_h() +# +# cpdef double get_u(self) except *: +# """ Get the specific internal energy [kJ/kg] """ +# return self.Props(iU) +# property u: +# """ The internal energy [kJ/kg] """ +# def __get__(self): +# return self.get_u() +# +# cpdef double get_s(self) except *: +# """ Get the specific enthalpy [kJ/kg/K] """ +# return self.Props(iS) +# property s: +# """ The specific enthalpy [kJ/kg/K] """ +# def __get__(self): +# return self.get_s() +# +# cpdef double get_cp0(self) except *: +# """ Get the specific heat at constant pressure for the ideal gas [kJ/kg/K] """ +# return self.Props(iC0) +# +# cpdef double get_cp(self) except *: +# """ Get the specific heat at constant pressure [kJ/kg/K] """ +# return self.Props(iC) +# property cp: +# """ The specific heat at constant pressure [kJ/kg/K] """ +# def __get__(self): +# return self.get_cp() +# +# cpdef double get_cv(self) except *: +# """ Get the specific heat at constant volume [kJ/kg/K] """ +# return self.Props(iO) +# property cv: +# """ The specific heat at constant volume [kJ/kg/K] """ +# def __get__(self): +# return self.get_cv() +# +# cpdef double get_speed_sound(self) except *: +# """ Get the speed of sound [m/s] """ +# return self.Props(iA) +# +# cpdef double get_visc(self) except *: +# """ Get the viscosity, in [Pa-s]""" +# return self.Props(iV) +# property visc: +# """ The viscosity, in [Pa-s]""" +# def __get__(self): +# return self.get_visc() + +# cpdef double get_cond(self) except *: +# """ Get the thermal conductivity, in [kW/m/K]""" +# return self.Props(iL) +# property k: +# """ The thermal conductivity, in [kW/m/K]""" +# def __get__(self): +# return self.get_cond() +# +# cpdef get_Tsat(self, double Q = 1): +# """ +# Get the saturation temperature, in [K] +# +# Returns ``None`` if pressure is not within the two-phase pressure range +# """ +# if self.p_ > _Props1(self.Fluid,'pcrit') or self.p_ < _Props1(self.Fluid,'ptriple'): +# return None +# else: +# return _Props('T', 'P', self.p_, 'Q', Q, self.Fluid) +# property Tsat: +# """ The saturation temperature (dew) for the given pressure, in [K]""" +# def __get__(self): +# return self.get_Tsat(1.0) +# +# cpdef get_superheat(self): +# """ +# Get the amount of superheat above the saturation temperature corresponding to the pressure, in [K] +# +# Returns ``None`` if pressure is not within the two-phase pressure range +# """ +# +# Tsat = self.get_Tsat(1) #dewpoint temp +# +# if Tsat is not None: +# return self.T_-Tsat +# else: +# return None +# property superheat: +# """ +# The amount of superheat above the saturation temperature corresponding to the pressure, in [K] +# +# Returns ``None`` if pressure is not within the two-phase pressure range +# """ +# def __get__(self): +# return self.get_superheat() +# +# cpdef get_subcooling(self): +# """ +# Get the amount of subcooling below the saturation temperature corresponding to the pressure, in [K] +# +# Returns ``None`` if pressure is not within the two-phase pressure range +# """ +# +# Tsat = self.get_Tsat(0) #bubblepoint temp +# +# if Tsat is not None: +# return Tsat - self.T_ +# else: +# return None +# property subcooling: +# """ +# The amount of subcooling below the saturation temperature corresponding to the pressure, in [K] +# +# Returns ``None`` if pressure is not within the two-phase pressure range +# """ +# def __get__(self): +# return self.get_subcooling() +# +# property Prandtl: +# """ The Prandtl number (cp*mu/k) [-] """ +# def __get__(self): +# return self.cp * self.visc / self.k +# +# cpdef double get_dpdT(self) except *: +# if self.is_CPFluid: +# return _fromSIints(iDERdp_dT__rho, self.CPS.dpdT_constrho(), _get_standard_unit_system()); +# else: +# raise ValueError("get_dpdT not supported for fluids that are not in CoolProp") +# property dpdT: +# def __get__(self): +# return self.get_dpdT() +# + cpdef speed_test(self, int N): + from time import clock +# cdef int i +# cdef char * k +# cdef long ikey +# cdef string Fluid = self.Fluid +# cdef long IT = 'T' +# cdef long ID = 'D' +# import CoolProp as CP +# +# print 'Call to the Python call layer (CoolProp.CoolProp.Props)' +# print "'M' involves basically no computational effort and is a good measure of the function call overhead" +# keys = ['H','P','S','U','C','O','V','L','M','C0','dpdT'] +# for key in keys: +# t1=clock() +# for i in range(N): +# CP.Props(key,'T',self.T_,'D',self.rho_,Fluid) +# t2=clock() +# print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,key,(t2-t1)/N*1e6) +# +# print 'Direct c++ call to CoolProp without the Python call layer (_Props function)' +# print "'M' involves basically no computational effort and is a good measure of the function call overhead" +# keys = ['H','P','S','U','C','O','V','L','M','C0','dpdT'] +# for key in keys: +# t1=clock() +# for i in range(N): +# _Props(key,'T',self.T_,'D',self.rho_,Fluid) +# t2=clock() +# print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,key,(t2-t1)/N*1e6) +# +# print 'Call to the c++ layer through IProps' +# keys = [iH,iP,iS,iU,iC,iO,iV,iL,iMM,iC0,iDpdT] +# for key in keys: +# t1=clock() +# for i in range(N): +# _IProps(key,iT,self.T_,iD,self.rho_,self.iFluid) +# t2=clock() +# print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[key],(t2-t1)/N*1e6) +# + print 'Call to the c++ layer using integers' + keys = [iHmass, iP,iSmass,iUmass] + for key in keys: + t1=clock() + for i in range(N): + self.pAS.update(DmassT_INPUTS,self.rho_,self.T_) + self.pAS.keyed_output(key) + t2=clock() + print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[key],(t2-t1)/N*1e6) +# +# keys = [iH,iP,iS,iU,iC,iO,iV,iL,iMM,iC0,iDpdT] +# isenabled = _isenabled_TTSE_LUT(Fluid) +# _enable_TTSE_LUT(Fluid) +# _IProps(iH,iT,self.T_,iD,self.rho_,self.iFluid) +# +# print 'Call using TTSE with T,rho' +# print "'M' involves basically no computational effort and is a good measure of the function call overhead" +# for ikey in keys: +# t1=clock() +# self.CPS.update(iT,self.T_,iD,self.rho_) +# for i in range(N): +# self.CPS.keyed_output(ikey) +# t2=clock() +# print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[ikey],(t2-t1)/N*1e6) +# +# print 'Call using TTSE with p,h' +# print "'M' involves basically no computational effort and is a good measure of the function call overhead" +# cdef double hh = self.h +# for ikey in keys: +# t1=clock() +# self.CPS.update(iP,self.p_,iH,hh) +# for i in range(N): +# self.CPS.keyed_output(ikey) +# t2=clock() +# print 'Elapsed time for {0:d} calls for "{1:s}" at {2:g} us/call'.format(N,paras[ikey],(t2-t1)/N*1e6) +# +# print 'Using CoolPropStateClass with T,rho with LUT' +# keys = [iH,iP,iC,iO,iDpdT] +# t1=clock() +# for i in range(N): +# self.CPS.update(iT,self.T_,iD,self.rho_) +# for ikey in keys: +# self.CPS.keyed_output(ikey) +# t2=clock() +# print 'Elapsed time for {0:d} calls of iH,iP,iC,iO,iDpdT takes {1:g} us/call'.format(N,(t2-t1)/N*1e6) +# +# if not isenabled: +# _disable_TTSE_LUT(Fluid) +# +# def __str__(self): +# """ +# Return a string representation of the state +# """ +# units={'T': 'K', +# 'p': 'kPa', +# 'rho': 'kg/m^3', +# 'Q':'kg/kg', +# 'h':'kJ/kg', +# 'u':'kJ/kg', +# 's':'kJ/kg/K', +# 'visc':'Pa-s', +# 'k':'kW/m/K', +# 'cp':'kJ/kg/K', +# 'cv':'kJ/kg/K', +# 'dpdT':'kPa/K', +# 'Tsat':'K', +# 'superheat':'K', +# 'subcooling':'K', +# } +# s='phase = '+self.phase+'\n' +# for k in ['T','p','rho','Q','h','u','s','visc','k','cp','cv','dpdT','Prandtl','superheat','subcooling']: +# if k in units: +# s+=k+' = '+str(getattr(self,k))+' '+units[k]+'\n' +# else: +# s+=k+' = '+str(getattr(self,k))+' NO UNITS'+'\n' +# return s.rstrip() +# +# cpdef State copy(self): +# """ +# Make a copy of this State class +# """ +# cdef State S = State(self.Fluid,dict(T=self.T_,D=self.rho_)) +# S.phase = self.phase +# return S +# +# def rebuildState(d): +# S=State(d['Fluid'],{'T':d['T'],'D':d['rho']},phase=d['phase']) +# return S +# diff --git a/wrappers/Python/CoolProp/CyState.pxd b/wrappers/Python/CoolProp5/CyState.pxd similarity index 100% rename from wrappers/Python/CoolProp/CyState.pxd rename to wrappers/Python/CoolProp5/CyState.pxd diff --git a/wrappers/Python/CoolProp/CyState.pyx b/wrappers/Python/CoolProp5/CyState.pyx similarity index 100% rename from wrappers/Python/CoolProp/CyState.pyx rename to wrappers/Python/CoolProp5/CyState.pyx diff --git a/wrappers/Python/CoolProp/GUI/CoolPropGUI.py b/wrappers/Python/CoolProp5/GUI/CoolPropGUI.py similarity index 100% rename from wrappers/Python/CoolProp/GUI/CoolPropGUI.py rename to wrappers/Python/CoolProp5/GUI/CoolPropGUI.py diff --git a/wrappers/Python/CoolProp/GUI/PsychScript.py b/wrappers/Python/CoolProp5/GUI/PsychScript.py similarity index 100% rename from wrappers/Python/CoolProp/GUI/PsychScript.py rename to wrappers/Python/CoolProp5/GUI/PsychScript.py diff --git a/wrappers/Python/CoolProp/GUI/__init__.py b/wrappers/Python/CoolProp5/GUI/__init__.py similarity index 100% rename from wrappers/Python/CoolProp/GUI/__init__.py rename to wrappers/Python/CoolProp5/GUI/__init__.py diff --git a/wrappers/Python/CoolProp/HumidAirProp.py b/wrappers/Python/CoolProp5/HumidAirProp.py similarity index 100% rename from wrappers/Python/CoolProp/HumidAirProp.py rename to wrappers/Python/CoolProp5/HumidAirProp.py diff --git a/wrappers/Python/CoolProp/HumidAirProp.pyx b/wrappers/Python/CoolProp5/HumidAirProp.pyx similarity index 100% rename from wrappers/Python/CoolProp/HumidAirProp.pyx rename to wrappers/Python/CoolProp5/HumidAirProp.pyx diff --git a/wrappers/Python/CoolProp/Plots/Common.py b/wrappers/Python/CoolProp5/Plots/Common.py similarity index 100% rename from wrappers/Python/CoolProp/Plots/Common.py rename to wrappers/Python/CoolProp5/Plots/Common.py diff --git a/wrappers/Python/CoolProp/Plots/Plots.py b/wrappers/Python/CoolProp5/Plots/Plots.py similarity index 100% rename from wrappers/Python/CoolProp/Plots/Plots.py rename to wrappers/Python/CoolProp5/Plots/Plots.py diff --git a/wrappers/Python/CoolProp/Plots/PsychChart.py b/wrappers/Python/CoolProp5/Plots/PsychChart.py similarity index 100% rename from wrappers/Python/CoolProp/Plots/PsychChart.py rename to wrappers/Python/CoolProp5/Plots/PsychChart.py diff --git a/wrappers/Python/CoolProp/Plots/PsychScript.py b/wrappers/Python/CoolProp5/Plots/PsychScript.py similarity index 100% rename from wrappers/Python/CoolProp/Plots/PsychScript.py rename to wrappers/Python/CoolProp5/Plots/PsychScript.py diff --git a/wrappers/Python/CoolProp/Plots/SimpleCycles.py b/wrappers/Python/CoolProp5/Plots/SimpleCycles.py similarity index 100% rename from wrappers/Python/CoolProp/Plots/SimpleCycles.py rename to wrappers/Python/CoolProp5/Plots/SimpleCycles.py diff --git a/wrappers/Python/CoolProp/Plots/Tests.py b/wrappers/Python/CoolProp5/Plots/Tests.py similarity index 100% rename from wrappers/Python/CoolProp/Plots/Tests.py rename to wrappers/Python/CoolProp5/Plots/Tests.py diff --git a/wrappers/Python/CoolProp/Plots/__init__.py b/wrappers/Python/CoolProp5/Plots/__init__.py similarity index 100% rename from wrappers/Python/CoolProp/Plots/__init__.py rename to wrappers/Python/CoolProp5/Plots/__init__.py diff --git a/wrappers/Python/CoolProp/State.pxd b/wrappers/Python/CoolProp5/State.pxd similarity index 100% rename from wrappers/Python/CoolProp/State.pxd rename to wrappers/Python/CoolProp5/State.pxd diff --git a/wrappers/Python/CoolProp/State.py b/wrappers/Python/CoolProp5/State.py similarity index 100% rename from wrappers/Python/CoolProp/State.py rename to wrappers/Python/CoolProp5/State.py diff --git a/wrappers/Python/CoolProp5/__init__.py b/wrappers/Python/CoolProp5/__init__.py new file mode 100644 index 00000000..9f24cd4b --- /dev/null +++ b/wrappers/Python/CoolProp5/__init__.py @@ -0,0 +1,59 @@ +from __future__ import absolute_import + +from . import AbstractState +from . import CoolProp +# from . import HumidAirProp +# from . import State +from .constants import * + +# __fluids__ = CoolProp.FluidsList() +__version__ = CoolProp.get_global_param_string(b'version') +__gitrevision__ = CoolProp.get_global_param_string(b'gitrevision') + +def test(): + """ + Run the tests in the test folder + """ + from .tests import runner + runner.run() + +def get_include_directory(): + """ + Get the include directory for CoolProp header files that are needed if you want + to compile anything else that uses the CoolProp Cython extension type + + Returns + ------- + include_directory: The path to the include folder for CoolProp + """ + import os + head,file = os.path.split(__file__) + return os.path.join(head,'include') + +def copy_BibTeX_library(file = None, folder = None): + """ + Copy the CoolProp BibTeX library file to the file given by ``file``, or the folder given by ``folder`` + + If no inputs are provided, the file will be copied to the current working + directory + + Parameters + ---------- + file : string + Provide if you want to put the file into a given file + folder : string + Provide if you want to put the CoolPropBibTeXLibrary.bib file into the given folder + + """ + import os, shutil + path_to_bib = os.path.join(os.path.split(__file__)[0],'CoolPropBibTeXLibrary.bib') + if file is None and folder is None: + shutil.copy2(path_to_bib,os.path.abspath(os.curdir)) + elif file and folder is None: + shutil.copy2(path_to_bib,file) + elif folder and file is None: + shutil.copy2(path_to_bib,os.path.join(folder,file)) + else: + raise ValueError('can only provide one of file or folder') + + \ No newline at end of file diff --git a/wrappers/Python/CoolProp5/cAbstractState.pxd b/wrappers/Python/CoolProp5/cAbstractState.pxd new file mode 100644 index 00000000..3090e8ef --- /dev/null +++ b/wrappers/Python/CoolProp5/cAbstractState.pxd @@ -0,0 +1,38 @@ +from libcpp cimport bool +from libcpp.string cimport string + +cdef extern from "AbstractState.h" namespace "CoolProp": + cdef cppclass AbstractState: + + ## Nullary Constructor + AbstractState() except + + + ## Constructor with fluid name + AbstractState(string FluidName) except + + + ## Property updater + ## Uses the indices in CoolProp for the input parameters + void update(long iInput1, double Value1, double Value2) except + + + ## Bulk properties accessors - temperature and density are directly calculated every time + ## All other parameters are calculated on an as-needed basis + ## If single-phase, just plug into the EOS, otherwise need to do two-phase analysis + double T() except + + double rhomolar() except + + double p() except + + double hmolar() except + + double smolar() except + + double cpmolar() except + + double cvmolar() except + + double speed_sound() except + + double rhomass() except + + double hmass() except + + double smass() except + + double cpmass() except + + double cvmass() except + + + double keyed_output(long) except+ + +# The static factory method for the AbstractState +cdef extern from "AbstractState.h" namespace "CoolProp::AbstractState": + AbstractState* factory(const string &backend, const string &fluid_string) diff --git a/wrappers/Python/CoolProp5/constants.pyx b/wrappers/Python/CoolProp5/constants.pyx new file mode 100644 index 00000000..5d1c8aee --- /dev/null +++ b/wrappers/Python/CoolProp5/constants.pyx @@ -0,0 +1,97 @@ +# This file is automatically generated by the generate_constants_module.py script in dev/scripts. +# DO NOT MODIFY THE CONTENTS OF THIS FILE! +cimport constants_header + +imolar_mass = constants_header.imolar_mass +irhomolar_reducing = constants_header.irhomolar_reducing +irhomolar_critical = constants_header.irhomolar_critical +iT_reducing = constants_header.iT_reducing +iT_critical = constants_header.iT_critical +iT = constants_header.iT +iP = constants_header.iP +iQ = constants_header.iQ +iTau = constants_header.iTau +iDelta = constants_header.iDelta +iDmolar = constants_header.iDmolar +iHmolar = constants_header.iHmolar +iSmolar = constants_header.iSmolar +iCpmolar = constants_header.iCpmolar +iCp0molar = constants_header.iCp0molar +iCvmolar = constants_header.iCvmolar +iUmolar = constants_header.iUmolar +iGmolar = constants_header.iGmolar +iDmass = constants_header.iDmass +iHmass = constants_header.iHmass +iSmass = constants_header.iSmass +iCpmass = constants_header.iCpmass +iCp0mass = constants_header.iCp0mass +iCvmass = constants_header.iCvmass +iUmass = constants_header.iUmass +iGmass = constants_header.iGmass +idrhodh_constp_smoothed = constants_header.idrhodh_constp_smoothed +idrhodp_consth_smoothed = constants_header.idrhodp_consth_smoothed +irho_smoothed = constants_header.irho_smoothed +iviscosity = constants_header.iviscosity +iconductivity = constants_header.iconductivity +isurface_tension = constants_header.isurface_tension +iPrandtl = constants_header.iPrandtl +ispeed_sound = constants_header.ispeed_sound +iisothermal_compressibility = constants_header.iisothermal_compressibility +iisobaric_expansion_coefficient = constants_header.iisobaric_expansion_coefficient +ifundamental_derivative_of_gas_dynamics = constants_header.ifundamental_derivative_of_gas_dynamics +id2pdv2_consts = constants_header.id2pdv2_consts +ialphar = constants_header.ialphar +idalphar_dtau_constdelta = constants_header.idalphar_dtau_constdelta +idalphar_ddelta_consttau = constants_header.idalphar_ddelta_consttau +ialpha0 = constants_header.ialpha0 +idalpha0_dtau_constdelta = constants_header.idalpha0_dtau_constdelta +idalpha0_ddelta_consttau = constants_header.idalpha0_ddelta_consttau +iBvirial = constants_header.iBvirial +iCvirial = constants_header.iCvirial +iZ = constants_header.iZ +idBvirial_dT = constants_header.idBvirial_dT +idCvirial_dT = constants_header.idCvirial_dT +idZdDelta = constants_header.idZdDelta +idZdTau = constants_header.idZdTau +iGWP20 = constants_header.iGWP20 +iGWP100 = constants_header.iGWP100 +iGWP500 = constants_header.iGWP500 +iFH = constants_header.iFH +iHH = constants_header.iHH +iPH = constants_header.iPH +iODP = constants_header.iODP +QT_INPUTS = constants_header.QT_INPUTS +PQ_INPUTS = constants_header.PQ_INPUTS +PT_INPUTS = constants_header.PT_INPUTS +DmassT_INPUTS = constants_header.DmassT_INPUTS +DmolarT_INPUTS = constants_header.DmolarT_INPUTS +HmolarT_INPUTS = constants_header.HmolarT_INPUTS +HmassT_INPUTS = constants_header.HmassT_INPUTS +SmolarT_INPUTS = constants_header.SmolarT_INPUTS +SmassT_INPUTS = constants_header.SmassT_INPUTS +TUmolar_INPUTS = constants_header.TUmolar_INPUTS +TUmass_INPUTS = constants_header.TUmass_INPUTS +DmassP_INPUTS = constants_header.DmassP_INPUTS +DmolarP_INPUTS = constants_header.DmolarP_INPUTS +HmassP_INPUTS = constants_header.HmassP_INPUTS +HmolarP_INPUTS = constants_header.HmolarP_INPUTS +PSmass_INPUTS = constants_header.PSmass_INPUTS +PSmolar_INPUTS = constants_header.PSmolar_INPUTS +PUmass_INPUTS = constants_header.PUmass_INPUTS +PUmolar_INPUTS = constants_header.PUmolar_INPUTS +HmassSmass_INPUTS = constants_header.HmassSmass_INPUTS +HmolarSmolar_INPUTS = constants_header.HmolarSmolar_INPUTS +SmassUmass_INPUTS = constants_header.SmassUmass_INPUTS +SmolarUmolar_INPUTS = constants_header.SmolarUmolar_INPUTS +DmassHmass_INPUTS = constants_header.DmassHmass_INPUTS +DmolarHmolar_INPUTS = constants_header.DmolarHmolar_INPUTS +DmassSmass_INPUTS = constants_header.DmassSmass_INPUTS +DmolarSmolar_INPUTS = constants_header.DmolarSmolar_INPUTS +DmassUmass_INPUTS = constants_header.DmassUmass_INPUTS +DmolarUmolar_INPUTS = constants_header.DmolarUmolar_INPUTS +FLUID_TYPE_PURE = constants_header.FLUID_TYPE_PURE +FLUID_TYPE_PSEUDOPURE = constants_header.FLUID_TYPE_PSEUDOPURE +FLUID_TYPE_REFPROP = constants_header.FLUID_TYPE_REFPROP +FLUID_TYPE_INCOMPRESSIBLE_LIQUID = constants_header.FLUID_TYPE_INCOMPRESSIBLE_LIQUID +FLUID_TYPE_INCOMPRESSIBLE_SOLUTION = constants_header.FLUID_TYPE_INCOMPRESSIBLE_SOLUTION +FLUID_TYPE_UNDEFINED = constants_header.FLUID_TYPE_UNDEFINED diff --git a/wrappers/Python/CoolProp5/constants_header.pxd b/wrappers/Python/CoolProp5/constants_header.pxd new file mode 100644 index 00000000..f095295e --- /dev/null +++ b/wrappers/Python/CoolProp5/constants_header.pxd @@ -0,0 +1,100 @@ +# This file is automatically generated by the generate_constants_module.py script in dev/scripts. +# DO NOT MODIFY THE CONTENTS OF THIS FILE! + +cdef extern from "DataStructures.h" namespace "CoolProp": + enum parameters: + imolar_mass + irhomolar_reducing + irhomolar_critical + iT_reducing + iT_critical + iT + iP + iQ + iTau + iDelta + iDmolar + iHmolar + iSmolar + iCpmolar + iCp0molar + iCvmolar + iUmolar + iGmolar + iDmass + iHmass + iSmass + iCpmass + iCp0mass + iCvmass + iUmass + iGmass + idrhodh_constp_smoothed + idrhodp_consth_smoothed + irho_smoothed + iviscosity + iconductivity + isurface_tension + iPrandtl + ispeed_sound + iisothermal_compressibility + iisobaric_expansion_coefficient + ifundamental_derivative_of_gas_dynamics + id2pdv2_consts + ialphar + idalphar_dtau_constdelta + idalphar_ddelta_consttau + ialpha0 + idalpha0_dtau_constdelta + idalpha0_ddelta_consttau + iBvirial + iCvirial + iZ + idBvirial_dT + idCvirial_dT + idZdDelta + idZdTau + iGWP20 + iGWP100 + iGWP500 + iFH + iHH + iPH + iODP + enum input_pairs: + QT_INPUTS + PQ_INPUTS + PT_INPUTS + DmassT_INPUTS + DmolarT_INPUTS + HmolarT_INPUTS + HmassT_INPUTS + SmolarT_INPUTS + SmassT_INPUTS + TUmolar_INPUTS + TUmass_INPUTS + DmassP_INPUTS + DmolarP_INPUTS + HmassP_INPUTS + HmolarP_INPUTS + PSmass_INPUTS + PSmolar_INPUTS + PUmass_INPUTS + PUmolar_INPUTS + HmassSmass_INPUTS + HmolarSmolar_INPUTS + SmassUmass_INPUTS + SmolarUmolar_INPUTS + DmassHmass_INPUTS + DmolarHmolar_INPUTS + DmassSmass_INPUTS + DmolarSmolar_INPUTS + DmassUmass_INPUTS + DmolarUmolar_INPUTS + enum fluid_types: + FLUID_TYPE_PURE + FLUID_TYPE_PSEUDOPURE + FLUID_TYPE_REFPROP + FLUID_TYPE_INCOMPRESSIBLE_LIQUID + FLUID_TYPE_INCOMPRESSIBLE_SOLUTION + FLUID_TYPE_UNDEFINED diff --git a/wrappers/Python/CoolProp/tests/__init__.py b/wrappers/Python/CoolProp5/tests/__init__.py similarity index 100% rename from wrappers/Python/CoolProp/tests/__init__.py rename to wrappers/Python/CoolProp5/tests/__init__.py diff --git a/wrappers/Python/CoolProp/tests/runner.py b/wrappers/Python/CoolProp5/tests/runner.py similarity index 100% rename from wrappers/Python/CoolProp/tests/runner.py rename to wrappers/Python/CoolProp5/tests/runner.py diff --git a/wrappers/Python/CoolProp/tests/test_CoolPropState.py b/wrappers/Python/CoolProp5/tests/test_CoolPropState.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_CoolPropState.py rename to wrappers/Python/CoolProp5/tests/test_CoolPropState.py diff --git a/wrappers/Python/CoolProp/tests/test_HAProps.py b/wrappers/Python/CoolProp5/tests/test_HAProps.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_HAProps.py rename to wrappers/Python/CoolProp5/tests/test_HAProps.py diff --git a/wrappers/Python/CoolProp/tests/test_Props.py b/wrappers/Python/CoolProp5/tests/test_Props.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_Props.py rename to wrappers/Python/CoolProp5/tests/test_Props.py diff --git a/wrappers/Python/CoolProp/tests/test_Props1.py b/wrappers/Python/CoolProp5/tests/test_Props1.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_Props1.py rename to wrappers/Python/CoolProp5/tests/test_Props1.py diff --git a/wrappers/Python/CoolProp/tests/test_Saturation.py b/wrappers/Python/CoolProp5/tests/test_Saturation.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_Saturation.py rename to wrappers/Python/CoolProp5/tests/test_Saturation.py diff --git a/wrappers/Python/CoolProp/tests/test_Units_CPState.py b/wrappers/Python/CoolProp5/tests/test_Units_CPState.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_Units_CPState.py rename to wrappers/Python/CoolProp5/tests/test_Units_CPState.py diff --git a/wrappers/Python/CoolProp/tests/test_consistency.py b/wrappers/Python/CoolProp5/tests/test_consistency.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_consistency.py rename to wrappers/Python/CoolProp5/tests/test_consistency.py diff --git a/wrappers/Python/CoolProp/tests/test_param_getters.py b/wrappers/Python/CoolProp5/tests/test_param_getters.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_param_getters.py rename to wrappers/Python/CoolProp5/tests/test_param_getters.py diff --git a/wrappers/Python/CoolProp/tests/test_plots.py b/wrappers/Python/CoolProp5/tests/test_plots.py similarity index 100% rename from wrappers/Python/CoolProp/tests/test_plots.py rename to wrappers/Python/CoolProp5/tests/test_plots.py diff --git a/wrappers/Python/setup2.py b/wrappers/Python/setup2.py new file mode 100644 index 00000000..5780bc70 --- /dev/null +++ b/wrappers/Python/setup2.py @@ -0,0 +1,172 @@ +from __future__ import print_function +#Check for cython >= 0.17 due to the use of STL containers +try: + import Cython +except ImportError: + raise ImportError("Cython not found") +major,minor = Cython.__version__.split('.')[0:2] +#Convert major to integer +major = int(major) +iEnd = 0 +while minor[iEnd].isdigit(): + iEnd+=1 + if iEnd == len(minor): + break + +minor = int(minor[0:iEnd]) +if not(major > 0 or minor >= 17): + raise ImportError('Cython version >= 0.17 required due to the use of STL wrappers. Please update your version of cython') + +if minor >= 20: + _profiling_enabled = True +else: + _profiling_enabled = False + +from distutils.core import setup, Extension +import subprocess, shutil, os, sys, glob +from Cython.Build import cythonize +from Cython.Distutils import build_ext +from Cython.Distutils.extension import Extension as CyExtension +from distutils.sysconfig import get_python_inc +from distutils.ccompiler import new_compiler +from distutils.dep_util import newer_group + +def find_cpp_sources(root = os.path.join('..','..','src'), extensions = ['.cpp'], skip_files = None): + file_listing = [] + for path, dirs, files in os.walk(root): + for file in files: + n,ext = os.path.splitext(file) + fname = os.path.relpath(os.path.join(path, file)) + if skip_files is not None and fname in skip_files: continue + if ext in extensions: + file_listing.append(fname) + return file_listing + +#This will generate HTML to show where there are still pythonic bits hiding out +Cython.Compiler.Options.annotate = True + +# Two options for the location of the C++ files. Either in the normal ../../CoolProp folder +# or they are in the CoolPropSource folder in this folder + +# For PYPI purposes +if 'sdist' in sys.argv: + CProot = '.' + shutil.copy2(os.path.join('..','..','version.txt'),'version.txt') + shutil.copytree(os.path.join('..','..','CoolProp'),'CoolPropSource') +else: + CProot = os.path.join('..','..') + +if os.path.exists('CoolPropSource'): + CPSourceDir = 'CoolPropSource' + CProot = '.' +else: + CPSourceDir = os.path.join(CProot,'src') + CPIncludeDir = os.path.join(CProot,'include') + +version = open(os.path.join(CProot,'version.txt'),'r').read().strip() + +if __name__=='__main__': + + #This will generate HTML to show where there are still pythonic bits hiding out + Cython.Compiler.Options.annotate = True + + ## If the file is run directly without any parameters, build and install + if len(sys.argv)==1: + #sys.argv += ['build_ext','--inplace'] + sys.argv += ['build','--compiler=mingw32','install'] +# sys.argv += ['build','install'] + #sys.argv += ['install'] + + Sources = find_cpp_sources(CPSourceDir,'*.cpp') + + ### Include folders for build + include_dirs = [os.path.join(CPIncludeDir)] + + if _profiling_enabled: + cython_directives = dict(profile = True, + embed_signature = True) + else: + cython_directives = dict(embed_signature = True) + + common_args = dict(include_dirs = include_dirs, + language='c++', + cython_c_in_temp = True, + cython_directives = cython_directives + ) + + AbstractState_module = CyExtension('CoolProp5.AbstractState', + [os.path.join('CoolProp5','AbstractState.pyx')]+Sources, + **common_args) + + CoolProp_module = CyExtension('CoolProp5.CoolProp', + [os.path.join('CoolProp5','CoolProp.pyx')]+Sources, + **common_args) + + constants_module = CyExtension('CoolProp5.constants', + [os.path.join('CoolProp5','constants.pyx')], + **common_args) + +# # Collect all the header files in the main folder into an include folder +# try: +# os.mkdir(os.path.join('CoolProp','include')) +# except: +# pass + +# for folder in [os.path.join(CPSourceDir)]: +# for header in glob.glob(os.path.join(folder,'*.h')): +# pth,fName = os.path.split(header) +# shutil.copy2(header,os.path.join('CoolProp','include',fName)) + + #shutil.copy2(os.path.join(CPSourceDir,'CoolPropBibTeXLibrary.bib'),os.path.join('CoolProp','CoolPropBibTeXLibrary.bib')) + + setup (name = 'CoolProp5', + version = version, #look above for the definition of version variable - don't modify it here + author = "Ian Bell", + author_email='ian.h.bell@gmail.com', + url='http://coolprop.sourceforge.net', + description = """Open-source thermodynamic and transport properties database""", + packages = ['CoolProp5','CoolProp5.Plots','CoolProp5.tests','CoolProp5.GUI'], + ext_modules = [CoolProp_module, constants_module], + package_dir = {'CoolProp5':'CoolProp5',}, + #package_data = {'CoolProp5':['State.pxd','CoolProp.pxd','constants_header.pxd','include/*.h','include/rapidjson/*.h','include/rapidjson/internal/*.h','CoolPropBibTeXLibrary.bib']}, + cmdclass={'build_ext': build_ext}, + + classifiers = [ + "Programming Language :: Python", + "Development Status :: 4 - Beta", + "Environment :: Other Environment", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Topic :: Software Development :: Libraries :: Python Modules" + ], + ) + + sys.path.pop(0) + import CoolProp5.CoolProp as CP5 + print(CP5.PropsSI('P','T',300,'D',1e-10,'Water')) + +# #Clean up the include folder +# shutil.rmtree(os.path.join('CoolProp','include'), ignore_errors = True) +# os.remove(os.path.join('CoolProp','CoolPropBibTeXLibrary.bib')) +# +# for file in glob.glob(os.path.join('CoolProp','__init__.*')): +# try: +# os.remove(file) +# except: +# pass +# +# if 'sdist' in sys.argv: +# shutil.rmtree('CoolPropSource') +# os.remove('version.txt') +# touch('setup.py') + +# try: +# import nose +# import CoolProp +# CoolProp.test() +# except ImportError: +# print("Could not run tests, nose not installed") + + +