mirror of
https://github.com/CoolProp/CoolProp.git
synced 2026-01-09 05:58:12 -05:00
More pep8 whitespace; see #1612
This commit is contained in:
@@ -30,7 +30,7 @@ def html_page_context(app, pagename, templatename, context, doctree):
|
||||
warnings.warn("edit_on_github_project not specified")
|
||||
return
|
||||
|
||||
path = os.path.relpath(doctree.get('source'), app.builder.srcdir).replace('\\','/')
|
||||
path = os.path.relpath(doctree.get('source'), app.builder.srcdir).replace('\\', '/')
|
||||
path_prefix = app.config.edit_on_github_path_prefix
|
||||
show_url = get_github_url(app, 'blob', path_prefix + '/' + path)
|
||||
edit_url = get_github_url(app, 'edit', path_prefix + '/' + path)
|
||||
|
||||
60
Web/conf.py
60
Web/conf.py
@@ -20,12 +20,12 @@
|
||||
import CoolProp
|
||||
ver = CoolProp.__version__
|
||||
# The short X.Y version.
|
||||
version = ver.rsplit('.',1)[0]
|
||||
version = ver.rsplit('.', 1)[0]
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = ver
|
||||
|
||||
# Some hacking to determine release or nightly build
|
||||
if ver[-2]=="." and ver[-1].isdigit()>=0 and ver[-3].isdigit()>=0:
|
||||
if ver[-2] == "." and ver[-1].isdigit() >= 0 and ver[-3].isdigit() >= 0:
|
||||
isRelease = True
|
||||
else:
|
||||
isRelease = False
|
||||
@@ -37,23 +37,23 @@ print("Public release : %s" % "True" if isRelease else "False")
|
||||
print("")
|
||||
|
||||
if isRelease:
|
||||
extlinks = {'sfdownloads': ('http://sourceforge.net/projects/coolprop/files/CoolProp/'+release+'/%s',''),
|
||||
'sfnightly' : ('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/%s',''),
|
||||
#'bbbinaries' : ('http://www.coolprop.dreamhosters.com:8010/binaries/%s',''),
|
||||
#'bbsphinx' : ('http://www.coolprop.dreamhosters.com:8010/sphinx/%s','')
|
||||
extlinks = {'sfdownloads': ('http://sourceforge.net/projects/coolprop/files/CoolProp/' + release + '/%s', ''),
|
||||
'sfnightly': ('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/%s', ''),
|
||||
# 'bbbinaries' : ('http://www.coolprop.dreamhosters.com:8010/binaries/%s',''),
|
||||
# 'bbsphinx' : ('http://www.coolprop.dreamhosters.com:8010/sphinx/%s','')
|
||||
}
|
||||
else:
|
||||
extlinks = {'sfdownloads': ('http://sourceforge.net/projects/coolprop/files/CoolProp/'+release+'/%s',''),
|
||||
'sfnightly' : ('http://www.coolprop.dreamhosters.com/binaries/%s',''),
|
||||
#'bbbinaries' : ('http://www.coolprop.dreamhosters.com:8010/binaries/%s',''),
|
||||
#'bbsphinx' : ('http://www.coolprop.dreamhosters.com:8010/sphinx/%s','')
|
||||
extlinks = {'sfdownloads': ('http://sourceforge.net/projects/coolprop/files/CoolProp/' + release + '/%s', ''),
|
||||
'sfnightly': ('http://www.coolprop.dreamhosters.com/binaries/%s', ''),
|
||||
# 'bbbinaries' : ('http://www.coolprop.dreamhosters.com:8010/binaries/%s',''),
|
||||
# 'bbsphinx' : ('http://www.coolprop.dreamhosters.com:8010/sphinx/%s','')
|
||||
}
|
||||
|
||||
import sys, os, datetime
|
||||
|
||||
#~ # If your extensions are in another directory, add it here. If the directory
|
||||
#~ # is relative to the documentation root, use os.path.abspath to make it
|
||||
#~ # absolute, like shown here.
|
||||
# ~ # If your extensions are in another directory, add it here. If the directory
|
||||
# ~ # is relative to the documentation root, use os.path.abspath to make it
|
||||
# ~ # absolute, like shown here.
|
||||
#~ sys.path.append(os.path.abspath('sphinxext'))
|
||||
|
||||
sys.path.insert(0, os.path.abspath('_ext'))
|
||||
@@ -65,11 +65,11 @@ except ImportError:
|
||||
|
||||
if isRelease:
|
||||
doxylink = {
|
||||
'cpapi' : ('_static/doxygen/CoolPropDoxyLink.tag', 'http://www.coolprop.org/_static/doxygen/html')
|
||||
'cpapi': ('_static/doxygen/CoolPropDoxyLink.tag', 'http://www.coolprop.org/_static/doxygen/html')
|
||||
}
|
||||
else:
|
||||
doxylink = {
|
||||
'cpapi' : ('_static/doxygen/CoolPropDoxyLink.tag', 'http://www.coolprop.dreamhosters.com/binaries/sphinx/_static/doxygen/html')
|
||||
'cpapi': ('_static/doxygen/CoolPropDoxyLink.tag', 'http://www.coolprop.dreamhosters.com/binaries/sphinx/_static/doxygen/html')
|
||||
}
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
@@ -89,22 +89,22 @@ extensions = ['IPython.sphinxext.ipython_console_highlighting',
|
||||
'edit_on_github', # see https://gist.github.com/mgedmin/6052926#file-edit_on_github-pyb
|
||||
|
||||
# cloud's extensions
|
||||
#'cloud_sptheme.ext.autodoc_sections',
|
||||
# 'cloud_sptheme.ext.autodoc_sections',
|
||||
'cloud_sptheme.ext.index_styling',
|
||||
'cloud_sptheme.ext.relbar_toc',
|
||||
#'cloud_sptheme.ext.escaped_samp_literals',
|
||||
# 'cloud_sptheme.ext.escaped_samp_literals',
|
||||
'cloud_sptheme.ext.issue_tracker',
|
||||
#'cloud_sptheme.ext.table_styling',
|
||||
# 'cloud_sptheme.ext.table_styling',
|
||||
|
||||
#'inheritance_diagram',
|
||||
#'numpydoc',
|
||||
#'breathe'
|
||||
# 'inheritance_diagram',
|
||||
# 'numpydoc',
|
||||
# 'breathe'
|
||||
]
|
||||
|
||||
# set path to issue tracker:
|
||||
issue_tracker_url = "gh:CoolProp/CoolProp"
|
||||
|
||||
plot_formats = [('png',80),('.pdf')]
|
||||
plot_formats = [('png', 80), ('.pdf')]
|
||||
|
||||
index_doc = "index"
|
||||
|
||||
@@ -144,7 +144,7 @@ copyright = u'2010-{0}, Ian H. Bell and the CoolProp Team'.format(d.year)
|
||||
|
||||
# List of directories, relative to source directory, that shouldn't be searched
|
||||
# for source files.
|
||||
exclude_trees = ['_build','sphinxext']
|
||||
exclude_trees = ['_build', 'sphinxext']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
@@ -166,10 +166,10 @@ pygments_style = 'sphinx'
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
#This value selects what content will be inserted into the main body of an autoclass directive.
|
||||
#'class' - Only the class’ docstring is inserted. This is the default.
|
||||
#'init' - Only the __init__ method’s docstring is inserted.
|
||||
#'both' - Both the class’ and the __init__ method’s docstring are concatenated and inserted
|
||||
# This value selects what content will be inserted into the main body of an autoclass directive.
|
||||
# 'class' - Only the class’ docstring is inserted. This is the default.
|
||||
# 'init' - Only the __init__ method’s docstring is inserted.
|
||||
# 'both' - Both the class’ and the __init__ method’s docstring are concatenated and inserted
|
||||
autoclass_content = 'both'
|
||||
|
||||
|
||||
@@ -195,8 +195,8 @@ html_theme = "cloud"
|
||||
html_theme_path = [csp.get_theme_dir()]
|
||||
|
||||
# [optional] set some of the options listed above...
|
||||
html_theme_options = { "roottarget": "index",
|
||||
"max_width" : "13in",
|
||||
html_theme_options = {"roottarget": "index",
|
||||
"max_width": "13in",
|
||||
"logotarget": "index",
|
||||
"googleanalytics_id": "UA-53205480-2",
|
||||
"default_layout_text_size": "85%"
|
||||
@@ -210,7 +210,7 @@ edit_on_github_path_prefix = 'Web'
|
||||
# Sphinx are currently 'default' and 'sphinxdoc'.
|
||||
## html_theme = 'sphinxdoc'
|
||||
|
||||
## html_theme='nature'
|
||||
# html_theme='nature'
|
||||
|
||||
# The style sheet to use for HTML and HTML Help pages. A file of that name
|
||||
# must exist either in Sphinx' static/ path, or in one of the custom paths
|
||||
|
||||
@@ -7,132 +7,132 @@ print(' Replicating the tables from ASHRAE RP-1485')
|
||||
print(' ')
|
||||
print('A.6.1 Psychrometric Properties of Moist Air at 0C and Below')
|
||||
print('Saturated air at 101.325 kPa')
|
||||
s5=' '*5
|
||||
s5 = ' ' * 5
|
||||
print('====================================================')
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=s5+' Ws',v=s5+' v',h=s5+'h',s=s5+' s',T=' T'))
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=' kgw/kg_da',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',T=' C'))
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=s5 + ' Ws', v=s5 + ' v', h=s5 + 'h', s=s5 + ' s', T=' T'))
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=' kgw/kg_da', v=' m3/kgda', h=' kJ/kgda', s=' kJ/kgda/K', T=' C'))
|
||||
print('----------------------------------------------------')
|
||||
for T in np.linspace(-60,0,13)+273.15:
|
||||
h = HAPropsSI('H','T',T,'R',1.0,'P',101325)/1000
|
||||
Twb = HAPropsSI('Twb','T',T,'R',1.0,'P',101325)-273.15
|
||||
W = HAPropsSI('W','T',T,'R',1.0,'P',101325)
|
||||
v = HAPropsSI('V','T',T,'R',1.0,'P',101325)
|
||||
s = HAPropsSI('S','T',T,'R',1.0,'P',101325)/1000
|
||||
print("{T:8.0f}{W:10.7f}{v:10.4f}{h:10.3f}{s:10.4f}".format(W=W,T=T-273.15,v=v,h=h,s=s))
|
||||
for T in np.linspace(-60, 0, 13) + 273.15:
|
||||
h = HAPropsSI('H', 'T', T, 'R', 1.0, 'P', 101325) / 1000
|
||||
Twb = HAPropsSI('Twb', 'T', T, 'R', 1.0, 'P', 101325) - 273.15
|
||||
W = HAPropsSI('W', 'T', T, 'R', 1.0, 'P', 101325)
|
||||
v = HAPropsSI('V', 'T', T, 'R', 1.0, 'P', 101325)
|
||||
s = HAPropsSI('S', 'T', T, 'R', 1.0, 'P', 101325) / 1000
|
||||
print("{T:8.0f}{W:10.7f}{v:10.4f}{h:10.3f}{s:10.4f}".format(W=W, T=T - 273.15, v=v, h=h, s=s))
|
||||
print('====================================================')
|
||||
print(' ')
|
||||
print('A.6.2 Psychrometric Properties of Moist Air at 0C and Above')
|
||||
print('Saturated air at 101.325 kPa')
|
||||
s5=' '*5
|
||||
s5 = ' ' * 5
|
||||
print('====================================================')
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=s5+' Ws',v=s5+' v',h=s5+'h',s=s5+' s',T=' T'))
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=' kgw/kg_da',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',T=' C'))
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=s5 + ' Ws', v=s5 + ' v', h=s5 + 'h', s=s5 + ' s', T=' T'))
|
||||
print("{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}".format(W=' kgw/kg_da', v=' m3/kgda', h=' kJ/kgda', s=' kJ/kgda/K', T=' C'))
|
||||
print('----------------------------------------------------')
|
||||
for T in np.linspace(0,90,19)+273.15:
|
||||
h=HAPropsSI('H','T',T,'R',1.0,'P',101325)/1000
|
||||
Twb=HAPropsSI('Twb','T',T,'R',1.0,'P',101325)-273.15
|
||||
W=HAPropsSI('W','T',T,'R',1.0,'P',101325)
|
||||
v=HAPropsSI('V','T',T,'R',1.0,'P',101325)
|
||||
s=HAPropsSI('S','T',T,'R',1.0,'P',101325)/1000
|
||||
print("{T:8.0f}{W:10.7f}{v:10.3f}{h:10.2f}{s:10.4f}".format(W=W,T=T-273.15,v=v,h=h,s=s))
|
||||
for T in np.linspace(0, 90, 19) + 273.15:
|
||||
h = HAPropsSI('H', 'T', T, 'R', 1.0, 'P', 101325) / 1000
|
||||
Twb = HAPropsSI('Twb', 'T', T, 'R', 1.0, 'P', 101325) - 273.15
|
||||
W = HAPropsSI('W', 'T', T, 'R', 1.0, 'P', 101325)
|
||||
v = HAPropsSI('V', 'T', T, 'R', 1.0, 'P', 101325)
|
||||
s = HAPropsSI('S', 'T', T, 'R', 1.0, 'P', 101325) / 1000
|
||||
print("{T:8.0f}{W:10.7f}{v:10.3f}{h:10.2f}{s:10.4f}".format(W=W, T=T - 273.15, v=v, h=h, s=s))
|
||||
print('====================================================')
|
||||
print(' ')
|
||||
|
||||
|
||||
def HotAir(num):
|
||||
from CoolProp.HumidAirProp import HAPropsSI
|
||||
if num=='8':
|
||||
Temp=str(200)
|
||||
T=200+273.15
|
||||
elif num=='9':
|
||||
Temp=str(320)
|
||||
T=320+273.15
|
||||
print('A.'+num+'.1 Psychrometric Properties of Moist Air at 101.325 kPa ')
|
||||
print('Dry Bulb temperature of '+Temp+'C')
|
||||
s5=' '*5
|
||||
if num == '8':
|
||||
Temp = str(200)
|
||||
T = 200 + 273.15
|
||||
elif num == '9':
|
||||
Temp = str(320)
|
||||
T = 320 + 273.15
|
||||
print('A.' + num + '.1 Psychrometric Properties of Moist Air at 101.325 kPa ')
|
||||
print('Dry Bulb temperature of ' + Temp + 'C')
|
||||
s5 = ' ' * 5
|
||||
print('================================================================')
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5 + ' W', Twb=s5 + 'Twb', v=s5 + ' v', h=s5 + 'h', s=s5 + ' s', R=s5 + 'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da', Twb=' C', v=' m3/kgda', h=' kJ/kgda', s=' kJ/kgda/K', R=' %'))
|
||||
print("----------------------------------------------------------------")
|
||||
for W in [0.0,0.05,0.1,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90,1.0]:
|
||||
h=HAPropsSI('H','T',T,'W',W,'P',101325)/1000
|
||||
Twb=HAPropsSI('Twb','T',T,'W',W,'P',101325)-273.15
|
||||
R=HAPropsSI('R','T',T,'W',W,'P',101325)*100
|
||||
v=HAPropsSI('V','T',T,'W',W,'P',101325)
|
||||
s=HAPropsSI('S','T',T,'W',W,'P',101325)/1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R))
|
||||
for W in [0.0, 0.05, 0.1, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.0]:
|
||||
h = HAPropsSI('H', 'T', T, 'W', W, 'P', 101325) / 1000
|
||||
Twb = HAPropsSI('Twb', 'T', T, 'W', W, 'P', 101325) - 273.15
|
||||
R = HAPropsSI('R', 'T', T, 'W', W, 'P', 101325) * 100
|
||||
v = HAPropsSI('V', 'T', T, 'W', W, 'P', 101325)
|
||||
s = HAPropsSI('S', 'T', T, 'W', W, 'P', 101325) / 1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W, Twb=Twb, v=v, h=h, s=s, R=R))
|
||||
print('================================================================')
|
||||
print(' ')
|
||||
print('A.'+num+'.2 Psychrometric Properties of Moist Air at 1000 kPa ')
|
||||
print('Dry Bulb temperature of '+Temp+'C')
|
||||
print('A.' + num + '.2 Psychrometric Properties of Moist Air at 1000 kPa ')
|
||||
print('Dry Bulb temperature of ' + Temp + 'C')
|
||||
print('================================================================')
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5 + ' W', Twb=s5 + 'Twb', v=s5 + ' v', h=s5 + 'h', s=s5 + ' s', R=s5 + 'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da', Twb=' C', v=' m3/kgda', h=' kJ/kgda', s=' kJ/kgda/K', R=' %'))
|
||||
print('----------------------------------------------------------------')
|
||||
for W in [0.0,0.05,0.1,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90,1.0]:
|
||||
h=HAPropsSI('H','T',T,'W',W,'P',1000e3)/1000
|
||||
Twb=HAPropsSI('Twb','T',T,'W',W,'P',1000e3)-273.15
|
||||
R=HAPropsSI('R','T',T,'W',W,'P',1000e3)*100
|
||||
v=HAPropsSI('V','T',T,'W',W,'P',1000e3)
|
||||
s=HAPropsSI('S','T',T,'W',W,'P',1000e3)/1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R))
|
||||
for W in [0.0, 0.05, 0.1, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.0]:
|
||||
h = HAPropsSI('H', 'T', T, 'W', W, 'P', 1000e3) / 1000
|
||||
Twb = HAPropsSI('Twb', 'T', T, 'W', W, 'P', 1000e3) - 273.15
|
||||
R = HAPropsSI('R', 'T', T, 'W', W, 'P', 1000e3) * 100
|
||||
v = HAPropsSI('V', 'T', T, 'W', W, 'P', 1000e3)
|
||||
s = HAPropsSI('S', 'T', T, 'W', W, 'P', 1000e3) / 1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W, Twb=Twb, v=v, h=h, s=s, R=R))
|
||||
print('================================================================')
|
||||
print(' ')
|
||||
s5=' '*5
|
||||
print('A.'+num+'.3 Psychrometric Properties of Moist Air at 2000 kPa ')
|
||||
print('Dry Bulb temperature of '+Temp+'C')
|
||||
s5 = ' ' * 5
|
||||
print('A.' + num + '.3 Psychrometric Properties of Moist Air at 2000 kPa ')
|
||||
print('Dry Bulb temperature of ' + Temp + 'C')
|
||||
print('================================================================')
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5 + ' W', Twb=s5 + 'Twb', v=s5 + ' v', h=s5 + 'h', s=s5 + ' s', R=s5 + 'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da', Twb=' C', v=' m3/kgda', h=' kJ/kgda', s=' kJ/kgda/K', R=' %'))
|
||||
print('----------------------------------------------------------------')
|
||||
for W in [0.0,0.05,0.1,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90,1.0]:
|
||||
h=HAPropsSI('H','T',T,'W',W,'P',2000e3)/1000
|
||||
Twb=HAPropsSI('Twb','T',T,'W',W,'P',2000e3)-273.15
|
||||
R=HAPropsSI('R','T',T,'W',W,'P',2000e3)*100
|
||||
v=HAPropsSI('V','T',T,'W',W,'P',2000e3)
|
||||
s=HAPropsSI('S','T',T,'W',W,'P',2000e3)/1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R))
|
||||
for W in [0.0, 0.05, 0.1, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.0]:
|
||||
h = HAPropsSI('H', 'T', T, 'W', W, 'P', 2000e3) / 1000
|
||||
Twb = HAPropsSI('Twb', 'T', T, 'W', W, 'P', 2000e3) - 273.15
|
||||
R = HAPropsSI('R', 'T', T, 'W', W, 'P', 2000e3) * 100
|
||||
v = HAPropsSI('V', 'T', T, 'W', W, 'P', 2000e3)
|
||||
s = HAPropsSI('S', 'T', T, 'W', W, 'P', 2000e3) / 1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W, Twb=Twb, v=v, h=h, s=s, R=R))
|
||||
print('================================================================')
|
||||
print(' ')
|
||||
s5=' '*5
|
||||
print('A.'+num+'.4 Psychrometric Properties of Moist Air at 5000 kPa ')
|
||||
print('Dry Bulb temperature of '+Temp+'C')
|
||||
s5 = ' ' * 5
|
||||
print('A.' + num + '.4 Psychrometric Properties of Moist Air at 5000 kPa ')
|
||||
print('Dry Bulb temperature of ' + Temp + 'C')
|
||||
print('================================================================')
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5 + ' W', Twb=s5 + 'Twb', v=s5 + ' v', h=s5 + 'h', s=s5 + ' s', R=s5 + 'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da', Twb=' C', v=' m3/kgda', h=' kJ/kgda', s=' kJ/kgda/K', R=' %'))
|
||||
print('----------------------------------------------------------------')
|
||||
if Temp=='200':
|
||||
Wrange = [0.0,0.05,0.1,0.15,0.20,0.25,0.30]
|
||||
if Temp == '200':
|
||||
Wrange = [0.0, 0.05, 0.1, 0.15, 0.20, 0.25, 0.30]
|
||||
else:
|
||||
Wrange = [0.0,0.05,0.1,0.15,0.20,0.25,0.30,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
|
||||
Wrange = [0.0, 0.05, 0.1, 0.15, 0.20, 0.25, 0.30, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
|
||||
for W in Wrange:
|
||||
h=HAPropsSI('H','T',T,'W',W,'P',5000e3)/1000
|
||||
Twb=HAPropsSI('Twb','T',T,'W',W,'P',5000e3)-273.15
|
||||
R=HAPropsSI('R','T',T,'W',W,'P',5000e3)*100
|
||||
v=HAPropsSI('V','T',T,'W',W,'P',5000e3)
|
||||
s=HAPropsSI('S','T',T,'W',W,'P',5000e3)/1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R))
|
||||
h = HAPropsSI('H', 'T', T, 'W', W, 'P', 5000e3) / 1000
|
||||
Twb = HAPropsSI('Twb', 'T', T, 'W', W, 'P', 5000e3) - 273.15
|
||||
R = HAPropsSI('R', 'T', T, 'W', W, 'P', 5000e3) * 100
|
||||
v = HAPropsSI('V', 'T', T, 'W', W, 'P', 5000e3)
|
||||
s = HAPropsSI('S', 'T', T, 'W', W, 'P', 5000e3) / 1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W, Twb=Twb, v=v, h=h, s=s, R=R))
|
||||
print('================================================================')
|
||||
print(' ')
|
||||
s5=' '*5
|
||||
print('A.'+num+'.5 Psychrometric Properties of Moist Air at 10,000 kPa ')
|
||||
print('Dry Bulb temperature of '+Temp+'C')
|
||||
s5 = ' ' * 5
|
||||
print('A.' + num + '.5 Psychrometric Properties of Moist Air at 10,000 kPa ')
|
||||
print('Dry Bulb temperature of ' + Temp + 'C')
|
||||
print('================================================================')
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=s5 + ' W', Twb=s5 + 'Twb', v=s5 + ' v', h=s5 + 'h', s=s5 + ' s', R=s5 + 'RH'))
|
||||
print("{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}".format(W=' kgw/kg_da', Twb=' C', v=' m3/kgda', h=' kJ/kgda', s=' kJ/kgda/K', R=' %'))
|
||||
print('----------------------------------------------------------------')
|
||||
|
||||
if Temp=='200':
|
||||
Wrange = [0.0,0.05,0.1]
|
||||
if Temp == '200':
|
||||
Wrange = [0.0, 0.05, 0.1]
|
||||
else:
|
||||
Wrange = [0.0,0.05,0.1,0.15,0.20,0.25,0.30,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
|
||||
Wrange = [0.0, 0.05, 0.1, 0.15, 0.20, 0.25, 0.30, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
|
||||
for W in Wrange:
|
||||
h=HAPropsSI('H','T',T,'W',W,'P',10000e3)/1000
|
||||
Twb=HAPropsSI('Twb','T',T,'W',W,'P',10000e3)-273.15
|
||||
R=HAPropsSI('R','T',T,'W',W,'P',10000e3)*100
|
||||
v=HAPropsSI('V','T',T,'W',W,'P',10000e3)
|
||||
s=HAPropsSI('S','T',T,'W',W,'P',10000e3)/1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R))
|
||||
h = HAPropsSI('H', 'T', T, 'W', W, 'P', 10000e3) / 1000
|
||||
Twb = HAPropsSI('Twb', 'T', T, 'W', W, 'P', 10000e3) - 273.15
|
||||
R = HAPropsSI('R', 'T', T, 'W', W, 'P', 10000e3) * 100
|
||||
v = HAPropsSI('V', 'T', T, 'W', W, 'P', 10000e3)
|
||||
s = HAPropsSI('S', 'T', T, 'W', W, 'P', 10000e3) / 1000
|
||||
print("{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}".format(W=W, Twb=Twb, v=v, h=h, s=s, R=R))
|
||||
print('================================================================')
|
||||
|
||||
|
||||
@@ -148,34 +148,34 @@ def Virials(variables):
|
||||
from CoolProp.HumidAirProp import HAProps_Aux
|
||||
import numpy as np
|
||||
|
||||
varString="%-10s"%('T')
|
||||
units="%-10s"%('C')
|
||||
#Build the header
|
||||
varString = "%-10s" % ('T')
|
||||
units = "%-10s" % ('C')
|
||||
# Build the header
|
||||
for var in variables:
|
||||
varString+="%-20s"%(var)
|
||||
units+="%-20s" %(HAProps_Aux(var,300,100,0.0)[1])
|
||||
varString += "%-20s" % (var)
|
||||
units += "%-20s" % (HAProps_Aux(var, 300, 100, 0.0)[1])
|
||||
print(varString)
|
||||
print(units)
|
||||
|
||||
#Build the table
|
||||
for T in np.linspace(-60,200,27)+273.15:
|
||||
values="%-10.1f" %(T-273.15)
|
||||
# Build the table
|
||||
for T in np.linspace(-60, 200, 27) + 273.15:
|
||||
values = "%-10.1f" % (T - 273.15)
|
||||
for var in variables:
|
||||
values+="%-20.10e" %(HAProps_Aux(var,T,100,0.0)[0])
|
||||
values += "%-20.10e" % (HAProps_Aux(var, T, 100, 0.0)[0])
|
||||
print(values)
|
||||
|
||||
|
||||
print("")
|
||||
print("Pure fluid Virial Coefficients")
|
||||
print("------------------------------")
|
||||
Virials(['Baa','Caaa','Bww','Cwww'])
|
||||
Virials(['Baw','Caaw','Caww'])
|
||||
Virials(['Baa', 'Caaa', 'Bww', 'Cwww'])
|
||||
Virials(['Baw', 'Caaw', 'Caww'])
|
||||
|
||||
print("")
|
||||
print("Pure fluid Virial Coefficients Derivatives")
|
||||
print("------------------------------------------")
|
||||
Virials(['dBaa','dCaaa','dBww','dCwww'])
|
||||
Virials(['dBaw','dCaaw','dCaww'])
|
||||
Virials(['dBaa', 'dCaaa', 'dBww', 'dCwww'])
|
||||
Virials(['dBaw', 'dCaaw', 'dCaww'])
|
||||
|
||||
|
||||
##############################
|
||||
@@ -186,13 +186,13 @@ print("")
|
||||
print("Water saturation pressure p_ws [kPa]")
|
||||
from CoolProp.HumidAirProp import HAProps_Aux
|
||||
import numpy as np
|
||||
Tv=np.linspace(-60,300,13)+273.15
|
||||
print("%-10s %-20s"%('T','p_ws'))
|
||||
print("%-10s %-20s"%('C',HAProps_Aux('p_ws',Tv[-1],100,0.0)[1]))
|
||||
#Build the table
|
||||
Tv = np.linspace(-60, 300, 13) + 273.15
|
||||
print("%-10s %-20s" % ('T', 'p_ws'))
|
||||
print("%-10s %-20s" % ('C', HAProps_Aux('p_ws', Tv[-1], 100, 0.0)[1]))
|
||||
# Build the table
|
||||
for T in Tv:
|
||||
values="%-10.2f" %(T-273.15)
|
||||
values+="%-20.10e" %(HAProps_Aux('p_ws',T,100,0.0)[0])
|
||||
values = "%-10.2f" % (T - 273.15)
|
||||
values += "%-20.10e" % (HAProps_Aux('p_ws', T, 100, 0.0)[0])
|
||||
print(values)
|
||||
|
||||
##############################
|
||||
@@ -203,13 +203,13 @@ print("")
|
||||
print("Henry Constant (zero for T < 273.15 K)")
|
||||
from CoolProp.HumidAirProp import HAProps_Aux
|
||||
import numpy as np
|
||||
Tv=np.linspace(0,300,11)+273.16
|
||||
print("%-10s %-20s"%('T','beta_H'))
|
||||
print("%-10s %-20s"%('C',HAProps_Aux('beta_H',Tv[-1],100,0.0)[1]))
|
||||
#Build the table
|
||||
Tv = np.linspace(0, 300, 11) + 273.16
|
||||
print("%-10s %-20s" % ('T', 'beta_H'))
|
||||
print("%-10s %-20s" % ('C', HAProps_Aux('beta_H', Tv[-1], 100, 0.0)[1]))
|
||||
# Build the table
|
||||
for T in Tv:
|
||||
values="%-10.2f" %(T-273.15)
|
||||
values+="%-20.10e" %(HAProps_Aux('beta_H',T,100,0.0)[0])
|
||||
values = "%-10.2f" % (T - 273.15)
|
||||
values += "%-20.10e" % (HAProps_Aux('beta_H', T, 100, 0.0)[0])
|
||||
print(values)
|
||||
|
||||
##########################################
|
||||
@@ -220,17 +220,17 @@ print("")
|
||||
print("Isothermal Compressibility of water (kT) [1/Pa]")
|
||||
from CoolProp.HumidAirProp import HAProps_Aux
|
||||
import numpy as np
|
||||
Tv=np.linspace(-60,300,13)+273.15
|
||||
Pv=[101325,200000,500000,1000000]
|
||||
variables="%-10s"%('T')
|
||||
Tv = np.linspace(-60, 300, 13) + 273.15
|
||||
Pv = [101325, 200000, 500000, 1000000]
|
||||
variables = "%-10s" % ('T')
|
||||
for p in Pv:
|
||||
variables+="%-20s"%("p = %-0.3f Pa "%(p))
|
||||
variables += "%-20s" % ("p = %-0.3f Pa " % (p))
|
||||
print(variables)
|
||||
#Build the actual table
|
||||
# Build the actual table
|
||||
for T in Tv:
|
||||
values="%-10.2f" %(T-273.15)
|
||||
values = "%-10.2f" % (T - 273.15)
|
||||
for p in Pv:
|
||||
values+="%-20.10e" %(HAProps_Aux('kT',T,p,0.0)[0])
|
||||
values += "%-20.10e" % (HAProps_Aux('kT', T, p, 0.0)[0])
|
||||
print(values)
|
||||
|
||||
##########################################
|
||||
@@ -241,17 +241,17 @@ print("")
|
||||
print("Molar volume of saturated liquid water or ice (vbar_ws) [m^3/mol_H2O]")
|
||||
from CoolProp.HumidAirProp import HAProps_Aux
|
||||
import numpy as np
|
||||
Tv=np.linspace(-60,300,13)+273.15
|
||||
Pv=[101325,200000,500000,1000000]
|
||||
variables="%-10s"%('T')
|
||||
Tv = np.linspace(-60, 300, 13) + 273.15
|
||||
Pv = [101325, 200000, 500000, 1000000]
|
||||
variables = "%-10s" % ('T')
|
||||
for p in Pv:
|
||||
variables+="%-20s"%("p = %-0.3f Pa "%(p))
|
||||
variables += "%-20s" % ("p = %-0.3f Pa " % (p))
|
||||
print(variables)
|
||||
#Build the actual table
|
||||
# Build the actual table
|
||||
for T in Tv:
|
||||
values="%-10.2f" %(T-273.15)
|
||||
values = "%-10.2f" % (T - 273.15)
|
||||
for p in Pv:
|
||||
values+="%-20.10e" %(HAProps_Aux('vbar_ws',T,p,0.0)[0])
|
||||
values += "%-20.10e" % (HAProps_Aux('vbar_ws', T, p, 0.0)[0])
|
||||
print(values)
|
||||
|
||||
##########################################
|
||||
@@ -262,15 +262,15 @@ print("")
|
||||
print("Enhancement factor (f) [no units]")
|
||||
from CoolProp.HumidAirProp import HAProps_Aux
|
||||
import numpy as np
|
||||
Tv=np.array([-60,-40,-20,0,40,80,120,160,200,250,300,350])+273.15
|
||||
Pv=[101325,200000,500000,1000000,10000000]
|
||||
variables="%-10s"%(u'T')
|
||||
Tv = np.array([-60, -40, -20, 0, 40, 80, 120, 160, 200, 250, 300, 350]) + 273.15
|
||||
Pv = [101325, 200000, 500000, 1000000, 10000000]
|
||||
variables = "%-10s" % (u'T')
|
||||
for p in Pv:
|
||||
variables+="%-20s"%("p = %-0.3f Pa "%(p))
|
||||
variables += "%-20s" % ("p = %-0.3f Pa " % (p))
|
||||
print(variables)
|
||||
#Build the actual table
|
||||
# Build the actual table
|
||||
for T in Tv:
|
||||
values="%-10.2f" %(T-273.15)
|
||||
values = "%-10.2f" % (T - 273.15)
|
||||
for p in Pv:
|
||||
values+="%-20.10e" %(HAProps_Aux('f',T,p,0.0)[0])
|
||||
values += "%-20.10e" % (HAProps_Aux('f', T, p, 0.0)[0])
|
||||
print(values)
|
||||
|
||||
@@ -4,37 +4,37 @@ from CoolProp.HumidAirProp import HAProps
|
||||
print("Validation against H.F. Nelson and H.J. Sauer,\"Formulation for High-Temperature Properties for Moist Air\", HVAC&R Research v.8 #3, 2002")
|
||||
print("Note: More accurate formulation employed than in Nelson. Just for sanity checking")
|
||||
print("Yields a negative relative humidity for Tdb=5C,Twb=-3C, point omitted")
|
||||
tdb = [5,5,5,25,25,25,25,50,50,50,50,50,50,50]
|
||||
twb = [5,2,-1,25,20,15,10,50,40,30,25,22,20,19]
|
||||
tdb = [5, 5, 5, 25, 25, 25, 25, 50, 50, 50, 50, 50, 50, 50]
|
||||
twb = [5, 2, -1, 25, 20, 15, 10, 50, 40, 30, 25, 22, 20, 19]
|
||||
print(" ")
|
||||
print("Table 6: Adiabatic Saturation")
|
||||
print("P=101325 Pa, Altitude = 0 m")
|
||||
print("========================================================================")
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='W',Twb='Twb',Tdp='Tdp',Tdb='Tdb',v='v',h='h',s='s',R='RH'))
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='-',Twb='C',Tdp='C',Tdb='C',v='m^3/kg_da',h='kJ/kg_da',s='kJ/kg_da/K',R='%'))
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='W', Twb='Twb', Tdp='Tdp', Tdb='Tdb', v='v', h='h', s='s', R='RH'))
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='-', Twb='C', Tdp='C', Tdb='C', v='m^3/kg_da', h='kJ/kg_da', s='kJ/kg_da/K', R='%'))
|
||||
print("------------------------------------------------------------------------")
|
||||
for (tdb_,twb_) in zip(tdb,twb):
|
||||
h=HAProps('H','T',tdb_+273.13,'Twb',twb_+273.15,'P',101.325)
|
||||
tdp=HAProps('Tdp','T',tdb_+273.13,'Twb',twb_+273.15,'P',101.325)-273.15
|
||||
W=HAProps('W','T',tdb_+273.13,'Twb',twb_+273.15,'P',101.325)
|
||||
R=HAProps('R','T',tdb_+273.13,'Twb',twb_+273.15,'P',101.325)*100
|
||||
v=HAProps('V','T',tdb_+273.13,'Twb',twb_+273.15,'P',101.325)
|
||||
s=0
|
||||
print("{Tdb:10.2f}{Twb:10.2f}{Tdp:10.2f}{R:10.1f}{W:10.5f}{h:10.2f}{v:10.3f}".format(W=W,Twb=twb_,Tdp=tdp,Tdb=tdb_,v=v,h=h,s=s,R=R))
|
||||
for (tdb_, twb_) in zip(tdb, twb):
|
||||
h = HAProps('H', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 101.325)
|
||||
tdp = HAProps('Tdp', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 101.325) - 273.15
|
||||
W = HAProps('W', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 101.325)
|
||||
R = HAProps('R', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 101.325) * 100
|
||||
v = HAProps('V', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 101.325)
|
||||
s = 0
|
||||
print("{Tdb:10.2f}{Twb:10.2f}{Tdp:10.2f}{R:10.1f}{W:10.5f}{h:10.2f}{v:10.3f}".format(W=W, Twb=twb_, Tdp=tdp, Tdb=tdb_, v=v, h=h, s=s, R=R))
|
||||
print("------------------------------------------------------------------------")
|
||||
print(" ")
|
||||
print("Table 7: Adiabatic Saturation")
|
||||
print("P=84,556 Pa, Altitude = 1500 m")
|
||||
print("========================================================================")
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='W',Twb='Twb',Tdp='Tdp',Tdb='Tdb',v='v',h='h',s='s',R='RH'))
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='-',Twb='C',Tdp='C',Tdb='C',v='m^3/kg_da',h='kJ/kg_da',s='kJ/kg_da/K',R='%'))
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='W', Twb='Twb', Tdp='Tdp', Tdb='Tdb', v='v', h='h', s='s', R='RH'))
|
||||
print("{Tdb:10s}{Twb:10s}{Tdp:10s}{R:10s}{W:10s}{h:10s}{v:10s}".format(W='-', Twb='C', Tdp='C', Tdb='C', v='m^3/kg_da', h='kJ/kg_da', s='kJ/kg_da/K', R='%'))
|
||||
print("------------------------------------------------------------------------")
|
||||
for (tdb_,twb_) in zip(tdb,twb):
|
||||
h=HAProps('H','T',tdb_+273.13,'Twb',twb_+273.15,'P',84.556)
|
||||
tdp=HAProps('Tdp','T',tdb_+273.13,'Twb',twb_+273.15,'P',84.556)-273.15
|
||||
W=HAProps('W','T',tdb_+273.13,'Twb',twb_+273.15,'P',84.556)
|
||||
R=HAProps('R','T',tdb_+273.13,'Twb',twb_+273.15,'P',84.556)*100
|
||||
v=HAProps('V','T',tdb_+273.13,'Twb',twb_+273.15,'P',84.556)
|
||||
s=0
|
||||
print("{Tdb:10.2f}{Twb:10.2f}{Tdp:10.2f}{R:10.1f}{W:10.5f}{h:10.2f}{v:10.3f}".format(W=W,Twb=twb_,Tdp=tdp,Tdb=tdb_,v=v,h=h,s=s,R=R))
|
||||
for (tdb_, twb_) in zip(tdb, twb):
|
||||
h = HAProps('H', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 84.556)
|
||||
tdp = HAProps('Tdp', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 84.556) - 273.15
|
||||
W = HAProps('W', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 84.556)
|
||||
R = HAProps('R', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 84.556) * 100
|
||||
v = HAProps('V', 'T', tdb_ + 273.13, 'Twb', twb_ + 273.15, 'P', 84.556)
|
||||
s = 0
|
||||
print("{Tdb:10.2f}{Twb:10.2f}{Tdp:10.2f}{R:10.1f}{W:10.5f}{h:10.2f}{v:10.3f}".format(W=W, Twb=twb_, Tdp=tdp, Tdb=tdb_, v=v, h=h, s=s, R=R))
|
||||
print("------------------------------------------------------------------------")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import CoolProp.CoolProp as CP
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
HEOS = CP.AbstractState('HEOS','Methane&Ethane')
|
||||
HEOS = CP.AbstractState('HEOS', 'Methane&Ethane')
|
||||
|
||||
for x0 in [0.02, 0.2, 0.4, 0.6, 0.8, 0.98]:
|
||||
HEOS.set_mole_fractions([x0, 1 - x0])
|
||||
|
||||
@@ -9,15 +9,15 @@ from CoolProp.BibtexParser import BibTeXerClass
|
||||
|
||||
def getPath(filename, search=True):
|
||||
# Path to root
|
||||
coolprop_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..'))
|
||||
coolprop_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
# Test for file
|
||||
fname = filename
|
||||
if os.path.exists(fname): return os.path.abspath(fname)
|
||||
# Test relative to this file
|
||||
fname = os.path.join(os.path.dirname(__file__),filename)
|
||||
fname = os.path.join(os.path.dirname(__file__), filename)
|
||||
if os.path.exists(fname): return os.path.abspath(fname)
|
||||
# Test relative to root notation
|
||||
fname = os.path.join(coolprop_dir,filename)
|
||||
fname = os.path.join(coolprop_dir, filename)
|
||||
if os.path.exists(fname): return os.path.abspath(fname)
|
||||
# Search in root tree
|
||||
fname = os.path.basename(filename)
|
||||
@@ -26,9 +26,9 @@ def getPath(filename, search=True):
|
||||
for root, dirs, files in os.walk(coolprop_dir):
|
||||
if fname in files:
|
||||
result.append(os.path.join(root, fname))
|
||||
if len(result)==1:
|
||||
if len(result) == 1:
|
||||
return os.path.abspath(result[0])
|
||||
elif len(result)>1:
|
||||
elif len(result) > 1:
|
||||
print("Found multiple files with the name {0}. Try to specify the path as well.".format(fname))
|
||||
print(result)
|
||||
return os.path.abspath(result[0])
|
||||
@@ -36,7 +36,7 @@ def getPath(filename, search=True):
|
||||
raise ValueError("Found no file with the name {0}. Try to specify the path as well.".format(fname))
|
||||
|
||||
|
||||
def getBibtexParser(filename = '../../../CoolPropBibTeXLibrary.bib'):
|
||||
def getBibtexParser(filename='../../../CoolPropBibTeXLibrary.bib'):
|
||||
"""Create a parser object that can be used to extract entries from a
|
||||
library in Bibtex format."""
|
||||
fpath = getPath(filename)
|
||||
|
||||
@@ -2,7 +2,7 @@ import CoolProp
|
||||
import os
|
||||
import codecs
|
||||
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..'))
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
root_dir = os.path.abspath(os.path.join(web_dir, '..'))
|
||||
|
||||
fluid_template = u""".. _fluid_{fluid:s}:
|
||||
@@ -80,7 +80,7 @@ Reducing point temperature [K]; {Tr:s}
|
||||
Reducing point density [mol/m3]; {rhor_molar:s}
|
||||
"""
|
||||
|
||||
bibtex_keys = ['EOS','CP0','CONDUCTIVITY','VISCOSITY','MELTING_LINE','SURFACE_TENSION']
|
||||
bibtex_keys = ['EOS', 'CP0', 'CONDUCTIVITY', 'VISCOSITY', 'MELTING_LINE', 'SURFACE_TENSION']
|
||||
bibtex_map = {'EOS': 'Equation of State',
|
||||
'CP0': 'Ideal gas specific heat',
|
||||
'CONDUCTIVITY': 'Thermal Conductivity',
|
||||
@@ -90,10 +90,10 @@ bibtex_map = {'EOS': 'Equation of State',
|
||||
|
||||
from pybtex.database.input import bibtex
|
||||
parser = bibtex.Parser()
|
||||
bibdata = parser.parse_file(os.path.join(root_dir,"CoolPropBibTeXLibrary.bib"))
|
||||
bibdata = parser.parse_file(os.path.join(root_dir, "CoolPropBibTeXLibrary.bib"))
|
||||
|
||||
from CoolProp.BibtexParser import BibTeXerClass
|
||||
BTC = BibTeXerClass(os.path.join(root_dir,"CoolPropBibTeXLibrary.bib"))
|
||||
BTC = BibTeXerClass(os.path.join(root_dir, "CoolPropBibTeXLibrary.bib"))
|
||||
|
||||
# See http://stackoverflow.com/questions/19751402/does-pybtex-support-accent-special-characters-in-bib-file/19754245#19754245
|
||||
import pybtex
|
||||
@@ -104,7 +104,7 @@ parser = pybtex.database.input.bibtex.Parser()
|
||||
|
||||
def entry2html(entry):
|
||||
for e in entry:
|
||||
return e.text.render(backend).replace('{','').replace('}','').replace('\n', ' ')
|
||||
return e.text.render(backend).replace('{', '').replace('}', '').replace('\n', ' ')
|
||||
|
||||
|
||||
def generate_bibtex_string(fluid):
|
||||
@@ -114,14 +114,14 @@ def generate_bibtex_string(fluid):
|
||||
sect_strings = []
|
||||
try:
|
||||
# get the item
|
||||
bibtex_key = CoolProp.CoolProp.get_BibTeXKey(fluid,key).strip()
|
||||
bibtex_key = CoolProp.CoolProp.get_BibTeXKey(fluid, key).strip()
|
||||
for thekey in bibtex_key.split(','):
|
||||
if thekey.strip() in bibdata.entries.keys():
|
||||
html = BTC.getEntry(key=thekey.strip(), fmt='html')
|
||||
if len(sect_strings) == 0:
|
||||
sect = bibtex_map[key]
|
||||
header_string = sect+'\n'+'-'*len(sect)+'\n\n'
|
||||
sect_strings.append('.. raw:: html\n\n '+html+'\n\n')
|
||||
header_string = sect + '\n' + '-' * len(sect) + '\n\n'
|
||||
sect_strings.append('.. raw:: html\n\n ' + html + '\n\n')
|
||||
except ValueError as E:
|
||||
print("error: %s" % E)
|
||||
string += header_string + '\n\n.. raw:: html\n\n <br><br> \n\n'.join(sect_strings)
|
||||
@@ -139,25 +139,25 @@ class FluidInfoTableGenerator(object):
|
||||
''' convert number to nicely formatted string '''
|
||||
n = str(n)
|
||||
if 'e' in n:
|
||||
n = n.replace('e',':math:`\times 10^{')
|
||||
n = n.replace('e', ':math:`\times 10^{')
|
||||
n += '}`'
|
||||
else:
|
||||
return n
|
||||
return n
|
||||
molar_mass = CoolProp.CoolProp.PropsSI(self.name,'molemass')
|
||||
Tt = CoolProp.CoolProp.PropsSI(self.name,'Ttriple')
|
||||
Tc = CoolProp.CoolProp.PropsSI(self.name,'Tcrit')
|
||||
Tr = CoolProp.CoolProp.PropsSI(self.name,'T_reducing')
|
||||
pc = CoolProp.CoolProp.PropsSI(self.name,'pcrit')
|
||||
pt = CoolProp.CoolProp.PropsSI(self.name,'ptriple')
|
||||
molar_mass = CoolProp.CoolProp.PropsSI(self.name, 'molemass')
|
||||
Tt = CoolProp.CoolProp.PropsSI(self.name, 'Ttriple')
|
||||
Tc = CoolProp.CoolProp.PropsSI(self.name, 'Tcrit')
|
||||
Tr = CoolProp.CoolProp.PropsSI(self.name, 'T_reducing')
|
||||
pc = CoolProp.CoolProp.PropsSI(self.name, 'pcrit')
|
||||
pt = CoolProp.CoolProp.PropsSI(self.name, 'ptriple')
|
||||
if pt is None:
|
||||
pt = "Unknown"
|
||||
Tmax = CoolProp.CoolProp.PropsSI(self.name,'Tmax')
|
||||
pmax = CoolProp.CoolProp.PropsSI(self.name,'pmax')
|
||||
acentric = CoolProp.CoolProp.PropsSI(self.name,'acentric')
|
||||
rhoc_mass = CoolProp.CoolProp.PropsSI(self.name,'rhomass_critical')
|
||||
rhoc_molar = CoolProp.CoolProp.PropsSI(self.name,'rhomolar_critical')
|
||||
rhor_molar = CoolProp.CoolProp.PropsSI(self.name,'rhomolar_reducing')
|
||||
Tmax = CoolProp.CoolProp.PropsSI(self.name, 'Tmax')
|
||||
pmax = CoolProp.CoolProp.PropsSI(self.name, 'pmax')
|
||||
acentric = CoolProp.CoolProp.PropsSI(self.name, 'acentric')
|
||||
rhoc_mass = CoolProp.CoolProp.PropsSI(self.name, 'rhomass_critical')
|
||||
rhoc_molar = CoolProp.CoolProp.PropsSI(self.name, 'rhomolar_critical')
|
||||
rhor_molar = CoolProp.CoolProp.PropsSI(self.name, 'rhomolar_reducing')
|
||||
|
||||
CAS = CoolProp.CoolProp.get_fluid_param_string(self.name, "CAS")
|
||||
ASHRAE = CoolProp.CoolProp.get_fluid_param_string(self.name, "ASHRAE34")
|
||||
@@ -166,7 +166,7 @@ class FluidInfoTableGenerator(object):
|
||||
formula = ':math:`' + formula + '`'
|
||||
else:
|
||||
formula = 'Not applicable'
|
||||
formula = formula.replace('_{1}','')
|
||||
formula = formula.replace('_{1}', '')
|
||||
InChI = CoolProp.CoolProp.get_fluid_param_string(self.name, "INCHI")
|
||||
InChiKey = CoolProp.CoolProp.get_fluid_param_string(self.name, "INCHIKEY")
|
||||
smiles = CoolProp.CoolProp.get_fluid_param_string(self.name, "SMILES")
|
||||
@@ -176,33 +176,33 @@ class FluidInfoTableGenerator(object):
|
||||
# Generate (or not) the reducing data
|
||||
reducing_data = ''
|
||||
if abs(Tr - Tc) > 1e-3:
|
||||
reducing_data = reducing_template.format(Tr = tos(Tr),
|
||||
rhor_molar = tos(rhor_molar))
|
||||
reducing_data = reducing_template.format(Tr=tos(Tr),
|
||||
rhor_molar=tos(rhor_molar))
|
||||
|
||||
args = dict(mm = tos(molar_mass),
|
||||
Tt = tos(Tt),
|
||||
pt = tos(pt),
|
||||
Tc = tos(Tc),
|
||||
rhoc_mass = tos(rhoc_mass),
|
||||
rhoc_molar = tos(rhoc_molar),
|
||||
pc = tos(pc),
|
||||
acentric = tos(acentric),
|
||||
CAS = tos(CAS),
|
||||
ASHRAE = tos(ASHRAE),
|
||||
Tmax = tos(Tmax),
|
||||
pmax = tos(pmax),
|
||||
reducing_string = reducing_data,
|
||||
formula = formula,
|
||||
inchi = InChI,
|
||||
inchikey = InChiKey,
|
||||
smiles = smiles,
|
||||
ChemSpider_id = ChemSpider_id,
|
||||
twoDurl = twoDurl
|
||||
args = dict(mm=tos(molar_mass),
|
||||
Tt=tos(Tt),
|
||||
pt=tos(pt),
|
||||
Tc=tos(Tc),
|
||||
rhoc_mass=tos(rhoc_mass),
|
||||
rhoc_molar=tos(rhoc_molar),
|
||||
pc=tos(pc),
|
||||
acentric=tos(acentric),
|
||||
CAS=tos(CAS),
|
||||
ASHRAE=tos(ASHRAE),
|
||||
Tmax=tos(Tmax),
|
||||
pmax=tos(pmax),
|
||||
reducing_string=reducing_data,
|
||||
formula=formula,
|
||||
inchi=InChI,
|
||||
inchikey=InChiKey,
|
||||
smiles=smiles,
|
||||
ChemSpider_id=ChemSpider_id,
|
||||
twoDurl=twoDurl
|
||||
)
|
||||
out = table_template.format(**args)
|
||||
|
||||
with open(os.path.join(path, self.name+'-info.csv'),'w') as fp:
|
||||
print("writing %s" % os.path.join(path, self.name+'-info.csv'))
|
||||
with open(os.path.join(path, self.name + '-info.csv'), 'w') as fp:
|
||||
print("writing %s" % os.path.join(path, self.name + '-info.csv'))
|
||||
fp.write(out)
|
||||
|
||||
|
||||
@@ -218,19 +218,19 @@ class FluidGenerator(object):
|
||||
|
||||
aliases = ', '.join(['``' + a.strip() + '``' for a in CoolProp.CoolProp.get_fluid_param_string(self.fluid, 'aliases').strip().split(',') if a])
|
||||
if aliases:
|
||||
aliases = 'Aliases\n=======\n\n'+aliases + '\n'
|
||||
aliases = 'Aliases\n=======\n\n' + aliases + '\n'
|
||||
|
||||
references = generate_bibtex_string(self.fluid)
|
||||
if references:
|
||||
references = 'References\n==========\n'+references+'\n'
|
||||
references = 'References\n==========\n' + references + '\n'
|
||||
|
||||
# Write RST file for fluid
|
||||
out = fluid_template.format(aliases = aliases,
|
||||
fluid = self.fluid,
|
||||
fluid_stars = '*'*len(self.fluid),
|
||||
references = references
|
||||
out = fluid_template.format(aliases=aliases,
|
||||
fluid=self.fluid,
|
||||
fluid_stars='*' * len(self.fluid),
|
||||
references=references
|
||||
)
|
||||
|
||||
with codecs.open(os.path.join(path, self.fluid+'.rst'), 'w', encoding='utf-8') as fp:
|
||||
print("writing %s" % os.path.join(path, self.fluid+'.rst'))
|
||||
with codecs.open(os.path.join(path, self.fluid + '.rst'), 'w', encoding='utf-8') as fp:
|
||||
print("writing %s" % os.path.join(path, self.fluid + '.rst'))
|
||||
fp.write(out)
|
||||
|
||||
@@ -11,5 +11,5 @@ def get_version():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print('You are using version %s of the Python package for creating CoolProp\' online documentation.'%(get_version()))
|
||||
print('You are using version %s of the Python package for creating CoolProp\' online documentation.' % (get_version()))
|
||||
print()
|
||||
|
||||
@@ -4,9 +4,9 @@ import os.path, glob, subprocess, sys, time, datetime, pytz
|
||||
#
|
||||
if len(sys.argv) < 2:
|
||||
full_rebuild = False
|
||||
if len(sys.argv)== 2:
|
||||
if sys.argv[1]=="True": full_rebuild = True
|
||||
elif sys.argv[1]=="1" : full_rebuild = True
|
||||
if len(sys.argv) == 2:
|
||||
if sys.argv[1] == "True": full_rebuild = True
|
||||
elif sys.argv[1] == "1": full_rebuild = True
|
||||
else: full_rebuild = False
|
||||
if len(sys.argv) > 2:
|
||||
full_rebuild = False
|
||||
@@ -26,10 +26,10 @@ def get_ftime(fname):
|
||||
|
||||
|
||||
#
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
|
||||
script_dir = os.path.abspath(os.path.join(web_dir,'scripts'))
|
||||
touch_file = os.path.abspath(os.path.join(script_dir,'last_run'))
|
||||
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..'))
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
script_dir = os.path.abspath(os.path.join(web_dir, 'scripts'))
|
||||
touch_file = os.path.abspath(os.path.join(script_dir, 'last_run'))
|
||||
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
#
|
||||
cur_time = time.time()
|
||||
fil_time = get_ftime(touch_file)
|
||||
@@ -37,8 +37,8 @@ fil_time = get_ftime(touch_file)
|
||||
# Static execution time
|
||||
#reg_hour = time.strftime("%H")
|
||||
#reg_minute = time.strftime("%M")
|
||||
#sch_hour = 12 #scheduled hour = 3am Boulder = 12pm CPH
|
||||
#sch_minute = 7 #scheduled minute = 7 past
|
||||
# sch_hour = 12 #scheduled hour = 3am Boulder = 12pm CPH
|
||||
# sch_minute = 7 #scheduled minute = 7 past
|
||||
#
|
||||
# Dynamically calculated execution (includes daylight saving time etc
|
||||
masterTime = pytz.timezone('US/Pacific')
|
||||
@@ -46,14 +46,14 @@ masterTime = pytz.timezone('US/Pacific')
|
||||
now_master = datetime.datetime.now(masterTime)
|
||||
run_master = datetime.datetime.strptime("03:00:00", '%H:%M:%S')
|
||||
#
|
||||
now_master = datetime.time(now_master.hour, now_master.minute , now_master.second)
|
||||
run_master = datetime.time(run_master.hour, run_master.minute , run_master.second)
|
||||
run_master_end = datetime.time(run_master.hour, run_master.minute+5, run_master.second)
|
||||
now_master = datetime.time(now_master.hour, now_master.minute, now_master.second)
|
||||
run_master = datetime.time(run_master.hour, run_master.minute, run_master.second)
|
||||
run_master_end = datetime.time(run_master.hour, run_master.minute + 5, run_master.second)
|
||||
#
|
||||
lim_days = 0.90
|
||||
lim_time = cur_time - 60*60*24*lim_days # seconds
|
||||
lim_time = cur_time - 60 * 60 * 24 * lim_days # seconds
|
||||
#
|
||||
if now_master >= run_master and \
|
||||
if now_master >= run_master and \
|
||||
now_master <= run_master_end and \
|
||||
not full_rebuild:
|
||||
print("This is a scheduled rebuild at {0}.".format(run_master))
|
||||
@@ -61,21 +61,21 @@ if now_master >= run_master and \
|
||||
else: print("It looks like the files have been rebuilt during the last day.")
|
||||
#
|
||||
lim_days = 3
|
||||
lim_time = cur_time - 60*60*24*lim_days # seconds
|
||||
lim_time = cur_time - 60 * 60 * 24 * lim_days # seconds
|
||||
if fil_time < lim_time and not full_rebuild:
|
||||
print("The static files have not been updated in {0} days, forcing an update now.".format(lim_days))
|
||||
full_rebuild = True
|
||||
|
||||
#req_dir = [os.path.abspath(os.path.join(web_dir,'_static','fluid_properties','Incompressibles_reports'))]
|
||||
#req_fil = [os.path.abspath(os.path.join(web_dir,'fluid_properties','Mixtures.csv')),
|
||||
# req_fil = [os.path.abspath(os.path.join(web_dir,'fluid_properties','Mixtures.csv')),
|
||||
# os.path.abspath(os.path.join(web_dir,'fluid_properties','PurePseudoPure.csv')),
|
||||
# os.path.abspath(os.path.join(web_dir,'fluid_properties','Incompressibles_pure-fluids.csv'))]
|
||||
#
|
||||
#for d in req_dir:
|
||||
# for d in req_dir:
|
||||
# if not os.path.exists(d) and not full_rebuild:
|
||||
# print "The required directory {0} is missing, trying to rebuild it.".format(d)
|
||||
# full_rebuild = True
|
||||
#for f in req_fil:
|
||||
# for f in req_fil:
|
||||
# if not os.path.exists(f):
|
||||
# print "The required file {0} is missing, trying to rebuild it.".format(f)
|
||||
# full_rebuild = True
|
||||
@@ -95,9 +95,9 @@ def run_script(path):
|
||||
file_extension = path.split(".")[-1]
|
||||
#file_name, file_extension = os.path.splitext(path)
|
||||
|
||||
if file_extension.lower()=="py":
|
||||
if file_extension.lower() == "py":
|
||||
subprocess.check_call('python -u {0}'.format(file_name), cwd=file_path, shell=True)
|
||||
elif file_extension.lower()=="sh" or file_extension.lower()=="bsh":
|
||||
elif file_extension.lower() == "sh" or file_extension.lower() == "bsh":
|
||||
subprocess.check_call('chmod +x {0}'.format(file_name), cwd=file_path, shell=True)
|
||||
subprocess.check_call('./{0}'.format(file_name), cwd=file_path, shell=True)
|
||||
else:
|
||||
@@ -109,23 +109,23 @@ def run_script(path):
|
||||
# Inject the version of CoolProp into the doxygen configuration files
|
||||
# Put it at the end, overwrites prior value
|
||||
import CoolProp
|
||||
with open(os.path.join(root_dir,'Doxyfile'),'a+') as fp:
|
||||
with open(os.path.join(root_dir, 'Doxyfile'), 'a+') as fp:
|
||||
fp.write('\n\n PROJECT_NUMBER = ' + CoolProp.__version__ + '\n')
|
||||
|
||||
# The normal tasks that are carried out each time the script runs
|
||||
normal_tasks = ["../../dev/scripts/examples/LinuxRun.py","coolprop.tabular.speed.py", "fluid_properties.phase_envelope.py", "fluid_properties.PurePseudoPure.py", "fluid_properties.Mixtures.py","coolprop.parametric_table.py","coolprop.configuration.py"]
|
||||
normal_tasks = ["../../dev/scripts/examples/LinuxRun.py", "coolprop.tabular.speed.py", "fluid_properties.phase_envelope.py", "fluid_properties.PurePseudoPure.py", "fluid_properties.Mixtures.py", "coolprop.parametric_table.py", "coolprop.configuration.py"]
|
||||
# The expensive tasks that are fired when full_rebuild is True
|
||||
expensive_tasks = ["fluid_properties.Consistency.py", "fluid_properties.Incompressibles.sh", "logo_2014.py", "fluid_properties.REFPROPcomparison.py"]
|
||||
print("Executing the normal scripts for generating static files.")
|
||||
for script in normal_tasks:
|
||||
print("Executing {0}".format(script))
|
||||
run_script(os.path.normpath(os.path.join(script_dir,script)))
|
||||
run_script(os.path.normpath(os.path.join(script_dir, script)))
|
||||
#
|
||||
if full_rebuild:
|
||||
print("Executing the computationally expensive scripts for generating the static files.")
|
||||
for script in expensive_tasks:
|
||||
print("Executing {0}".format(script))
|
||||
run_script(os.path.join(script_dir,script))
|
||||
run_script(os.path.join(script_dir, script))
|
||||
touch(touch_file)
|
||||
else:
|
||||
print("Skipping the computationally expensive scripts for generating the static files.")
|
||||
|
||||
@@ -7,7 +7,7 @@ grouping2 = []
|
||||
for parameter in CoolProp.get('parameter_list').split(','):
|
||||
|
||||
index = CoolProp.CoolProp.get_parameter_index(parameter)
|
||||
units = CoolProp.CoolProp.get_parameter_information(index, 'units').replace('-',' ')
|
||||
units = CoolProp.CoolProp.get_parameter_information(index, 'units').replace('-', ' ')
|
||||
IO = CoolProp.CoolProp.get_parameter_information(index, 'IO')
|
||||
long = CoolProp.CoolProp.get_parameter_information(index, 'long')
|
||||
short = CoolProp.CoolProp.get_parameter_information(index, 'short')
|
||||
@@ -20,12 +20,12 @@ for parameter in CoolProp.get('parameter_list').split(','):
|
||||
grouping[RHS].append(parameter)
|
||||
|
||||
for k, v in six.iteritems(grouping):
|
||||
grouping2.append([', '.join(['``'+_+'``' for _ in v])] + list(k))
|
||||
grouping2.append([', '.join(['``' + _ + '``' for _ in v])] + list(k))
|
||||
|
||||
headers = ['Parameter','Units','Input/Output','Trivial','Description']
|
||||
headers = ['Parameter', 'Units', 'Input/Output', 'Trivial', 'Description']
|
||||
|
||||
df3 = pandas.DataFrame(grouping2, columns = headers)
|
||||
df4 = df3.sort_values(by = ['Input/Output', 'Parameter'])
|
||||
df3 = pandas.DataFrame(grouping2, columns=headers)
|
||||
df4 = df3.sort_values(by=['Input/Output', 'Parameter'])
|
||||
grouping2 = [row for row in df4.values]
|
||||
|
||||
N = []
|
||||
@@ -36,8 +36,8 @@ for i in range(len(N)):
|
||||
if N[i] < len(headers[i]):
|
||||
N[i] = len(headers[i])
|
||||
|
||||
top_line = '='*N[0] + ' ' + '='*N[1] + ' ' + '='*N[2] + ' ' + '='*N[3] + ' ' + '='*N[4]
|
||||
header = ' '.join([h.ljust(n) for h,n in zip(headers,N)])
|
||||
top_line = '=' * N[0] + ' ' + '=' * N[1] + ' ' + '=' * N[2] + ' ' + '=' * N[3] + ' ' + '=' * N[4]
|
||||
header = ' '.join([h.ljust(n) for h, n in zip(headers, N)])
|
||||
|
||||
fp = open('../coolprop/parameter_table.rst.in', 'w')
|
||||
fp.write('.. constructed with the coolprop.parameter_table.py script in the web/scripts folder \n\n')
|
||||
@@ -45,6 +45,6 @@ fp.write(top_line + '\n')
|
||||
fp.write(header + '\n')
|
||||
fp.write(top_line + '\n')
|
||||
for line in grouping2:
|
||||
fp.write(' '.join([h.ljust(n) for h,n in zip(line,N)]) + '\n')
|
||||
fp.write(' '.join([h.ljust(n) for h, n in zip(line, N)]) + '\n')
|
||||
fp.write(top_line + '\n')
|
||||
fp.close()
|
||||
|
||||
@@ -5,5 +5,5 @@ import AbstractStateTTSE
|
||||
|
||||
shutil.copy2('../../dev/TTSE/AbstractStateTTSE.py', '../coolprop/speed_script.py')
|
||||
|
||||
with open('../coolprop/tabular_data.rst.in','w') as fp:
|
||||
with open('../coolprop/tabular_data.rst.in', 'w') as fp:
|
||||
fp.write(AbstractStateTTSE.generate_rst())
|
||||
|
||||
@@ -6,8 +6,8 @@ import sys
|
||||
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
root_dir = os.path.abspath(os.path.join(web_dir, '..'))
|
||||
fluids_path = os.path.join(web_dir,'fluid_properties','fluids')
|
||||
plots_path = os.path.join(web_dir,'fluid_properties','fluids','Consistencyplots')
|
||||
fluids_path = os.path.join(web_dir, 'fluid_properties', 'fluids')
|
||||
plots_path = os.path.join(web_dir, 'fluid_properties', 'fluids', 'Consistencyplots')
|
||||
|
||||
template = """from __future__ import division, print_function
|
||||
import matplotlib
|
||||
@@ -27,10 +27,10 @@ if not os.path.exists(plots_path):
|
||||
|
||||
for fluid in CoolProp.__fluids__:
|
||||
print('fluid:', fluid)
|
||||
file_string = template.format(fluid = fluid)
|
||||
file_string = template.format(fluid=fluid)
|
||||
file_path = os.path.join(plots_path, fluid + '.py')
|
||||
print('Writing to', file_path)
|
||||
with open(file_path, 'w') as fp:
|
||||
fp.write(file_string)
|
||||
print('calling:', 'python "' + fluid + '.py"', 'in',plots_path)
|
||||
subprocess.check_call('python -u "' + fluid + '.py"', cwd = plots_path, stdout = sys.stdout, stderr = sys.stderr, shell = True)
|
||||
print('calling:', 'python "' + fluid + '.py"', 'in', plots_path)
|
||||
subprocess.check_call('python -u "' + fluid + '.py"', cwd=plots_path, stdout=sys.stdout, stderr=sys.stderr, shell=True)
|
||||
|
||||
@@ -8,12 +8,12 @@ import sys
|
||||
import numpy as np
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use('Agg') #Force mpl to use a non-GUI backend
|
||||
matplotlib.use('Agg') # Force mpl to use a non-GUI backend
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
#plots_path = os.path.join(web_dir,'fluid_properties','incompressibles_consistency')
|
||||
plots_path = os.path.join(web_dir,'scripts','incompressibles_consistency')
|
||||
plots_path = os.path.join(web_dir, 'scripts', 'incompressibles_consistency')
|
||||
|
||||
checked = ["TVP1869", "T66"]
|
||||
|
||||
@@ -37,47 +37,47 @@ cp_axis = fig.add_subplot(224)
|
||||
|
||||
Pr_axis.set_xlabel("Temperature $T$ / deg C")
|
||||
Pr_axis.set_ylabel("Prandtl Number $Pr$")
|
||||
#Pr_axis.set_ylim([0,10000])
|
||||
#Pr_axis.set_yscale("log")
|
||||
# Pr_axis.set_ylim([0,10000])
|
||||
# Pr_axis.set_yscale("log")
|
||||
la_axis.set_xlabel("Temperature $T$ / deg C")
|
||||
la_axis.set_ylabel("Thermal Conductivity $\lambda$ / W/m/K")
|
||||
#la_axis.set_ylim([0,1])
|
||||
# la_axis.set_ylim([0,1])
|
||||
mu_axis.set_xlabel("Temperature $T$ / deg C")
|
||||
mu_axis.set_ylabel("Dynamic Viscosity $\mu$ / Pa s")
|
||||
#mu_axis.set_ylim([0,1])
|
||||
#mu_axis.set_yscale("log")
|
||||
# mu_axis.set_ylim([0,1])
|
||||
# mu_axis.set_yscale("log")
|
||||
cp_axis.set_xlabel("Temperature $T$ / deg C")
|
||||
cp_axis.set_ylabel("Isobaric Heat Capacity $c_p$ / J/kg/K")
|
||||
#cp_axis.set_ylim([0,5000])
|
||||
# cp_axis.set_ylim([0,5000])
|
||||
|
||||
for fluid in CoolProp.__incompressibles_pure__ + CoolProp.__incompressibles_solution__:
|
||||
#for fluid in CoolProp.__incompressibles_solution__:
|
||||
#for fluid in CoolProp.__incompressibles_pure__:
|
||||
# for fluid in CoolProp.__incompressibles_solution__:
|
||||
# for fluid in CoolProp.__incompressibles_pure__:
|
||||
skip_fluid = False
|
||||
for ignored in ["example","iceea","icena","icepg"]:
|
||||
for ignored in ["example", "iceea", "icena", "icepg"]:
|
||||
if ignored in fluid.lower():
|
||||
skip_fluid = True
|
||||
if skip_fluid:
|
||||
continue
|
||||
state = CoolProp.AbstractState("INCOMP",fluid)
|
||||
state = CoolProp.AbstractState("INCOMP", fluid)
|
||||
error = ""
|
||||
for frac in [0.5,0.2,0.8,0.1,0.9]:
|
||||
for frac in [0.5, 0.2, 0.8, 0.1, 0.9]:
|
||||
error = ""
|
||||
try:
|
||||
state.set_mass_fractions([frac])
|
||||
state.update(CoolProp.PT_INPUTS,p,state.Tmax())
|
||||
state.update(CoolProp.PT_INPUTS, p, state.Tmax())
|
||||
break
|
||||
except Exception as e:
|
||||
error = e.message
|
||||
try:
|
||||
state.set_volu_fractions([frac])
|
||||
state.update(CoolProp.PT_INPUTS,p,state.Tmax())
|
||||
state.update(CoolProp.PT_INPUTS, p, state.Tmax())
|
||||
break
|
||||
except Exception as e:
|
||||
error = e.message
|
||||
try:
|
||||
state.set_mole_fractions([frac])
|
||||
state.update(CoolProp.PT_INPUTS,p,state.Tmax())
|
||||
state.update(CoolProp.PT_INPUTS, p, state.Tmax())
|
||||
break
|
||||
except Exception as e:
|
||||
error = e.message
|
||||
@@ -88,9 +88,9 @@ for fluid in CoolProp.__incompressibles_pure__ + CoolProp.__incompressibles_solu
|
||||
Tmin = state.keyed_output(CoolProp.iT_freeze)
|
||||
except:
|
||||
pass
|
||||
Tmin = max(state.Tmin(), Tmin)+1
|
||||
Tmin = max(state.Tmin(), Tmin) + 1
|
||||
Tmax = state.Tmax()
|
||||
T = np.linspace(Tmin,Tmax, N)
|
||||
T = np.linspace(Tmin, Tmax, N)
|
||||
for i, Ti in enumerate(T):
|
||||
state.update(CoolProp.PT_INPUTS, p, Ti)
|
||||
Pr[i] = state.Prandtl()
|
||||
@@ -98,41 +98,41 @@ for fluid in CoolProp.__incompressibles_pure__ + CoolProp.__incompressibles_solu
|
||||
mu[i] = state.viscosity()
|
||||
cp[i] = state.cpmass()
|
||||
#print(np.min(Pr), np.max(Pr))
|
||||
Pr_axis.plot(T-273.15,Pr)
|
||||
la_axis.plot(T-273.15,la)
|
||||
mu_axis.plot(T-273.15,mu)
|
||||
cp_axis.plot(T-273.15,cp)
|
||||
Pr_axis.plot(T - 273.15, Pr)
|
||||
la_axis.plot(T - 273.15, la)
|
||||
mu_axis.plot(T - 273.15, mu)
|
||||
cp_axis.plot(T - 273.15, cp)
|
||||
|
||||
if np.max(Pr)>10000:
|
||||
if np.max(Pr) > 10000:
|
||||
if fluid not in checked:
|
||||
print("Very high Prandtl number for {0:s} of {1:f}".format(fluid,np.max(Pr)))
|
||||
if np.min(Pr)<0.0:
|
||||
print("Very high Prandtl number for {0:s} of {1:f}".format(fluid, np.max(Pr)))
|
||||
if np.min(Pr) < 0.0:
|
||||
if fluid not in checked:
|
||||
print("Very low Prandtl number for {0:s} of {1:f}".format(fluid,np.min(Pr)))
|
||||
if np.max(la)>0.8:
|
||||
print("Very low Prandtl number for {0:s} of {1:f}".format(fluid, np.min(Pr)))
|
||||
if np.max(la) > 0.8:
|
||||
if fluid not in checked:
|
||||
print("Very high thermal conductivity for {0:s} of {1:f}".format(fluid,np.max(la)))
|
||||
if np.min(la)<0.3:
|
||||
print("Very high thermal conductivity for {0:s} of {1:f}".format(fluid, np.max(la)))
|
||||
if np.min(la) < 0.3:
|
||||
if fluid not in checked:
|
||||
print("Very low thermal conductivity for {0:s} of {1:f}".format(fluid,np.min(la)))
|
||||
if np.max(mu)>0.2:
|
||||
print("Very low thermal conductivity for {0:s} of {1:f}".format(fluid, np.min(la)))
|
||||
if np.max(mu) > 0.2:
|
||||
if fluid not in checked:
|
||||
print("Very high viscosity for {0:s} of {1:f}".format(fluid,np.max(mu)))
|
||||
if np.min(mu)<1e-8:
|
||||
print("Very high viscosity for {0:s} of {1:f}".format(fluid, np.max(mu)))
|
||||
if np.min(mu) < 1e-8:
|
||||
if fluid not in checked:
|
||||
print("Very low viscosity for {0:s} of {1:f}".format(fluid,np.min(mu)))
|
||||
if np.max(cp)>5000:
|
||||
print("Very low viscosity for {0:s} of {1:f}".format(fluid, np.min(mu)))
|
||||
if np.max(cp) > 5000:
|
||||
if fluid not in checked:
|
||||
print("Very high heat capacity for {0:s} of {1:f}".format(fluid,np.max(cp)))
|
||||
if np.min(cp)<1000:
|
||||
print("Very high heat capacity for {0:s} of {1:f}".format(fluid, np.max(cp)))
|
||||
if np.min(cp) < 1000:
|
||||
if fluid not in checked:
|
||||
print("Very low heat capacity for {0:s} of {1:f}".format(fluid,np.min(cp)))
|
||||
print("Very low heat capacity for {0:s} of {1:f}".format(fluid, np.min(cp)))
|
||||
|
||||
#for fluid in CoolProp.__fluids__:
|
||||
# for fluid in CoolProp.__fluids__:
|
||||
for fluid in ["Water"]:
|
||||
state = CoolProp.AbstractState("HEOS",fluid)
|
||||
Tmin = max(state.Tmin(), Pr_axis.get_xlim()[0]+273.15)
|
||||
Tmax = min(state.Tmax(), Pr_axis.get_xlim()[1]+273.15)
|
||||
state = CoolProp.AbstractState("HEOS", fluid)
|
||||
Tmin = max(state.Tmin(), Pr_axis.get_xlim()[0] + 273.15)
|
||||
Tmax = min(state.Tmax(), Pr_axis.get_xlim()[1] + 273.15)
|
||||
|
||||
T = np.linspace(Tmin, Tmax, N)
|
||||
for i, Ti in enumerate(T):
|
||||
@@ -167,28 +167,28 @@ for fluid in ["Water"]:
|
||||
pass
|
||||
#print(np.min(Pr), np.max(Pr))
|
||||
if np.sum(np.isnan(Pr)) == 0:
|
||||
Pr_axis.plot(T-273.15,Pr,alpha=0.5,ls=":")
|
||||
Pr_axis.plot(T - 273.15, Pr, alpha=0.5, ls=":")
|
||||
else:
|
||||
#print("Error: Prandtl undefined for "+fluid)
|
||||
pass
|
||||
if np.sum(np.isnan(la)) == 0:
|
||||
la_axis.plot(T-273.15,la,alpha=0.5,ls=":")
|
||||
la_axis.plot(T - 273.15, la, alpha=0.5, ls=":")
|
||||
else:
|
||||
#print("Error: Conductivuty undefined for "+fluid)
|
||||
pass
|
||||
if np.sum(np.isnan(mu)) == 0:
|
||||
mu_axis.plot(T-273.15,mu,alpha=0.5,ls=":")
|
||||
mu_axis.plot(T - 273.15, mu, alpha=0.5, ls=":")
|
||||
else:
|
||||
#print("Error: Viscosity undefined for "+fluid)
|
||||
pass
|
||||
if np.sum(np.isnan(cp)) == 0:
|
||||
cp_axis.plot(T-273.15,cp,alpha=0.5,ls=":")
|
||||
cp_axis.plot(T - 273.15, cp, alpha=0.5, ls=":")
|
||||
else:
|
||||
#print("Error: Heat capacity undefined for "+fluid)
|
||||
pass
|
||||
|
||||
|
||||
fig.tight_layout()
|
||||
fig.savefig(plots_path+'.pdf')
|
||||
#fig.savefig(plots_path+'.png')
|
||||
fig.savefig(plots_path + '.pdf')
|
||||
# fig.savefig(plots_path+'.png')
|
||||
sys.exit(0)
|
||||
|
||||
@@ -4,8 +4,8 @@ from CPWeb.BibtexTools import getCitationOrAlternative, getBibtexParser
|
||||
import CoolProp
|
||||
import os.path
|
||||
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
|
||||
csvfile = os.path.join(web_dir,'fluid_properties','Mixtures.csv')
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
csvfile = os.path.join(web_dir, 'fluid_properties', 'Mixtures.csv')
|
||||
|
||||
|
||||
def merge_args(*args):
|
||||
@@ -14,12 +14,12 @@ def merge_args(*args):
|
||||
|
||||
def printCoeff(number):
|
||||
if number is None or \
|
||||
len(str(number).strip())<1:
|
||||
len(str(number).strip()) < 1:
|
||||
return " "
|
||||
number = float(number)
|
||||
short = "{0:.4e}".format(number)
|
||||
long = "{0:.14e}".format(number)
|
||||
return u':raw-html:`<span title="{1}">{0}</span>`'.format(short,long)
|
||||
long = "{0:.14e}".format(number)
|
||||
return u':raw-html:`<span title="{1}">{0}</span>`'.format(short, long)
|
||||
|
||||
|
||||
class Dossier:
|
||||
@@ -40,7 +40,7 @@ for pair in pairs.split(','):
|
||||
CAS1, CAS2 = pair.split('&')
|
||||
d.add('CAS1', CAS1)
|
||||
d.add('CAS2', CAS2)
|
||||
for key in ['name1','name2','F','function','BibTeX','xi','zeta','betaT','betaV','gammaT','gammaV']:
|
||||
for key in ['name1', 'name2', 'F', 'function', 'BibTeX', 'xi', 'zeta', 'betaT', 'betaV', 'gammaT', 'gammaV']:
|
||||
try:
|
||||
d.add(key, CoolProp.CoolProp.get_mixture_binary_pair_data(CAS1, CAS2, key))
|
||||
except BaseException as BE:
|
||||
@@ -48,27 +48,27 @@ for pair in pairs.split(','):
|
||||
|
||||
import pandas
|
||||
df = pandas.DataFrame(d.data)
|
||||
df = df.sort_values(by=['BibTeX','name1'], ascending = [0, 1])
|
||||
df = df.sort_values(by=['BibTeX', 'name1'], ascending=[0, 1])
|
||||
|
||||
bibtexer = getBibtexParser()#filename = '../../../CoolPropBibTeXLibrary.bib')
|
||||
bibtexer = getBibtexParser() # filename = '../../../CoolPropBibTeXLibrary.bib')
|
||||
|
||||
with open(csvfile,'w') as fp:
|
||||
with open(csvfile, 'w') as fp:
|
||||
header = 'Ref.,Name1,Name2,function,F,'
|
||||
header += merge_args("xi","zeta,")
|
||||
header += merge_args("betaT","betaV,")
|
||||
header += merge_args("gammaT","gammaV")
|
||||
header += merge_args("xi", "zeta,")
|
||||
header += merge_args("betaT", "betaV,")
|
||||
header += merge_args("gammaT", "gammaV")
|
||||
header += '\n'
|
||||
fp.write(header)
|
||||
|
||||
for index, row in df.iterrows():
|
||||
text = ','.join([ \
|
||||
getCitationOrAlternative(bibtexer,row['BibTeX']),
|
||||
getCitationOrAlternative(bibtexer, row['BibTeX']),
|
||||
row['name1'],
|
||||
row['name2'],
|
||||
row['function'],
|
||||
row['F'],
|
||||
merge_args(printCoeff(row['xi']),printCoeff(row['zeta'])),
|
||||
merge_args(printCoeff(row['betaT']),printCoeff(row['betaV'])),
|
||||
merge_args(printCoeff(row['gammaT']),printCoeff(row['gammaV']))
|
||||
])+'\n'
|
||||
merge_args(printCoeff(row['xi']), printCoeff(row['zeta'])),
|
||||
merge_args(printCoeff(row['betaT']), printCoeff(row['betaV'])),
|
||||
merge_args(printCoeff(row['gammaT']), printCoeff(row['gammaV']))
|
||||
]) + '\n'
|
||||
fp.write(text)
|
||||
|
||||
@@ -3,10 +3,10 @@ from CPWeb.SphinxTools import FluidGenerator
|
||||
import os.path
|
||||
import CoolProp
|
||||
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
root_dir = os.path.abspath(os.path.join(web_dir, '..'))
|
||||
csvfile = os.path.join(web_dir,'fluid_properties','PurePseudoPure.csv')
|
||||
indexfile = os.path.join(web_dir,'fluid_properties', 'fluidstoc.rst.in')
|
||||
csvfile = os.path.join(web_dir, 'fluid_properties', 'PurePseudoPure.csv')
|
||||
indexfile = os.path.join(web_dir, 'fluid_properties', 'fluidstoc.rst.in')
|
||||
|
||||
|
||||
class Dossier:
|
||||
@@ -23,7 +23,7 @@ d = Dossier()
|
||||
|
||||
from pybtex.database.input import bibtex
|
||||
parser = bibtex.Parser()
|
||||
bibdata = parser.parse_file(os.path.join(root_dir,"CoolPropBibTeXLibrary.bib"))
|
||||
bibdata = parser.parse_file(os.path.join(root_dir, "CoolPropBibTeXLibrary.bib"))
|
||||
|
||||
bibtexer = getBibtexParser()
|
||||
|
||||
@@ -33,9 +33,9 @@ bibtex_map = {'EOS': 'EOS',
|
||||
'VISCOSITY': ':math:`\eta`',
|
||||
'MELTING_LINE': 'melt',
|
||||
'SURFACE_TENSION': ':math:`\sigma`'}
|
||||
bibtex_keys = ['EOS','CP0','CONDUCTIVITY','VISCOSITY','MELTING_LINE','SURFACE_TENSION']
|
||||
bibtex_keys = ['EOS', 'CP0', 'CONDUCTIVITY', 'VISCOSITY', 'MELTING_LINE', 'SURFACE_TENSION']
|
||||
|
||||
fluids_path = os.path.join(web_dir,'fluid_properties','fluids')
|
||||
fluids_path = os.path.join(web_dir, 'fluid_properties', 'fluids')
|
||||
if not os.path.exists(fluids_path):
|
||||
os.makedirs(fluids_path)
|
||||
|
||||
@@ -48,10 +48,10 @@ for fluid in CoolProp.__fluids__:
|
||||
for key in bibtex_keys:
|
||||
try:
|
||||
# get the item
|
||||
s = CoolProp.CoolProp.get_BibTeXKey(fluid,key)
|
||||
s = CoolProp.CoolProp.get_BibTeXKey(fluid, key)
|
||||
s = s.strip()
|
||||
if s and any([_s not in bibdata.entries.keys() for _s in s.split(',')]):
|
||||
print("problem %s %s %s %s" % (fluid, key, '\t\t\t\t', "|"+s+'|'))
|
||||
print("problem %s %s %s %s" % (fluid, key, '\t\t\t\t', "|" + s + '|'))
|
||||
d.add(key, '')
|
||||
else:
|
||||
d.add(key, s)
|
||||
@@ -60,30 +60,30 @@ for fluid in CoolProp.__fluids__:
|
||||
|
||||
import pandas
|
||||
df = pandas.DataFrame(d.data)
|
||||
df = df.sort_values(by=['name'], ascending = [1])
|
||||
df = df.sort_values(by=['name'], ascending=[1])
|
||||
|
||||
|
||||
def build_citation(key):
|
||||
if not key:
|
||||
return ''
|
||||
else:
|
||||
return ':cite:`'+key+'`'
|
||||
return ':cite:`' + key + '`'
|
||||
|
||||
|
||||
def fluid_reference(fluid):
|
||||
return ':ref:`{fluid:s} <fluid_{fluid:s}>`'.format(fluid = fluid)
|
||||
return ':ref:`{fluid:s} <fluid_{fluid:s}>`'.format(fluid=fluid)
|
||||
|
||||
|
||||
# Write the table
|
||||
with open(csvfile,'w') as fp:
|
||||
with open(csvfile, 'w') as fp:
|
||||
rowdata = ["Name"] + [bibtex_map[key] for key in bibtex_keys]
|
||||
fp.write(';'.join(rowdata)+'\n')
|
||||
fp.write(';'.join(rowdata) + '\n')
|
||||
for index, row in df.iterrows():
|
||||
rowdata = [fluid_reference(row['name'])] + [build_citation(row[key]) for key in bibtex_keys]
|
||||
fp.write(';'.join(rowdata)+'\n')
|
||||
fp.write(';'.join(rowdata) + '\n')
|
||||
|
||||
# Write the hidden table to make sphinx happy
|
||||
with open(indexfile,'w') as fp:
|
||||
with open(indexfile, 'w') as fp:
|
||||
fp.write('.. toctree::\n :hidden:\n\n')
|
||||
for index, row in df.iterrows():
|
||||
fp.write(' fluids/' + row['name'] + '.rst\n')
|
||||
|
||||
@@ -6,8 +6,8 @@ import sys
|
||||
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
root_dir = os.path.abspath(os.path.join(web_dir, '..'))
|
||||
fluids_path = os.path.join(web_dir,'fluid_properties','fluids')
|
||||
plots_path = os.path.join(web_dir,'fluid_properties','fluids','REFPROPplots')
|
||||
fluids_path = os.path.join(web_dir, 'fluid_properties', 'fluids')
|
||||
plots_path = os.path.join(web_dir, 'fluid_properties', 'fluids', 'REFPROPplots')
|
||||
|
||||
template = """
|
||||
from __future__ import division, print_function
|
||||
@@ -88,9 +88,9 @@ with open(os.path.join(plots_path, 'matplotlibrc'), 'w') as fp:
|
||||
|
||||
for fluid in CoolProp.__fluids__:
|
||||
print('fluid:', fluid)
|
||||
file_string = template.format(fluid = fluid, rpv = CP.get_global_param_string("REFPROP_version"))
|
||||
file_string = template.format(fluid=fluid, rpv=CP.get_global_param_string("REFPROP_version"))
|
||||
file_path = os.path.join(plots_path, fluid + '.py')
|
||||
print('Writing to', file_path)
|
||||
with open(file_path, 'w') as fp:
|
||||
fp.write(file_string)
|
||||
subprocess.check_call('python "' + fluid + '.py"', cwd = plots_path, stdout = sys.stdout, stderr = sys.stderr, shell = True)
|
||||
subprocess.check_call('python "' + fluid + '.py"', cwd=plots_path, stdout=sys.stdout, stderr=sys.stderr, shell=True)
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# Hack due to hang in plot_directive for some unknown reason
|
||||
import subprocess,sys
|
||||
subprocess.call('python methane-ethane.py', shell = True, stdout = sys.stdout, stderr = sys.stderr, cwd='../fluid_properties')
|
||||
import subprocess, sys
|
||||
subprocess.call('python methane-ethane.py', shell=True, stdout=sys.stdout, stderr=sys.stderr, cwd='../fluid_properties')
|
||||
|
||||
@@ -2,19 +2,19 @@ import matplotlib.pyplot as plt
|
||||
from CoolProp.Plots import Ph
|
||||
from CoolProp.Plots.SimpleCycles import SimpleCycle
|
||||
|
||||
fig=plt.figure(figsize=(6,1))
|
||||
ax=fig.add_axes((0,0,1,1))
|
||||
ax.set_xlim(0,6)
|
||||
ax.set_ylim(0,2)
|
||||
plt.text(3,1,'CoolProp',size=50,name='Times',ha='center',va='center')
|
||||
fig = plt.figure(figsize=(6, 1))
|
||||
ax = fig.add_axes((0, 0, 1, 1))
|
||||
ax.set_xlim(0, 6)
|
||||
ax.set_ylim(0, 2)
|
||||
plt.text(3, 1, 'CoolProp', size=50, name='Times', ha='center', va='center')
|
||||
ax.axis('off')
|
||||
|
||||
ax2=fig.add_axes((0,0,0.3,1))
|
||||
Ph('R410A',lw=2,color='white')
|
||||
SimpleCycle(Ref='R410A',Te=280,Tc=310,DTsh=5,DTsc=5,eta_a=0.7,Ts_Ph='Ph',axis=ax2,lw=2,color='b')
|
||||
ax2.set_xlim(-6,600)
|
||||
ax2.set_ylim(-1000,6000)
|
||||
ax2 = fig.add_axes((0, 0, 0.3, 1))
|
||||
Ph('R410A', lw=2, color='white')
|
||||
SimpleCycle(Ref='R410A', Te=280, Tc=310, DTsh=5, DTsc=5, eta_a=0.7, Ts_Ph='Ph', axis=ax2, lw=2, color='b')
|
||||
ax2.set_xlim(-6, 600)
|
||||
ax2.set_ylim(-1000, 6000)
|
||||
ax2.axis('off')
|
||||
plt.draw()
|
||||
plt.savefig('_static/header.png',transparent=True)
|
||||
plt.savefig('_static/header.png', transparent=True)
|
||||
plt.show()
|
||||
|
||||
@@ -6,26 +6,26 @@ import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import CoolProp
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
fig = plt.figure(figsize = (2,2))
|
||||
fig = plt.figure(figsize=(2, 2))
|
||||
ax = fig.add_subplot(111, projection='3d')
|
||||
|
||||
NT = 1000
|
||||
NR = 1000
|
||||
rho,t = np.logspace(np.log10(2e-3), np.log10(1100), NR),np.linspace(275.15,700,NT)
|
||||
RHO,T = np.meshgrid(rho,t)
|
||||
rho, t = np.logspace(np.log10(2e-3), np.log10(1100), NR), np.linspace(275.15, 700, NT)
|
||||
RHO, T = np.meshgrid(rho, t)
|
||||
|
||||
P = CoolProp.CoolProp.PropsSI('P','D',RHO.reshape((NR*NT,1)),'T',T.reshape((NR*NT,1)),'REFPROP-Water').reshape(NT,NR)
|
||||
P = CoolProp.CoolProp.PropsSI('P', 'D', RHO.reshape((NR * NT, 1)), 'T', T.reshape((NR * NT, 1)), 'REFPROP-Water').reshape(NT, NR)
|
||||
|
||||
Tsat = np.linspace(273.17,647.0,100)
|
||||
psat = CoolProp.CoolProp.PropsSI('P','Q',0,'T',Tsat,'Water')
|
||||
rhoL = CoolProp.CoolProp.PropsSI('D','Q',0,'T',Tsat,'Water')
|
||||
rhoV = CoolProp.CoolProp.PropsSI('D','Q',1,'T',Tsat,'Water')
|
||||
Tsat = np.linspace(273.17, 647.0, 100)
|
||||
psat = CoolProp.CoolProp.PropsSI('P', 'Q', 0, 'T', Tsat, 'Water')
|
||||
rhoL = CoolProp.CoolProp.PropsSI('D', 'Q', 0, 'T', Tsat, 'Water')
|
||||
rhoV = CoolProp.CoolProp.PropsSI('D', 'Q', 1, 'T', Tsat, 'Water')
|
||||
|
||||
ax.plot_surface(np.log(RHO),T,np.log(P), cmap=cm.jet, edgecolor = 'none')
|
||||
ax.plot(np.log(rhoL),Tsat,np.log(psat),color='k',lw=2)
|
||||
ax.plot(np.log(rhoV),Tsat,np.log(psat),color='k',lw=2)
|
||||
ax.plot_surface(np.log(RHO), T, np.log(P), cmap=cm.jet, edgecolor='none')
|
||||
ax.plot(np.log(rhoL), Tsat, np.log(psat), color='k', lw=2)
|
||||
ax.plot(np.log(rhoV), Tsat, np.log(psat), color='k', lw=2)
|
||||
|
||||
ax.text(0.3,800,22, "CoolProp", size = 12)
|
||||
ax.text(0.3, 800, 22, "CoolProp", size=12)
|
||||
ax.set_frame_on(False)
|
||||
ax.set_axis_off()
|
||||
ax.view_init(22, -136)
|
||||
@@ -33,6 +33,6 @@ ax.set_xlabel(r'$\ln\rho$ ')
|
||||
ax.set_ylabel('$T$')
|
||||
ax.set_zlabel('$p$')
|
||||
plt.tight_layout()
|
||||
plt.savefig('_static/PVTCP.png',transparent = True)
|
||||
plt.savefig('_static/PVTCP.pdf',transparent = True)
|
||||
plt.savefig('_static/PVTCP.png', transparent=True)
|
||||
plt.savefig('_static/PVTCP.pdf', transparent=True)
|
||||
plt.close()
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import matplotlib
|
||||
matplotlib.use('Agg') # use a non-interactive backend
|
||||
matplotlib.use('Agg') # use a non-interactive backend
|
||||
import CoolProp
|
||||
import os.path
|
||||
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
|
||||
tar_fil = os.path.join(web_dir,'_static','CoolPropLogo.png')
|
||||
tar_fil_long = os.path.join(web_dir,'_static','CoolPropLogoLong.png')
|
||||
tar_fil_long_large = os.path.join(web_dir,'_static','CoolPropLogoLongLarge.png')
|
||||
web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
tar_fil = os.path.join(web_dir, '_static', 'CoolPropLogo.png')
|
||||
tar_fil_long = os.path.join(web_dir, '_static', 'CoolPropLogoLong.png')
|
||||
tar_fil_long_large = os.path.join(web_dir, '_static', 'CoolPropLogoLongLarge.png')
|
||||
|
||||
import matplotlib
|
||||
import numpy as np
|
||||
@@ -28,31 +28,31 @@ T_triple = 273.16
|
||||
steps = 2000
|
||||
|
||||
TT = []
|
||||
PP = list(np.logspace(np.log10(p_triple), np.log10(p_max),steps))
|
||||
PP = list(np.logspace(np.log10(p_triple), np.log10(p_max), steps))
|
||||
for p in PP:
|
||||
TT.append(Water.melting_line(CP.iT, CP.iP, p))
|
||||
|
||||
#Zone VI
|
||||
for T in np.linspace(max(TT), 355, int(steps/10)):
|
||||
# Zone VI
|
||||
for T in np.linspace(max(TT), 355, int(steps / 10)):
|
||||
TT.append(T)
|
||||
theta = T/273.31
|
||||
pi = 1-1.07476*(1-theta**4.6)
|
||||
p = pi*632.4e6
|
||||
theta = T / 273.31
|
||||
pi = 1 - 1.07476 * (1 - theta**4.6)
|
||||
p = pi * 632.4e6
|
||||
PP.append(p)
|
||||
|
||||
#Zone VII
|
||||
for T in np.linspace(355, 715, int(steps/10)):
|
||||
# Zone VII
|
||||
for T in np.linspace(355, 715, int(steps / 10)):
|
||||
TT.append(T)
|
||||
theta = T/355
|
||||
lnpi = 0.173683e1*(1-1/theta)-0.544606e-1*(1-theta**5)+0.806106e-7*(1-theta**22)
|
||||
p = np.exp(lnpi)*2216e6
|
||||
theta = T / 355
|
||||
lnpi = 0.173683e1 * (1 - 1 / theta) - 0.544606e-1 * (1 - theta**5) + 0.806106e-7 * (1 - theta**22)
|
||||
p = np.exp(lnpi) * 2216e6
|
||||
PP.append(p)
|
||||
|
||||
# Changes number of points
|
||||
steps = int(steps/10.0)
|
||||
steps = int(steps / 10.0)
|
||||
|
||||
p_melt = np.logspace(np.log10(np.min(PP)), np.log10(np.max(PP)),steps)
|
||||
T_melt_f = scipy.interpolate.interp1d(np.log10(PP),TT)
|
||||
p_melt = np.logspace(np.log10(np.min(PP)), np.log10(np.max(PP)), steps)
|
||||
T_melt_f = scipy.interpolate.interp1d(np.log10(PP), TT)
|
||||
#T_melt_f = scipy.interpolate.spline(np.log10(PP),TT,np.log10(p_melt))
|
||||
T_melt = T_melt_f(np.log10(p_melt))
|
||||
#T_melt = np.array(TT)
|
||||
@@ -61,18 +61,18 @@ T_melt = T_melt_f(np.log10(p_melt))
|
||||
#
|
||||
# Prepare the data for the saturation line
|
||||
T_sat = np.linspace(T_triple, Tc, len(T_melt))
|
||||
p_sat = CP.CoolProp.PropsSI('P','T',T_sat,'Q',[0]*len(T_sat),'Water')
|
||||
p_sat = CP.CoolProp.PropsSI('P', 'T', T_sat, 'Q', [0] * len(T_sat), 'Water')
|
||||
|
||||
#
|
||||
# Prepare density data
|
||||
TT,DD,PP = [], [], []
|
||||
TT, DD, PP = [], [], []
|
||||
for T in np.linspace(T_min, T_max, steps):
|
||||
for p in np.logspace(np.log10(np.min(p_melt)), np.log10(np.max(p_melt)), steps):
|
||||
Tm = scipy.interpolate.interp1d(p_melt, T_melt)(p)
|
||||
if T < Tm: continue
|
||||
if p > p_max: pin = p_max
|
||||
else: pin = p
|
||||
D = CP.CoolProp.PropsSI('D','T',T,'P',pin,'Water')
|
||||
D = CP.CoolProp.PropsSI('D', 'T', T, 'P', pin, 'Water')
|
||||
TT.append(T)
|
||||
DD.append(np.log10(D))
|
||||
PP.append(p)
|
||||
@@ -83,33 +83,33 @@ for T in np.linspace(T_min, T_max, steps):
|
||||
#dd = np.empty(tt.shape)
|
||||
#dd[:][:] = np.NAN
|
||||
#nr,nc = tt.shape
|
||||
#for i in range(nr):
|
||||
#for j in range(nc):
|
||||
# for i in range(nr):
|
||||
# for j in range(nc):
|
||||
#Tm = T_melt_f(np.log10(pp[i][j]))
|
||||
#if tt[i][j] < Tm: continue
|
||||
# if tt[i][j] < Tm: continue
|
||||
#D = CP.CoolProp.PropsSI('D','T',tt[i][j],'P',pp[i][j],'Water')
|
||||
#dd[i][j] = np.log10(D)
|
||||
|
||||
#
|
||||
# Define colours etc
|
||||
lw = 3
|
||||
melt_args = dict(color = 'orange', lw = lw, solid_capstyle = 'round')
|
||||
sat_args = melt_args.copy()
|
||||
melt_args = dict(color='orange', lw=lw, solid_capstyle='round')
|
||||
sat_args = melt_args.copy()
|
||||
|
||||
nm = matplotlib.colors.Normalize(min(DD), max(DD))
|
||||
rho_args = dict(cmap=plt.cm.get_cmap('Blues'), norm = nm)
|
||||
rho_args = dict(cmap=plt.cm.get_cmap('Blues'), norm=nm)
|
||||
|
||||
fig = plt.figure(figsize = (1.0,1.0))
|
||||
ax = fig.add_axes((0.0,0.0,1.0,1.0))
|
||||
fig = plt.figure(figsize=(1.0, 1.0))
|
||||
ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
|
||||
|
||||
plt.plot(T_melt, p_melt, **melt_args)
|
||||
plt.plot(T_sat, p_sat, **sat_args )
|
||||
plt.scatter(TT, PP, c=DD, edgecolor = 'none', s = 6, **rho_args )
|
||||
plt.plot(T_sat, p_sat, **sat_args)
|
||||
plt.scatter(TT, PP, c=DD, edgecolor='none', s=6, **rho_args)
|
||||
#plt.contourf(tt, pp, dd, steps, **rho_args )
|
||||
delta_x = np.min(T_melt)*0.01
|
||||
x_lim = [np.min(T_melt)-delta_x, np.max(T_melt)+delta_x]
|
||||
y_lim = [np.min(p_melt)*0.875 , np.max(p_melt)*1.125]
|
||||
#y_lim = [np.power(np.log10(np.min(p_melt))*1.01,10),
|
||||
delta_x = np.min(T_melt) * 0.01
|
||||
x_lim = [np.min(T_melt) - delta_x, np.max(T_melt) + delta_x]
|
||||
y_lim = [np.min(p_melt) * 0.875, np.max(p_melt) * 1.125]
|
||||
# y_lim = [np.power(np.log10(np.min(p_melt))*1.01,10),
|
||||
# np.power(np.log10(np.max(p_melt))*1.01,10)]
|
||||
|
||||
ax.set_xlim(x_lim)
|
||||
@@ -117,18 +117,18 @@ ax.set_ylim(y_lim)
|
||||
ax.set_yscale('log')
|
||||
ax.axis('off')
|
||||
|
||||
plt.savefig(os.path.basename(__file__)+'.pdf')
|
||||
plt.savefig(tar_fil, transparent = True, dpi = 100)
|
||||
plt.savefig(os.path.basename(__file__) + '.pdf')
|
||||
plt.savefig(tar_fil, transparent=True, dpi=100)
|
||||
plt.close()
|
||||
|
||||
fig = plt.figure(figsize = (9,3))
|
||||
ax = fig.add_axes((0.66,0.01,0.333,0.98))
|
||||
fig = plt.figure(figsize=(9, 3))
|
||||
ax = fig.add_axes((0.66, 0.01, 0.333, 0.98))
|
||||
plt.plot(T_melt, p_melt, **melt_args)
|
||||
plt.plot(T_sat, p_sat, **sat_args )
|
||||
plt.scatter(TT, PP, c=DD, edgecolor = 'none', s = 6, **rho_args )
|
||||
plt.plot(T_sat, p_sat, **sat_args)
|
||||
plt.scatter(TT, PP, c=DD, edgecolor='none', s=6, **rho_args)
|
||||
|
||||
#ax.text(0.4,800, "CoolProp", size = 12)
|
||||
ax.annotate('CoolProp', xy=(-0.1, 0.5), xycoords='axes fraction', fontsize=88, ha='right', va='center') # va='baseline')
|
||||
ax.annotate('CoolProp', xy=(-0.1, 0.5), xycoords='axes fraction', fontsize=88, ha='right', va='center') # va='baseline')
|
||||
|
||||
|
||||
ax.set_xlim(x_lim)
|
||||
@@ -136,7 +136,7 @@ ax.set_ylim(y_lim)
|
||||
ax.set_yscale('log')
|
||||
ax.axis('off')
|
||||
|
||||
plt.savefig(tar_fil_long_large, transparent = True)
|
||||
plt.savefig(tar_fil_long_large, transparent=True)
|
||||
plt.close()
|
||||
|
||||
# # Just a hack to resize the image
|
||||
|
||||
@@ -210,8 +210,8 @@ def make3Dlpot(X,Y,Z=None,ax=None,invert='',draw='CXYZ',color='blue',xlim=None,y
|
||||
|
||||
|
||||
def getlim(key,dicts,fac=1):
|
||||
min = np.min([ dict[key]/fac for dict in dicts ])
|
||||
max = np.max([ dict[key]/fac for dict in dicts ])
|
||||
min = np.min([dict[key]/fac for dict in dicts])
|
||||
max = np.max([dict[key]/fac for dict in dicts])
|
||||
return [np.floor(min)*fac, np.ceil(max)*fac]
|
||||
|
||||
|
||||
|
||||
@@ -247,8 +247,8 @@ def getPTRanges(propsfluid):
|
||||
|
||||
if backend == "REFPROP":
|
||||
T_min = max(T_min,PropsSI('Ttriple',"T",0,"D",0,propsfluid))+1
|
||||
p_min = PropsSI( 'P',"T",T_min,"Q",0,propsfluid)+1
|
||||
p_max = PropsSI( 'pmax',"T",0,"D",0,propsfluid)-1
|
||||
p_min = PropsSI('P',"T",T_min,"Q",0,propsfluid)+1
|
||||
p_max = PropsSI('pmax',"T",0,"D",0,propsfluid)-1
|
||||
elif backend == "INCOMP":
|
||||
p_min = 1.5*1e5
|
||||
p_max = 200.0*1e5
|
||||
@@ -256,7 +256,7 @@ def getPTRanges(propsfluid):
|
||||
T_min = max(T_min,PropsSI('Ttriple',"T",0,"D",0,propsfluid))+1
|
||||
p_min = PropsSI('ptriple',"T",0,"D",0,propsfluid)
|
||||
p_min = max(p_min,PropsSI('pmin',"T",0,"D",0,propsfluid))+1
|
||||
p_max = PropsSI( 'pmax',"T",0,"D",0,propsfluid)-1
|
||||
p_max = PropsSI('pmax',"T",0,"D",0,propsfluid)-1
|
||||
|
||||
# One more check to debug things:
|
||||
#p_min = max(p_min,0.01e5)
|
||||
@@ -296,7 +296,7 @@ def getLists(propsfluid):
|
||||
while loop:
|
||||
count += 1
|
||||
|
||||
h_list = np.random.uniform( h_min, h_max,int(xypoints*2.0))
|
||||
h_list = np.random.uniform(h_min, h_max,int(xypoints*2.0))
|
||||
p_list = np.random.uniform(np.log10(p_min),np.log10(p_max),int(xypoints*2.0))
|
||||
p_list = np.power(10,p_list)
|
||||
|
||||
@@ -563,14 +563,14 @@ def getData(fld,backend,inp,out,fluidData):
|
||||
cData = fluidData[fld][backend][dkey]
|
||||
inputs1.append(cData[i1key])
|
||||
inputs2.append(cData[i2key])
|
||||
values.append( cData[vkey] )
|
||||
times.append( cData[tkey] )
|
||||
values.append(cData[vkey])
|
||||
times.append(cData[tkey])
|
||||
ret = {}
|
||||
if len(inputs1)>0:
|
||||
ret[i1key] = np.concatenate(inputs1)
|
||||
ret[i2key] = np.concatenate(inputs2)
|
||||
ret[vkey] = np.concatenate(values )
|
||||
ret[tkey] = np.concatenate(times )
|
||||
ret[vkey] = np.concatenate(values)
|
||||
ret[tkey] = np.concatenate(times)
|
||||
return ret
|
||||
|
||||
|
||||
@@ -584,13 +584,13 @@ def getSingleData(fld,backend,key,fluidData):
|
||||
#mask = fluidData[fld][backend][dkey]["P"]>0.3e5
|
||||
mask = fluidData[fld][backend][dkey]["P"]>0.0e5
|
||||
try:
|
||||
values.append( fluidData[fld][backend][dkey][key][mask] )
|
||||
values.append(fluidData[fld][backend][dkey][key][mask])
|
||||
except Exception as e:
|
||||
values.append( fluidData[fld][backend][dkey][key] )
|
||||
values.append(fluidData[fld][backend][dkey][key])
|
||||
print(e)
|
||||
pass
|
||||
else:
|
||||
values.append( fluidData[fld][backend][dkey][key] )
|
||||
values.append(fluidData[fld][backend][dkey][key])
|
||||
if len(values)>0:
|
||||
if np.size(values[0])>1:
|
||||
return np.concatenate(values)
|
||||
@@ -833,7 +833,7 @@ def axislabel(txt,ax,xPos,yPos=-1):
|
||||
#############################################################
|
||||
# The first plot contains the time data, this is averaged and
|
||||
# plotted as a bar graph with the standard deviation.
|
||||
hatchLst = ["", "///" ,"\\\\\\" ]
|
||||
hatchLst = ["", "///" ,"\\\\\\"]
|
||||
backendsLst = ["INCOMP","HEOS","REFPROP"]
|
||||
for fluidstr in fluids[:-1]:
|
||||
_,fld,_ = splitFluid(fluidstr)
|
||||
@@ -1023,7 +1023,7 @@ for fluidstr in fluids[:-1]:
|
||||
|
||||
ratio = 10.0/4.0 * y_max / 250.0 # height of 10 for 4 points if y_max==250
|
||||
|
||||
x_min = rects1[ 0].get_x()
|
||||
x_min = rects1[0].get_x()
|
||||
x_max = rects1[-1].get_x() + dx
|
||||
x,y = range_brace(x_min, x_max)
|
||||
dy = np.ceil(y_max_c/10.0)*10.0
|
||||
@@ -1031,7 +1031,7 @@ for fluidstr in fluids[:-1]:
|
||||
ax1.plot(x, y, ls='-',color='k')
|
||||
ax1.text(np.mean(x), np.max(y), "const.", rotation=0, ha='center', va='bottom', fontsize='medium')
|
||||
|
||||
x_min = rects2[ 0].get_x()
|
||||
x_min = rects2[0].get_x()
|
||||
x_max = rects2[-1].get_x() + dx
|
||||
x,y = range_brace(x_min, x_max)
|
||||
dy = np.ceil(y_max_e/10.0)*10.0
|
||||
@@ -1039,7 +1039,7 @@ for fluidstr in fluids[:-1]:
|
||||
ax1.plot(x, y, ls='-',color='k')
|
||||
ax1.text(np.mean(x), np.max(y), "explicit", rotation=0, ha='center', va='bottom', fontsize='medium')
|
||||
|
||||
x_min = rects3[ 0].get_x()
|
||||
x_min = rects3[0].get_x()
|
||||
x_max = rects3[-1].get_x() + dx
|
||||
x,y = range_brace(x_min, x_max)
|
||||
dy = np.ceil(y_max_i/100.0)*10
|
||||
@@ -1344,8 +1344,8 @@ else:
|
||||
fg2 = plt.figure()
|
||||
ccycle = cycle(["b","g","r"])
|
||||
|
||||
fg1.set_size_inches( (fg1.get_size_inches()[0]*1, fg1.get_size_inches()[1]*0.75) )
|
||||
fg2.set_size_inches( (fg2.get_size_inches()[0]*1, fg2.get_size_inches()[1]*0.75) )
|
||||
fg1.set_size_inches((fg1.get_size_inches()[0]*1, fg1.get_size_inches()[1]*0.75))
|
||||
fg2.set_size_inches((fg2.get_size_inches()[0]*1, fg2.get_size_inches()[1]*0.75))
|
||||
ccycle.next() # No incomp
|
||||
#
|
||||
#ax1 = fg.add_subplot(111)
|
||||
@@ -1434,7 +1434,7 @@ for fluidstr in fluids:
|
||||
if backend!="INCOMP":
|
||||
TP = {}
|
||||
points = max(int(xypoints/2),250)
|
||||
T_range_TP = np.linspace(PropsSI('Ttriple',"T",0,"D",0,propsfluid)+1,PropsSI( 'Tcrit',"T",0,"D",0,propsfluid)-0.1,points)
|
||||
T_range_TP = np.linspace(PropsSI('Ttriple',"T",0,"D",0,propsfluid)+1,PropsSI('Tcrit',"T",0,"D",0,propsfluid)-0.1,points)
|
||||
T_TP = np.append(T_range_TP,T_range_TP[::-1])
|
||||
Q_TP = np.zeros_like(T_TP)
|
||||
Q_TP[points:] = 1
|
||||
|
||||
@@ -113,7 +113,7 @@ for colourmap in ['jorrithelix']:
|
||||
isoT = np.array([0,100,200,300,400])+273.15
|
||||
isoP = np.logspace(np.log10(p_min),np.log10(p_max),base=10)
|
||||
ones = np.ones(isoP.shape)
|
||||
isoH = [ CP.PropsSI('H','T',T*ones,'P',isoP,Ref) for T in isoT ]
|
||||
isoH = [CP.PropsSI('H','T',T*ones,'P',isoP,Ref) for T in isoT]
|
||||
|
||||
print("Lower left and upper right coordinates: ({0},{1}), ({2},{3})".format(h_min,p_min,h_max,p_max))
|
||||
|
||||
@@ -310,7 +310,7 @@ for colourmap in ['jorrithelix']:
|
||||
#plt.savefig(out+'_'+colourmap+'_TTSE_BICUBIC.eps')
|
||||
# plt.savefig(out+'_'+colourmap+'_TTSE_BICUBIC.pdf')
|
||||
plt.tight_layout()
|
||||
plt.savefig('check_TTSE_'+colourmap+'.pdf' )
|
||||
plt.savefig('check_TTSE_'+colourmap+'.pdf')
|
||||
#tikz_save( 'check_TTSE.tikz')
|
||||
#plt.savefig(out+'_'+colourmap+'_TTSE_BICUBIC.jpg', dpi = 1200)
|
||||
plt.close()
|
||||
|
||||
@@ -100,7 +100,7 @@ for colourmap in ['cubehelix']:
|
||||
isoT = np.array([0,100,200,300,400])+273.15
|
||||
isoP = np.logspace(np.log10(p_min),np.log10(p_max),base=10)
|
||||
ones = np.ones(isoP.shape)
|
||||
isoH = [ CP.PropsSI('H','T',T*ones,'P',isoP,Ref) for T in isoT ]
|
||||
isoH = [CP.PropsSI('H','T',T*ones,'P',isoP,Ref) for T in isoT]
|
||||
|
||||
print("Lower left and upper right coordinates: ({0},{1}), ({2},{3})".format(h_min,p_min,h_max,p_max))
|
||||
|
||||
@@ -265,7 +265,7 @@ for colourmap in ['cubehelix']:
|
||||
#plt.savefig(out+'_'+colourmap+'_TTSE_BICUBIC.eps')
|
||||
# plt.savefig(out+'_'+colourmap+'_TTSE_BICUBIC.pdf')
|
||||
plt.tight_layout()
|
||||
plt.savefig('check_TTSE.pdf' )
|
||||
plt.savefig('check_TTSE.pdf')
|
||||
#tikz_save( 'check_TTSE.tikz')
|
||||
#plt.savefig(out+'_'+colourmap+'_TTSE_BICUBIC.jpg', dpi = 1200)
|
||||
plt.close()
|
||||
|
||||
@@ -17,7 +17,7 @@ keys = multiply[:]
|
||||
|
||||
fluid = "n-Pentane"
|
||||
|
||||
T = numpy.array([ 30,100,150,210])+273.15
|
||||
T = numpy.array([30,100,150,210])+273.15
|
||||
D = numpy.array([710, 20, 20,210])
|
||||
|
||||
for key in keys:
|
||||
|
||||
@@ -12,8 +12,8 @@ drawIsoLines(fluid, 'Ts', 'Q', iValues=[0.0, 1.0], axis=ax1) # for predefined st
|
||||
drawIsoLines(fluid, 'Ts', 'Q', iValues=[0.3, 0.7], axis=ax1) # for predefined styles
|
||||
|
||||
# Get the data points
|
||||
saturation = getIsoLines(fluid, 'Ts', 'Q', [0.0, 1.0 ], axis=ax2)
|
||||
quality = getIsoLines(fluid, 'Ts', 'Q', [0.3, 0.7 ], axis=ax2)
|
||||
saturation = getIsoLines(fluid, 'Ts', 'Q', [0.0, 1.0], axis=ax2)
|
||||
quality = getIsoLines(fluid, 'Ts', 'Q', [0.3, 0.7], axis=ax2)
|
||||
# define custom styles
|
||||
plt_kwargs = {"color": "green","linewidth": 1.5}
|
||||
drawLines(fluid,saturation,ax2,plt_kwargs=plt_kwargs)
|
||||
|
||||
@@ -5,8 +5,8 @@ from package_json import json_options
|
||||
for fluid in glob.glob('fluids/*.json'):
|
||||
|
||||
print(fluid)
|
||||
j = json.load(open(fluid,'r'))
|
||||
j = json.load(open(fluid, 'r'))
|
||||
|
||||
fp = open(fluid,'w')
|
||||
fp.write(json.dumps(j,**json_options))
|
||||
fp = open(fluid, 'w')
|
||||
fp.write(json.dumps(j, **json_options))
|
||||
fp.close()
|
||||
|
||||
@@ -2,21 +2,21 @@ import CoolProp, json
|
||||
PropsSI = CoolProp.CoolProp.PropsSI
|
||||
data = []
|
||||
for fluid in CoolProp.__fluids__:
|
||||
if CoolProp.CoolProp.get_fluid_param_string(fluid,"pure") == 'true':
|
||||
data.append(dict(Tc = PropsSI('Tcrit', fluid),
|
||||
Tc_units = "K",
|
||||
pc = PropsSI('pcrit', fluid),
|
||||
pc_units = "Pa",
|
||||
acentric = PropsSI('acentric', fluid),
|
||||
rhomolarc = PropsSI('rhomolar_critical', fluid),
|
||||
rhomolarc_units = "mol/m^3",
|
||||
molemass = PropsSI('molemass', fluid),
|
||||
molemass_units = "kg/mol",
|
||||
name = fluid.upper(),
|
||||
alpha0 = json.loads(open('../fluids/'+fluid+'.json','r').read())['EOS'][0]['alpha0'],
|
||||
CAS = CoolProp.CoolProp.get_fluid_param_string(fluid,"CAS"),
|
||||
aliases = list(set([_.upper() for _ in CoolProp.CoolProp.get_fluid_param_string(fluid,"aliases").split(', ')]))
|
||||
if CoolProp.CoolProp.get_fluid_param_string(fluid, "pure") == 'true':
|
||||
data.append(dict(Tc=PropsSI('Tcrit', fluid),
|
||||
Tc_units="K",
|
||||
pc=PropsSI('pcrit', fluid),
|
||||
pc_units="Pa",
|
||||
acentric=PropsSI('acentric', fluid),
|
||||
rhomolarc=PropsSI('rhomolar_critical', fluid),
|
||||
rhomolarc_units="mol/m^3",
|
||||
molemass=PropsSI('molemass', fluid),
|
||||
molemass_units="kg/mol",
|
||||
name=fluid.upper(),
|
||||
alpha0=json.loads(open('../fluids/' + fluid + '.json', 'r').read())['EOS'][0]['alpha0'],
|
||||
CAS=CoolProp.CoolProp.get_fluid_param_string(fluid, "CAS"),
|
||||
aliases=list(set([_.upper() for _ in CoolProp.CoolProp.get_fluid_param_string(fluid, "aliases").split(', ')]))
|
||||
))
|
||||
|
||||
with open('all_cubic_fluids.json','w') as fp:
|
||||
json.dump(data, fp, indent = 2, sort_keys = True)
|
||||
with open('all_cubic_fluids.json', 'w') as fp:
|
||||
json.dump(data, fp, indent=2, sort_keys=True)
|
||||
|
||||
@@ -13,7 +13,7 @@ import hashlib
|
||||
import struct
|
||||
import glob
|
||||
|
||||
json_options = {'indent' : 2, 'sort_keys' : True}
|
||||
json_options = {'indent': 2, 'sort_keys': True}
|
||||
|
||||
|
||||
def get_hash(data):
|
||||
@@ -27,9 +27,9 @@ def get_hash(data):
|
||||
repo_root_path = os.path.normpath(os.path.join(os.path.abspath(__file__), '..', '..'))
|
||||
|
||||
# Load up the hashes of the data that will be written to each file
|
||||
hashes_fname = os.path.join(repo_root_path,'dev','hashes.json')
|
||||
hashes_fname = os.path.join(repo_root_path, 'dev', 'hashes.json')
|
||||
if os.path.exists(hashes_fname):
|
||||
hashes = json.load(open(hashes_fname,'r'))
|
||||
hashes = json.load(open(hashes_fname, 'r'))
|
||||
else:
|
||||
hashes = dict()
|
||||
|
||||
@@ -37,8 +37,8 @@ else:
|
||||
# 1: Output file path relative to include folder
|
||||
# 2: Name of variable
|
||||
values = [
|
||||
('all_fluids.json','all_fluids_JSON.h','all_fluids_JSON'),
|
||||
('all_incompressibles.json','all_incompressibles_JSON.h','all_incompressibles_JSON'),
|
||||
('all_fluids.json', 'all_fluids_JSON.h', 'all_fluids_JSON'),
|
||||
('all_incompressibles.json', 'all_incompressibles_JSON.h', 'all_incompressibles_JSON'),
|
||||
('mixtures/mixture_departure_functions.json', 'mixture_departure_functions_JSON.h', 'mixture_departure_functions_JSON'),
|
||||
('mixtures/mixture_binary_pairs.json', 'mixture_binary_pairs_JSON.h', 'mixture_binary_pairs_JSON'),
|
||||
('mixtures/predefined_mixtures.json', 'predefined_mixtures_JSON.h', 'predefined_mixtures_JSON'),
|
||||
@@ -49,9 +49,9 @@ values = [
|
||||
|
||||
def TO_CPP(root_dir, hashes):
|
||||
def to_chunks(l, n):
|
||||
if n<1:
|
||||
n=1
|
||||
return [l[i:i+n] for i in range(0, len(l), n)]
|
||||
if n < 1:
|
||||
n = 1
|
||||
return [l[i:i + n] for i in range(0, len(l), n)]
|
||||
|
||||
# Normalise path name
|
||||
root_dir = os.path.normpath(root_dir)
|
||||
@@ -59,21 +59,21 @@ def TO_CPP(root_dir, hashes):
|
||||
# First we package up the JSON files
|
||||
combine_json(root_dir)
|
||||
|
||||
for infile,outfile,variable in values:
|
||||
for infile, outfile, variable in values:
|
||||
|
||||
import json
|
||||
|
||||
# Confirm that the JSON file can be loaded and doesn't have any formatting problems
|
||||
with open(os.path.join(root_dir,'dev',infile), 'r') as fp:
|
||||
with open(os.path.join(root_dir, 'dev', infile), 'r') as fp:
|
||||
try:
|
||||
jj = json.load(fp)
|
||||
except ValueError:
|
||||
file = os.path.join(root_dir,'dev',infile)
|
||||
print('"python -mjson.tool '+file+'" returns ->', end='')
|
||||
subprocess.call('python -mjson.tool '+file, shell = True)
|
||||
file = os.path.join(root_dir, 'dev', infile)
|
||||
print('"python -mjson.tool ' + file + '" returns ->', end='')
|
||||
subprocess.call('python -mjson.tool ' + file, shell=True)
|
||||
raise ValueError('unable to decode file %s' % file)
|
||||
|
||||
json = open(os.path.join(root_dir,'dev',infile),'r').read().encode('ascii')
|
||||
json = open(os.path.join(root_dir, 'dev', infile), 'r').read().encode('ascii')
|
||||
|
||||
# convert each character to hex and add a terminating NULL character to end the
|
||||
# string, join into a comma separated string
|
||||
@@ -91,24 +91,24 @@ def TO_CPP(root_dir, hashes):
|
||||
hex_string = ',\n'.join([', '.join(chunk) for chunk in chunks])
|
||||
|
||||
# Check if hash is up to date based on using variable as key
|
||||
if not os.path.isfile(os.path.join(root_dir,'include',outfile)) or variable not in hashes or (variable in hashes and hashes[variable] != get_hash(hex_string.encode('ascii'))):
|
||||
if not os.path.isfile(os.path.join(root_dir, 'include', outfile)) or variable not in hashes or (variable in hashes and hashes[variable] != get_hash(hex_string.encode('ascii'))):
|
||||
|
||||
# Generate the output string
|
||||
output = '// File generated by the script dev/generate_headers.py on '+ str(datetime.now()) + '\n\n'
|
||||
output = '// File generated by the script dev/generate_headers.py on ' + str(datetime.now()) + '\n\n'
|
||||
output += '// JSON file encoded in binary form\n'
|
||||
output += 'const unsigned char '+variable+'_binary[] = {\n' + hex_string + '\n};'+'\n\n'
|
||||
output += 'const unsigned char ' + variable + '_binary[] = {\n' + hex_string + '\n};' + '\n\n'
|
||||
output += '// Combined into a single std::string \n'
|
||||
output += 'std::string {v:s}({v:s}_binary, {v:s}_binary + sizeof({v:s}_binary)/sizeof({v:s}_binary[0]));'.format(v = variable)
|
||||
output += 'std::string {v:s}({v:s}_binary, {v:s}_binary + sizeof({v:s}_binary)/sizeof({v:s}_binary[0]));'.format(v=variable)
|
||||
|
||||
# Write it to file
|
||||
f = open(os.path.join(root_dir,'include',outfile), 'w')
|
||||
f = open(os.path.join(root_dir, 'include', outfile), 'w')
|
||||
f.write(output)
|
||||
f.close()
|
||||
|
||||
# Store the hash of the data that was written to file (not including the header)
|
||||
hashes[variable] = get_hash(hex_string.encode('ascii'))
|
||||
|
||||
print(os.path.join(root_dir,'include',outfile)+ ' written to file')
|
||||
print(os.path.join(root_dir, 'include', outfile) + ' written to file')
|
||||
else:
|
||||
print(outfile + ' is up to date')
|
||||
|
||||
@@ -125,7 +125,7 @@ def version_to_file(root_dir):
|
||||
"
|
||||
"""
|
||||
|
||||
lines = open(os.path.join(root_dir,'CMakeLists.txt'),'r').readlines()
|
||||
lines = open(os.path.join(root_dir, 'CMakeLists.txt'), 'r').readlines()
|
||||
# Find the necessary lines
|
||||
MAJOR_line = [line for line in lines if ('VERSION_MAJOR' in line and 'MINOR' not in line)]
|
||||
MINOR_line = [line for line in lines if ('VERSION_MINOR' in line and 'MAJOR' not in line)]
|
||||
@@ -137,14 +137,14 @@ def version_to_file(root_dir):
|
||||
PATCH = PATCH_line[0].strip().split('VERSION_PATCH')[1].split(')')[0].strip()
|
||||
REVISION = REVISION_line[0].strip().split('VERSION_REVISION')[1].split(')')[0].strip()
|
||||
# Generate the strings
|
||||
version = '.'.join([MAJOR,MINOR,PATCH]) + REVISION
|
||||
version = '.'.join([MAJOR, MINOR, PATCH]) + REVISION
|
||||
|
||||
# Get the hash of the version
|
||||
if 'version' not in hashes or ('version' in hashes and hashes['version'] != get_hash(version.encode('ascii'))):
|
||||
hashes['version'] = get_hash(version)
|
||||
|
||||
# Format the string to be written
|
||||
string_for_file = '//Generated by the generate_headers.py script on {t:s}\n\nstatic char version [] ="{v:s}";'.format(t = str(datetime.now()),v = version)
|
||||
string_for_file = '//Generated by the generate_headers.py script on {t:s}\n\nstatic char version [] ="{v:s}";'.format(t=str(datetime.now()), v=version)
|
||||
|
||||
# Include path relative to the root
|
||||
include_dir = os.path.join(root_dir, 'include')
|
||||
@@ -153,7 +153,7 @@ def version_to_file(root_dir):
|
||||
file_name = os.path.join(include_dir, 'cpversion.h')
|
||||
|
||||
# Write to file
|
||||
f = open(file_name,'w')
|
||||
f = open(file_name, 'w')
|
||||
f.write(string_for_file)
|
||||
f.close()
|
||||
|
||||
@@ -165,7 +165,7 @@ def version_to_file(root_dir):
|
||||
hidden_file_name = os.path.join(root_dir, '.version')
|
||||
|
||||
# Write to file
|
||||
f = open(hidden_file_name,'w')
|
||||
f = open(hidden_file_name, 'w')
|
||||
f.write(version)
|
||||
f.close()
|
||||
|
||||
@@ -187,8 +187,8 @@ def gitrev_to_file(root_dir):
|
||||
p = subprocess.Popen('git rev-parse HEAD',
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
shell = True,
|
||||
cwd = os.path.abspath(os.path.dirname(__file__)))
|
||||
shell=True,
|
||||
cwd=os.path.abspath(os.path.dirname(__file__)))
|
||||
stdout, stderr = p.communicate()
|
||||
stdout = stdout.decode('utf-8')
|
||||
|
||||
@@ -198,7 +198,7 @@ def gitrev_to_file(root_dir):
|
||||
if os.path.exists(gitrevision_path):
|
||||
gitrev = open(gitrevision_path, 'r').read().strip()
|
||||
else:
|
||||
print('tried to get git revision from '+gitrevision_path+', but could not')
|
||||
print('tried to get git revision from ' + gitrevision_path + ', but could not')
|
||||
gitrev = '???'
|
||||
else:
|
||||
gitrev = stdout.strip()
|
||||
@@ -206,31 +206,31 @@ def gitrev_to_file(root_dir):
|
||||
is_hash = not ' ' in gitrev
|
||||
|
||||
if not is_hash:
|
||||
raise ValueError('No hash returned from call to git, got '+rev+' instead')
|
||||
raise ValueError('No hash returned from call to git, got ' + rev + ' instead')
|
||||
|
||||
except subprocess.CalledProcessError:
|
||||
print('git was not found')
|
||||
gitrev = '???'
|
||||
|
||||
# Include path relative to the root
|
||||
include_dir = os.path.join(root_dir,'include')
|
||||
include_dir = os.path.join(root_dir, 'include')
|
||||
|
||||
print('git revision is', str(gitrev))
|
||||
|
||||
if 'gitrevision' not in hashes or ('gitrevision' in hashes and hashes['gitrevision'] != get_hash(gitrev)):
|
||||
print('*** Generating gitrevision.h ***')
|
||||
gitstring = '//Generated by the generate_headers.py script on {t:s}\n\nstd::string gitrevision = \"{rev:s}\";'.format(t = str(datetime.now()), rev = gitrev)
|
||||
gitstring = '//Generated by the generate_headers.py script on {t:s}\n\nstd::string gitrevision = \"{rev:s}\";'.format(t=str(datetime.now()), rev=gitrev)
|
||||
|
||||
f = open(os.path.join(include_dir,'gitrevision.h'),'w')
|
||||
f = open(os.path.join(include_dir, 'gitrevision.h'), 'w')
|
||||
f.write(gitstring)
|
||||
f.close()
|
||||
|
||||
hashes['gitrevision'] = get_hash(gitrev)
|
||||
print(os.path.join(include_dir,'gitrevision.h') + ' written to file')
|
||||
print(os.path.join(include_dir, 'gitrevision.h') + ' written to file')
|
||||
else:
|
||||
print('gitrevision.h is up to date')
|
||||
|
||||
except (subprocess.CalledProcessError,OSError) as err:
|
||||
except (subprocess.CalledProcessError, OSError) as err:
|
||||
print('err:', err)
|
||||
|
||||
|
||||
@@ -238,7 +238,7 @@ def combine_json(root_dir):
|
||||
|
||||
master = []
|
||||
|
||||
for file in glob.glob(os.path.join(root_dir,'dev','fluids','*.json')):
|
||||
for file in glob.glob(os.path.join(root_dir, 'dev', 'fluids', '*.json')):
|
||||
|
||||
path, file_name = os.path.split(file)
|
||||
fluid_name = file_name.split('.')[0]
|
||||
@@ -247,23 +247,23 @@ def combine_json(root_dir):
|
||||
# Load the fluid file
|
||||
fluid = json.load(open(file, 'r'))
|
||||
except ValueError:
|
||||
print('"python -mjson.tool '+file+'" returns ->', end='')
|
||||
subprocess.call('python -mjson.tool '+file, shell = True)
|
||||
print('"python -mjson.tool ' + file + '" returns ->', end='')
|
||||
subprocess.call('python -mjson.tool ' + file, shell=True)
|
||||
raise ValueError('unable to decode file %s' % file)
|
||||
|
||||
master += [fluid]
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_fluids_verbose.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_fluids_verbose.json'), 'w')
|
||||
fp.write(json.dumps(master, **json_options))
|
||||
fp.close()
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_fluids.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_fluids.json'), 'w')
|
||||
fp.write(json.dumps(master))
|
||||
fp.close()
|
||||
|
||||
master = []
|
||||
|
||||
for file in glob.glob(os.path.join(root_dir,'dev','incompressible_liquids','json','*.json')):
|
||||
for file in glob.glob(os.path.join(root_dir, 'dev', 'incompressible_liquids', 'json', '*.json')):
|
||||
|
||||
path, file_name = os.path.split(file)
|
||||
fluid_name = file_name.split('.')[0]
|
||||
@@ -272,17 +272,17 @@ def combine_json(root_dir):
|
||||
# Load the fluid file
|
||||
fluid = json.load(open(file, 'r'))
|
||||
except ValueError:
|
||||
print('"python -mjson.tool '+file+'" returns ->', end='')
|
||||
subprocess.call('python -mjson.tool '+file, shell = True)
|
||||
print('"python -mjson.tool ' + file + '" returns ->', end='')
|
||||
subprocess.call('python -mjson.tool ' + file, shell=True)
|
||||
raise ValueError('unable to decode file %s' % file)
|
||||
|
||||
master += [fluid]
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_incompressibles_verbose.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_incompressibles_verbose.json'), 'w')
|
||||
fp.write(json.dumps(master, **json_options))
|
||||
fp.close()
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_incompressibles.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_incompressibles.json'), 'w')
|
||||
fp.write(json.dumps(master))
|
||||
fp.close()
|
||||
|
||||
@@ -290,20 +290,20 @@ def combine_json(root_dir):
|
||||
def generate():
|
||||
|
||||
import shutil
|
||||
shutil.copy2(os.path.join(repo_root_path, 'externals','Catch','single_include','catch.hpp'),os.path.join(repo_root_path,'include','catch.hpp'))
|
||||
shutil.copy2(os.path.join(repo_root_path, 'externals', 'Catch', 'single_include', 'catch.hpp'), os.path.join(repo_root_path, 'include', 'catch.hpp'))
|
||||
#shutil.copy2(os.path.join(repo_root_path, 'externals','REFPROP-headers','REFPROP_lib.h'),os.path.join(repo_root_path,'include','REFPROP_lib.h'))
|
||||
|
||||
version_to_file(root_dir = repo_root_path)
|
||||
gitrev_to_file(root_dir = repo_root_path)
|
||||
version_to_file(root_dir=repo_root_path)
|
||||
gitrev_to_file(root_dir=repo_root_path)
|
||||
|
||||
TO_CPP(root_dir = repo_root_path, hashes = hashes)
|
||||
TO_CPP(root_dir=repo_root_path, hashes=hashes)
|
||||
|
||||
# Write the hashes to a hashes JSON file
|
||||
if hashes:
|
||||
fp = open(hashes_fname,'w')
|
||||
fp = open(hashes_fname, 'w')
|
||||
fp.write(json.dumps(hashes))
|
||||
fp.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
generate()
|
||||
|
||||
130
dev/genetic.py
130
dev/genetic.py
@@ -10,26 +10,26 @@ import matplotlib.pyplot as plt
|
||||
import CoolProp
|
||||
import CoolProp.CoolProp as CP
|
||||
|
||||
LIBRARY = [i/6.0 for i in range(1,151)]+[0.35+i/2000 for i in range(1,100)]+[0.05+0.001*i for i in range(1,100)]+[i+0.5 for i in range(10)]
|
||||
LIBRARY = [i / 6.0 for i in range(1, 151)] + [0.35 + i / 2000 for i in range(1, 100)] + [0.05 + 0.001 * i for i in range(1, 100)] + [i + 0.5 for i in range(10)]
|
||||
#LIBRARY = [i/1000 for i in range(1,20000)]
|
||||
|
||||
|
||||
class Sample(object):
|
||||
def __init__(self,v):
|
||||
def __init__(self, v):
|
||||
self.v = v
|
||||
|
||||
|
||||
class GeneticAncillaryFitter(object):
|
||||
def __init__(self,
|
||||
num_samples = 600, # Have this many chromos in the sample group
|
||||
num_selected = 60, # Have this many chromos in the selected group
|
||||
mutation_factor = 2, # Randomly mutate 1/n of the chromosomes
|
||||
num_powers = 5, # How many powers in the fit
|
||||
Ref = 'R407C',
|
||||
value = 'rhoV',
|
||||
addTr = True,
|
||||
values = None,
|
||||
Tlims = None
|
||||
num_samples=600, # Have this many chromos in the sample group
|
||||
num_selected=60, # Have this many chromos in the selected group
|
||||
mutation_factor=2, # Randomly mutate 1/n of the chromosomes
|
||||
num_powers=5, # How many powers in the fit
|
||||
Ref='R407C',
|
||||
value='rhoV',
|
||||
addTr=True,
|
||||
values=None,
|
||||
Tlims=None
|
||||
):
|
||||
self.num_samples = num_samples
|
||||
self.num_selected = num_selected
|
||||
@@ -39,22 +39,22 @@ class GeneticAncillaryFitter(object):
|
||||
self.value = value
|
||||
self.Ref = Ref
|
||||
|
||||
#Thermodynamics
|
||||
# Thermodynamics
|
||||
from CoolProp.CoolProp import PropsSI
|
||||
|
||||
if values is None:
|
||||
self.Tc = PropsSI(Ref,'Tcrit')
|
||||
self.pc = PropsSI(Ref,'pcrit')
|
||||
self.rhoc = PropsSI(Ref,'rhomolar_critical')
|
||||
self.Tmin = PropsSI(Ref,'Tmin')
|
||||
self.Tc = PropsSI(Ref, 'Tcrit')
|
||||
self.pc = PropsSI(Ref, 'pcrit')
|
||||
self.rhoc = PropsSI(Ref, 'rhomolar_critical')
|
||||
self.Tmin = PropsSI(Ref, 'Tmin')
|
||||
if Tlims is None:
|
||||
self.T = np.append(np.linspace(self.Tmin+1e-14, self.Tc-1,150), np.logspace(np.log10(self.Tc-1), np.log10(self.Tc)-1e-15,40))
|
||||
self.T = np.append(np.linspace(self.Tmin + 1e-14, self.Tc - 1, 150), np.logspace(np.log10(self.Tc - 1), np.log10(self.Tc) - 1e-15, 40))
|
||||
else:
|
||||
self.T = np.linspace(Tlims[0],Tlims[1])
|
||||
self.pL = np.array(PropsSI('P','T',self.T,'Q',[0]*len(self.T),Ref))
|
||||
self.pV = np.array(PropsSI('P','T',self.T,'Q',[1]*len(self.T),Ref))
|
||||
self.rhoL = PropsSI('Dmolar','T',self.T,'Q',[0]*len(self.T),Ref)
|
||||
self.rhoV = PropsSI('Dmolar','T',self.T,'Q',[1]*len(self.T),Ref)
|
||||
self.T = np.linspace(Tlims[0], Tlims[1])
|
||||
self.pL = np.array(PropsSI('P', 'T', self.T, 'Q', [0] * len(self.T), Ref))
|
||||
self.pV = np.array(PropsSI('P', 'T', self.T, 'Q', [1] * len(self.T), Ref))
|
||||
self.rhoL = PropsSI('Dmolar', 'T', self.T, 'Q', [0] * len(self.T), Ref)
|
||||
self.rhoV = PropsSI('Dmolar', 'T', self.T, 'Q', [1] * len(self.T), Ref)
|
||||
else:
|
||||
self.Tc = values['Tcrit']
|
||||
self.pc = values['pcrit']
|
||||
@@ -67,16 +67,16 @@ class GeneticAncillaryFitter(object):
|
||||
self.rhoL = np.array(values['rhoL'])
|
||||
self.rhoV = np.array(values['rhoV'])
|
||||
|
||||
self.logpLpc = (np.log(self.pL)-np.log(self.pc))
|
||||
self.logpVpc = (np.log(self.pV)-np.log(self.pc))
|
||||
self.rhoLrhoc = np.array(self.rhoL)/self.rhoc
|
||||
self.rhoVrhoc = np.array(self.rhoV)/self.rhoc
|
||||
self.logrhoLrhoc = np.log(self.rhoL)-np.log(self.rhoc)
|
||||
self.logrhoVrhoc = np.log(self.rhoV)-np.log(self.rhoc)
|
||||
self.logpLpc = (np.log(self.pL) - np.log(self.pc))
|
||||
self.logpVpc = (np.log(self.pV) - np.log(self.pc))
|
||||
self.rhoLrhoc = np.array(self.rhoL) / self.rhoc
|
||||
self.rhoVrhoc = np.array(self.rhoV) / self.rhoc
|
||||
self.logrhoLrhoc = np.log(self.rhoL) - np.log(self.rhoc)
|
||||
self.logrhoVrhoc = np.log(self.rhoV) - np.log(self.rhoc)
|
||||
|
||||
self.x = 1.0-self.T/self.Tc
|
||||
self.x = 1.0 - self.T / self.Tc
|
||||
|
||||
MM = PropsSI(Ref,'molemass')
|
||||
MM = PropsSI(Ref, 'molemass')
|
||||
self.T_r = self.Tc
|
||||
|
||||
if self.value == 'pL':
|
||||
@@ -112,7 +112,7 @@ class GeneticAncillaryFitter(object):
|
||||
self.description = "rho'' = rhoc*exp(Tc/T*sum(n_i*theta^t_i))"
|
||||
self.reducing_value = self.rhoc
|
||||
elif self.value == 'rhoLnoexp':
|
||||
self.LHS = (self.rhoLrhoc-1).copy()
|
||||
self.LHS = (self.rhoLrhoc - 1).copy()
|
||||
self.EOS_value = self.rhoL
|
||||
self.description = "rho' = rhoc*(1+sum(n_i*theta^t_i))"
|
||||
self.reducing_value = self.rhoc
|
||||
@@ -123,7 +123,7 @@ class GeneticAncillaryFitter(object):
|
||||
raise ValueError('Invalid combination')
|
||||
|
||||
if self.addTr:
|
||||
self.LHS *= self.T/self.Tc
|
||||
self.LHS *= self.T / self.Tc
|
||||
|
||||
def generate_random_chromosomes(self,):
|
||||
'''
|
||||
@@ -131,7 +131,7 @@ class GeneticAncillaryFitter(object):
|
||||
'''
|
||||
chromos = []
|
||||
while len(chromos) < self.num_samples:
|
||||
chromos.append(Sample(sorted(random.sample(LIBRARY,self.num_powers))))
|
||||
chromos.append(Sample(sorted(random.sample(LIBRARY, self.num_powers))))
|
||||
return chromos
|
||||
|
||||
def fitness(self, chromo):
|
||||
@@ -146,12 +146,12 @@ class GeneticAncillaryFitter(object):
|
||||
# TODO: more numpy broadcasting should speed this up even more
|
||||
# Another few times faster ought to be possible
|
||||
I = len(chromo.v)
|
||||
A = np.zeros((I,I))
|
||||
b = np.zeros((I,1))
|
||||
A = np.zeros((I, I))
|
||||
b = np.zeros((I, 1))
|
||||
for i in range(I):
|
||||
for j in range(I):
|
||||
A[i,j] = np.sum(theta_t[i]*theta_t[j])
|
||||
b[i] = np.sum(theta_t[i]*self.LHS)
|
||||
A[i, j] = np.sum(theta_t[i] * theta_t[j])
|
||||
b[i] = np.sum(theta_t[i] * self.LHS)
|
||||
|
||||
# If you end up with a singular matrix, quit this run
|
||||
try:
|
||||
@@ -161,21 +161,21 @@ class GeneticAncillaryFitter(object):
|
||||
return
|
||||
|
||||
chromo.beta = n
|
||||
RHS = np.sum(n * self.x.reshape(-1, 1)**chromo.v, axis = 1)
|
||||
RHS = np.sum(n * self.x.reshape(-1, 1)**chromo.v, axis=1)
|
||||
|
||||
if self.addTr:
|
||||
RHS *= self.Tc/self.T
|
||||
RHS *= self.Tc / self.T
|
||||
|
||||
if self.value in ['pL','pV']:
|
||||
fit_value = np.exp(RHS)*self.pc
|
||||
elif self.value in ['rhoL','rhoV']:
|
||||
fit_value = np.exp(RHS)*self.rhoc
|
||||
if self.value in ['pL', 'pV']:
|
||||
fit_value = np.exp(RHS) * self.pc
|
||||
elif self.value in ['rhoL', 'rhoV']:
|
||||
fit_value = np.exp(RHS) * self.rhoc
|
||||
elif self.value == 'rhoLnoexp':
|
||||
fit_value = self.rhoc*(1+RHS)
|
||||
fit_value = self.rhoc * (1 + RHS)
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
max_abserror = np.max(np.abs((fit_value/self.EOS_value)-1)*100)
|
||||
max_abserror = np.max(np.abs((fit_value / self.EOS_value) - 1) * 100)
|
||||
|
||||
chromo.fitness = max_abserror
|
||||
chromo.fit_value = fit_value
|
||||
@@ -210,7 +210,7 @@ class GeneticAncillaryFitter(object):
|
||||
Mutate a chromosome by changing one of the parameters, but only if it improves the fitness
|
||||
'''
|
||||
v = chromo.v
|
||||
if hasattr(chromo,'fitness'):
|
||||
if hasattr(chromo, 'fitness'):
|
||||
old_fitness = chromo.fitness
|
||||
else:
|
||||
old_fitness = self.fitness(chromo)
|
||||
@@ -233,10 +233,10 @@ class GeneticAncillaryFitter(object):
|
||||
self.fitness(chromo)
|
||||
# print '#'
|
||||
|
||||
decorated = sorted([(sample.fitness,sample) for sample in samples])
|
||||
samples = [s for sv,s in decorated]
|
||||
values = [sv for sv,s in decorated]
|
||||
plt.plot(values[0:len(values)//2])
|
||||
decorated = sorted([(sample.fitness, sample) for sample in samples])
|
||||
samples = [s for sv, s in decorated]
|
||||
values = [sv for sv, s in decorated]
|
||||
plt.plot(values[0:len(values) // 2])
|
||||
plt.close()
|
||||
|
||||
# Main loop: each generation select a subset of the sample and breed from
|
||||
@@ -247,7 +247,7 @@ class GeneticAncillaryFitter(object):
|
||||
|
||||
# Generate the selected group from sample- take the top 10% of samples
|
||||
# and tourny select to generate the rest of selected.
|
||||
ten_percent = int(len(samples)*.1)
|
||||
ten_percent = int(len(samples) * .1)
|
||||
selected = samples[:ten_percent]
|
||||
while len(selected) < self.num_selected:
|
||||
selected.append(self.tourny_select_chromo(samples))
|
||||
@@ -259,7 +259,7 @@ class GeneticAncillaryFitter(object):
|
||||
random.choice(selected)))
|
||||
|
||||
# Apply a mutation to a subset of the solution set
|
||||
mutate_indices = random.sample(range(len(solution)), len(solution)//self.mutation_factor)
|
||||
mutate_indices = random.sample(range(len(solution)), len(solution) // self.mutation_factor)
|
||||
for i in mutate_indices:
|
||||
solution[i] = self.mutate(solution[i])
|
||||
|
||||
@@ -267,8 +267,8 @@ class GeneticAncillaryFitter(object):
|
||||
self.fitness(chromo)
|
||||
# print '#'
|
||||
|
||||
decorated = sorted([(sample.fitness,sample) for sample in solution])
|
||||
samples = [s for sv,s in decorated]
|
||||
decorated = sorted([(sample.fitness, sample) for sample in solution])
|
||||
samples = [s for sv, s in decorated]
|
||||
|
||||
# print '------------------ Top 10 values ---------------'
|
||||
# for sample in samples[0:10]:
|
||||
@@ -278,7 +278,7 @@ class GeneticAncillaryFitter(object):
|
||||
# print str(samples[0].v), samples[0].beta.tolist()
|
||||
|
||||
# Print useful stats about this generation
|
||||
(min, median, max) = [samples[0].fitness, samples[len(samples)//2].fitness, samples[-1].fitness]
|
||||
(min, median, max) = [samples[0].fitness, samples[len(samples) // 2].fitness, samples[-1].fitness]
|
||||
# print("{0} best value: {1}. fitness: best {2}, median {3}, worst {4}".format(generation, samples[0].v, min, median, max))
|
||||
|
||||
# If the string representations of all the chromosomes are the same, stop
|
||||
@@ -313,17 +313,17 @@ def build_ancillaries(name, **kwargs):
|
||||
|
||||
j = dict()
|
||||
j['ANCILLARIES'] = dict()
|
||||
gaf = GeneticAncillaryFitter(Ref = name, value = 'pL', addTr = True, num_powers = 6, **kwargs)
|
||||
gaf = GeneticAncillaryFitter(Ref=name, value='pL', addTr=True, num_powers=6, **kwargs)
|
||||
j['ANCILLARIES']['pL'] = gaf.run()
|
||||
gaf = GeneticAncillaryFitter(Ref = name, value = 'pV', addTr = True, num_powers = 6, **kwargs)
|
||||
gaf = GeneticAncillaryFitter(Ref=name, value='pV', addTr=True, num_powers=6, **kwargs)
|
||||
j['ANCILLARIES']['pV'] = gaf.run()
|
||||
gaf = GeneticAncillaryFitter(Ref = name, value = 'rhoLnoexp', addTr = False, num_powers = 6, **kwargs)
|
||||
gaf = GeneticAncillaryFitter(Ref=name, value='rhoLnoexp', addTr=False, num_powers=6, **kwargs)
|
||||
j['ANCILLARIES']['rhoL'] = gaf.run()
|
||||
gaf = GeneticAncillaryFitter(Ref = name, value = 'rhoV', addTr = True, num_powers = 6, **kwargs)
|
||||
gaf = GeneticAncillaryFitter(Ref=name, value='rhoV', addTr=True, num_powers=6, **kwargs)
|
||||
j['ANCILLARIES']['rhoV'] = gaf.run()
|
||||
|
||||
fp = open(os.path.join('ancillaries',name+'_anc.json'),'w')
|
||||
print(json.dumps(j, indent = 2), file=fp)
|
||||
fp = open(os.path.join('ancillaries', name + '_anc.json'), 'w')
|
||||
print(json.dumps(j, indent=2), file=fp)
|
||||
fp.close()
|
||||
|
||||
|
||||
@@ -331,11 +331,11 @@ def build_all_ancillaries():
|
||||
for fluid in sorted(CoolProp.__fluids__):
|
||||
print(fluid)
|
||||
if fluid in ['SES36']:
|
||||
build_ancillaries(fluid, Tlims = [CP.Props(fluid,'Ttriple'), CP.Props(fluid, 'Tcrit')-1])
|
||||
build_ancillaries(fluid, Tlims=[CP.Props(fluid, 'Ttriple'), CP.Props(fluid, 'Tcrit') - 1])
|
||||
elif fluid == 'R507A':
|
||||
build_ancillaries(fluid, Tlims = [CP.Props(fluid,'Ttriple'), CP.Props(fluid, 'Tcrit')-0.1])
|
||||
build_ancillaries(fluid, Tlims=[CP.Props(fluid, 'Ttriple'), CP.Props(fluid, 'Tcrit') - 0.1])
|
||||
elif fluid == 'R407F':
|
||||
build_ancillaries(fluid, Tlims = [CP.Props(fluid,'Ttriple'), CP.Props(fluid, 'Tcrit')-2])
|
||||
build_ancillaries(fluid, Tlims=[CP.Props(fluid, 'Ttriple'), CP.Props(fluid, 'Tcrit') - 2])
|
||||
else:
|
||||
build_ancillaries(fluid)
|
||||
|
||||
@@ -344,7 +344,7 @@ if __name__ == "__main__":
|
||||
|
||||
fluid = 'Methanol'
|
||||
RPfluid = fluid
|
||||
build_ancillaries(RPfluid, Tlims = [CP.PropsSI(fluid,'Ttriple'), CP.PropsSI(fluid, 'Tcrit')-0.01])
|
||||
build_ancillaries(RPfluid, Tlims=[CP.PropsSI(fluid, 'Ttriple'), CP.PropsSI(fluid, 'Tcrit') - 0.01])
|
||||
|
||||
#~ build_all_ancillaries()
|
||||
# inject_ancillaries()
|
||||
|
||||
@@ -14,20 +14,20 @@ class IncompressibleData(object):
|
||||
Implements both data structures and fitting
|
||||
procedures.
|
||||
"""
|
||||
INCOMPRESSIBLE_NOT_SET = 'notdefined'
|
||||
INCOMPRESSIBLE_POLYNOMIAL = 'polynomial'
|
||||
INCOMPRESSIBLE_NOT_SET = 'notdefined'
|
||||
INCOMPRESSIBLE_POLYNOMIAL = 'polynomial'
|
||||
INCOMPRESSIBLE_EXPPOLYNOMIAL = 'exppolynomial'
|
||||
INCOMPRESSIBLE_EXPONENTIAL = 'exponential'
|
||||
INCOMPRESSIBLE_LOGEXPONENTIAL= 'logexponential'
|
||||
INCOMPRESSIBLE_POLYOFFSET = 'polyoffset'
|
||||
INCOMPRESSIBLE_CHEBYSHEV = 'chebyshev'
|
||||
INCOMPRESSIBLE_EXPONENTIAL = 'exponential'
|
||||
INCOMPRESSIBLE_LOGEXPONENTIAL = 'logexponential'
|
||||
INCOMPRESSIBLE_POLYOFFSET = 'polyoffset'
|
||||
INCOMPRESSIBLE_CHEBYSHEV = 'chebyshev'
|
||||
|
||||
SOURCE_DATA = 'data'
|
||||
SOURCE_DATA = 'data'
|
||||
SOURCE_EQUATION = 'equation'
|
||||
SOURCE_COEFFS = 'coefficients'
|
||||
SOURCE_NOT_SET = 'notdefined'
|
||||
SOURCE_COEFFS = 'coefficients'
|
||||
SOURCE_NOT_SET = 'notdefined'
|
||||
|
||||
maxLin = np.finfo(np.float64).max-1
|
||||
maxLin = np.finfo(np.float64).max - 1
|
||||
minLin = -maxLin
|
||||
|
||||
maxLog = np.log(maxLin)
|
||||
@@ -35,14 +35,14 @@ class IncompressibleData(object):
|
||||
|
||||
def __init__(self):
|
||||
self.source = self.SOURCE_NOT_SET
|
||||
self.type = self.INCOMPRESSIBLE_NOT_SET
|
||||
self.coeffs = None #np.zeros((4,4))
|
||||
self.data = None # None #np.zeros((10,10))
|
||||
self.xData = None # In case you need a customised first data set (temperature?)
|
||||
self.yData = None # In case you need a customised second data set (concentration?)
|
||||
self.sErr = None # Coefficient of determination
|
||||
self.NRMS = None # Normalised RMS: (square root of the mean of the squares of the deviations)/(max-min)
|
||||
self.DEBUG = False
|
||||
self.type = self.INCOMPRESSIBLE_NOT_SET
|
||||
self.coeffs = None # np.zeros((4,4))
|
||||
self.data = None # None #np.zeros((10,10))
|
||||
self.xData = None # In case you need a customised first data set (temperature?)
|
||||
self.yData = None # In case you need a customised second data set (concentration?)
|
||||
self.sErr = None # Coefficient of determination
|
||||
self.NRMS = None # Normalised RMS: (square root of the mean of the squares of the deviations)/(max-min)
|
||||
self.DEBUG = False
|
||||
|
||||
@staticmethod
|
||||
def baseFunc(x, y=0.0, xbase=0.0, ybase=0.0, eqnType=None, c=None):
|
||||
@@ -50,53 +50,53 @@ class IncompressibleData(object):
|
||||
if eqnType is None: raise ValueError("You did not provide data for eqnType.")
|
||||
if c is None: raise ValueError("You did not provide data for the coefficients.")
|
||||
|
||||
if eqnType==IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL:
|
||||
return np.polynomial.polynomial.polyval2d(x-xbase, y-ybase, c)
|
||||
if eqnType == IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL:
|
||||
return np.polynomial.polynomial.polyval2d(x - xbase, y - ybase, c)
|
||||
|
||||
elif eqnType==IncompressibleData.INCOMPRESSIBLE_POLYOFFSET:
|
||||
elif eqnType == IncompressibleData.INCOMPRESSIBLE_POLYOFFSET:
|
||||
#if y!=0.0: raise ValueError("This is 1D only, use x not y.")
|
||||
return IncompressibleData.basePolyOffset(c, x) # offset included in coeffs
|
||||
return IncompressibleData.basePolyOffset(c, x) # offset included in coeffs
|
||||
|
||||
elif eqnType==IncompressibleData.INCOMPRESSIBLE_EXPONENTIAL:
|
||||
elif eqnType == IncompressibleData.INCOMPRESSIBLE_EXPONENTIAL:
|
||||
#if y!=0.0: raise ValueError("This is 1D only, use x not y.")
|
||||
return IncompressibleData.baseExponential(c, x)
|
||||
|
||||
elif eqnType==IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL:
|
||||
elif eqnType == IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL:
|
||||
#if y!=0.0: raise ValueError("This is 1D only, use x not y.")
|
||||
return IncompressibleData.baseLogexponential(c, x)
|
||||
|
||||
elif eqnType==IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL:
|
||||
return np.exp(np.polynomial.polynomial.polyval2d(x-xbase, y-ybase, c))
|
||||
elif eqnType == IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL:
|
||||
return np.exp(np.polynomial.polynomial.polyval2d(x - xbase, y - ybase, c))
|
||||
|
||||
else:
|
||||
raise ValueError("Unknown function: {0}.".format(eqnType))
|
||||
|
||||
@staticmethod
|
||||
def baseExponential(co, x):
|
||||
r,c,coeffs = IncompressibleFitter.shapeArray(co)
|
||||
if not ( (r==3 and c==1) or (r==1 and c==3) ):
|
||||
raise ValueError("You have to provide a 3,1 matrix of coefficients, not ({0},{1}).".format(r,c))
|
||||
r, c, coeffs = IncompressibleFitter.shapeArray(co)
|
||||
if not ((r == 3 and c == 1) or (r == 1 and c == 3)):
|
||||
raise ValueError("You have to provide a 3,1 matrix of coefficients, not ({0},{1}).".format(r, c))
|
||||
coeffs_tmp = np.array(coeffs.flat)
|
||||
return np.exp(np.clip( (coeffs_tmp[0]/ ( x+coeffs_tmp[1] ) - coeffs_tmp[2]),IncompressibleData.minLog,IncompressibleData.maxLog))
|
||||
return np.exp(np.clip((coeffs_tmp[0] / (x + coeffs_tmp[1]) - coeffs_tmp[2]), IncompressibleData.minLog, IncompressibleData.maxLog))
|
||||
|
||||
@staticmethod
|
||||
def baseLogexponential(co, x):
|
||||
r,c,coeffs = IncompressibleFitter.shapeArray(co)
|
||||
if not ( (r==3 and c==1) or (r==1 and c==3) ):
|
||||
raise ValueError("You have to provide a 4,1 matrix of coefficients, not ({0},{1}).".format(r,c))
|
||||
r, c, coeffs = IncompressibleFitter.shapeArray(co)
|
||||
if not ((r == 3 and c == 1) or (r == 1 and c == 3)):
|
||||
raise ValueError("You have to provide a 4,1 matrix of coefficients, not ({0},{1}).".format(r, c))
|
||||
coeffs_tmp = np.array(coeffs.flat)
|
||||
return np.exp(np.clip(np.log(np.clip(1.0/(x+coeffs_tmp[0]) + 1.0/(x+coeffs_tmp[0])**2,1e-10,IncompressibleData.maxLin))*coeffs_tmp[1]+coeffs_tmp[2],IncompressibleData.minLog,IncompressibleData.maxLog))
|
||||
return np.exp(np.clip(np.log(np.clip(1.0 / (x + coeffs_tmp[0]) + 1.0 / (x + coeffs_tmp[0])**2, 1e-10, IncompressibleData.maxLin)) * coeffs_tmp[1] + coeffs_tmp[2], IncompressibleData.minLog, IncompressibleData.maxLog))
|
||||
|
||||
@staticmethod
|
||||
def basePolyOffset(co, x):
|
||||
r,c,coeffs = IncompressibleFitter.shapeArray(co)
|
||||
if not ( c==1 or r==1 ):
|
||||
raise ValueError("You have to provide a 1D vector of coefficients, not ({0},{1}).".format(r,c))
|
||||
r, c, coeffs = IncompressibleFitter.shapeArray(co)
|
||||
if not (c == 1 or r == 1):
|
||||
raise ValueError("You have to provide a 1D vector of coefficients, not ({0},{1}).".format(r, c))
|
||||
offset = coeffs[0][0]
|
||||
coeffs = np.array(coeffs.flat)[1:]
|
||||
return np.polynomial.polynomial.polyval(x-offset, coeffs)
|
||||
return np.polynomial.polynomial.polyval(x - offset, coeffs)
|
||||
|
||||
### Base functions that handle the custom data type, just a place holder to show the structure.
|
||||
# Base functions that handle the custom data type, just a place holder to show the structure.
|
||||
def baseFunction(self, x, y=0.0, xbase=0.0, ybase=0.0, c=None):
|
||||
if c is None: c = self.coeffs
|
||||
return self.baseFunc(x, y, xbase, ybase, self.type, c)
|
||||
@@ -108,46 +108,46 @@ class IncompressibleData(object):
|
||||
if (not y is None and not self.yData is None and not IncompressibleFitter.allClose(y, self.yData)) \
|
||||
or (y is None and self.yData is None): raise ValueError("I do not know which y-value you would like to use. Define either y or self.yData.")
|
||||
|
||||
if x is None and not self.xData is None: x=self.xData
|
||||
if y is None and not self.yData is None: y=self.yData
|
||||
if x is None and not self.xData is None: x = self.xData
|
||||
if y is None and not self.yData is None: y = self.yData
|
||||
|
||||
#res = None
|
||||
#r2 = None
|
||||
|
||||
res,sErr = IncompressibleFitter.fitter(x=x, y=y, z=self.data, \
|
||||
res, sErr = IncompressibleFitter.fitter(x=x, y=y, z=self.data, \
|
||||
xbase=xbase, ybase=ybase, \
|
||||
eqnType=self.type, \
|
||||
coeffs=self.coeffs, DEBUG=self.DEBUG)
|
||||
|
||||
bestCoeffs = np.copy(res)
|
||||
bestType = self.type
|
||||
bestsErr = np.copy(sErr)
|
||||
bestRMS = np.sqrt(np.square(bestsErr).mean()).sum()
|
||||
bestType = self.type
|
||||
bestsErr = np.copy(sErr)
|
||||
bestRMS = np.sqrt(np.square(bestsErr).mean()).sum()
|
||||
|
||||
count = 0
|
||||
while bestRMS>0.03 and count<2:
|
||||
while bestRMS > 0.03 and count < 2:
|
||||
#if self.DEBUG: print("Poor solution found, trying once more with more coefficients.")
|
||||
if self.type==IncompressibleData.INCOMPRESSIBLE_EXPONENTIAL:
|
||||
if self.type == IncompressibleData.INCOMPRESSIBLE_EXPONENTIAL:
|
||||
if self.DEBUG: print("Poor solution found with exponential, trying once more with log exponential.")
|
||||
self.type=IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL
|
||||
self.coeffs = np.array([-250,1.5,10])
|
||||
res,sErr = IncompressibleFitter.fitter(x=x, y=y, z=self.data, \
|
||||
self.type = IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL
|
||||
self.coeffs = np.array([-250, 1.5, 10])
|
||||
res, sErr = IncompressibleFitter.fitter(x=x, y=y, z=self.data, \
|
||||
xbase=xbase, ybase=ybase, \
|
||||
eqnType=self.type, \
|
||||
coeffs=self.coeffs, DEBUG=self.DEBUG)
|
||||
|
||||
elif self.type==IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL:
|
||||
xLen = np.round([len(x)/1.5])
|
||||
yLen = np.round([len(y)/1.5])
|
||||
xLen = np.min([xLen,4])
|
||||
yLen = np.min([yLen,6])
|
||||
elif self.type == IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL:
|
||||
xLen = np.round([len(x) / 1.5])
|
||||
yLen = np.round([len(y) / 1.5])
|
||||
xLen = np.min([xLen, 4])
|
||||
yLen = np.min([yLen, 6])
|
||||
|
||||
if (xLen+yLen) > 2:
|
||||
if (xLen + yLen) > 2:
|
||||
if self.DEBUG: print("Poor solution found with log exponential, trying once more with exponential polynomial.")
|
||||
self.type=IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL
|
||||
self.type = IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL
|
||||
|
||||
self.coeffs = np.zeros((xLen,yLen))
|
||||
res,sErr = IncompressibleFitter.fitter(x=x, y=y, z=self.data, \
|
||||
self.coeffs = np.zeros((xLen, yLen))
|
||||
res, sErr = IncompressibleFitter.fitter(x=x, y=y, z=self.data, \
|
||||
xbase=xbase, ybase=ybase, \
|
||||
eqnType=self.type, \
|
||||
coeffs=self.coeffs, DEBUG=self.DEBUG)
|
||||
@@ -162,11 +162,11 @@ class IncompressibleData(object):
|
||||
# coeffs=self.coeffs, DEBUG=self.DEBUG)
|
||||
|
||||
RMS = np.sqrt(np.square(sErr).mean()).sum()
|
||||
if RMS<bestRMS: # Better fit
|
||||
if RMS < bestRMS: # Better fit
|
||||
bestCoeffs = np.copy(res)
|
||||
bestType = self.type
|
||||
bestsErr = np.copy(sErr)
|
||||
bestRMS = RMS
|
||||
bestType = self.type
|
||||
bestsErr = np.copy(sErr)
|
||||
bestRMS = RMS
|
||||
|
||||
count += 1
|
||||
|
||||
@@ -177,19 +177,19 @@ class IncompressibleData(object):
|
||||
else:
|
||||
if self.DEBUG: print("Best fit for: {0}".format(bestType))
|
||||
self.coeffs = bestCoeffs
|
||||
self.type = bestType
|
||||
self.sErr = bestsErr
|
||||
self.type = bestType
|
||||
self.sErr = bestsErr
|
||||
if self.type == IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL:
|
||||
self.NRMS = bestRMS/(np.nanmax(self.data)-np.nanmin(self.data))
|
||||
self.NRMS = bestRMS / (np.nanmax(self.data) - np.nanmin(self.data))
|
||||
elif self.type == IncompressibleData.INCOMPRESSIBLE_EXPONENTIAL or \
|
||||
self.type == IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL or \
|
||||
self.type == IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL:
|
||||
self.NRMS = bestRMS/(np.log(np.nanmax(self.data))-np.log(np.nanmin(self.data)))
|
||||
self.NRMS = bestRMS / (np.log(np.nanmax(self.data)) - np.log(np.nanmin(self.data)))
|
||||
else:
|
||||
raise ValueError("Unknown function.")
|
||||
|
||||
#if self.DEBUG: print("Fitting statistics:")
|
||||
#SSE = np.square(self.sErr).sum() # Sum of squares due to error
|
||||
# SSE = np.square(self.sErr).sum() # Sum of squares due to error
|
||||
#SST = ((zData-zData.mean())**2).sum()
|
||||
#R2 = 1-(ssErr/ssTot )
|
||||
|
||||
@@ -221,18 +221,18 @@ class IncompressibleData(object):
|
||||
except:
|
||||
j['NRMS'] = 'null'
|
||||
|
||||
j['type'] = self.type
|
||||
j['type'] = self.type
|
||||
return j
|
||||
|
||||
def fromJSON(self, j):
|
||||
try:
|
||||
self.coeffs = np.array(j['coeffs'])
|
||||
self.type = j['type']
|
||||
self.type = j['type']
|
||||
except:
|
||||
self.coeffs = None
|
||||
self.type = IncompressibleData.INCOMPRESSIBLE_NOT_SET
|
||||
self.type = IncompressibleData.INCOMPRESSIBLE_NOT_SET
|
||||
try:
|
||||
self.NRMS = j['NRMS']
|
||||
self.NRMS = j['NRMS']
|
||||
except:
|
||||
self.NRMS = None
|
||||
return
|
||||
@@ -241,8 +241,8 @@ class IncompressibleData(object):
|
||||
class IncompressibleFitter(object):
|
||||
|
||||
@staticmethod
|
||||
def allClose(a,b):
|
||||
if np.array(a).shape==np.array(b).shape:
|
||||
def allClose(a, b):
|
||||
if np.array(a).shape == np.array(b).shape:
|
||||
return np.allclose(a, b)
|
||||
else: return False
|
||||
|
||||
@@ -256,25 +256,25 @@ class IncompressibleFitter(object):
|
||||
r = 0
|
||||
c = 0
|
||||
array = np.array(array)
|
||||
if array.ndim==0:
|
||||
if array.ndim == 0:
|
||||
array = np.array([[array]])
|
||||
r = 1
|
||||
c = 1
|
||||
elif array.ndim==1:
|
||||
if axs==0:
|
||||
elif array.ndim == 1:
|
||||
if axs == 0:
|
||||
r = len(array)
|
||||
c = 1
|
||||
elif axs==1:
|
||||
elif axs == 1:
|
||||
r = 1
|
||||
c = len(array)
|
||||
else:
|
||||
raise ValueError("You have to provide 0 or 1 to the axs parameter, not {0}.".format(axs))
|
||||
elif array.ndim==2:
|
||||
(r,c) = array.shape
|
||||
elif array.ndim == 2:
|
||||
(r, c) = array.shape
|
||||
else:
|
||||
print(array)
|
||||
raise ValueError("You have to provide a 1D-vector or a 2D-matrix.")
|
||||
return (r,c,np.reshape(array,(r,c)))
|
||||
return (r, c, np.reshape(array, (r, c)))
|
||||
|
||||
@staticmethod
|
||||
def fitter(x=None, y=None, z=None, \
|
||||
@@ -309,73 +309,73 @@ class IncompressibleFitter(object):
|
||||
if coeffs is None: raise ValueError("You did not provide data for the coefficients.")
|
||||
if DEBUG is None: raise ValueError("You did not provide data for DEBUG.")
|
||||
|
||||
zr,zc,_ = IncompressibleFitter.shapeArray(z)
|
||||
xr,xc,x = IncompressibleFitter.shapeArray(x)
|
||||
yr,yc,y = IncompressibleFitter.shapeArray(y, axs=1)
|
||||
zr, zc, _ = IncompressibleFitter.shapeArray(z)
|
||||
xr, xc, x = IncompressibleFitter.shapeArray(x)
|
||||
yr, yc, y = IncompressibleFitter.shapeArray(y, axs=1)
|
||||
|
||||
if DEBUG: print("Data : ({0},{1})".format(zr,zc))
|
||||
if DEBUG: print("x-axis : ({0},{1})".format(xr,xc))
|
||||
if DEBUG: print("y-axis : ({0},{1})".format(yr,yc))
|
||||
if DEBUG: print("Data : ({0},{1})".format(zr, zc))
|
||||
if DEBUG: print("x-axis : ({0},{1})".format(xr, xc))
|
||||
if DEBUG: print("y-axis : ({0},{1})".format(yr, yc))
|
||||
|
||||
if zr==1 and zc==1: #
|
||||
if zr == 1 and zc == 1:
|
||||
if DEBUG: print("Data no set, we cannot fit the coefficients")
|
||||
return None,None
|
||||
return None, None
|
||||
|
||||
if (xc!=1): raise ValueError("The first input has to be a 2D array with one column.")
|
||||
if (yr!=1): raise ValueError("The second input has to be a 2D array with one row.")
|
||||
if (xr!=zr): raise ValueError("First independent vector and result vector have to have the same number of rows, {0} is not {1}.".format(xr,zr))
|
||||
if (yc!=zc): raise ValueError("Second independent vector and result vector have to have the same number of columns, {0} is not {1}.".format(yc,zc))
|
||||
if (xc != 1): raise ValueError("The first input has to be a 2D array with one column.")
|
||||
if (yr != 1): raise ValueError("The second input has to be a 2D array with one row.")
|
||||
if (xr != zr): raise ValueError("First independent vector and result vector have to have the same number of rows, {0} is not {1}.".format(xr, zr))
|
||||
if (yc != zc): raise ValueError("Second independent vector and result vector have to have the same number of columns, {0} is not {1}.".format(yc, zc))
|
||||
|
||||
if DEBUG: print("Coefficients before fitting: \n{0}".format(coeffs))
|
||||
|
||||
# Polynomial fitting works for both 1D and 2D functions
|
||||
if eqnType==IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL or eqnType==IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL:
|
||||
if eqnType == IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL or eqnType == IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL:
|
||||
|
||||
cr,cc,_ = IncompressibleFitter.shapeArray(coeffs)
|
||||
if DEBUG: print("Coefficients: ({0},{1})".format(cr,cc))
|
||||
if (xr==1 and xc==1 and cr>1):
|
||||
if DEBUG: print("Discarding coefficient rows, {0} -> {1}".format(cr,xr))
|
||||
cr, cc, _ = IncompressibleFitter.shapeArray(coeffs)
|
||||
if DEBUG: print("Coefficients: ({0},{1})".format(cr, cc))
|
||||
if (xr == 1 and xc == 1 and cr > 1):
|
||||
if DEBUG: print("Discarding coefficient rows, {0} -> {1}".format(cr, xr))
|
||||
coeffs = coeffs[0]
|
||||
coeffs = coeffs.reshape((1,cc))
|
||||
if (yr==1 and yc==1 and cc>1):
|
||||
if DEBUG: print("Discarding coefficient columns, {0} -> {1}".format(cc,yc))
|
||||
coeffs = coeffs.reshape((1, cc))
|
||||
if (yr == 1 and yc == 1 and cc > 1):
|
||||
if DEBUG: print("Discarding coefficient columns, {0} -> {1}".format(cc, yc))
|
||||
coeffs = coeffs.T[0]
|
||||
coeffs = coeffs.reshape((cr,1))
|
||||
cr,cc,_ = IncompressibleFitter.shapeArray(coeffs)
|
||||
coeffs = coeffs.reshape((cr, 1))
|
||||
cr, cc, _ = IncompressibleFitter.shapeArray(coeffs)
|
||||
|
||||
if DEBUG: print("polynomial detected, fitting {0}".format(eqnType))
|
||||
if cr==1 and cc==1:
|
||||
if cr == 1 and cc == 1:
|
||||
if DEBUG: print("No coefficients left to fit, aborting procedure.")
|
||||
coeffs = np.array([[0.0]])
|
||||
return coeffs, None
|
||||
if (xr<cr):
|
||||
if DEBUG: print("Less data points than coefficients in first dimension ({0} < {1}), reducing coefficient matrix.".format(xr,cr))
|
||||
coeffs = coeffs[:xr,:]
|
||||
if (yc<cc):
|
||||
if DEBUG: print("Less data points than coefficients in second dimension ({0} < {1}), reducing coefficient matrix.".format(yc,cc))
|
||||
coeffs = coeffs[:,:yc]
|
||||
cr,cc,_ = IncompressibleFitter.shapeArray(coeffs)
|
||||
x_input = np.array(x.flat)-xbase
|
||||
y_input = np.array(y.flat)-ybase
|
||||
if (xr < cr):
|
||||
if DEBUG: print("Less data points than coefficients in first dimension ({0} < {1}), reducing coefficient matrix.".format(xr, cr))
|
||||
coeffs = coeffs[:xr, :]
|
||||
if (yc < cc):
|
||||
if DEBUG: print("Less data points than coefficients in second dimension ({0} < {1}), reducing coefficient matrix.".format(yc, cc))
|
||||
coeffs = coeffs[:, :yc]
|
||||
cr, cc, _ = IncompressibleFitter.shapeArray(coeffs)
|
||||
x_input = np.array(x.flat) - xbase
|
||||
y_input = np.array(y.flat) - ybase
|
||||
z_input = np.copy(z)
|
||||
if eqnType==IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL:
|
||||
if eqnType == IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL:
|
||||
z_input = np.log(z_input)
|
||||
coeffs,sErr = IncompressibleFitter.getCoeffs2d(x_input, y_input, z_input, cr-1, cc-1, DEBUG=DEBUG)
|
||||
coeffs, sErr = IncompressibleFitter.getCoeffs2d(x_input, y_input, z_input, cr - 1, cc - 1, DEBUG=DEBUG)
|
||||
if DEBUG: print("Coefficients after fitting: \n{0}".format(coeffs))
|
||||
if DEBUG: print("Standard deviation: {0}".format(np.nanstd(sErr)))
|
||||
if DEBUG: print("Sum of squared errors: {0}".format(np.square(sErr).sum()))
|
||||
if DEBUG: print("Root mean squared errors: {0}".format(np.sqrt(np.square(sErr).mean()).sum()))
|
||||
return coeffs,sErr
|
||||
return coeffs, sErr
|
||||
|
||||
# Select if 1D or 2D fitting
|
||||
if yc==1 or xr==1: # 1D fitting, only one input
|
||||
if yc == 1 or xr == 1: # 1D fitting, only one input
|
||||
if DEBUG: print("1D function detected.")
|
||||
if yc==1:
|
||||
if yc == 1:
|
||||
if DEBUG: print("Fitting {0} in x-direction.".format(eqnType))
|
||||
coeffs,sErr = IncompressibleFitter.getCoeffsIterative1D(x, z, eqnType=eqnType, coeffs=coeffs, DEBUG=DEBUG)
|
||||
elif xr==1:
|
||||
coeffs, sErr = IncompressibleFitter.getCoeffsIterative1D(x, z, eqnType=eqnType, coeffs=coeffs, DEBUG=DEBUG)
|
||||
elif xr == 1:
|
||||
if DEBUG: print("Fitting {0} in y-direction.".format(eqnType))
|
||||
coeffs,sErr = IncompressibleFitter.getCoeffsIterative1D(y, z, eqnType=eqnType, coeffs=coeffs, DEBUG=DEBUG)
|
||||
coeffs, sErr = IncompressibleFitter.getCoeffsIterative1D(y, z, eqnType=eqnType, coeffs=coeffs, DEBUG=DEBUG)
|
||||
else: raise ValueError("Unknown error in matrix shapes.")
|
||||
if DEBUG: print("Coefficients after fitting: \n{0}".format(coeffs))
|
||||
if DEBUG: print("Standard deviation: {0}".format(np.nanstd(sErr)))
|
||||
@@ -383,7 +383,7 @@ class IncompressibleFitter(object):
|
||||
if DEBUG: print("Root mean squared errors: {0}".format(np.sqrt(np.square(sErr).mean()).sum()))
|
||||
return coeffs, sErr
|
||||
|
||||
elif yc>1: # 2D fitting
|
||||
elif yc > 1: # 2D fitting
|
||||
raise ValueError("There are no other 2D fitting functions than polynomials, cannot use {0}.".format(eqnType))
|
||||
|
||||
else:
|
||||
@@ -412,18 +412,18 @@ class IncompressibleFitter(object):
|
||||
|
||||
x_order += 1
|
||||
y_order += 1
|
||||
#To avoid overfitting, we only use the upper left triangle of the coefficient matrix
|
||||
# To avoid overfitting, we only use the upper left triangle of the coefficient matrix
|
||||
x_exp = range(x_order)
|
||||
y_exp = range(y_order)
|
||||
limit = max(x_order,y_order)
|
||||
limit = max(x_order, y_order)
|
||||
xy_exp = []
|
||||
# Construct the upper left triangle of coefficients
|
||||
for i in x_exp:
|
||||
for j in y_exp:
|
||||
if(i+j<limit): xy_exp.append((i,j))
|
||||
if(i + j < limit): xy_exp.append((i, j))
|
||||
|
||||
# Construct input pairs
|
||||
xx, yy = np.meshgrid(x_in,y_in,indexing='ij')
|
||||
xx, yy = np.meshgrid(x_in, y_in, indexing='ij')
|
||||
xx = np.array(xx.flat)
|
||||
yy = np.array(yy.flat)
|
||||
zz = np.array(z_in.flat)
|
||||
@@ -434,17 +434,17 @@ class IncompressibleFitter(object):
|
||||
|
||||
cols = len(xy_exp)
|
||||
eqns = x_num * y_num
|
||||
#if (eqns<cols):
|
||||
# if (eqns<cols):
|
||||
# raise ValueError("You have only {0} equations and try to fit {1} coefficients, please reduce the order.".format(eqns,cols))
|
||||
if (x_num<x_order):
|
||||
raise ValueError("You have only {0} x-entries and try to fit {1} x-coefficients, please reduce the x_order.".format(x_num,x_order))
|
||||
if (y_num<y_order):
|
||||
raise ValueError("You have only {0} y-entries and try to fit {1} y-coefficients, please reduce the y_order.".format(y_num,y_order))
|
||||
if (x_num < x_order):
|
||||
raise ValueError("You have only {0} x-entries and try to fit {1} x-coefficients, please reduce the x_order.".format(x_num, x_order))
|
||||
if (y_num < y_order):
|
||||
raise ValueError("You have only {0} y-entries and try to fit {1} y-coefficients, please reduce the y_order.".format(y_num, y_order))
|
||||
|
||||
# Build the functional matrix
|
||||
A = np.zeros((eqns,cols))
|
||||
for i in range(eqns): # row loop
|
||||
for j, (xj,yj) in enumerate(xy_exp): # makes columns
|
||||
A = np.zeros((eqns, cols))
|
||||
for i in range(eqns): # row loop
|
||||
for j, (xj, yj) in enumerate(xy_exp): # makes columns
|
||||
A[i][j] = xx[i]**xj * yy[i]**yj
|
||||
|
||||
# Remove np.nan elements
|
||||
@@ -455,24 +455,24 @@ class IncompressibleFitter(object):
|
||||
zz = zz[mask]
|
||||
|
||||
if (len(A) < cols):
|
||||
raise ValueError("Your matrix has only {0} valid rows and you try to fit {1} coefficients, please reduce the order.".format(len(A),cols))
|
||||
raise ValueError("Your matrix has only {0} valid rows and you try to fit {1} coefficients, please reduce the order.".format(len(A), cols))
|
||||
|
||||
coeffs, resids, rank, singulars = np.linalg.lstsq(A, zz)
|
||||
coeffs, resids, rank, singulars = np.linalg.lstsq(A, zz)
|
||||
if DEBUG: print("Linear algebra solver returned:")
|
||||
if DEBUG: print(coeffs)
|
||||
if DEBUG: print(resids)
|
||||
if DEBUG: print(rank)
|
||||
if DEBUG: print(singulars)
|
||||
|
||||
#if resids.size>0:
|
||||
# if resids.size>0:
|
||||
# r2 = 1 - resids / (zz.size * zz.var())
|
||||
#else:
|
||||
# else:
|
||||
# r2 = 0
|
||||
#print("\n r2 2d: ",r2.shape,r2,"\n")
|
||||
|
||||
#Rearrange coefficients to a matrix shape
|
||||
C = np.zeros((x_order,y_order))
|
||||
for i, (xi,yi) in enumerate(xy_exp): # makes columns
|
||||
# Rearrange coefficients to a matrix shape
|
||||
C = np.zeros((x_order, y_order))
|
||||
for i, (xi, yi) in enumerate(xy_exp): # makes columns
|
||||
C[xi][yi] = coeffs[i]
|
||||
|
||||
sErr = zz - np.polynomial.polynomial.polyval2d(xx, yy, C)
|
||||
@@ -489,23 +489,23 @@ class IncompressibleFitter(object):
|
||||
|
||||
sErr = None
|
||||
|
||||
#fit = "Powell" # use Powell's algorithm
|
||||
#fit = "BFGS" # use Broyden-Fletcher-Goldfarb-Shanno
|
||||
#fit = "LMA" # use the Levenberg-Marquardt algorithm from curve_fit
|
||||
fit = ["LMA","Powell","BFGS"] # First try LMA, use others as fall-back
|
||||
# fit = "Powell" # use Powell's algorithm
|
||||
# fit = "BFGS" # use Broyden-Fletcher-Goldfarb-Shanno
|
||||
# fit = "LMA" # use the Levenberg-Marquardt algorithm from curve_fit
|
||||
fit = ["LMA", "Powell", "BFGS"] # First try LMA, use others as fall-back
|
||||
|
||||
# make sure that we use other routines for polynomials
|
||||
if (eqnType==IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL) or \
|
||||
(eqnType==IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL) :
|
||||
if (eqnType == IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL) or \
|
||||
(eqnType == IncompressibleData.INCOMPRESSIBLE_EXPPOLYNOMIAL):
|
||||
raise ValueError("Please use the specific polynomial functions, they are much better.")
|
||||
|
||||
expLog = False
|
||||
# Fitting the logarithm of z_in?
|
||||
if (eqnType==IncompressibleData.INCOMPRESSIBLE_EXPONENTIAL or eqnType==IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL):
|
||||
if (eqnType == IncompressibleData.INCOMPRESSIBLE_EXPONENTIAL or eqnType == IncompressibleData.INCOMPRESSIBLE_LOGEXPONENTIAL):
|
||||
expLog = True
|
||||
|
||||
xData = np.array(x_in.flat)
|
||||
if expLog: zData = np.log(np.clip(z_in.flat,1e-10,IncompressibleData.maxLin))
|
||||
if expLog: zData = np.log(np.clip(z_in.flat, 1e-10, IncompressibleData.maxLin))
|
||||
else: zData = np.array(z_in.flat)
|
||||
|
||||
# Remove np.nan elements
|
||||
@@ -514,7 +514,7 @@ class IncompressibleFitter(object):
|
||||
zData = zData[mask]
|
||||
|
||||
# The residual function
|
||||
def fun(coefficients,xArray,yArray):
|
||||
def fun(coefficients, xArray, yArray):
|
||||
"""
|
||||
This function takes the coefficient array and
|
||||
x and y data. It evaluates the function and returns
|
||||
@@ -525,55 +525,55 @@ class IncompressibleFitter(object):
|
||||
calculated = IncompressibleData.baseFunc(xArray, y=0.0, xbase=0.0, ybase=0.0, eqnType=eqnType, c=coefficients)
|
||||
if expLog: calculated = np.log(calculated)
|
||||
if yArray is None: return calculated
|
||||
data = yArray
|
||||
res = np.sum(np.square(calculated-data))
|
||||
data = yArray
|
||||
res = np.sum(np.square(calculated - data))
|
||||
return res
|
||||
|
||||
# Loop through the list of algorithms with basic settings to keep track of our efforts
|
||||
success = False
|
||||
counter = 0
|
||||
success = False
|
||||
counter = 0
|
||||
tolerance = 1e-16
|
||||
while (not success):
|
||||
algorithm = fit[counter]
|
||||
#fit = "LMA" # use the Levenberg-Marquardt algorithm from curve_fit
|
||||
if algorithm=="LMA":
|
||||
# fit = "LMA" # use the Levenberg-Marquardt algorithm from curve_fit
|
||||
if algorithm == "LMA":
|
||||
|
||||
def func(xVector, *coefficients):
|
||||
return fun(np.array(coefficients), xVector, None)
|
||||
#return self.baseFunction(xVector, 0.0, 0.0, 0.0, np.array(coefficients)) #np.array([self._PropsFit(coefficients,xName,T=Ti) for Ti in T])
|
||||
# return self.baseFunction(xVector, 0.0, 0.0, 0.0, np.array(coefficients)) #np.array([self._PropsFit(coefficients,xName,T=Ti) for Ti in T])
|
||||
|
||||
try:
|
||||
#print func(xData, coeffs_start)
|
||||
# print func(xData, coeffs_start)
|
||||
# Do the actual fitting
|
||||
popt, pcov = curve_fit(func, xData, zData, p0=coeffs, ftol=tolerance)
|
||||
if np.any(popt!=coeffs):
|
||||
if np.any(popt != coeffs):
|
||||
success = True
|
||||
if DEBUG: print("Fit succeeded with: {0}".format(algorithm))
|
||||
sErr = zData - func(xData, popt)
|
||||
#print "Fit succeeded for "+fit[counter]+": "
|
||||
#print "data: {0}, func: {1}".format(yData[ 2],func(xData[ 2], popt))
|
||||
#print "data: {0}, func: {1}".format(yData[ 6],func(xData[ 6], popt))
|
||||
#print "data: {0}, func: {1}".format(yData[-1],func(xData[-1], popt))
|
||||
# print "Fit succeeded for "+fit[counter]+": "
|
||||
# print "data: {0}, func: {1}".format(yData[ 2],func(xData[ 2], popt))
|
||||
# print "data: {0}, func: {1}".format(yData[ 6],func(xData[ 6], popt))
|
||||
# print "data: {0}, func: {1}".format(yData[-1],func(xData[-1], popt))
|
||||
#if DEBUG: print("Estimated covariance of parameters: {0}".format(pcov))
|
||||
#ssErr = np.sqrt(np.diag(pcov)).sum()
|
||||
#ssTot = ((zData-zData.mean())**2).sum()
|
||||
#r2 = 1-(ssErr/ssTot )
|
||||
#print("\n r2 FMA: ",r2.shape,r2,"\n")
|
||||
return popt,sErr
|
||||
return popt, sErr
|
||||
else:
|
||||
if DEBUG: print("Fit failed for {0}.".format(algorithm))
|
||||
if DEBUG: sys.stdout.flush()
|
||||
success = False
|
||||
|
||||
except RuntimeError as e:
|
||||
if DEBUG: print("Exception using "+algorithm+": "+str(e))
|
||||
if DEBUG: print("Exception using " + algorithm + ": " + str(e))
|
||||
if DEBUG: sys.stdout.flush()
|
||||
success = False
|
||||
|
||||
#fit = "MIN" # use a home-made minimisation with Powell and Broyden-Fletcher-Goldfarb-Shanno
|
||||
elif algorithm=="Powell" or algorithm=="BFGS":
|
||||
# fit = "MIN" # use a home-made minimisation with Powell and Broyden-Fletcher-Goldfarb-Shanno
|
||||
elif algorithm == "Powell" or algorithm == "BFGS":
|
||||
|
||||
arguments = (xData,zData)
|
||||
arguments = (xData, zData)
|
||||
#options = {'maxiter': 1e2, 'maxfev': 1e5}
|
||||
|
||||
try:
|
||||
@@ -582,18 +582,18 @@ class IncompressibleFitter(object):
|
||||
success = True
|
||||
if DEBUG: print("Fit succeeded with: {0}".format(algorithm))
|
||||
sErr = zData - fun(np.array(res.x), xData, None)
|
||||
#if res.has_key('fvec'):
|
||||
# if res.has_key('fvec'):
|
||||
#ssErr = (res['fvec']**2).sum()
|
||||
#ssTot = ((zData-zData.mean())**2).sum()
|
||||
#r2 = 1-(ssErr/ssTot )
|
||||
#print("\n r2 : ",r2.shape,r2,algorithm,"\n")
|
||||
return res.x,sErr
|
||||
return res.x, sErr
|
||||
else:
|
||||
if DEBUG: print("Fit failed for {0}.".format(algorithm))
|
||||
if DEBUG: sys.stdout.flush()
|
||||
success = False
|
||||
except RuntimeError as e:
|
||||
if DEBUG: print("Exception using "+algorithm+": "+str(e))
|
||||
if DEBUG: print("Exception using " + algorithm + ": " + str(e))
|
||||
if DEBUG: sys.stdout.flush()
|
||||
success = False
|
||||
|
||||
@@ -601,11 +601,11 @@ class IncompressibleFitter(object):
|
||||
else:
|
||||
raise (ValueError("Error: You used an unknown fit method."))
|
||||
|
||||
if counter<len(fit)-1:
|
||||
if counter < len(fit) - 1:
|
||||
#print("Fit did not succeed with {0}, reducing tolerance to {1}.".format(algorithm,tol))
|
||||
success = False
|
||||
counter += 1
|
||||
elif tolerance<1e-3:
|
||||
elif tolerance < 1e-3:
|
||||
tolerance *= 1e2
|
||||
if DEBUG: print("Fit did not succeed, reducing tolerance to {0}.".format(tolerance))
|
||||
success = False
|
||||
@@ -614,4 +614,4 @@ class IncompressibleFitter(object):
|
||||
if DEBUG: print("--------------------------------------------------------------")
|
||||
if DEBUG: print("Fit failed for {0}. ".format(fit))
|
||||
if DEBUG: print("--------------------------------------------------------------")
|
||||
return coeffs,1
|
||||
return coeffs, 1
|
||||
|
||||
@@ -112,7 +112,7 @@ class SolutionData(object):
|
||||
if ((self.Tmin > T) or (T > self.Tmax)): raise ValueError("Your temperature {0} is not between {1} and {2}.".format(T, self.Tmin, self.Tmax))
|
||||
TF = 0.0
|
||||
if (self.T_freeze.type!=IncompressibleData.INCOMPRESSIBLE_NOT_SET): TF = self.Tfreeze(T, p, x)
|
||||
if ( T<TF ): raise ValueError("Your temperature {0} is below the freezing point of {1}.".format(T, TF))
|
||||
if (T<TF): raise ValueError("Your temperature {0} is below the freezing point of {1}.".format(T, TF))
|
||||
else: return True
|
||||
return False
|
||||
|
||||
@@ -242,7 +242,7 @@ class PureData(SolutionData):
|
||||
SolutionData.__init__(self)
|
||||
self.xbase = 0.0
|
||||
self.xid = self.ifrac_pure
|
||||
self.concentration.data = np.array([ 0 ]) # mass fraction
|
||||
self.concentration.data = np.array([0]) # mass fraction
|
||||
|
||||
def reshapeData(self, dataArray, length):
|
||||
"""
|
||||
@@ -324,7 +324,7 @@ class DigitalData(SolutionData):
|
||||
# First we try to read the file
|
||||
if (not dataID is None and os.path.isfile(self.getFile(dataID))): # File found
|
||||
fileArray = self.getFromFile(dataID)
|
||||
x = np.copy(fileArray[1:,0 ])
|
||||
x = np.copy(fileArray[1:,0])
|
||||
y = np.copy(fileArray[0 ,1:])
|
||||
z = np.copy(fileArray[1:,1:])
|
||||
else:
|
||||
@@ -369,7 +369,7 @@ class DigitalData(SolutionData):
|
||||
# Overwrite inputs
|
||||
x = x_in
|
||||
y = y_in
|
||||
z = np.zeros( (len(x)+1,len(y)+1) )
|
||||
z = np.zeros((len(x)+1,len(y)+1))
|
||||
r,c = z.shape
|
||||
|
||||
if func is None: raise ValueError("Need a function to update the data file.")
|
||||
@@ -377,7 +377,7 @@ class DigitalData(SolutionData):
|
||||
for i in range(r-1):
|
||||
for j in range(c-1):
|
||||
z[i+1,j+1] = func(x[i],y[j])
|
||||
z[0,0 ] = np.NaN
|
||||
z[0,0] = np.NaN
|
||||
z[1:,0] = x
|
||||
z[0,1:] = y
|
||||
|
||||
@@ -503,23 +503,23 @@ class CoefficientData(SolutionData):
|
||||
tmp = np.zeros((18,5))
|
||||
|
||||
for j in range(5):
|
||||
tmp[ 0][j] = array[ 0][j]
|
||||
tmp[ 1][j] = array[ 4][j]
|
||||
tmp[ 2][j] = array[ 8][j]
|
||||
tmp[ 3][j] = array[12][j]
|
||||
tmp[ 4][j] = array[15][j]
|
||||
tmp[ 5][j] = array[17][j]
|
||||
tmp[ 6][j] = array[ 1][j]
|
||||
tmp[ 7][j] = array[ 5][j]
|
||||
tmp[ 8][j] = array[ 9][j]
|
||||
tmp[ 9][j] = array[13][j]
|
||||
tmp[0][j] = array[0][j]
|
||||
tmp[1][j] = array[4][j]
|
||||
tmp[2][j] = array[8][j]
|
||||
tmp[3][j] = array[12][j]
|
||||
tmp[4][j] = array[15][j]
|
||||
tmp[5][j] = array[17][j]
|
||||
tmp[6][j] = array[1][j]
|
||||
tmp[7][j] = array[5][j]
|
||||
tmp[8][j] = array[9][j]
|
||||
tmp[9][j] = array[13][j]
|
||||
tmp[10][j] = array[16][j]
|
||||
tmp[11][j] = array[ 2][j]
|
||||
tmp[12][j] = array[ 6][j]
|
||||
tmp[11][j] = array[2][j]
|
||||
tmp[12][j] = array[6][j]
|
||||
tmp[13][j] = array[10][j]
|
||||
tmp[14][j] = array[14][j]
|
||||
tmp[15][j] = array[ 3][j]
|
||||
tmp[16][j] = array[ 7][j]
|
||||
tmp[15][j] = array[3][j]
|
||||
tmp[16][j] = array[7][j]
|
||||
tmp[17][j] = array[11][j]
|
||||
|
||||
return tmp
|
||||
|
||||
@@ -20,12 +20,12 @@ class PureExample(PureData):
|
||||
self.viscosity.source = self.viscosity.SOURCE_DATA
|
||||
self.saturation_pressure.source = self.saturation_pressure.SOURCE_DATA
|
||||
|
||||
self.temperature.data = np.array([ 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150])+273.15 # Kelvin
|
||||
self.density.data = np.array([ 740, 733, 726, 717, 710, 702, 695, 687, 679, 670, 662]) # kg/m3
|
||||
self.specific_heat.data = np.array([ 2235, 2280, 2326, 2361, 2406, 2445, 2485, 2528, 2571, 2607, 2645]) # J/kg-K
|
||||
self.temperature.data = np.array([50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150])+273.15 # Kelvin
|
||||
self.density.data = np.array([740, 733, 726, 717, 710, 702, 695, 687, 679, 670, 662]) # kg/m3
|
||||
self.specific_heat.data = np.array([2235, 2280, 2326, 2361, 2406, 2445, 2485, 2528, 2571, 2607, 2645]) # J/kg-K
|
||||
self.viscosity.data = np.array([0.804, 0.704, 0.623, 0.556, 0.498, 0.451, 0.410, 0.374, 0.346, 0.317, 0.289]) # Pa-s
|
||||
self.conductivity.data = np.array([0.105, 0.104, 0.102, 0.100, 0.098, 0.096, 0.095, 0.093, 0.091, 0.089, 0.087]) # W/m-K
|
||||
self.saturation_pressure.data = np.array([ 0.5, 0.9, 1.4, 2.3, 3.9, 6.0, 8.7, 12.4, 17.6, 24.4, 33.2]) # Pa
|
||||
self.saturation_pressure.data = np.array([0.5, 0.9, 1.4, 2.3, 3.9, 6.0, 8.7, 12.4, 17.6, 24.4, 33.2]) # Pa
|
||||
self.reshapeAll()
|
||||
|
||||
|
||||
@@ -36,8 +36,8 @@ class SolutionExample(SolutionData):
|
||||
self.description = "Ethanol ice slurry"
|
||||
self.reference = "SecCool software,Skovrup2013"
|
||||
|
||||
self.temperature.data = np.array([ -45 , -40 , -35 , -30 , -25 , -20 , -15 , -10])+273.15 # Kelvin
|
||||
self.concentration.data = np.array([ 5 , 10 , 15 , 20 , 25 , 30 , 35 ])/100.0 # mass fraction
|
||||
self.temperature.data = np.array([-45 , -40 , -35 , -30 , -25 , -20 , -15 , -10])+273.15 # Kelvin
|
||||
self.concentration.data = np.array([5 , 10 , 15 , 20 , 25 , 30 , 35])/100.0 # mass fraction
|
||||
|
||||
self.density.data = np.array([
|
||||
[1064.0, 1054.6, 1045.3, 1036.3, 1027.4, 1018.6, 1010.0],
|
||||
@@ -283,24 +283,24 @@ class MelinderExample(CoefficientData):
|
||||
self.xbase = 30.5128 / 100.0
|
||||
|
||||
coeffs = np.array([
|
||||
[-26.29 , 958.1 ,3887 , 0.4175 , 1.153 ],
|
||||
[ -0.000002575 , -0.4151 , 7.201 , 0.0007271 , -0.03866 ],
|
||||
[ -0.000006732 , -0.002261 , -0.08979 , 0.0000002823 , 0.0002779 ],
|
||||
[ 0.000000163 , 0.0000002998 , -0.000439 , 0.000000009718 , -0.000001543 ],
|
||||
[ -1.187 , -1.391 , -18.5 , -0.004421 , 0.005448 ],
|
||||
[ -0.00001609 , -0.0151 , 0.2984 , -0.00002952 , 0.0001008 ],
|
||||
[ 0.000000342 , 0.0001113 , -0.001865 , 0.00000007336 , -0.000002809 ],
|
||||
[ 0.0000000005687, -0.0000003264 , -0.00001718 , 0.0000000004328 , 0.000000009811 ],
|
||||
[ -0.01218 , -0.01105 , -0.03769 , 0.00002044 , -0.0005552 ],
|
||||
[ 0.0000003865 , 0.0001828 , -0.01196 , 0.0000003413 , 0.000008384 ],
|
||||
[ 0.000000008768 , -0.000001641 , 0.00009801 , -0.000000003665 , -0.00000003997 ],
|
||||
[ -0.0000000002095, 0.0000000151 , 0.000000666 , -0.00000000002791 , -0.0000000003466 ],
|
||||
[ -0.00006823 , -0.0001208 , -0.003776 , 0.0000002943 , 0.000003038 ],
|
||||
[ 0.00000002137 , 0.000002992 , -0.00005611 , -0.0000000009646 , -0.00000007435 ],
|
||||
[ -0.0000000004271, 0.000000001455, -0.0000007811, 0.00000000003174 , 0.0000000007442 ],
|
||||
[ 0.0000001297 , 0.000004927 , -0.0001504 , -0.0000000008666 , 0.00000006669 ],
|
||||
[ -0.0000000005407, -0.0000001325 , 0.000007373 , -0.0000000000004573, -0.0000000009105 ],
|
||||
[ 0.00000002363 , -0.00000007727 , 0.000006433 , -0.0000000002033 , -0.0000000008472 ]
|
||||
[-26.29 , 958.1 ,3887 , 0.4175 , 1.153],
|
||||
[-0.000002575 , -0.4151 , 7.201 , 0.0007271 , -0.03866],
|
||||
[-0.000006732 , -0.002261 , -0.08979 , 0.0000002823 , 0.0002779],
|
||||
[0.000000163 , 0.0000002998 , -0.000439 , 0.000000009718 , -0.000001543],
|
||||
[-1.187 , -1.391 , -18.5 , -0.004421 , 0.005448],
|
||||
[-0.00001609 , -0.0151 , 0.2984 , -0.00002952 , 0.0001008],
|
||||
[0.000000342 , 0.0001113 , -0.001865 , 0.00000007336 , -0.000002809],
|
||||
[0.0000000005687, -0.0000003264 , -0.00001718 , 0.0000000004328 , 0.000000009811],
|
||||
[-0.01218 , -0.01105 , -0.03769 , 0.00002044 , -0.0005552],
|
||||
[0.0000003865 , 0.0001828 , -0.01196 , 0.0000003413 , 0.000008384],
|
||||
[0.000000008768 , -0.000001641 , 0.00009801 , -0.000000003665 , -0.00000003997],
|
||||
[-0.0000000002095, 0.0000000151 , 0.000000666 , -0.00000000002791 , -0.0000000003466],
|
||||
[-0.00006823 , -0.0001208 , -0.003776 , 0.0000002943 , 0.000003038],
|
||||
[0.00000002137 , 0.000002992 , -0.00005611 , -0.0000000009646 , -0.00000007435],
|
||||
[-0.0000000004271, 0.000000001455, -0.0000007811, 0.00000000003174 , 0.0000000007442],
|
||||
[0.0000001297 , 0.000004927 , -0.0001504 , -0.0000000008666 , 0.00000006669],
|
||||
[-0.0000000005407, -0.0000001325 , 0.000007373 , -0.0000000000004573, -0.0000000009105],
|
||||
[0.00000002363 , -0.00000007727 , 0.000006433 , -0.0000000002033 , -0.0000000008472]
|
||||
])
|
||||
|
||||
self.setMelinderMatrix(coeffs)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -180,16 +180,16 @@ class MITSeaWater(SolutionData):
|
||||
|
||||
self.saturation_pressure.source = self.saturation_pressure.SOURCE_EQUATION
|
||||
self.saturation_pressure.data = np.array([
|
||||
[ 0.611, 0.608, 0.604, 0.601, 0.597, 0.593, 0.590, 0.586, 0.582, 0.578, 0.575, 0.571, 0.567],
|
||||
[ 1.228, 1.221, 1.214, 1.207, 1.199, 1.192, 1.185, 1.177, 1.170, 1.162, 1.154, 1.147, 1.139],
|
||||
[ 2.339, 2.325, 2.312, 2.298, 2.284, 2.270, 2.256, 2.242, 2.228, 2.213, 2.199, 2.184, 2.169],
|
||||
[ 4.247, 4.222, 4.197, 4.172, 4.147, 4.122, 4.096, 4.070, 4.044, 4.018, 3.992, 3.965, 3.938],
|
||||
[ 7.384, 7.341, 7.298, 7.255, 7.211, 7.167, 7.123, 7.078, 7.033, 6.987, 6.941, 6.895, 6.848],
|
||||
[ 12.351, 12.279, 12.207, 12.135, 12.062, 11.988, 11.914, 11.839, 11.763, 11.687, 11.610, 11.532, 11.454],
|
||||
[ 19.946, 19.829, 19.713, 19.596, 19.478, 19.359, 19.239, 19.118, 18.996, 18.873, 18.749, 18.624, 18.497],
|
||||
[ 31.201, 31.018, 30.837, 30.654, 30.470, 30.284, 30.096, 29.907, 29.716, 29.523, 29.329, 29.133, 28.935],
|
||||
[ 47.415, 47.139, 46.863, 46.585, 46.305, 46.022, 45.737, 45.449, 45.159, 44.866, 44.571, 44.273, 43.972],
|
||||
[ 70.182, 69.776, 69.368, 68.957, 68.542, 68.124, 67.701, 67.276, 66.846, 66.413, 65.975, 65.534, 65.089],
|
||||
[0.611, 0.608, 0.604, 0.601, 0.597, 0.593, 0.590, 0.586, 0.582, 0.578, 0.575, 0.571, 0.567],
|
||||
[1.228, 1.221, 1.214, 1.207, 1.199, 1.192, 1.185, 1.177, 1.170, 1.162, 1.154, 1.147, 1.139],
|
||||
[2.339, 2.325, 2.312, 2.298, 2.284, 2.270, 2.256, 2.242, 2.228, 2.213, 2.199, 2.184, 2.169],
|
||||
[4.247, 4.222, 4.197, 4.172, 4.147, 4.122, 4.096, 4.070, 4.044, 4.018, 3.992, 3.965, 3.938],
|
||||
[7.384, 7.341, 7.298, 7.255, 7.211, 7.167, 7.123, 7.078, 7.033, 6.987, 6.941, 6.895, 6.848],
|
||||
[12.351, 12.279, 12.207, 12.135, 12.062, 11.988, 11.914, 11.839, 11.763, 11.687, 11.610, 11.532, 11.454],
|
||||
[19.946, 19.829, 19.713, 19.596, 19.478, 19.359, 19.239, 19.118, 18.996, 18.873, 18.749, 18.624, 18.497],
|
||||
[31.201, 31.018, 30.837, 30.654, 30.470, 30.284, 30.096, 29.907, 29.716, 29.523, 29.329, 29.133, 28.935],
|
||||
[47.415, 47.139, 46.863, 46.585, 46.305, 46.022, 45.737, 45.449, 45.159, 44.866, 44.571, 44.273, 43.972],
|
||||
[70.182, 69.776, 69.368, 68.957, 68.542, 68.124, 67.701, 67.276, 66.846, 66.413, 65.975, 65.534, 65.089],
|
||||
[101.418, 100.835, 100.245, 99.651, 99.052, 98.447, 97.837, 97.221, 96.601, 95.974, 95.343, 94.705, 94.062],
|
||||
[143.376, 142.558, 141.725, 140.884, 140.037, 139.182, 138.320, 137.450, 136.572, 135.687, 134.793, 133.892, 132.982],
|
||||
[198.665, 197.541, 196.386, 195.222, 194.048, 192.863, 191.668, 190.463, 189.246, 188.019, 186.782, 185.533, 184.272]]) * 1e3 #, Pa
|
||||
|
||||
@@ -930,7 +930,7 @@ class SolutionDataWriter(object):
|
||||
if i==0:
|
||||
myAnnotate('Source: ',refs[i],x=x,y=y); x += .0 #; y -= 2*dy
|
||||
elif i==1:
|
||||
myAnnotate( ' ',refs[i],x=x,y=y-dy); x += .0 #; y -= 2*dy
|
||||
myAnnotate(' ',refs[i],x=x,y=y-dy); x += .0 #; y -= 2*dy
|
||||
else:
|
||||
warn("Discarding all reference after the second line")
|
||||
|
||||
@@ -1145,7 +1145,7 @@ class SolutionDataWriter(object):
|
||||
if a.get_ylabel()==self.errLabel:
|
||||
mi,ma = a.get_ylim()
|
||||
if mi>-minAbsErrorScale: a.set_ylim(bottom=-minAbsErrorScale)
|
||||
if ma< minAbsErrorScale: a.set_ylim( top= minAbsErrorScale)
|
||||
if ma< minAbsErrorScale: a.set_ylim(top= minAbsErrorScale)
|
||||
a.xaxis.set_major_locator(MaxNLocator(5))
|
||||
#a.yaxis.set_major_locator(MaxNLocator(7))
|
||||
|
||||
@@ -1305,7 +1305,7 @@ class SolutionDataWriter(object):
|
||||
header_flag = False
|
||||
if i == 0 or i == len(grid)-1: header_flag = True
|
||||
rst += self.normalize_row(row,max_cols)
|
||||
rst += self.table_div(max_cols, header_flag )
|
||||
rst += self.table_div(max_cols, header_flag)
|
||||
return rst
|
||||
|
||||
def table_div(self, max_cols, header_flag=1, indent=2):
|
||||
@@ -1588,7 +1588,7 @@ class SolutionDataWriter(object):
|
||||
except: av = 0.0
|
||||
#print("min: {0}({1}), avg: {2}, max: {3}({4})".format(c[k][mi],c["name"][mi],av,c[k][ma],c["name"][ma]),end="")
|
||||
minLine.append("{0:5.3f} ({1:5s})".format(e[k][mi]*100.0,e["name"][mi]))
|
||||
avgLine.append("{0:5.3f} {1:5s} ".format( av*100.0,""))
|
||||
avgLine.append("{0:5.3f} {1:5s} ".format(av*100.0,""))
|
||||
maxLine.append("{0:5.3f} ({1:5s})".format(e[k][ma]*100.0,e["name"][ma]))
|
||||
|
||||
polyLine.append("{0:3d}".format(t[k].count(IncompressibleData.INCOMPRESSIBLE_POLYNOMIAL)))
|
||||
|
||||
@@ -26,38 +26,38 @@ class IncompLiquidFit(object):
|
||||
# parameters for the different fits
|
||||
self._cDensity = numpy.ones(4) # Typically 4 parameters
|
||||
self._cHeatCapacity = numpy.ones(4) # Typically 4 parameters
|
||||
self._cTConductivity = numpy.ones(3) # Typically 3 parameters
|
||||
self._cTConductivity = numpy.ones(3) # Typically 3 parameters
|
||||
self._cViscosity = numpy.ones(3) # Typically 3 parameters
|
||||
self._cPsat = numpy.ones(3) # Typically 3 parameters
|
||||
|
||||
# bounds for fit
|
||||
self._Tmin = None
|
||||
self._Tmin = None
|
||||
self._TminPsat = None
|
||||
self._Tmax = None
|
||||
self._Tref = 273.15 + 25.
|
||||
self._Tbase = 0.0
|
||||
self._Tmax = None
|
||||
self._Tref = 273.15 + 25.
|
||||
self._Tbase = 0.0
|
||||
|
||||
# some flags to set
|
||||
self._TinC = False # Temperature in Celsius
|
||||
self._DynVisc = True # Data for dynamic viscosity
|
||||
self._DynVisc = True # Data for dynamic viscosity
|
||||
self._minPoints = 3
|
||||
|
||||
self._expPoly = False # Fit exponential as polynomial
|
||||
self._expPoly = False # Fit exponential as polynomial
|
||||
|
||||
def setParams(self,fluid):
|
||||
if fluid=='init':
|
||||
def setParams(self, fluid):
|
||||
if fluid == 'init':
|
||||
# initial parameters for the different fits
|
||||
# self._cDensity = [+9.2e+2, -0.5e+0, +2.8e-4, -1.1e-6]
|
||||
# self._cHeatCapacity = [+1.0e+0, +3.6e-3, -2.9e-7, +1.7e-9]
|
||||
# self._cTConductivity = [+1.1e-1, +7.8e-5, +3.5e-7]
|
||||
# self._cViscosity = [+7.1e+2, +2.3e+2, +3.4e+1]
|
||||
# self._cPsat = [-5.3e+3, +3.2e+1, -1.6e+1]
|
||||
self._cDensity = [1, 1, 1, 1]
|
||||
self._cHeatCapacity = [1, 1, 1, 1]
|
||||
self._cTConductivity = [1, 1, 1]
|
||||
self._cDensity = [1, 1, 1, 1]
|
||||
self._cHeatCapacity = [1, 1, 1, 1]
|
||||
self._cTConductivity = [1, 1, 1]
|
||||
#self._cViscosity = [+8e+2, -2e+2, +3e+1]
|
||||
self._cViscosity = [+7e+2, -6e+1, +1e+1]
|
||||
self._cPsat = [-5e+3, +3e+1, -1e+1]
|
||||
self._cViscosity = [+7e+2, -6e+1, +1e+1]
|
||||
self._cPsat = [-5e+3, +3e+1, -1e+1]
|
||||
return True
|
||||
|
||||
|
||||
@@ -81,28 +81,28 @@ class IncompLiquidFit(object):
|
||||
# self._Tmax = 260.0 + 273.15
|
||||
|
||||
else:
|
||||
raise (ValueError("No coefficients available for "+str(fluid)))
|
||||
raise (ValueError("No coefficients available for " + str(fluid)))
|
||||
|
||||
def _checkT(self,T=0):
|
||||
def _checkT(self, T=0):
|
||||
Tmin = self.Props('Tmin')
|
||||
Tmax = self.Props('Tmax')
|
||||
if Tmin is None:
|
||||
raise (ValueError("Please specify the minimum temperature."))
|
||||
if Tmax is None:
|
||||
raise (ValueError("Please specify the maximum temperature."))
|
||||
if not (Tmin<=T<=Tmax):
|
||||
raise (ValueError("Temperature out of range: "+str(T)+" not in "+str(Tmin)+"-"+str(Tmax)+". "))
|
||||
if not (Tmin <= T <= Tmax):
|
||||
raise (ValueError("Temperature out of range: " + str(T) + " not in " + str(Tmin) + "-" + str(Tmax) + ". "))
|
||||
|
||||
def _checkP(self,T=0,P=0):
|
||||
Psat = self.Props('Psat',T=T)
|
||||
if P<Psat:
|
||||
raise (ValueError("Equations are valid for liquid phase only: "+str(P)+" < "+str(Psat)+". "))
|
||||
def _checkP(self, T=0, P=0):
|
||||
Psat = self.Props('Psat', T=T)
|
||||
if P < Psat:
|
||||
raise (ValueError("Equations are valid for liquid phase only: " + str(P) + " < " + str(Psat) + ". "))
|
||||
|
||||
def _checkTP(self,T=0,P=0):
|
||||
def _checkTP(self, T=0, P=0):
|
||||
self._checkT(T=T)
|
||||
#self._checkP(T=T, P=P)
|
||||
|
||||
def _basePolynomial(self,coefficients,x):
|
||||
def _basePolynomial(self, coefficients, x):
|
||||
""" Base function to produce polynomials of
|
||||
order len(coefficients) with the coefficients
|
||||
"""
|
||||
@@ -111,196 +111,196 @@ class IncompLiquidFit(object):
|
||||
result += coefficients[i] * x**i
|
||||
return result
|
||||
|
||||
def _basePolynomialInt(self,coefficients,x1,x0=-1):
|
||||
def _basePolynomialInt(self, coefficients, x1, x0=-1):
|
||||
""" Base function to produce the integral of
|
||||
order len(coefficients) with coefficients from
|
||||
x0 to x1.
|
||||
"""
|
||||
if x0==-1: x0 = self._Tref-self._Tbase
|
||||
if x0 == -1: x0 = self._Tref - self._Tbase
|
||||
result = 0.
|
||||
for i in range(len(coefficients)):
|
||||
result += 1./(i+1.) * coefficients[i] * (x1**(i+1.) - x0**(i+1.))
|
||||
result += 1. / (i + 1.) * coefficients[i] * (x1**(i + 1.) - x0**(i + 1.))
|
||||
return result
|
||||
|
||||
def _baseExponential(self,coefficients,x,num):
|
||||
def _baseExponential(self, coefficients, x, num):
|
||||
""" Base function to produce exponential
|
||||
with defined coefficients
|
||||
"""
|
||||
# Determine limits:
|
||||
maxVal = numpy.log(numpy.finfo(numpy.float64).max-1)
|
||||
minVal = -maxVal#numpy.log(numpy.finfo(numpy.float64).min+1)
|
||||
#if len(coefficients)==num:
|
||||
if num==1: return numpy.exp(numpy.clip((coefficients[0]/(x+coefficients[1]) - coefficients[2]),minVal,maxVal))
|
||||
if num==2: return numpy.exp(numpy.clip(self._basePolynomial(coefficients, x),minVal,maxVal))
|
||||
#else:
|
||||
maxVal = numpy.log(numpy.finfo(numpy.float64).max - 1)
|
||||
minVal = -maxVal # numpy.log(numpy.finfo(numpy.float64).min+1)
|
||||
# if len(coefficients)==num:
|
||||
if num == 1: return numpy.exp(numpy.clip((coefficients[0] / (x + coefficients[1]) - coefficients[2]), minVal, maxVal))
|
||||
if num == 2: return numpy.exp(numpy.clip(self._basePolynomial(coefficients, x), minVal, maxVal))
|
||||
# else:
|
||||
# print "Error!"
|
||||
|
||||
def Props(self,out,T=0,P=0):
|
||||
if out=='D':
|
||||
self._checkTP(T=T,P=P)
|
||||
return self._basePolynomial(self._cDensity,T-self._Tbase)
|
||||
elif out=='C':
|
||||
self._checkTP(T=T,P=P)
|
||||
return self._basePolynomial(self._cHeatCapacity,T-self._Tbase)
|
||||
elif out=='L':
|
||||
self._checkTP(T=T,P=P)
|
||||
return self._basePolynomial(self._cTConductivity,T-self._Tbase)
|
||||
elif out=='V':
|
||||
self._checkTP(T=T,P=P)
|
||||
def Props(self, out, T=0, P=0):
|
||||
if out == 'D':
|
||||
self._checkTP(T=T, P=P)
|
||||
return self._basePolynomial(self._cDensity, T - self._Tbase)
|
||||
elif out == 'C':
|
||||
self._checkTP(T=T, P=P)
|
||||
return self._basePolynomial(self._cHeatCapacity, T - self._Tbase)
|
||||
elif out == 'L':
|
||||
self._checkTP(T=T, P=P)
|
||||
return self._basePolynomial(self._cTConductivity, T - self._Tbase)
|
||||
elif out == 'V':
|
||||
self._checkTP(T=T, P=P)
|
||||
if self._expPoly:
|
||||
return numpy.exp(self._basePolynomial(self._cViscosity,T-self._Tbase))
|
||||
return numpy.exp(self._basePolynomial(self._cViscosity, T - self._Tbase))
|
||||
else:
|
||||
return self._baseExponential(self._cViscosity,T-self._Tbase,1)
|
||||
return self._baseExponential(self._cViscosity, T - self._Tbase, 1)
|
||||
|
||||
elif out=='Psat':
|
||||
elif out == 'Psat':
|
||||
self._checkT(T=T)
|
||||
if T<self._TminPsat:
|
||||
if T < self._TminPsat:
|
||||
return 1e-14
|
||||
if self._expPoly:
|
||||
return numpy.exp(self._basePolynomial(self._cPsat,T-self._Tbase))
|
||||
return numpy.exp(self._basePolynomial(self._cPsat, T - self._Tbase))
|
||||
else:
|
||||
return self._baseExponential(self._cPsat,T-self._Tbase,1)
|
||||
elif out=='Tmin':
|
||||
return self._baseExponential(self._cPsat, T - self._Tbase, 1)
|
||||
elif out == 'Tmin':
|
||||
return self._Tmin
|
||||
elif out=='Tmax':
|
||||
elif out == 'Tmax':
|
||||
return self._Tmax
|
||||
else:
|
||||
raise (ValueError("Error: You used an unknown output qualifier."))
|
||||
|
||||
def _PropsFit(self,coefficients,inVal,T=0):
|
||||
def _PropsFit(self, coefficients, inVal, T=0):
|
||||
"""
|
||||
Calculates a property from a given set of
|
||||
coefficients for a certain temperature. Is used
|
||||
to obtain data to feed to the optimisation
|
||||
procedures.
|
||||
"""
|
||||
if inVal=='D':
|
||||
if inVal == 'D':
|
||||
self._checkT(T=T)
|
||||
return self._basePolynomial(coefficients,T-self._Tbase)
|
||||
elif inVal=='C':
|
||||
return self._basePolynomial(coefficients, T - self._Tbase)
|
||||
elif inVal == 'C':
|
||||
self._checkT(T=T)
|
||||
return self._basePolynomial(coefficients,T-self._Tbase)
|
||||
elif inVal=='L':
|
||||
return self._basePolynomial(coefficients, T - self._Tbase)
|
||||
elif inVal == 'L':
|
||||
self._checkT(T=T)
|
||||
return self._basePolynomial(coefficients,T-self._Tbase)
|
||||
elif inVal=='V':
|
||||
return self._basePolynomial(coefficients, T - self._Tbase)
|
||||
elif inVal == 'V':
|
||||
self._checkT(T=T)
|
||||
if self._expPoly:
|
||||
return numpy.exp(self._basePolynomial(coefficients,T-self._Tbase))
|
||||
return numpy.exp(self._basePolynomial(coefficients, T - self._Tbase))
|
||||
else:
|
||||
return self._baseExponential(coefficients,T-self._Tbase,1)
|
||||
return self._baseExponential(coefficients, T - self._Tbase, 1)
|
||||
|
||||
elif inVal=='Psat':
|
||||
elif inVal == 'Psat':
|
||||
self._checkT(T=T)
|
||||
if T<self._TminPsat:
|
||||
if T < self._TminPsat:
|
||||
return 1e-14
|
||||
if self._expPoly:
|
||||
return numpy.exp(self._basePolynomial(coefficients,T-self._Tbase))
|
||||
return numpy.exp(self._basePolynomial(coefficients, T - self._Tbase))
|
||||
else:
|
||||
return self._baseExponential(coefficients,T-self._Tbase,1)
|
||||
return self._baseExponential(coefficients, T - self._Tbase, 1)
|
||||
|
||||
else:
|
||||
raise (ValueError("Error: You used an unknown property qualifier."))
|
||||
|
||||
def inCoolProp(self,name):
|
||||
def inCoolProp(self, name):
|
||||
from CoolProp.CoolProp import FluidsList
|
||||
#print FluidsList()
|
||||
# print FluidsList()
|
||||
result = name in FluidsList()
|
||||
if not result:
|
||||
try:
|
||||
CP.PropsU('Tmin','T',0,'P',0,name,"SI")
|
||||
CP.PropsU('Tmin', 'T', 0, 'P', 0, name, "SI")
|
||||
return True
|
||||
except ValueError as e:
|
||||
print(e)
|
||||
return False
|
||||
|
||||
def getCoefficients(self,inVal):
|
||||
def getCoefficients(self, inVal):
|
||||
"""
|
||||
Get the array with coefficients.
|
||||
"""
|
||||
if inVal=='D':
|
||||
if inVal == 'D':
|
||||
return self._cDensity
|
||||
elif inVal=='C':
|
||||
elif inVal == 'C':
|
||||
return self._cHeatCapacity
|
||||
elif inVal=='L':
|
||||
elif inVal == 'L':
|
||||
return self._cTConductivity
|
||||
elif inVal=='V':
|
||||
elif inVal == 'V':
|
||||
return self._cViscosity
|
||||
elif inVal=='Psat':
|
||||
elif inVal == 'Psat':
|
||||
return self._cPsat
|
||||
else:
|
||||
raise (ValueError("Error: You used an unknown property qualifier."))
|
||||
|
||||
def setCoefficients(self,inVal,coeffs):
|
||||
def setCoefficients(self, inVal, coeffs):
|
||||
"""
|
||||
Set the array of coefficients.
|
||||
"""
|
||||
if inVal=='D':
|
||||
if inVal == 'D':
|
||||
self._cDensity = coeffs
|
||||
elif inVal=='C':
|
||||
elif inVal == 'C':
|
||||
self._cHeatCapacity = coeffs
|
||||
elif inVal=='L':
|
||||
elif inVal == 'L':
|
||||
self._cTConductivity = coeffs
|
||||
elif inVal=='V':
|
||||
elif inVal == 'V':
|
||||
self._cViscosity = coeffs
|
||||
elif inVal=='Psat':
|
||||
elif inVal == 'Psat':
|
||||
self._cPsat = coeffs
|
||||
else:
|
||||
raise (ValueError("Error: You used an unknown property qualifier."))
|
||||
|
||||
def setTmin(self,T):
|
||||
def setTmin(self, T):
|
||||
self._Tmin = T
|
||||
|
||||
def setTmax(self,T):
|
||||
def setTmax(self, T):
|
||||
self._Tmax = T
|
||||
|
||||
def setTminPsat(self,T):
|
||||
def setTminPsat(self, T):
|
||||
self._TminPsat = T
|
||||
|
||||
def setTref(self,T):
|
||||
def setTref(self, T):
|
||||
self._Tref = T
|
||||
|
||||
def setTbase(self,T):
|
||||
def setTbase(self, T):
|
||||
self._Tbase = T
|
||||
|
||||
def setExpPoly(self,bo):
|
||||
def setExpPoly(self, bo):
|
||||
self._expPoly = bo
|
||||
|
||||
def fitCoefficients(self,xName,T=[],xData=[]):
|
||||
def fitCoefficients(self, xName, T=[], xData=[]):
|
||||
|
||||
if (len(T)!=len(xData)):
|
||||
if (len(T) != len(xData)):
|
||||
raise (ValueError("Error: There has to be the same number of temperature and data points."))
|
||||
if len(T)<self._minPoints:
|
||||
raise (ValueError("Error: You should use at least "+str(self._minPoints)+" points."))
|
||||
if len(T) < self._minPoints:
|
||||
raise (ValueError("Error: You should use at least " + str(self._minPoints) + " points."))
|
||||
|
||||
def fun(coefficients,xName,T,xData):
|
||||
def fun(coefficients, xName, T, xData):
|
||||
# Values for conductivity are very small,
|
||||
# algorithms prefer larger values
|
||||
if xName=='L':
|
||||
calculated = numpy.array([self._PropsFit(coefficients,xName,T=Ti) for Ti in T])
|
||||
data = numpy.array(xData)
|
||||
if xName == 'L':
|
||||
calculated = numpy.array([self._PropsFit(coefficients, xName, T=Ti) for Ti in T])
|
||||
data = numpy.array(xData)
|
||||
# Fit logarithms for viscosity and saturation pressure
|
||||
elif xName=='V' or xName=='Psat':
|
||||
calculated = numpy.log(numpy.array([self._PropsFit(coefficients,xName,T=Ti) for Ti in T]))
|
||||
data = numpy.log(numpy.array(xData))
|
||||
elif xName == 'V' or xName == 'Psat':
|
||||
calculated = numpy.log(numpy.array([self._PropsFit(coefficients, xName, T=Ti) for Ti in T]))
|
||||
data = numpy.log(numpy.array(xData))
|
||||
else:
|
||||
calculated = numpy.array([self._PropsFit(coefficients,xName,T=Ti) for Ti in T])
|
||||
data = numpy.array(xData)
|
||||
calculated = numpy.array([self._PropsFit(coefficients, xName, T=Ti) for Ti in T])
|
||||
data = numpy.array(xData)
|
||||
|
||||
res = numpy.sum((calculated-data)**2.)
|
||||
res = numpy.sum((calculated - data)**2.)
|
||||
return res
|
||||
|
||||
initValues = self.getCoefficients(xName)[:]
|
||||
# Fit logarithms for viscosity and saturation pressure
|
||||
if xName=='V' or xName=='Psat':
|
||||
if xName == 'V' or xName == 'Psat':
|
||||
|
||||
#fit = "MIN" # use a home-made minimisation with Powell and Broyden-Fletcher-Goldfarb-Shanno
|
||||
#fit = "LMA" # use the Levenberg-Marquardt algorithm from curve_fit
|
||||
#fit = "POL" # use a polynomial in an exponential function
|
||||
# fit = "MIN" # use a home-made minimisation with Powell and Broyden-Fletcher-Goldfarb-Shanno
|
||||
# fit = "LMA" # use the Levenberg-Marquardt algorithm from curve_fit
|
||||
# fit = "POL" # use a polynomial in an exponential function
|
||||
|
||||
fit = ["LMA","MIN"] # First try LMA, use MIN as a fall-back solver
|
||||
fit = ["LMA", "MIN"] # First try LMA, use MIN as a fall-back solver
|
||||
if self._expPoly:
|
||||
fit = ["POL"] # Overwrite preferences for polynomial
|
||||
fit = ["POL"] # Overwrite preferences for polynomial
|
||||
|
||||
success = False
|
||||
counter = -1
|
||||
@@ -308,13 +308,13 @@ class IncompLiquidFit(object):
|
||||
while (not success):
|
||||
counter += 1
|
||||
|
||||
if fit[counter]=="LMA":
|
||||
if fit[counter] == "LMA":
|
||||
xData = numpy.array(xData)
|
||||
|
||||
fit_log = True
|
||||
|
||||
def func(T, *coefficients):
|
||||
result = numpy.array([self._PropsFit(coefficients,xName,T=Ti) for Ti in T])
|
||||
result = numpy.array([self._PropsFit(coefficients, xName, T=Ti) for Ti in T])
|
||||
if fit_log:
|
||||
return numpy.log(result)
|
||||
else:
|
||||
@@ -326,36 +326,36 @@ class IncompLiquidFit(object):
|
||||
try:
|
||||
# Do the actual fitting
|
||||
popt, pcov = curve_fit(func, T, xData, p0=initValues, maxfev=1000)
|
||||
#print popt
|
||||
#print pcov
|
||||
# print popt
|
||||
# print pcov
|
||||
success = True
|
||||
return popt
|
||||
|
||||
except RuntimeError as e:
|
||||
print("Exception: "+str(e))
|
||||
print("Using: "+str(fit[counter+1])+" as a fall-back.")
|
||||
print("Exception: " + str(e))
|
||||
print("Using: " + str(fit[counter + 1]) + " as a fall-back.")
|
||||
success = False
|
||||
|
||||
elif fit[counter]=="MIN":
|
||||
print("Fitting exponential with "+str(len(initValues))+" coefficients.")
|
||||
arguments = (xName,T,numpy.exp(xData))
|
||||
elif fit[counter] == "MIN":
|
||||
print("Fitting exponential with " + str(len(initValues)) + " coefficients.")
|
||||
arguments = (xName, T, numpy.exp(xData))
|
||||
#options = {'maxiter': 1e2, 'maxfev': 1e5}
|
||||
if xName=='V':
|
||||
method = "Powell"
|
||||
elif xName=='Psat':
|
||||
method = "BFGS"
|
||||
if xName == 'V':
|
||||
method = "Powell"
|
||||
elif xName == 'Psat':
|
||||
method = "BFGS"
|
||||
|
||||
tolStart = 1e-13
|
||||
tol = tolStart
|
||||
tolStart = 1e-13
|
||||
tol = tolStart
|
||||
res = minimize(fun, initValues, method=method, args=arguments, tol=tol)
|
||||
|
||||
while ((not res.success) and tol<1e-2):
|
||||
while ((not res.success) and tol < 1e-2):
|
||||
tol *= 1e2
|
||||
print("Fit did not succeed, reducing tolerance to "+str(tol))
|
||||
print("Fit did not succeed, reducing tolerance to " + str(tol))
|
||||
res = minimize(fun, initValues, method=method, args=arguments, tol=tol)
|
||||
|
||||
# Include these lines for an additional fit with new guess values.
|
||||
#if res.success and tol>tolStart:
|
||||
# if res.success and tol>tolStart:
|
||||
# print "Refitting with new guesses and original tolerance of "+str(tolStart)
|
||||
# res = minimize(fun, res.x, method=method, args=arguments, tol=tolStart)
|
||||
|
||||
@@ -367,17 +367,17 @@ class IncompLiquidFit(object):
|
||||
print(res)
|
||||
success = False
|
||||
|
||||
elif fit[counter]=="POL":
|
||||
print("Fitting exponential polynomial with "+str(len(initValues))+" coefficients.")
|
||||
z = numpy.polyfit(T-self._Tbase, numpy.log(xData)[:], len(initValues)-1)
|
||||
elif fit[counter] == "POL":
|
||||
print("Fitting exponential polynomial with " + str(len(initValues)) + " coefficients.")
|
||||
z = numpy.polyfit(T - self._Tbase, numpy.log(xData)[:], len(initValues) - 1)
|
||||
return z[::-1]
|
||||
|
||||
else:
|
||||
raise (ValueError("Error: You used an unknown fit method."))
|
||||
|
||||
else: # just a polynomial
|
||||
print("Fitting polynomial with "+str(len(initValues))+" coefficients.")
|
||||
z = numpy.polyfit(T-self._Tbase, xData, len(initValues)-1)
|
||||
else: # just a polynomial
|
||||
print("Fitting polynomial with " + str(len(initValues)) + " coefficients.")
|
||||
z = numpy.polyfit(T - self._Tbase, xData, len(initValues) - 1)
|
||||
return z[::-1]
|
||||
|
||||
# def fitCoefficientsCentered(self,xName,T=[],xData=[]):
|
||||
@@ -386,21 +386,21 @@ class IncompLiquidFit(object):
|
||||
# return self.fitCoefficients(xName,T=T,xData=xData)
|
||||
|
||||
|
||||
### Load the data
|
||||
# Load the data
|
||||
from data_incompressible import *
|
||||
|
||||
containerList = []
|
||||
containerList += [TherminolD12()]
|
||||
containerList += [TherminolVP1(), Therminol66(), Therminol72()]
|
||||
containerList += [DowthermJ(), DowthermQ()]
|
||||
containerList += [Texatherm22(), NitrateSalt(), SylthermXLT()]
|
||||
containerList += [Texatherm22(), NitrateSalt(), SylthermXLT()]
|
||||
containerList += [HC50(), HC40(), HC30(), HC20(), HC10()]
|
||||
containerList += [AS10(), AS20(), AS30(), AS40(), AS55()]
|
||||
containerList += [ZS10(), ZS25(), ZS40(), ZS45(), ZS55()]
|
||||
|
||||
|
||||
def relError(A=[],B=[],PCT=False):
|
||||
result = (numpy.array(A)-numpy.array(B))/numpy.array(B);
|
||||
def relError(A=[], B=[], PCT=False):
|
||||
result = (numpy.array(A) - numpy.array(B)) / numpy.array(B);
|
||||
if PCT:
|
||||
return result * 100.
|
||||
else:
|
||||
@@ -409,7 +409,7 @@ def relError(A=[],B=[],PCT=False):
|
||||
|
||||
j = {}
|
||||
for data in containerList:
|
||||
### Some test case
|
||||
# Some test case
|
||||
liqObj = IncompLiquidFit()
|
||||
liqObj.setParams("init")
|
||||
liqObj.setTmin(data.Tmin)
|
||||
@@ -430,39 +430,39 @@ for data in containerList:
|
||||
|
||||
print("")
|
||||
print("------------------------------------------------------")
|
||||
print("Fitting "+str(data.Name))
|
||||
print("Fitting " + str(data.Name))
|
||||
print("------------------------------------------------------")
|
||||
print("")
|
||||
print("minimum T: "+str(data.Tmin))
|
||||
print("maximum T: "+str(data.Tmax))
|
||||
print("min T pSat:"+str(data.TminPsat))
|
||||
print("minimum T: " + str(data.Tmin))
|
||||
print("maximum T: " + str(data.Tmax))
|
||||
print("min T pSat:" + str(data.TminPsat))
|
||||
#liqObj.setTbase((data.Tmax-data.Tmin) / 2.0 + data.Tmin)
|
||||
#liqObj.setExpPoly(True)
|
||||
print("T base:"+str(liqObj._Tbase))
|
||||
# liqObj.setExpPoly(True)
|
||||
print("T base:" + str(liqObj._Tbase))
|
||||
print("")
|
||||
|
||||
# row and column sharing for test plots
|
||||
#matplotlib.pyplot.subplots_adjust(top=0.85)
|
||||
# matplotlib.pyplot.subplots_adjust(top=0.85)
|
||||
f, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = matplotlib.pyplot.subplots(3, 2, sharex='col')
|
||||
f.set_size_inches(matplotlib.pyplot.figaspect(1.2)*1.5)
|
||||
f.set_size_inches(matplotlib.pyplot.figaspect(1.2) * 1.5)
|
||||
#f.suptitle("Fit for "+str(data.Desc), fontsize=14)
|
||||
|
||||
### This is the actual fitting
|
||||
# This is the actual fitting
|
||||
tData = data.T
|
||||
tDat1 = numpy.linspace(numpy.min(tData)+1, numpy.max(tData)-1, 10)
|
||||
Pin = 1e20 # Dummy pressure
|
||||
inCP =liqObj.inCoolProp(data.Name)
|
||||
print("Fluid in CoolProp: "+str(inCP))
|
||||
tDat1 = numpy.linspace(numpy.min(tData) + 1, numpy.max(tData) - 1, 10)
|
||||
Pin = 1e20 # Dummy pressure
|
||||
inCP = liqObj.inCoolProp(data.Name)
|
||||
print("Fluid in CoolProp: " + str(inCP))
|
||||
print("")
|
||||
|
||||
inVal = 'D'
|
||||
xData = data.rho
|
||||
oldCoeffs = liqObj.getCoefficients(inVal)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal,T=tData,xData=xData)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal, T=tData, xData=xData)
|
||||
# print "Density, old: "+str(oldCoeffs)
|
||||
print("Density, new: "+str(newCoeffs))
|
||||
print("Density, new: " + str(newCoeffs))
|
||||
# print
|
||||
liqObj.setCoefficients(inVal,newCoeffs)
|
||||
liqObj.setCoefficients(inVal, newCoeffs)
|
||||
# fData = numpy.array([liqObj.Props(inVal, T=Tin, P=Pin) for Tin in tDat1])
|
||||
# ax1.plot(tData-273.15, xData, 'o', label="Data Sheet")
|
||||
# ax1.plot(tDat1-273.15, fData, 'o', label="Python")
|
||||
@@ -484,11 +484,11 @@ for data in containerList:
|
||||
inVal = 'C'
|
||||
xData = data.c_p
|
||||
oldCoeffs = liqObj.getCoefficients(inVal)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal,T=tData,xData=xData)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal, T=tData, xData=xData)
|
||||
# print "Heat c., old: "+str(oldCoeffs)
|
||||
# print "Heat c., new: "+str(newCoeffs)
|
||||
# print
|
||||
liqObj.setCoefficients(inVal,newCoeffs)
|
||||
liqObj.setCoefficients(inVal, newCoeffs)
|
||||
# fData = numpy.array([liqObj.Props(inVal, T=Tin, P=Pin) for Tin in tDat1])
|
||||
# ax2.plot(tData-273.15, xData/1e3, 'o', label="Data Sheet")
|
||||
# ax2.plot(tDat1-273.15, fData/1e3, 'o', label="Python")
|
||||
@@ -507,11 +507,11 @@ for data in containerList:
|
||||
inVal = 'L'
|
||||
xData = data.lam
|
||||
oldCoeffs = liqObj.getCoefficients(inVal)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal,T=tData,xData=xData)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal, T=tData, xData=xData)
|
||||
# print "Th. Co., old: "+str(oldCoeffs)
|
||||
# print "Th. Co., new: "+str(newCoeffs)
|
||||
# print
|
||||
liqObj.setCoefficients(inVal,newCoeffs)
|
||||
liqObj.setCoefficients(inVal, newCoeffs)
|
||||
# fData = numpy.array([liqObj.Props(inVal, T=Tin, P=Pin) for Tin in tDat1])
|
||||
# ax3.plot(tData-273.15, xData*1e3, 'o', label="Data Sheet")
|
||||
# ax3.plot(tDat1-273.15, fData*1e3, 'o', label="Python")
|
||||
@@ -529,15 +529,15 @@ for data in containerList:
|
||||
|
||||
inVal = 'V'
|
||||
tData = data.T[data.mu_dyn > 0]
|
||||
if len(tData)>liqObj._minPoints:
|
||||
tDat1 = numpy.linspace(numpy.min(tData)+1, numpy.max(tData)-1, 10)
|
||||
if len(tData) > liqObj._minPoints:
|
||||
tDat1 = numpy.linspace(numpy.min(tData) + 1, numpy.max(tData) - 1, 10)
|
||||
xData = data.mu_dyn[data.mu_dyn > 0]
|
||||
oldCoeffs = liqObj.getCoefficients(inVal)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal,T=tData,xData=xData)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal, T=tData, xData=xData)
|
||||
# print "Viscos., old: "+str(oldCoeffs)
|
||||
# print "Viscos., new: "+str(newCoeffs)
|
||||
# print
|
||||
liqObj.setCoefficients(inVal,newCoeffs)
|
||||
liqObj.setCoefficients(inVal, newCoeffs)
|
||||
# fData = numpy.array([liqObj.Props(inVal, T=Tin, P=Pin) for Tin in tDat1])
|
||||
# ax4.plot(tData-273.15, xData*1e3, 'o', label="Data Sheet")
|
||||
# ax4.plot(tDat1-273.15, fData*1e3, 'o', label="Python")
|
||||
@@ -556,17 +556,17 @@ for data in containerList:
|
||||
j['viscosity']['type'] = 'polynomial'
|
||||
|
||||
inVal = 'Psat'
|
||||
mask = numpy.logical_and(numpy.greater_equal(data.T,data.TminPsat),numpy.greater(data.psat,0))
|
||||
mask = numpy.logical_and(numpy.greater_equal(data.T, data.TminPsat), numpy.greater(data.psat, 0))
|
||||
tData = data.T[mask]
|
||||
if len(tData)>liqObj._minPoints:
|
||||
tDat1 = numpy.linspace(numpy.min(tData)+1, numpy.max(tData)-1, 10)
|
||||
if len(tData) > liqObj._minPoints:
|
||||
tDat1 = numpy.linspace(numpy.min(tData) + 1, numpy.max(tData) - 1, 10)
|
||||
xData = data.psat[mask]
|
||||
oldCoeffs = liqObj.getCoefficients(inVal)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal,T=tData,xData=xData)
|
||||
newCoeffs = liqObj.fitCoefficients(inVal, T=tData, xData=xData)
|
||||
# print "P sat. , old: "+str(oldCoeffs)
|
||||
# print "P sat. , new: "+str(newCoeffs)
|
||||
# print
|
||||
liqObj.setCoefficients(inVal,newCoeffs)
|
||||
liqObj.setCoefficients(inVal, newCoeffs)
|
||||
# fData = numpy.array([liqObj.Props(inVal, T=Tin, P=Pin) for Tin in tDat1])
|
||||
# ax5.plot(tData-273.15, xData/1e3, 'o', label="Data Sheet")
|
||||
# ax5.plot(tDat1-273.15, fData/1e3, 'o', label="Python")
|
||||
@@ -663,8 +663,8 @@ for data in containerList:
|
||||
# raw_input("Finished with "+data.Name+", press Enter to continue...")
|
||||
|
||||
import json
|
||||
print(json.dumps(j, indent = 2))
|
||||
print(json.dumps(j, indent=2))
|
||||
|
||||
fp = open(j['name']+'.json', 'w')
|
||||
fp.write(json.dumps(j, indent = 2, sort_keys = True))
|
||||
fp = open(j['name'] + '.json', 'w')
|
||||
fp.write(json.dumps(j, indent=2, sort_keys=True))
|
||||
fp.close()
|
||||
|
||||
@@ -6,42 +6,42 @@ import numpy as np
|
||||
|
||||
def props(in1=None, in2=None, in3=None, in4=None, in5=None, in6=None):
|
||||
try:
|
||||
return cp.PropsU(in1=in1,in2=in2,in3=in3,in4=in4,in5=in5,in6=in6,in7="SI")
|
||||
return cp.PropsU(in1=in1, in2=in2, in3=in3, in4=in4, in5=in5, in6=in6, in7="SI")
|
||||
except ValueError as ve:
|
||||
#print "Error in CoolProp, try adjusting the fluid or T and p:"
|
||||
# print "Error in CoolProp, try adjusting the fluid or T and p:"
|
||||
print(ve)
|
||||
return -1.0*np.NAN
|
||||
return -1.0 * np.NAN
|
||||
|
||||
|
||||
#print "{0:14.8f}".format(CP.Props('V','D',13,'P',500,'n-Pentane'))
|
||||
#print "{0:14.8f}".format(CP.Props('V','H',158,'P',1000,'TX22'))
|
||||
# print "{0:14.8f}".format(CP.Props('V','D',13,'P',500,'n-Pentane'))
|
||||
# print "{0:14.8f}".format(CP.Props('V','H',158,'P',1000,'TX22'))
|
||||
#T = 300
|
||||
T = float(sys.argv[1])+273.15
|
||||
P = float(sys.argv[2])*1e5
|
||||
print("Temperature: "+str(T-273.15)+" C")
|
||||
print("Pressure: "+str(P/1e5)+" bar")
|
||||
T = float(sys.argv[1]) + 273.15
|
||||
P = float(sys.argv[2]) * 1e5
|
||||
print("Temperature: " + str(T - 273.15) + " C")
|
||||
print("Pressure: " + str(P / 1e5) + " bar")
|
||||
print("")
|
||||
Melinder = ["MEG", "MPG", "MEA", "MMA", "MGL", "MAM", "MKC", "MCA", "MMG", "MNA", "MKA", "MKF", "MLI"]
|
||||
SecCool = ["ZiAC", "IceEA", "IcePG", "IceNA", "PK2000"]
|
||||
Other = ["LiBr"]
|
||||
SecCool = ["ZiAC", "IceEA", "IcePG", "IceNA", "PK2000"]
|
||||
Other = ["LiBr"]
|
||||
|
||||
fluids = []
|
||||
#fluids.extend(Melinder)
|
||||
#fluids.extend(SecCool)
|
||||
# fluids.extend(Melinder)
|
||||
# fluids.extend(SecCool)
|
||||
fluids.extend(Other)
|
||||
|
||||
for fluid in fluids:
|
||||
print("Fluid: "+str(fluid))
|
||||
print("Fluid: " + str(fluid))
|
||||
try:
|
||||
print("Density: "+"{0:14.8f} kg/m3 ".format(props('D','T',T,'P',P,fluid+'-20%')))
|
||||
print("Heat cap.: "+"{0:14.8f} kJ/kg/K".format(props('C','T',T,'P',P,fluid+'-20%')/1e3))
|
||||
print("Th. cond.: "+"{0:14.8f} W/m/K ".format(props('L','T',T,'P',P,fluid+'-20%')))
|
||||
print("Dyn. visc.: "+"{0:14.8f} mPas ".format(props('V','T',T,'P',P,fluid+'-20%')*1e3))
|
||||
print("Enthalpy: "+"{0:14.8f} kJ/kg ".format(props('H','T',T,'P',P,fluid+'-20%')/1e3))
|
||||
print("In. energy: "+"{0:14.8f} kJ/kg ".format(props('U','T',T,'P',P,fluid+'-20%')/1e3))
|
||||
print("Entropy: "+"{0:14.8f} kJ/kg/K".format(props('S','T',T,'P',P,fluid+'-20%')/1e3))
|
||||
print("Saturation: "+"{0:14.8f} bar ".format(props('Psat','T',T,'P',P,fluid+'-20%')/1e5))
|
||||
print("Freezing: "+"{0:14.8f} C ".format(props('Tfreeze','T',T,'P',P,fluid+'-20%')-273.15))
|
||||
print("Density: " + "{0:14.8f} kg/m3 ".format(props('D', 'T', T, 'P', P, fluid + '-20%')))
|
||||
print("Heat cap.: " + "{0:14.8f} kJ/kg/K".format(props('C', 'T', T, 'P', P, fluid + '-20%') / 1e3))
|
||||
print("Th. cond.: " + "{0:14.8f} W/m/K ".format(props('L', 'T', T, 'P', P, fluid + '-20%')))
|
||||
print("Dyn. visc.: " + "{0:14.8f} mPas ".format(props('V', 'T', T, 'P', P, fluid + '-20%') * 1e3))
|
||||
print("Enthalpy: " + "{0:14.8f} kJ/kg ".format(props('H', 'T', T, 'P', P, fluid + '-20%') / 1e3))
|
||||
print("In. energy: " + "{0:14.8f} kJ/kg ".format(props('U', 'T', T, 'P', P, fluid + '-20%') / 1e3))
|
||||
print("Entropy: " + "{0:14.8f} kJ/kg/K".format(props('S', 'T', T, 'P', P, fluid + '-20%') / 1e3))
|
||||
print("Saturation: " + "{0:14.8f} bar ".format(props('Psat', 'T', T, 'P', P, fluid + '-20%') / 1e5))
|
||||
print("Freezing: " + "{0:14.8f} C ".format(props('Tfreeze', 'T', T, 'P', P, fluid + '-20%') - 273.15))
|
||||
except ValueError as ve:
|
||||
print("Error in CoolProp, try adjusting T and p:")
|
||||
print(ve)
|
||||
|
||||
@@ -1,103 +1,103 @@
|
||||
#!/usr/bin/python
|
||||
import sys
|
||||
import CoolProp.CoolProp as CP
|
||||
#print "{0:14.8f}".format(CP.Props('V','D',13,'P',500,'n-Pentane'))
|
||||
#print "{0:14.8f}".format(CP.Props('V','H',158,'P',1000,'TX22'))
|
||||
# print "{0:14.8f}".format(CP.Props('V','D',13,'P',500,'n-Pentane'))
|
||||
# print "{0:14.8f}".format(CP.Props('V','H',158,'P',1000,'TX22'))
|
||||
#T = 300
|
||||
T = float(sys.argv[1])
|
||||
P = float(sys.argv[2])
|
||||
print("Temperature: "+str(T))
|
||||
print("Pressure: "+str(P))
|
||||
print("Temperature: " + str(T))
|
||||
print("Pressure: " + str(P))
|
||||
print("")
|
||||
print("Viscosity: ")
|
||||
print("{0:14.8f}".format(CP.Props('V','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('V','T',T,'P',P,'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('V','T',T,'P',P,'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('V','T',T,'P',P,'water')))
|
||||
#print
|
||||
#print "{0:14.8f}".format(CP.Props('L','D',13,'P',500,'n-Pentane'))
|
||||
#print "{0:14.8f}".format(CP.Props('L','H',158,'P',P,'TX22'))
|
||||
print("{0:14.8f}".format(CP.Props('V', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('V', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('V', 'T', T, 'P', P, 'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('V', 'T', T, 'P', P, 'water')))
|
||||
# print
|
||||
# print "{0:14.8f}".format(CP.Props('L','D',13,'P',500,'n-Pentane'))
|
||||
# print "{0:14.8f}".format(CP.Props('L','H',158,'P',P,'TX22'))
|
||||
print("")
|
||||
print("Conductivity: ")
|
||||
print("{0:14.8f}".format(CP.Props('L','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('L','T',T,'P',P,'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('L','T',T,'P',P,'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('L','T',T,'P',P,'water')))
|
||||
print("{0:14.8f}".format(CP.Props('L', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('L', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('L', 'T', T, 'P', P, 'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('L', 'T', T, 'P', P, 'water')))
|
||||
print("")
|
||||
print("Density: ")
|
||||
print("{0:14.8f}".format(CP.Props('D','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('D','T',T,'P',P,'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('D','T',T,'P',P,'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('D','T',T,'P',P,'water')))
|
||||
print("{0:14.8f}".format(CP.Props('D', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('D', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('D', 'T', T, 'P', P, 'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('D', 'T', T, 'P', P, 'water')))
|
||||
print("")
|
||||
print("Capacity: ")
|
||||
print("{0:14.8f}".format(CP.Props('C','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('C','T',T,'P',P,'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('C','T',T,'P',P,'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('C','T',T,'P',P,'water')))
|
||||
print("{0:14.8f}".format(CP.Props('C', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('C', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('C', 'T', T, 'P', P, 'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('C', 'T', T, 'P', P, 'water')))
|
||||
print("")
|
||||
print("Enthalpy: ")
|
||||
print("{0:14.8f}".format(CP.Props('H','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('H','T',T,'P',P,'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('H','T',T,'P',P,'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('H','T',T,'P',P,'water')))
|
||||
print("{0:14.8f}".format(CP.Props('H', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('H', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('H', 'T', T, 'P', P, 'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('H', 'T', T, 'P', P, 'water')))
|
||||
print("")
|
||||
print("Internal energy: ")
|
||||
print("{0:14.8f}".format(CP.Props('U','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('U','T',T,'P',P,'MEG-20%')))
|
||||
print("-")#"{0:14.8f}".format(CP.Props('U','T',T,'P',P,'EG-20%'))
|
||||
print("{0:14.8f}".format(CP.Props('U','T',T,'P',P,'water')))
|
||||
print("{0:14.8f}".format(CP.Props('U', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('U', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("-") # "{0:14.8f}".format(CP.Props('U','T',T,'P',P,'EG-20%'))
|
||||
print("{0:14.8f}".format(CP.Props('U', 'T', T, 'P', P, 'water')))
|
||||
print("")
|
||||
print("Entropy: ")
|
||||
print("{0:14.8f}".format(CP.Props('S','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('S','T',T,'P',P,'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('S','T',T,'P',P,'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('S','T',T,'P',P,'water')))
|
||||
print("{0:14.8f}".format(CP.Props('S', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('S', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('S', 'T', T, 'P', P, 'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('S', 'T', T, 'P', P, 'water')))
|
||||
print("")
|
||||
print("Freezing point: ")
|
||||
print("{0:14.8f}".format(CP.Props('Tfreeze','T',T,'P',P,'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('Tfreeze','T',T,'P',P,'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('F','T',T,'P',P,'EG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('Tfreeze', 'T', T, 'P', P, 'SecCoolSolution-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('Tfreeze', 'T', T, 'P', P, 'MEG-20%')))
|
||||
print("{0:14.8f}".format(CP.Props('F', 'T', T, 'P', P, 'EG-20%')))
|
||||
print("")
|
||||
print("TX22: ")
|
||||
print("{0:14.8f}".format(CP.Props('H','T',T+50,'P',P,'TX22')))
|
||||
print("{0:14.8f}".format(CP.Props('U','T',T+50,'P',P,'TX22')))
|
||||
print("{0:14.8f}".format(CP.Props('S','T',T+50,'P',P,'TX22')))
|
||||
print("{0:14.8f}".format(CP.Props('H', 'T', T + 50, 'P', P, 'TX22')))
|
||||
print("{0:14.8f}".format(CP.Props('U', 'T', T + 50, 'P', P, 'TX22')))
|
||||
print("{0:14.8f}".format(CP.Props('S', 'T', T + 50, 'P', P, 'TX22')))
|
||||
print("")
|
||||
#print "HCB: "
|
||||
#print "{0:14.8f}".format(CP.Props('H','T',T+50,'P',P,'HCB'))
|
||||
#print "{0:14.8f}".format(CP.Props('U','T',T+50,'P',P,'HCB'))
|
||||
#print "{0:14.8f}".format(CP.Props('S','T',T+50,'P',P,'HCB'))
|
||||
#print
|
||||
#print CP.Props('T','D',13,'P',500,'n-Pentane')
|
||||
#print 378.29349366868433
|
||||
#print
|
||||
#print CP.Props('D','T',373,'P',500,'n-Pentane')
|
||||
#print 13.28572300574231
|
||||
#print
|
||||
#print CP.Props('C','T',375,'P',1000,'TX22')
|
||||
#print 2.1829549872783205
|
||||
#print
|
||||
#print CP.Props('H','T',375,'P',1000,'TX22')
|
||||
#print 158.1306573393763
|
||||
#print
|
||||
#print CP.Props('C','H',158,'P',1000,'TX22')
|
||||
#print 2.18273570194
|
||||
#print
|
||||
#print CP.Props('C','T',275,'P',1000,'TestSolution-20%')
|
||||
#print 4.0917018571
|
||||
#print
|
||||
#print CP.Props('H','T',275,'P',1000,'TestSolution-20%')
|
||||
# print "HCB: "
|
||||
# print "{0:14.8f}".format(CP.Props('H','T',T+50,'P',P,'HCB'))
|
||||
# print "{0:14.8f}".format(CP.Props('U','T',T+50,'P',P,'HCB'))
|
||||
# print "{0:14.8f}".format(CP.Props('S','T',T+50,'P',P,'HCB'))
|
||||
# print
|
||||
# print CP.Props('T','D',13,'P',500,'n-Pentane')
|
||||
# print 378.29349366868433
|
||||
# print
|
||||
# print CP.Props('D','T',373,'P',500,'n-Pentane')
|
||||
# print 13.28572300574231
|
||||
# print
|
||||
# print CP.Props('C','T',375,'P',1000,'TX22')
|
||||
# print 2.1829549872783205
|
||||
# print
|
||||
# print CP.Props('H','T',375,'P',1000,'TX22')
|
||||
# print 158.1306573393763
|
||||
# print
|
||||
# print CP.Props('C','H',158,'P',1000,'TX22')
|
||||
# print 2.18273570194
|
||||
# print
|
||||
# print CP.Props('C','T',275,'P',1000,'TestSolution-20%')
|
||||
# print 4.0917018571
|
||||
# print
|
||||
# print CP.Props('H','T',275,'P',1000,'TestSolution-20%')
|
||||
#print -93.759593807
|
||||
#print
|
||||
#print CP.Props('C','H',-94,'P',1000,'TestSolution-0.2')
|
||||
#print 4.09169432982
|
||||
#print
|
||||
#print CP.Props('C','T',275,'P',1000,'EG-20%')
|
||||
#print 4.07399544409
|
||||
#print
|
||||
#print CP.Props('H','T',275,'P',1000,'EG-20%')
|
||||
# print
|
||||
# print CP.Props('C','H',-94,'P',1000,'TestSolution-0.2')
|
||||
# print 4.09169432982
|
||||
# print
|
||||
# print CP.Props('C','T',275,'P',1000,'EG-20%')
|
||||
# print 4.07399544409
|
||||
# print
|
||||
# print CP.Props('H','T',275,'P',1000,'EG-20%')
|
||||
#print -5.8439608317
|
||||
#print
|
||||
#print CP.Props('C','H',-5.8,'P',1000,'EG-20%')
|
||||
#print 4.07402880961
|
||||
# print
|
||||
# print CP.Props('C','H',-5.8,'P',1000,'EG-20%')
|
||||
# print 4.07402880961
|
||||
|
||||
@@ -2,11 +2,11 @@ import CoolProp.CoolProp as CP
|
||||
fluid = 'Propane'
|
||||
print(CP.enable_TTSE_LUT(fluid))
|
||||
print(CP.isenabled_TTSE_LUT(fluid))
|
||||
print(CP.Props('H','P',300,'Q',0,fluid))
|
||||
print(CP.Props('H','P',310,'Q',0,fluid))
|
||||
print(CP.Props('H','P',315,'Q',0,fluid))
|
||||
print(CP.Props('H', 'P', 300, 'Q', 0, fluid))
|
||||
print(CP.Props('H', 'P', 310, 'Q', 0, fluid))
|
||||
print(CP.Props('H', 'P', 315, 'Q', 0, fluid))
|
||||
#
|
||||
fluid = 'TestSolution-0.3'
|
||||
print(CP.enable_TTSE_LUT(fluid))
|
||||
print(CP.isenabled_TTSE_LUT(fluid))
|
||||
print(CP.Props('H','P',3000,'T',280,fluid))
|
||||
print(CP.Props('H', 'P', 3000, 'T', 280, fluid))
|
||||
|
||||
@@ -4,7 +4,7 @@ import matplotlib.pyplot as plt
|
||||
import numpy.ma as ma
|
||||
from numpy.random import uniform, seed
|
||||
# make up some randomly distributed data
|
||||
#seed(1234)
|
||||
# seed(1234)
|
||||
#npts = 200
|
||||
#x = uniform(-2,2,npts)
|
||||
#y = uniform(-2,2,npts)
|
||||
@@ -14,34 +14,34 @@ from numpy.random import uniform, seed
|
||||
#yi = np.linspace(-2.1,2.1,100)
|
||||
# grid the data.
|
||||
|
||||
Ti = np.linspace(300,500)
|
||||
xi = np.linspace(0.4,0.7)
|
||||
Ti = np.linspace(300, 500)
|
||||
xi = np.linspace(0.4, 0.7)
|
||||
|
||||
Tv = [312.9, 333.0, 353.2, 373.9, 393.3, 413.2, 433.0, 453.2, 472.5]
|
||||
xv = [ 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45]
|
||||
zv = [1.919, 1.363, 1.054, 0.854, 0.725, 0.632, 0.564, 0.516, 0.480]
|
||||
Tv = [312.9, 333.0, 353.2, 373.9, 393.3, 413.2, 433.0, 453.2, 472.5]
|
||||
xv = [0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45]
|
||||
zv = [1.919, 1.363, 1.054, 0.854, 0.725, 0.632, 0.564, 0.516, 0.480]
|
||||
|
||||
Tv += [314.9, 333.2, 353.7, 373.2, 393.3, 412.3, 432.6, 453.2, 472.6]
|
||||
xv += [ 0.50, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50]
|
||||
xv += [0.50, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50]
|
||||
zv += [2.446, 1.822, 1.400, 1.131, 0.942, 0.813, 0.712, 0.650, 0.589]
|
||||
|
||||
Tv += [314.2, 333.6, 353.1, 373.1, 393.5, 412.7, 433.0, 453.2, 472.6]
|
||||
xv += [ 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55]
|
||||
xv += [0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55]
|
||||
zv += [3.418, 2.476, 1.895, 1.503, 1.228, 1.037, 0.900, 0.796, 0.720]
|
||||
|
||||
Tv += [316.0, 333.5, 353.6, 372.9, 394.3, 412.7, 433.0, 453.2, 472.9]
|
||||
xv += [ 0.599, 0.599, 0.599, 0.599, 0.599, 0.599, 0.599, 0.599, 0.599]
|
||||
xv += [0.599, 0.599, 0.599, 0.599, 0.599, 0.599, 0.599, 0.599, 0.599]
|
||||
zv += [4.952, 3.603, 2.657, 2.066, 1.634, 1.372, 1.164, 1.018, 0.886]
|
||||
|
||||
Tv += [333.1, 353.2, 373.6, 393.8, 413.2, 432.9, 452.9, 472.8]
|
||||
xv += [ 0.63, 0.63, 0.63, 0.63, 0.63, 0.63, 0.63, 0.63]
|
||||
xv += [0.63, 0.63, 0.63, 0.63, 0.63, 0.63, 0.63, 0.63]
|
||||
zv += [4.964, 3.537, 2.665, 2.090, 1.720, 1.463, 1.245, 1.099]
|
||||
|
||||
Tv += [333.4, 352.4, 372.3, 393.6, 413.2, 433.4, 452.6, 472.7]
|
||||
xv += [ 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65]
|
||||
xv += [0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65]
|
||||
zv += [5.680, 4.158, 3.095, 2.372, 1.925, 1.633, 1.405, 1.240]
|
||||
|
||||
zi = griddata((Tv, xv), zv, (Ti[None,:], xi[:,None]), method='linear')#, method='cubic')
|
||||
zi = griddata((Tv, xv), zv, (Ti[None, :], xi[:, None]), method='linear') # , method='cubic')
|
||||
|
||||
#Tv += [000.0, 000.0, 000.0, 000.0, 000.0, 000.0, 000.0, 000.0, 000.0]
|
||||
#xv += [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]
|
||||
@@ -53,14 +53,14 @@ z = zv
|
||||
yi = xi
|
||||
xi = Ti
|
||||
|
||||
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')
|
||||
zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method='cubic')
|
||||
# contour the gridded data, plotting dots at the randomly spaced data points.
|
||||
CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
|
||||
CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)
|
||||
plt.colorbar() # draw colorbar
|
||||
CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
|
||||
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.jet)
|
||||
plt.colorbar() # draw colorbar
|
||||
# plot data points.
|
||||
plt.scatter(x,y,marker='o',c='b',s=5)
|
||||
#plt.xlim(-2,2)
|
||||
#plt.ylim(-2,2)
|
||||
plt.scatter(x, y, marker='o', c='b', s=5)
|
||||
# plt.xlim(-2,2)
|
||||
# plt.ylim(-2,2)
|
||||
#plt.title('griddata test (%d points)' % npts)
|
||||
plt.show()
|
||||
|
||||
@@ -21,42 +21,42 @@ def mergePdfIfNewer(singlePdfs, combined):
|
||||
for fi in singlePdfs:
|
||||
singles_time = np.append(singles_time, [getTime(fi)])
|
||||
combined_time = getTime(combined)
|
||||
if np.any(singles_time>combined_time):
|
||||
if np.any(singles_time > combined_time):
|
||||
allcombined = PdfFileMerger()
|
||||
for fl in singlePdfs:
|
||||
allcombined.append(PdfFileReader(fl,"rb"))
|
||||
allcombined.append(PdfFileReader(fl, "rb"))
|
||||
allcombined.write(combined)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-t","--test", action='store_true', help="only run a subset of fluid")
|
||||
parser.add_argument("-nf","--nofit", action='store_true', help="Do not fit the data, but read the JSON files")
|
||||
parser.add_argument("-nr","--noreports", action='store_true', help="Do not write the fitting reports")
|
||||
parser.add_argument("-ns","--nosummary", action='store_true', help="Do not generate the summary figures")
|
||||
parser.add_argument("-nt","--notables", action='store_true', help="Do not write the fluid tables")
|
||||
parser.add_argument("-nst","--nostats", action='store_true', help="Do not process statistical parameters")
|
||||
parser.add_argument("-t", "--test", action='store_true', help="only run a subset of fluid")
|
||||
parser.add_argument("-nf", "--nofit", action='store_true', help="Do not fit the data, but read the JSON files")
|
||||
parser.add_argument("-nr", "--noreports", action='store_true', help="Do not write the fitting reports")
|
||||
parser.add_argument("-ns", "--nosummary", action='store_true', help="Do not generate the summary figures")
|
||||
parser.add_argument("-nt", "--notables", action='store_true', help="Do not write the fluid tables")
|
||||
parser.add_argument("-nst", "--nostats", action='store_true', help="Do not process statistical parameters")
|
||||
#parser.add_argument("-f","--fluid", help="Only process the fluid FLUID")
|
||||
|
||||
args = parser.parse_args()
|
||||
# if args.verbosity:
|
||||
# print "verbosity turned on"
|
||||
|
||||
if args.test: runTest = True
|
||||
else: runTest = False
|
||||
if args.nofit: runFitting = False
|
||||
else: runFitting = True
|
||||
if args.test: runTest = True
|
||||
else: runTest = False
|
||||
if args.nofit: runFitting = False
|
||||
else: runFitting = True
|
||||
if args.noreports: runReports = False
|
||||
else: runReports = True
|
||||
else: runReports = True
|
||||
if args.nosummary: runSummary = False
|
||||
else: runSummary = True
|
||||
if args.notables: runTables = False
|
||||
else: runTables = True
|
||||
if args.nostats: runStats = False
|
||||
else: runStats = True
|
||||
else: runSummary = True
|
||||
if args.notables: runTables = False
|
||||
else: runTables = True
|
||||
if args.nostats: runStats = False
|
||||
else: runStats = True
|
||||
#if args.fluid: onlyFluid = args.fluid
|
||||
#else: onlyFluid = None
|
||||
# else: onlyFluid = None
|
||||
|
||||
#runReports = False
|
||||
#runFitting = False
|
||||
@@ -72,7 +72,7 @@ if __name__ == '__main__':
|
||||
# To debug single fluids
|
||||
if runTest:
|
||||
solObjs = []
|
||||
from CPIncomp.SecCoolFluids import SecCoolSolutionData,SecCoolIceData,ThermogenVP1869
|
||||
from CPIncomp.SecCoolFluids import SecCoolSolutionData, SecCoolIceData, ThermogenVP1869
|
||||
from CPIncomp.PureFluids import PMR
|
||||
#from CPIncomp.PureFluids import Texatherm22
|
||||
#solObjs += [SecCoolSolutionData(sFile='Melinder, Ethanol' ,sFolder='xMass',name='MEA2',desc='Melinder, Ethanol' ,ref='Melinder2010,Skovrup2013')]
|
||||
@@ -87,7 +87,7 @@ if __name__ == '__main__':
|
||||
|
||||
# treat the examples first
|
||||
fluidObjs = getExampleNames(obj=True)
|
||||
examplesToFit = ["ExamplePure","ExampleSolution","ExampleDigital","ExampleDigitalPure"]
|
||||
examplesToFit = ["ExamplePure", "ExampleSolution", "ExampleDigital", "ExampleDigitalPure"]
|
||||
|
||||
print("\nProcessing example fluids")
|
||||
for obj in fluidObjs:
|
||||
@@ -98,8 +98,8 @@ if __name__ == '__main__':
|
||||
if runFitting: writer.writeFluidList(doneObjs)
|
||||
if runReports:
|
||||
# TODO: The new method for multipage PDFs produces larger files, why?
|
||||
if writer.usetex: combined_name=None
|
||||
else: combined_name = os.path.join(os.path.abspath("report"),"all_examples.pdf")
|
||||
if writer.usetex: combined_name = None
|
||||
else: combined_name = os.path.join(os.path.abspath("report"), "all_examples.pdf")
|
||||
writer.writeReportList(doneObjs, pdfFile=combined_name)
|
||||
#singleNames = [writer.get_report_file(fl.name) for fl in doneObjs]
|
||||
#mergePdfIfNewer(singleNames, "all_examples.pdf")
|
||||
@@ -146,35 +146,35 @@ if __name__ == '__main__':
|
||||
doneObjs = sorted(doneObjs, key=lambda x: x.name)
|
||||
|
||||
purefluids = []
|
||||
solMass = []
|
||||
solMole = []
|
||||
solVolu = []
|
||||
errors = []
|
||||
solMass = []
|
||||
solMole = []
|
||||
solVolu = []
|
||||
errors = []
|
||||
|
||||
for i in range(0,len(doneObjs)):
|
||||
for i in range(0, len(doneObjs)):
|
||||
|
||||
curObj = doneObjs[i]
|
||||
|
||||
if i < len(doneObjs)-2:
|
||||
nexObj = doneObjs[i+1]
|
||||
if i < len(doneObjs) - 2:
|
||||
nexObj = doneObjs[i + 1]
|
||||
else:
|
||||
nexObj = doneObjs[0]
|
||||
|
||||
if curObj.name==nexObj.name:
|
||||
print("Conflict between {0} and {1}, aborting".format(curObj,nexObj))
|
||||
if curObj.name == nexObj.name:
|
||||
print("Conflict between {0} and {1}, aborting".format(curObj, nexObj))
|
||||
raise ValueError("Two elements have the same name, that does not work: {0}".format(curObj.name))
|
||||
else:
|
||||
#print("Processing {0}: ".format(curObj.name), end="")
|
||||
if curObj.xid==SolutionData.ifrac_mass:
|
||||
if curObj.xid == SolutionData.ifrac_mass:
|
||||
solMass.append(curObj)
|
||||
#print("added to mass-based fluids ({0})".format(curObj.xid))
|
||||
elif curObj.xid==SolutionData.ifrac_mole:
|
||||
elif curObj.xid == SolutionData.ifrac_mole:
|
||||
solMole.append(curObj)
|
||||
#print("added to mole-based fluids ({0})".format(curObj.xid))
|
||||
elif curObj.xid==SolutionData.ifrac_volume:
|
||||
elif curObj.xid == SolutionData.ifrac_volume:
|
||||
solVolu.append(curObj)
|
||||
#print("added to volume-based fluids ({0})".format(curObj.xid))
|
||||
elif curObj.xid==SolutionData.ifrac_pure:
|
||||
elif curObj.xid == SolutionData.ifrac_pure:
|
||||
purefluids.append(curObj)
|
||||
#print("added to pure fluids ({0})".format(curObj.xid))
|
||||
else:
|
||||
@@ -192,7 +192,7 @@ if __name__ == '__main__':
|
||||
# printNames(solVolu, "Volume-based: ")
|
||||
# printNames(purefluids,"Pure fluids : ")
|
||||
|
||||
if len(errors)>0:
|
||||
if len(errors) > 0:
|
||||
raise ValueError("There was a problem processing the fluid(s): {0}".format([error.name for error in errors]))
|
||||
|
||||
#solutions = solMass
|
||||
@@ -209,14 +209,14 @@ if __name__ == '__main__':
|
||||
combined_time = 0
|
||||
else:
|
||||
combined_name = "all_incompressibles.pdf"
|
||||
combined_name = os.path.join(os.path.abspath("report"),combined_name)
|
||||
combined_name = os.path.join(os.path.abspath("report"), combined_name)
|
||||
combined_time = getTime(combined_name)
|
||||
|
||||
singles_time = np.array([])
|
||||
for fl in doneObjs:
|
||||
singles_time = np.append(singles_time, [getTime(writer.get_json_file(fl.name))])
|
||||
|
||||
if np.any(singles_time>combined_time):
|
||||
if np.any(singles_time > combined_time):
|
||||
print("Processing {0:2d} fluids - ".format(len(doneObjs)), end="")
|
||||
writer.writeReportList(doneObjs, pdfFile=combined_name)
|
||||
else:
|
||||
@@ -229,23 +229,23 @@ if __name__ == '__main__':
|
||||
#####################################
|
||||
# Table generation routines
|
||||
#####################################
|
||||
#FLUID_INFO_FOLDER=os.path.abspath("table")
|
||||
#FLUID_INFO_MASS_LIST=os.path.join(FLUID_INFO_FOLDER,"mass-based-fluids")
|
||||
#FLUID_INFO_MOLE_LIST=os.path.join(FLUID_INFO_FOLDER,"mole-based-fluids")
|
||||
#FLUID_INFO_VOLU_LIST=os.path.join(FLUID_INFO_FOLDER,"volume-based-fluids")
|
||||
#FLUID_INFO_PURE_LIST=os.path.join(FLUID_INFO_FOLDER,"pure-fluids")
|
||||
FLUID_INFO_FOLDER=os.path.abspath("tables")
|
||||
FLUID_INFO_MASS_LIST=os.path.join(FLUID_INFO_FOLDER,"Incompressibles_mass-based-fluids")
|
||||
FLUID_INFO_MOLE_LIST=os.path.join(FLUID_INFO_FOLDER,"Incompressibles_mole-based-fluids")
|
||||
FLUID_INFO_VOLU_LIST=os.path.join(FLUID_INFO_FOLDER,"Incompressibles_volume-based-fluids")
|
||||
FLUID_INFO_PURE_LIST=os.path.join(FLUID_INFO_FOLDER,"Incompressibles_pure-fluids")
|
||||
# FLUID_INFO_FOLDER=os.path.abspath("table")
|
||||
# FLUID_INFO_MASS_LIST=os.path.join(FLUID_INFO_FOLDER,"mass-based-fluids")
|
||||
# FLUID_INFO_MOLE_LIST=os.path.join(FLUID_INFO_FOLDER,"mole-based-fluids")
|
||||
# FLUID_INFO_VOLU_LIST=os.path.join(FLUID_INFO_FOLDER,"volume-based-fluids")
|
||||
# FLUID_INFO_PURE_LIST=os.path.join(FLUID_INFO_FOLDER,"pure-fluids")
|
||||
FLUID_INFO_FOLDER = os.path.abspath("tables")
|
||||
FLUID_INFO_MASS_LIST = os.path.join(FLUID_INFO_FOLDER, "Incompressibles_mass-based-fluids")
|
||||
FLUID_INFO_MOLE_LIST = os.path.join(FLUID_INFO_FOLDER, "Incompressibles_mole-based-fluids")
|
||||
FLUID_INFO_VOLU_LIST = os.path.join(FLUID_INFO_FOLDER, "Incompressibles_volume-based-fluids")
|
||||
FLUID_INFO_PURE_LIST = os.path.join(FLUID_INFO_FOLDER, "Incompressibles_pure-fluids")
|
||||
|
||||
# After all the list got populated, we can process the entries
|
||||
# and generate some tables
|
||||
#
|
||||
objLists = [purefluids,solMass,solMole,solVolu]
|
||||
filLists = [FLUID_INFO_PURE_LIST,FLUID_INFO_MASS_LIST]
|
||||
filLists +=[FLUID_INFO_MOLE_LIST,FLUID_INFO_VOLU_LIST]
|
||||
objLists = [purefluids, solMass, solMole, solVolu]
|
||||
filLists = [FLUID_INFO_PURE_LIST, FLUID_INFO_MASS_LIST]
|
||||
filLists += [FLUID_INFO_MOLE_LIST, FLUID_INFO_VOLU_LIST]
|
||||
#
|
||||
for i in range(len(objLists)):
|
||||
#print("Processing fluid list: ", end="")
|
||||
@@ -255,10 +255,10 @@ if __name__ == '__main__':
|
||||
writer.generateTexTable(objLists[i], filLists[i])
|
||||
|
||||
if runStats:
|
||||
lists = [purefluids, solMass, solVolu]#, solMole, errors]
|
||||
labels = ["Pure", "Mass", "Volume"]#, "Mole", "Error"]
|
||||
lists = [purefluids, solMass, solVolu] # , solMole, errors]
|
||||
labels = ["Pure", "Mass", "Volume"] # , "Mole", "Error"]
|
||||
|
||||
fits = ["rho", "cp", "visc", "cond", "psat", "Tfreeze"]
|
||||
fits = ["rho", "cp", "visc", "cond", "psat", "Tfreeze"]
|
||||
|
||||
writer.generateStatsTable(lists, labels)
|
||||
|
||||
|
||||
@@ -2,90 +2,90 @@ import os, json
|
||||
|
||||
|
||||
Simon_curves = {
|
||||
"n-Propane" : {
|
||||
"BibTeX" : "Reeves-JCP-1964", "T_m": -187.75 + 273.15, "parts": [{"T_0" : 85.3, "a" : 7.180e8, "c" : 1.283, "p_0" : 0.0, "T_max" : 168.63}]
|
||||
"n-Propane": {
|
||||
"BibTeX": "Reeves-JCP-1964", "T_m": -187.75 + 273.15, "parts": [{"T_0": 85.3, "a": 7.180e8, "c": 1.283, "p_0": 0.0, "T_max": 168.63}]
|
||||
},
|
||||
"n-Pentane" : {
|
||||
"BibTeX" : "Reeves-JCP-1964", "T_m": -129.89 + 273.15, "parts": [{"T_0" : 143.5, "a" : 6.600e8, "c" : 1.649, "p_0" : 0.0, "T_max" : 156.2}]
|
||||
"n-Pentane": {
|
||||
"BibTeX": "Reeves-JCP-1964", "T_m": -129.89 + 273.15, "parts": [{"T_0": 143.5, "a": 6.600e8, "c": 1.649, "p_0": 0.0, "T_max": 156.2}]
|
||||
},
|
||||
"Isopentane" : {
|
||||
"BibTeX" : "Reeves-JCP-1964", "T_m": -159.92 + 273.15, "parts": [{"T_0" : 112.5, "a" : 5.916e8, "c" : 1.563, "p_0" : 0, "T_max" : 212.16}]
|
||||
"Isopentane": {
|
||||
"BibTeX": "Reeves-JCP-1964", "T_m": -159.92 + 273.15, "parts": [{"T_0": 112.5, "a": 5.916e8, "c": 1.563, "p_0": 0, "T_max": 212.16}]
|
||||
},
|
||||
"Propylene" : {
|
||||
"BibTeX" : "Reeves-JCP-1964", "T_m": -185.09 + 273.15, "parts": [{"T_0" : 86.0, "a" : 3.196e8, "c" : 2.821, "p_0" : 0, "T_min": 86.0, "T_max" : 129},
|
||||
{"T_0" : 109.6, "a" : 3.064e8, "c" : 3.871, "p_0" : 4.450e8, "T_min": 129, "T_max" : 145.3}]
|
||||
"Propylene": {
|
||||
"BibTeX": "Reeves-JCP-1964", "T_m": -185.09 + 273.15, "parts": [{"T_0": 86.0, "a": 3.196e8, "c": 2.821, "p_0": 0, "T_min": 86.0, "T_max": 129},
|
||||
{"T_0": 109.6, "a": 3.064e8, "c": 3.871, "p_0": 4.450e8, "T_min": 129, "T_max": 145.3}]
|
||||
},
|
||||
"Cyclohexane" : {
|
||||
"BibTeX" : "Penoncello-IJT-1995", "T_m": 6.81 + 273.15, "parts": [{"T_0" : 279.7, "a" : 383.4e6, "c" : 1.41, "p_0" : 0, "T_max" : 401.7}]
|
||||
"Cyclohexane": {
|
||||
"BibTeX": "Penoncello-IJT-1995", "T_m": 6.81 + 273.15, "parts": [{"T_0": 279.7, "a": 383.4e6, "c": 1.41, "p_0": 0, "T_max": 401.7}]
|
||||
},
|
||||
"Krypton" : {
|
||||
"BibTeX" : "Michels-PHYSICA-1962", "T_m": 115.95, "parts": [{"T_0" : 1, "a" : 109479.2307, "c" : 1.6169841, "p_0" : -237497645.7, "T_max" : 168.7}]
|
||||
"Krypton": {
|
||||
"BibTeX": "Michels-PHYSICA-1962", "T_m": 115.95, "parts": [{"T_0": 1, "a": 109479.2307, "c": 1.6169841, "p_0": -237497645.7, "T_max": 168.7}]
|
||||
},
|
||||
"Xenon" : {
|
||||
"BibTeX" : "Michels-PHYSICA-1962", "T_m": 165.02, "parts": [{"T_0" : 1, "a" : 80890.5544859, "c" : 1.5891650, "p_0" : -260932309.446, "T_max" : 366.4}]
|
||||
"Xenon": {
|
||||
"BibTeX": "Michels-PHYSICA-1962", "T_m": 165.02, "parts": [{"T_0": 1, "a": 80890.5544859, "c": 1.5891650, "p_0": -260932309.446, "T_max": 366.4}]
|
||||
},
|
||||
"CarbonMonoxide" : {
|
||||
"BibTeX" : "Barreiros-JCT-1982", "T_m": 68.3, "parts": [{"T_0" : 1, "a" : 19560.8, "c" : 2.10747, "p_0" : -142921439.2, "T_max" : 87.5}]
|
||||
"CarbonMonoxide": {
|
||||
"BibTeX": "Barreiros-JCT-1982", "T_m": 68.3, "parts": [{"T_0": 1, "a": 19560.8, "c": 2.10747, "p_0": -142921439.2, "T_max": 87.5}]
|
||||
},
|
||||
"Oxygen": {
|
||||
"BibTeX" : "Younglove-NIST-1982", "T_m": 54.75, "parts": [{"T_0" : 1, "a" : 227606.348, "c" : 1.769, "p_0" : -266999247.652, "T_max" : 63.1}]
|
||||
"BibTeX": "Younglove-NIST-1982", "T_m": 54.75, "parts": [{"T_0": 1, "a": 227606.348, "c": 1.769, "p_0": -266999247.652, "T_max": 63.1}]
|
||||
},
|
||||
"ParaHydrogen": {
|
||||
"BibTeX" : "Younglove-NIST-1982", "T_m": 18.9, "parts": [{"T_0" : 1, "a" : 125746.643, "c" : 1.955, "p_0" : -21155737.752, "T_min" : 13.8033, "T_max" : 22},
|
||||
{"T_0" : 1, "a" : 248578.596, "c" : 1.764739, "p_0" : -26280332.904, "T_min" : 22, "T_max" : 164.5}]
|
||||
"BibTeX": "Younglove-NIST-1982", "T_m": 18.9, "parts": [{"T_0": 1, "a": 125746.643, "c": 1.955, "p_0": -21155737.752, "T_min": 13.8033, "T_max": 22},
|
||||
{"T_0": 1, "a": 248578.596, "c": 1.764739, "p_0": -26280332.904, "T_min": 22, "T_max": 164.5}]
|
||||
},
|
||||
"Methane": {
|
||||
"BibTeX" : "Abramson-HPR-2011", "T_m": 90.7, "parts": [{"T_0" : 90.6941, "a" : 0.208e9, "c" : 1.698, "p_0" : 1.17e4, "T_max" : 600}]
|
||||
"BibTeX": "Abramson-HPR-2011", "T_m": 90.7, "parts": [{"T_0": 90.6941, "a": 0.208e9, "c": 1.698, "p_0": 1.17e4, "T_max": 600}]
|
||||
},
|
||||
"Helium": {
|
||||
"BibTeX" : "Datchi-PRB-2000", "T_m": 1.15, "parts": [{"T_0" : 1, "a" : 1.6067e6, "c" : 1.565, "p_0" : -1.6067e6, "T_max" : 700}]
|
||||
"BibTeX": "Datchi-PRB-2000", "T_m": 1.15, "parts": [{"T_0": 1, "a": 1.6067e6, "c": 1.565, "p_0": -1.6067e6, "T_max": 700}]
|
||||
},
|
||||
"Neon": {
|
||||
"BibTeX" : "SantamariaPerez-PRB-2010", "T_m": -1, "parts": [{"T_0" : 24.4, "a" : 1.7e9, "c" : 1/0.77, "p_0" : 101325, "T_max" : 700}]
|
||||
"BibTeX": "SantamariaPerez-PRB-2010", "T_m": -1, "parts": [{"T_0": 24.4, "a": 1.7e9, "c": 1 / 0.77, "p_0": 101325, "T_max": 700}]
|
||||
},
|
||||
"Hydrogen": {
|
||||
"BibTeX" : "Datchi-PRB-2000", "T_m": 14.009985, "parts": [{"T_0" : 1, "a" : 2.31e5, "c" : 1.7627, "p_0" : -0.0052e6-2.31e5, "T_max" : 700}]
|
||||
"BibTeX": "Datchi-PRB-2000", "T_m": 14.009985, "parts": [{"T_0": 1, "a": 2.31e5, "c": 1.7627, "p_0": -0.0052e6 - 2.31e5, "T_max": 700}]
|
||||
}
|
||||
}
|
||||
|
||||
polynomial_in_Tr = {
|
||||
"Argon" : {
|
||||
"BibTeX" : "Tegeler-JPCRD-1999", "T_m": 87.28, "parts": [{"T_0" : 83.8058, "a" : [-7476.2665, 9959.0613], "t" : [1.05,1.275], "p_0" : 68891, "T_max" : 254.0}]
|
||||
"Argon": {
|
||||
"BibTeX": "Tegeler-JPCRD-1999", "T_m": 87.28, "parts": [{"T_0": 83.8058, "a": [-7476.2665, 9959.0613], "t": [1.05, 1.275], "p_0": 68891, "T_max": 254.0}]
|
||||
},
|
||||
"Fluorine" : {
|
||||
"BibTeX" : "deReuck-BOOK-1990", "T_m": 53.15, "parts": [{"T_0" : 53.4811, "a" : [988043.478261], "t" : [2.1845], "p_0" : 252, "T_max" : 55.4}]
|
||||
"Fluorine": {
|
||||
"BibTeX": "deReuck-BOOK-1990", "T_m": 53.15, "parts": [{"T_0": 53.4811, "a": [988043.478261], "t": [2.1845], "p_0": 252, "T_max": 55.4}]
|
||||
},
|
||||
"Nitrogen" : {
|
||||
"BibTeX" : "Span-JPCRD-2000", "T_m": 77.34, "parts": [{"T_0" : 63.151, "a" : [12798.61], "t" : [1.78963], "p_0" : 12523, "T_max" : 283.8}]
|
||||
"Nitrogen": {
|
||||
"BibTeX": "Span-JPCRD-2000", "T_m": 77.34, "parts": [{"T_0": 63.151, "a": [12798.61], "t": [1.78963], "p_0": 12523, "T_max": 283.8}]
|
||||
},
|
||||
"Ethane" : {
|
||||
"BibTeX" : "Buecker-JCRD-2006", "T_m": 90.4, "parts": [{"T_0" : 90.368, "a" : [2.23626315e8, 1.05262374e8], "t" : [1.0, 2.55], "p_0" : 1.14, "T_max" : 110.2}]
|
||||
"Ethane": {
|
||||
"BibTeX": "Buecker-JCRD-2006", "T_m": 90.4, "parts": [{"T_0": 90.368, "a": [2.23626315e8, 1.05262374e8], "t": [1.0, 2.55], "p_0": 1.14, "T_max": 110.2}]
|
||||
},
|
||||
"Isobutane" : {
|
||||
"BibTeX" : "Buecker-JPCRD-2006B", "T_m": 113.55, "parts": [{"T_0" : 113.73, "a" : [1.9536371309e9], "t" : [6.12], "p_0" : 0.0219, "T_max" : 124.9}]
|
||||
"Isobutane": {
|
||||
"BibTeX": "Buecker-JPCRD-2006B", "T_m": 113.55, "parts": [{"T_0": 113.73, "a": [1.9536371309e9], "t": [6.12], "p_0": 0.0219, "T_max": 124.9}]
|
||||
},
|
||||
"Ethylene" : {
|
||||
"BibTeX" : "Smukala-JPCRD-2000", "T_m": 169, "parts": [{"T_0" : 103.989, "a" : [2947001.84], "t" : [2.045], "p_0" : 122.65, "T_min" : 103.989, "T_max" : 110.369},
|
||||
{"T_0" : 110.369, "a" : [6.82693421], "t" : [1.089], "p_0" : 46.8e6, "T_min" : 110.369, "T_max" : 188}]
|
||||
"Ethylene": {
|
||||
"BibTeX": "Smukala-JPCRD-2000", "T_m": 169, "parts": [{"T_0": 103.989, "a": [2947001.84], "t": [2.045], "p_0": 122.65, "T_min": 103.989, "T_max": 110.369},
|
||||
{"T_0": 110.369, "a": [6.82693421], "t": [1.089], "p_0": 46.8e6, "T_min": 110.369, "T_max": 188}]
|
||||
},
|
||||
"n-Butane" : {
|
||||
"BibTeX" : "Buecker-JPCRD-2006B", "T_m": -137.92 + 273.15, "parts": [{"T_0" : 134.895, "a" : [5.585582364e8], "t" : [2.206], "p_0" : 0.653, "T_max" : 163.9}]
|
||||
"n-Butane": {
|
||||
"BibTeX": "Buecker-JPCRD-2006B", "T_m": -137.92 + 273.15, "parts": [{"T_0": 134.895, "a": [5.585582364e8], "t": [2.206], "p_0": 0.653, "T_max": 163.9}]
|
||||
},
|
||||
"Water" : {
|
||||
"BibTeX" : "IAPWS", "T_m": -1, "parts": [{"T_0" : 273.16, "a" : [-0.119539337e7,-0.808183159e5,-0.333826860e4], "t" : [0.3000000e1, 0.257500e2, 0.103750e3], "p_0" : 611.657, "T_min": 273.16, "T_max" : 251.165},
|
||||
{"T_0" : 251.165, "a" : [0.299948], "t" : [60], "p_0" : 208.566e6, "T_min": 251.165, "T_max" : 256.164},
|
||||
{"T_0" : 256.164, "a" : [1.18721], "t" : [8], "p_0" : 350.1e6, "T_min": 256.164, "T_max" : 273.31},
|
||||
{"T_0" : 273.31, "a" : [1.07476], "t" : [4.6], "p_0" : 623.4e6, "T_min": 273.31, "T_max" : 355}
|
||||
"Water": {
|
||||
"BibTeX": "IAPWS", "T_m": -1, "parts": [{"T_0": 273.16, "a": [-0.119539337e7, -0.808183159e5, -0.333826860e4], "t": [0.3000000e1, 0.257500e2, 0.103750e3], "p_0": 611.657, "T_min": 273.16, "T_max": 251.165},
|
||||
{"T_0": 251.165, "a": [0.299948], "t": [60], "p_0": 208.566e6, "T_min": 251.165, "T_max": 256.164},
|
||||
{"T_0": 256.164, "a": [1.18721], "t": [8], "p_0": 350.1e6, "T_min": 256.164, "T_max": 273.31},
|
||||
{"T_0": 273.31, "a": [1.07476], "t": [4.6], "p_0": 623.4e6, "T_min": 273.31, "T_max": 355}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
polynomial_in_theta = {
|
||||
"Methanol" : {
|
||||
"BibTeX" : "deReuck-BOOK-1993", "T_m": 337.8, "parts": [{"T_0" : 175.61, "a" : [5.330770e9, 4.524780e9, 3.888861e10], "t" : [1, 1.5, 4], "p_0" : 0.187, "T_max" : 245.9}]
|
||||
"Methanol": {
|
||||
"BibTeX": "deReuck-BOOK-1993", "T_m": 337.8, "parts": [{"T_0": 175.61, "a": [5.330770e9, 4.524780e9, 3.888861e10], "t": [1, 1.5, 4], "p_0": 0.187, "T_max": 245.9}]
|
||||
},
|
||||
"CarbonDioxide" : {
|
||||
"BibTeX" : "Span-JPCRD-1996", "T_m": 216.58, "parts": [{"T_0" : 216.592, "a" : [1955.5390, 2055.4593], "t" : [1, 2], "p_0" : 517950, "T_max" : 327.6}]
|
||||
"CarbonDioxide": {
|
||||
"BibTeX": "Span-JPCRD-1996", "T_m": 216.58, "parts": [{"T_0": 216.592, "a": [1955.5390, 2055.4593], "t": [1, 2], "p_0": 517950, "T_max": 327.6}]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ for fluid in CoolProp.__fluids__:
|
||||
print(fluid)
|
||||
__ += 1
|
||||
else:
|
||||
print(' '*30, fluid)
|
||||
print(' ' * 30, fluid)
|
||||
print(__)
|
||||
|
||||
import CoolProp.CoolProp as CP
|
||||
@@ -104,23 +104,23 @@ import json, numpy as np, matplotlib.pyplot as plt, pandas
|
||||
|
||||
ip = 1
|
||||
irho = 1
|
||||
Nrow,Ncol = 5,5
|
||||
Nrow, Ncol = 5, 5
|
||||
|
||||
figp = plt.figure(figsize = (20,20))
|
||||
figrho = plt.figure(figsize = (20,20))
|
||||
figp = plt.figure(figsize=(20, 20))
|
||||
figrho = plt.figure(figsize=(20, 20))
|
||||
|
||||
|
||||
def plot_rho(T, rho, fit = False):
|
||||
x, y = (T-T[0])/(T[len(T)-1]-T[0]), (rho-rho[0])/(rho[len(rho)-1]-rho[0])
|
||||
def plot_rho(T, rho, fit=False):
|
||||
x, y = (T - T[0]) / (T[len(T) - 1] - T[0]), (rho - rho[0]) / (rho[len(rho) - 1] - rho[0])
|
||||
|
||||
c = np.polyfit(x, y, 3)
|
||||
yfit = np.polyval(c, x)
|
||||
err = yfit - y
|
||||
rms = np.sqrt(np.mean(np.power(err,2)))
|
||||
rms = np.sqrt(np.mean(np.power(err, 2)))
|
||||
|
||||
rhofit = yfit*(rho[len(rho)-1]-rho[0])+rho[0]
|
||||
rhofit = yfit * (rho[len(rho) - 1] - rho[0]) + rho[0]
|
||||
if fit:
|
||||
return T, (rhofit/rho-1)*100
|
||||
return T, (rhofit / rho - 1) * 100
|
||||
else:
|
||||
return x, y
|
||||
|
||||
@@ -135,21 +135,21 @@ def simon():
|
||||
axp.set_ylabel('p [Pa]')
|
||||
axrho.set_xlabel('T [K]')
|
||||
axrho.set_ylabel('rho [mol/m$^3$]')
|
||||
axp.set_title(fluid+' - '+str(round(CP.Props(fluid,"molemass"),2)))
|
||||
axp.set_title(fluid + ' - ' + str(round(CP.Props(fluid, "molemass"), 2)))
|
||||
axrho.set_title(fluid)
|
||||
|
||||
fname = os.path.join('fluids',fluid+'.json')
|
||||
j = json.load(open(fname,'r'))
|
||||
fname = os.path.join('fluids', fluid + '.json')
|
||||
j = json.load(open(fname, 'r'))
|
||||
for part in values['parts']:
|
||||
if 'T_min' not in part:
|
||||
part['T_min'] = round(CP.Props(fluid,"Tmin"),4)
|
||||
part['T_min'] = round(CP.Props(fluid, "Tmin"), 4)
|
||||
values['type'] = 'Simon'
|
||||
|
||||
j['ANCILLARIES']['melting_line'] = values
|
||||
|
||||
fp = open(fname,'w')
|
||||
fp = open(fname, 'w')
|
||||
from package_json import json_options
|
||||
fp.write(json.dumps(j,**json_options))
|
||||
fp.write(json.dumps(j, **json_options))
|
||||
fp.close()
|
||||
|
||||
# if not isinstance(values, list):
|
||||
@@ -168,7 +168,7 @@ def simon():
|
||||
T_m = values['T_m']
|
||||
for i, value in enumerate(values['parts']):
|
||||
|
||||
Tmin = value.get('T_min',CP.Props(fluid,"Tmin"))
|
||||
Tmin = value.get('T_min', CP.Props(fluid, "Tmin"))
|
||||
Tmax = value['T_max']
|
||||
|
||||
T = np.linspace(Tmin, Tmax, 200)
|
||||
@@ -177,18 +177,18 @@ def simon():
|
||||
a = value['a']
|
||||
c = value['c']
|
||||
|
||||
p = p_0 + a*((T/T_0)**c - 1)
|
||||
p = p_0 + a * ((T / T_0)**c - 1)
|
||||
|
||||
axp.plot(T, p)
|
||||
|
||||
cc = 1.75
|
||||
aa = 3e8#(101325-p_0)/((T_m/T_0)**cc-1)
|
||||
pt = CP.Props(fluid,'ptriple')
|
||||
pp = pt + aa*((T/Tmin)**cc - 1)
|
||||
axp.plot(T_m,101325,'*')
|
||||
axp.plot(T,pp,'--')
|
||||
aa = 3e8 # (101325-p_0)/((T_m/T_0)**cc-1)
|
||||
pt = CP.Props(fluid, 'ptriple')
|
||||
pp = pt + aa * ((T / Tmin)**cc - 1)
|
||||
axp.plot(T_m, 101325, '*')
|
||||
axp.plot(T, pp, '--')
|
||||
|
||||
print("%s %s %s %s" % (fluid, CP.Props(fluid,"molemass"), CP.Props(fluid, 'accentric'), pp[-1]/p[-1]-1))
|
||||
print("%s %s %s %s" % (fluid, CP.Props(fluid, "molemass"), CP.Props(fluid, 'accentric'), pp[-1] / p[-1] - 1))
|
||||
|
||||
# if fluid == 'Helium':
|
||||
# T = np.array([326.2,345.1,362.8,385.1,419.4,459,499,535.7,570,608])
|
||||
@@ -206,28 +206,28 @@ def Tr():
|
||||
axp.set_ylabel('p [Pa]')
|
||||
axrho.set_xlabel('T [K]')
|
||||
axrho.set_ylabel('rho [mol/m$^3$]')
|
||||
axp.set_title(fluid+' - '+str(round(CP.Props(fluid,"molemass"),2)))
|
||||
axp.set_title(fluid + ' - ' + str(round(CP.Props(fluid, "molemass"), 2)))
|
||||
axrho.set_title(fluid)
|
||||
|
||||
fname = os.path.join('fluids',fluid+'.json')
|
||||
j = json.load(open(fname,'r'))
|
||||
fname = os.path.join('fluids', fluid + '.json')
|
||||
j = json.load(open(fname, 'r'))
|
||||
for part in values['parts']:
|
||||
if 'T_min' not in part:
|
||||
part['T_min'] = round(CP.Props(fluid,"Tmin"),4)
|
||||
part['T_min'] = round(CP.Props(fluid, "Tmin"), 4)
|
||||
values['type'] = 'polynomial_in_Tr'
|
||||
|
||||
j['ANCILLARIES']['melting_line'] = values
|
||||
|
||||
fp = open(fname,'w')
|
||||
fp = open(fname, 'w')
|
||||
from package_json import json_options
|
||||
fp.write(json.dumps(j,**json_options))
|
||||
fp.write(json.dumps(j, **json_options))
|
||||
fp.close()
|
||||
|
||||
if fluid == 'Ethylene':
|
||||
T = [104.003, 104.059, 104.13, 104.2, 104.27, 104.41, 104.55, 104.69, 104.83, 104.969, 105.108, 105.386, 106.077, 106.764, 107.446, 111.384, 119.283, 127.136, 158.146, 188.621]
|
||||
p = np.array([0.1, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 10, 15, 20, 25, 50, 75, 100, 200, 300])*1e6
|
||||
p = np.array([0.1, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 10, 15, 20, 25, 50, 75, 100, 200, 300]) * 1e6
|
||||
|
||||
axp.plot(T,p,'*')
|
||||
axp.plot(T, p, '*')
|
||||
|
||||
# if not isinstance(values, list):
|
||||
# values = [values]
|
||||
@@ -244,9 +244,9 @@ def Tr():
|
||||
# axrho.plot(x,y, 'o', mfc='none')
|
||||
|
||||
T_m = values['T_m']
|
||||
for i,value in enumerate(values['parts']):
|
||||
for i, value in enumerate(values['parts']):
|
||||
|
||||
Tmin = value.get('T_min',CP.Props(fluid,"Tmin"))
|
||||
Tmin = value.get('T_min', CP.Props(fluid, "Tmin"))
|
||||
Tmax = value['T_max']
|
||||
T = np.linspace(Tmin, Tmax, 200)
|
||||
|
||||
@@ -257,20 +257,20 @@ def Tr():
|
||||
|
||||
RHS = 0
|
||||
for i in range(len(a)):
|
||||
RHS += a[i]*((T/T_t)**t[i] - 1)
|
||||
RHS += a[i] * ((T / T_t)**t[i] - 1)
|
||||
|
||||
p = p_t*(RHS + 1)
|
||||
p = p_t * (RHS + 1)
|
||||
|
||||
axp.plot(T, p)
|
||||
|
||||
cc = 1.75
|
||||
aa = 3e8#(101325-p_0)/((T_m/T_0)**cc-1)
|
||||
pt = CP.Props(fluid,'ptriple')
|
||||
pp = pt + aa*((T/Tmin)**cc - 1)
|
||||
axp.plot(T_m,101325,'*')
|
||||
axp.plot(T,pp,'--')
|
||||
aa = 3e8 # (101325-p_0)/((T_m/T_0)**cc-1)
|
||||
pt = CP.Props(fluid, 'ptriple')
|
||||
pp = pt + aa * ((T / Tmin)**cc - 1)
|
||||
axp.plot(T_m, 101325, '*')
|
||||
axp.plot(T, pp, '--')
|
||||
|
||||
print("%s %s %s %s" % (fluid, CP.Props(fluid,"molemass"), CP.Props(fluid, 'accentric'), pp[-1]/p[-1]-1))
|
||||
print("%s %s %s %s" % (fluid, CP.Props(fluid, "molemass"), CP.Props(fluid, 'accentric'), pp[-1] / p[-1] - 1))
|
||||
|
||||
|
||||
def theta():
|
||||
@@ -283,21 +283,21 @@ def theta():
|
||||
axp.set_ylabel('p [Pa]')
|
||||
axrho.set_xlabel('T [K]')
|
||||
axrho.set_ylabel('rho [mol/m$^3$]')
|
||||
axp.set_title(fluid+' - '+str(round(CP.Props(fluid,"molemass"),2)))
|
||||
axp.set_title(fluid + ' - ' + str(round(CP.Props(fluid, "molemass"), 2)))
|
||||
axrho.set_title(fluid)
|
||||
|
||||
fname = os.path.join('fluids',fluid+'.json')
|
||||
j = json.load(open(fname,'r'))
|
||||
fname = os.path.join('fluids', fluid + '.json')
|
||||
j = json.load(open(fname, 'r'))
|
||||
for part in values['parts']:
|
||||
if 'T_min' not in part:
|
||||
part['T_min'] = round(CP.Props(fluid,"Tmin"),4)
|
||||
part['T_min'] = round(CP.Props(fluid, "Tmin"), 4)
|
||||
values['type'] = 'polynomial_in_Theta'
|
||||
|
||||
j['ANCILLARIES']['melting_line'] = values
|
||||
|
||||
fp = open(fname,'w')
|
||||
fp = open(fname, 'w')
|
||||
from package_json import json_options
|
||||
fp.write(json.dumps(j,**json_options))
|
||||
fp.write(json.dumps(j, **json_options))
|
||||
fp.close()
|
||||
|
||||
T_m = values['T_m']
|
||||
@@ -314,9 +314,9 @@ def theta():
|
||||
|
||||
RHS = 0
|
||||
for i in range(len(a)):
|
||||
RHS += a[i]*(T/T_t - 1)**t[i]
|
||||
RHS += a[i] * (T / T_t - 1)**t[i]
|
||||
|
||||
p = p_t*(RHS + 1)
|
||||
p = p_t * (RHS + 1)
|
||||
|
||||
#df = pandas.read_csv('melting_curves/' + fluid + '.mlt', names=['T','p','rho'])
|
||||
|
||||
@@ -328,16 +328,16 @@ def theta():
|
||||
#axrho.plot(x,y, 'o', mfc='none')
|
||||
|
||||
cc = 1.75
|
||||
aa = 3e8#(101325-p_0)/((T_m/T_0)**cc-1)
|
||||
pt = CP.Props(fluid,'ptriple')
|
||||
pp = pt + aa*((T/Tmin)**cc - 1)
|
||||
axp.plot(T_m,101325,'*')
|
||||
axp.plot(T,pp,'--')
|
||||
aa = 3e8 # (101325-p_0)/((T_m/T_0)**cc-1)
|
||||
pt = CP.Props(fluid, 'ptriple')
|
||||
pp = pt + aa * ((T / Tmin)**cc - 1)
|
||||
axp.plot(T_m, 101325, '*')
|
||||
axp.plot(T, pp, '--')
|
||||
|
||||
print("%s %s %s %s" % (fluid, CP.Props(fluid,"molemass"), CP.Props(fluid, 'accentric'), pp[-1]/p[-1]-1))
|
||||
print("%s %s %s %s" % (fluid, CP.Props(fluid, "molemass"), CP.Props(fluid, 'accentric'), pp[-1] / p[-1] - 1))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
simon()
|
||||
Tr()
|
||||
theta()
|
||||
|
||||
@@ -15,7 +15,7 @@ with open('mixture_binary_pairs.json','r') as fp:
|
||||
|
||||
CAS_pairs = []
|
||||
for pair in jj:
|
||||
CAS_pairs.append( (pair['CAS1'],pair['CAS2']) )
|
||||
CAS_pairs.append((pair['CAS1'],pair['CAS2']))
|
||||
|
||||
for line in lines:
|
||||
Name1,Name2,betaT,gammaT,MARE,N = line.strip().split(' ')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import print_function
|
||||
import os, json, glob, textwrap
|
||||
|
||||
json_options = {'indent' : 2, 'sort_keys' : True}
|
||||
json_options = {'indent': 2, 'sort_keys': True}
|
||||
|
||||
# Data from Mulero, JPCRD, 2012
|
||||
# CAS codes added from CoolProp 4.2, and wikipedia where necessary
|
||||
@@ -90,88 +90,88 @@ Mulero2012_data = """67-64-1 Acetone 0.0633 1.160
|
||||
|
||||
def inject_surface_tension_2012(root_dir):
|
||||
print("*** Injecting surface tension curves from Mulero")
|
||||
Tc_dict = {'Argon':150.687,
|
||||
'Benzene':562.02,
|
||||
'1-Butene':419.29, #Butene from Mulero
|
||||
'CarbonMonoxide':132.86,
|
||||
'Cyclohexane':553.64,
|
||||
'D2O':643.847,
|
||||
'n-Decane':617.7,
|
||||
'Ethane':305.322,
|
||||
'Fluorine':144.414,
|
||||
'Helium':5.1953,
|
||||
'Isobutane':407.81,
|
||||
'Isobutene':418.09,
|
||||
'Isopentane':460.35,
|
||||
'Methanol':513.38,
|
||||
'Nitrogen':126.192,
|
||||
'n-Nonane':594.55,
|
||||
'Oxygen':154.581,
|
||||
'Parahydrogen':32.938,
|
||||
'Perfluorobutane':386.326,
|
||||
'n-Propane':369.89,
|
||||
'Propyne':402.38,
|
||||
'R11':471.11,
|
||||
'R113':487.21,
|
||||
'R114':418.83,
|
||||
'R115':353.1,
|
||||
'R123':456.831,
|
||||
'R1234yf':367.85,
|
||||
'R124':395.425,
|
||||
'R125':339.173,
|
||||
'R134a':374.21,
|
||||
'R14':227.51,
|
||||
'R142b':410.26,
|
||||
'R143a':345.857,
|
||||
'R152a':386.411,
|
||||
'R21':451.48,
|
||||
'R218':345.02,
|
||||
'R227ea':374.9,
|
||||
'R32':351.255,
|
||||
'R365mfc':460,
|
||||
'RC318':388.38,
|
||||
'SulfurDioxide':430.64,
|
||||
'Toluene':591.75,
|
||||
'Trifluoroiodomethane':396.44,
|
||||
'Water':647.096,
|
||||
'Acetone':508.1,
|
||||
'n-Butane':425.125,
|
||||
'CarbonDioxide':304.128,
|
||||
'DimethylEther':400.378,
|
||||
'n-Dodecane':658.1, #Decane in Mulero
|
||||
'Ethylene':282.35,
|
||||
'n-Heptane':540.13,
|
||||
'n-Hexane':507.82,
|
||||
'HydrogenSulfide':373.1,
|
||||
'Isohexane':497.7,
|
||||
'Krypton':209.48,
|
||||
'NitrousOxide':309.52,
|
||||
'n-Pentane':469.7,
|
||||
'R116':293.03,
|
||||
'R13':302,
|
||||
'R23':299.293,
|
||||
'R245ca':447.57,
|
||||
'Xenon':289.733,
|
||||
'CarbonylSulfide':378.77,
|
||||
'Hydrogen':33.145,
|
||||
'Methane':190.564,
|
||||
'n-Octane':569.32,
|
||||
'Perfluoropentane':420.555,
|
||||
'Propylene':364.211,
|
||||
'R12':385.12,
|
||||
'R141b':477.5,
|
||||
'R161':375.3,
|
||||
'R22':369.295,
|
||||
'R236ea':412.44,
|
||||
'R236fa':398.07,
|
||||
'R245fa':427.16,
|
||||
'R41':317.28,
|
||||
'SulfurHexafluoride':318.723,
|
||||
'Ammonia':405.4,
|
||||
'Deuterium':38.34,
|
||||
'Ethanol':513.9,
|
||||
'Neon':44.4918,
|
||||
'Decafluorobutane':113.3+273.15 # According to http://encyclopedia.airliquide.com/Encyclopedia.asp?GasID=19#GeneralData, not in Mulero
|
||||
Tc_dict = {'Argon': 150.687,
|
||||
'Benzene': 562.02,
|
||||
'1-Butene': 419.29, # Butene from Mulero
|
||||
'CarbonMonoxide': 132.86,
|
||||
'Cyclohexane': 553.64,
|
||||
'D2O': 643.847,
|
||||
'n-Decane': 617.7,
|
||||
'Ethane': 305.322,
|
||||
'Fluorine': 144.414,
|
||||
'Helium': 5.1953,
|
||||
'Isobutane': 407.81,
|
||||
'Isobutene': 418.09,
|
||||
'Isopentane': 460.35,
|
||||
'Methanol': 513.38,
|
||||
'Nitrogen': 126.192,
|
||||
'n-Nonane': 594.55,
|
||||
'Oxygen': 154.581,
|
||||
'Parahydrogen': 32.938,
|
||||
'Perfluorobutane': 386.326,
|
||||
'n-Propane': 369.89,
|
||||
'Propyne': 402.38,
|
||||
'R11': 471.11,
|
||||
'R113': 487.21,
|
||||
'R114': 418.83,
|
||||
'R115': 353.1,
|
||||
'R123': 456.831,
|
||||
'R1234yf': 367.85,
|
||||
'R124': 395.425,
|
||||
'R125': 339.173,
|
||||
'R134a': 374.21,
|
||||
'R14': 227.51,
|
||||
'R142b': 410.26,
|
||||
'R143a': 345.857,
|
||||
'R152a': 386.411,
|
||||
'R21': 451.48,
|
||||
'R218': 345.02,
|
||||
'R227ea': 374.9,
|
||||
'R32': 351.255,
|
||||
'R365mfc': 460,
|
||||
'RC318': 388.38,
|
||||
'SulfurDioxide': 430.64,
|
||||
'Toluene': 591.75,
|
||||
'Trifluoroiodomethane': 396.44,
|
||||
'Water': 647.096,
|
||||
'Acetone': 508.1,
|
||||
'n-Butane': 425.125,
|
||||
'CarbonDioxide': 304.128,
|
||||
'DimethylEther': 400.378,
|
||||
'n-Dodecane': 658.1, # Decane in Mulero
|
||||
'Ethylene': 282.35,
|
||||
'n-Heptane': 540.13,
|
||||
'n-Hexane': 507.82,
|
||||
'HydrogenSulfide': 373.1,
|
||||
'Isohexane': 497.7,
|
||||
'Krypton': 209.48,
|
||||
'NitrousOxide': 309.52,
|
||||
'n-Pentane': 469.7,
|
||||
'R116': 293.03,
|
||||
'R13': 302,
|
||||
'R23': 299.293,
|
||||
'R245ca': 447.57,
|
||||
'Xenon': 289.733,
|
||||
'CarbonylSulfide': 378.77,
|
||||
'Hydrogen': 33.145,
|
||||
'Methane': 190.564,
|
||||
'n-Octane': 569.32,
|
||||
'Perfluoropentane': 420.555,
|
||||
'Propylene': 364.211,
|
||||
'R12': 385.12,
|
||||
'R141b': 477.5,
|
||||
'R161': 375.3,
|
||||
'R22': 369.295,
|
||||
'R236ea': 412.44,
|
||||
'R236fa': 398.07,
|
||||
'R245fa': 427.16,
|
||||
'R41': 317.28,
|
||||
'SulfurHexafluoride': 318.723,
|
||||
'Ammonia': 405.4,
|
||||
'Deuterium': 38.34,
|
||||
'Ethanol': 513.9,
|
||||
'Neon': 44.4918,
|
||||
'Decafluorobutane': 113.3 + 273.15 # According to http://encyclopedia.airliquide.com/Encyclopedia.asp?GasID=19#GeneralData, not in Mulero
|
||||
}
|
||||
|
||||
import glob, json, os
|
||||
@@ -184,24 +184,24 @@ def inject_surface_tension_2012(root_dir):
|
||||
n = row[1:len(row):2]
|
||||
n = [float(_) for _ in n]
|
||||
if name not in Tc_dict:
|
||||
raise ValueError( 'could not find Tc for ' + name)
|
||||
raise ValueError('could not find Tc for ' + name)
|
||||
continue
|
||||
Tc = Tc_dict[name]
|
||||
|
||||
# The dictionary of values for the surface tension
|
||||
j_st = dict(Tc = Tc,
|
||||
a = a,
|
||||
n = n,
|
||||
BibTeX = 'Mulero-JPCRD-2012',
|
||||
description = 'sigma = sum(a_i*(1-T/Tc)^n_i)'
|
||||
j_st = dict(Tc=Tc,
|
||||
a=a,
|
||||
n=n,
|
||||
BibTeX='Mulero-JPCRD-2012',
|
||||
description='sigma = sum(a_i*(1-T/Tc)^n_i)'
|
||||
)
|
||||
|
||||
fname = os.path.join(root_dir,'dev','fluids',name+'.json')
|
||||
fname = os.path.join(root_dir, 'dev', 'fluids', name + '.json')
|
||||
if not os.path.exists(fname):
|
||||
print(fname+' does not exist')
|
||||
print(fname + ' does not exist')
|
||||
continue
|
||||
|
||||
j = json.load(open(fname,'r'))
|
||||
j = json.load(open(fname, 'r'))
|
||||
|
||||
j['ANCILLARIES']['surface_tension'] = j_st
|
||||
|
||||
@@ -253,29 +253,29 @@ def inject_surface_tension_2014(root_dir):
|
||||
rename = {'Undecane': 'n-Undecane',
|
||||
'm-xylene (1,3-dimethylbenzene)': 'm-Xylene',
|
||||
'o-xylene (1,2-dimethylbenzene)': 'o-Xylene',
|
||||
'R1234ze(E) (trans-1,3,3,3-tetrafluoropropene)':'R1234ze(E)',
|
||||
'R143a (1,1,1-Trifluoroethane)':'R143a',
|
||||
'Methyl linoleate (Methyl (Z,Z)- 9,12-octadecadienoate)':'MethylLinoleate',
|
||||
'Methyl oleate (Methyl cis-9-octadecenoate)':'MethylOleate',
|
||||
'Methyl palmitate (Methyl hexadecanoate)':'MethylPalmitate',
|
||||
'Methyl stearate (Methyl octadecanoate)':'MethylStearate',
|
||||
'Dimethyl carbonate (Dimethyl ester carbonic acid)':'DimethylCarbonate',
|
||||
'R1234ze(E) (trans-1,3,3,3-tetrafluoropropene)': 'R1234ze(E)',
|
||||
'R143a (1,1,1-Trifluoroethane)': 'R143a',
|
||||
'Methyl linoleate (Methyl (Z,Z)- 9,12-octadecadienoate)': 'MethylLinoleate',
|
||||
'Methyl oleate (Methyl cis-9-octadecenoate)': 'MethylOleate',
|
||||
'Methyl palmitate (Methyl hexadecanoate)': 'MethylPalmitate',
|
||||
'Methyl stearate (Methyl octadecanoate)': 'MethylStearate',
|
||||
'Dimethyl carbonate (Dimethyl ester carbonic acid)': 'DimethylCarbonate',
|
||||
'Hexamethyldisiloxane': 'MM',
|
||||
'Tetradecamethylhexasiloxane':'MD4M',
|
||||
'Dodecamethylpentasiloxane':'MD3M',
|
||||
'Octamethyltrisiloxane':'MDM',
|
||||
'Decamethyltetrasiloxane':'MD2M',
|
||||
'Octamethylcyclotetrasiloxane':'D4',
|
||||
'Dodecamethylcyclohexasiloxane':'D6',
|
||||
'Decamethylcyclopentasiloxane':'D5',
|
||||
'Diethyl ether':'DiethylEther',
|
||||
'Neopentane (2,2- dimethylpropane)':'Neopentane'
|
||||
'Tetradecamethylhexasiloxane': 'MD4M',
|
||||
'Dodecamethylpentasiloxane': 'MD3M',
|
||||
'Octamethyltrisiloxane': 'MDM',
|
||||
'Decamethyltetrasiloxane': 'MD2M',
|
||||
'Octamethylcyclotetrasiloxane': 'D4',
|
||||
'Dodecamethylcyclohexasiloxane': 'D6',
|
||||
'Decamethylcyclopentasiloxane': 'D5',
|
||||
'Diethyl ether': 'DiethylEther',
|
||||
'Neopentane (2,2- dimethylpropane)': 'Neopentane'
|
||||
}
|
||||
import glob, json, os
|
||||
for line in Mulero2014_data.split('\n'):
|
||||
|
||||
row = line.split(' ')
|
||||
#print(row)
|
||||
# print(row)
|
||||
values = []
|
||||
j = 0
|
||||
for i in range(len(row)):
|
||||
@@ -284,28 +284,28 @@ def inject_surface_tension_2014(root_dir):
|
||||
except:
|
||||
j = i
|
||||
|
||||
name = ' '.join(row[0:j+1])
|
||||
name = ' '.join(row[0:j + 1])
|
||||
|
||||
Tc = values.pop(0)
|
||||
a = values[0:len(row):2]
|
||||
n = values[1:len(row):2]
|
||||
|
||||
# The dictionary of values for the surface tension
|
||||
j_st = dict(Tc = Tc,
|
||||
a = a,
|
||||
n = n,
|
||||
BibTeX = 'Mulero-JPCRD-2014',
|
||||
description = 'sigma = sum(a_i*(1-T/Tc)^n_i)'
|
||||
j_st = dict(Tc=Tc,
|
||||
a=a,
|
||||
n=n,
|
||||
BibTeX='Mulero-JPCRD-2014',
|
||||
description='sigma = sum(a_i*(1-T/Tc)^n_i)'
|
||||
)
|
||||
|
||||
if name in rename:
|
||||
name = rename[name]
|
||||
fname = os.path.join(root_dir,'dev','fluids',name+'.json')
|
||||
fname = os.path.join(root_dir, 'dev', 'fluids', name + '.json')
|
||||
if not os.path.exists(fname):
|
||||
print(fname + ' does not exist')
|
||||
continue
|
||||
|
||||
j = json.load(open(fname,'r'))
|
||||
j = json.load(open(fname, 'r'))
|
||||
|
||||
j['ANCILLARIES']['surface_tension'] = j_st
|
||||
|
||||
@@ -316,36 +316,36 @@ def inject_surface_tension_2014(root_dir):
|
||||
|
||||
def inject_environmental_data(root_dir):
|
||||
print('*** Injecting environmental data from DTU')
|
||||
j = json.load(open(os.path.join(root_dir,'dev','environmental_data_from_DTU','DTU_environmental.json'),'r'))
|
||||
j = json.load(open(os.path.join(root_dir, 'dev', 'environmental_data_from_DTU', 'DTU_environmental.json'), 'r'))
|
||||
|
||||
for CAS in j:
|
||||
data = j[CAS]
|
||||
fname = os.path.join(root_dir,'dev','fluids',data['Name']+'.json')
|
||||
fname = os.path.join(root_dir, 'dev', 'fluids', data['Name'] + '.json')
|
||||
if os.path.isfile(fname):
|
||||
fluid = json.load(open(fname,'r'))
|
||||
fluid = json.load(open(fname, 'r'))
|
||||
fluid['ENVIRONMENTAL'] = data
|
||||
fp = open(fname, 'w')
|
||||
fp.write(json.dumps(fluid, **json_options))
|
||||
else:
|
||||
print('Could not inject environmental data for',data['Name'])
|
||||
print('Could not inject environmental data for', data['Name'])
|
||||
|
||||
|
||||
def inject_ancillaries(root_dir):
|
||||
print('*** Injecting saturation ancillary curves')
|
||||
master = []
|
||||
|
||||
for file in glob.glob(os.path.join(root_dir,'dev','fluids','*.json')):
|
||||
for file in glob.glob(os.path.join(root_dir, 'dev', 'fluids', '*.json')):
|
||||
path, file_name = os.path.split(file)
|
||||
fluid_name = file_name.split('.')[0]
|
||||
# Load the fluid file
|
||||
fluid = json.load(open(os.path.join(root_dir,'dev','fluids', fluid_name+'.json'), 'r'))
|
||||
fluid = json.load(open(os.path.join(root_dir, 'dev', 'fluids', fluid_name + '.json'), 'r'))
|
||||
|
||||
# Load the ancillary
|
||||
anc = json.load(open(os.path.join(root_dir,'dev','ancillaries',fluid_name+'_anc.json'),'r'))
|
||||
anc = json.load(open(os.path.join(root_dir, 'dev', 'ancillaries', fluid_name + '_anc.json'), 'r'))
|
||||
# Apply the ancillary by merging dictionaries
|
||||
fluid.update(anc)
|
||||
# Write fluid back to file
|
||||
fp = open(os.path.join(root_dir,'dev','fluids', fluid_name+'.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'fluids', fluid_name + '.json'), 'w')
|
||||
fp.write(json.dumps(fluid, **json_options))
|
||||
|
||||
|
||||
@@ -361,7 +361,7 @@ def combine_json(root_dir):
|
||||
master = []
|
||||
|
||||
print('*** Combining fluid JSON files in JSON format in dev folder...')
|
||||
for file in glob.glob(os.path.join(root_dir,'dev','fluids','*.json')):
|
||||
for file in glob.glob(os.path.join(root_dir, 'dev', 'fluids', '*.json')):
|
||||
|
||||
path, file_name = os.path.split(file)
|
||||
fluid_name = file_name.split('.')[0]
|
||||
@@ -371,18 +371,18 @@ def combine_json(root_dir):
|
||||
|
||||
master += [fluid]
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_fluids_verbose.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_fluids_verbose.json'), 'w')
|
||||
fp.write(json.dumps(master, **json_options))
|
||||
fp.close()
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_fluids.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_fluids.json'), 'w')
|
||||
fp.write(json.dumps(master))
|
||||
fp.close()
|
||||
|
||||
master = []
|
||||
|
||||
print('*** Combining incompressible JSON files in JSON format in dev folder...')
|
||||
for file in glob.glob(os.path.join(root_dir,'dev','IncompressibleLiquids','*.json')):
|
||||
for file in glob.glob(os.path.join(root_dir, 'dev', 'IncompressibleLiquids', '*.json')):
|
||||
|
||||
path, file_name = os.path.split(file)
|
||||
fluid_name = file_name.split('.')[0]
|
||||
@@ -392,15 +392,15 @@ def combine_json(root_dir):
|
||||
|
||||
master += [fluid]
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_incompressibles_verbose.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_incompressibles_verbose.json'), 'w')
|
||||
fp.write(json.dumps(master, **json_options))
|
||||
fp.close()
|
||||
|
||||
fp = open(os.path.join(root_dir,'dev','all_incompressibles.json'),'w')
|
||||
fp = open(os.path.join(root_dir, 'dev', 'all_incompressibles.json'), 'w')
|
||||
fp.write(json.dumps(master))
|
||||
fp.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
inject_surface_tension_2014(root_dir = '..')
|
||||
combine_json(root_dir = '..')
|
||||
if __name__ == '__main__':
|
||||
inject_surface_tension_2014(root_dir='..')
|
||||
combine_json(root_dir='..')
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
|
||||
from distutils.core import setup, Extension
|
||||
import subprocess,shutil,os,sys
|
||||
import subprocess, shutil, os, sys
|
||||
|
||||
sys.argv += ['build_ext','--inplace','--reswig']
|
||||
sys.argv += ['build_ext', '--inplace', '--reswig']
|
||||
|
||||
if '--reswig' in sys.argv:
|
||||
import subprocess
|
||||
subprocess.check_output(['swig','-python','-outcurrentdir','-c++','-I../../../CoolProp','Helmholtz.i'])
|
||||
subprocess.check_output(['swig', '-python', '-outcurrentdir', '-c++', '-I../../../CoolProp', 'Helmholtz.i'])
|
||||
sys.argv.remove('--reswig')
|
||||
|
||||
commons = dict()
|
||||
@@ -16,10 +16,10 @@ helm_module = Extension('_helmholtz',
|
||||
**commons
|
||||
)
|
||||
|
||||
setup (name = 'EOSTerms',
|
||||
version = '0.0.0',
|
||||
author = "Ian Bell",
|
||||
author_email = 'ian.h.bell@gmail.com',
|
||||
description = """ helmholtz energy terms for EOS fitting """,
|
||||
ext_modules = [helm_module],
|
||||
setup(name='EOSTerms',
|
||||
version='0.0.0',
|
||||
author="Ian Bell",
|
||||
author_email='ian.h.bell@gmail.com',
|
||||
description=""" helmholtz energy terms for EOS fitting """,
|
||||
ext_modules=[helm_module],
|
||||
)
|
||||
|
||||
@@ -19,32 +19,32 @@ class TermLibrary():
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
L,D,T = [],[],[]
|
||||
L, D, T = [], [], []
|
||||
|
||||
for i in range(1,6):
|
||||
for j in range(-4,9):
|
||||
T.append(float(j)/8.0)
|
||||
for i in range(1, 6):
|
||||
for j in range(-4, 9):
|
||||
T.append(float(j) / 8.0)
|
||||
D.append(float(i))
|
||||
L.append(float(0))
|
||||
for i in range(1,16):
|
||||
for j in range(1,16):
|
||||
for i in range(1, 16):
|
||||
for j in range(1, 16):
|
||||
T.append(float(j))
|
||||
D.append(float(i))
|
||||
L.append(float(1))
|
||||
for i in range(1,13):
|
||||
for j in range(1,11):
|
||||
for i in range(1, 13):
|
||||
for j in range(1, 11):
|
||||
T.append(float(j))
|
||||
D.append(float(i))
|
||||
L.append(float(2))
|
||||
for i in range(1,6):
|
||||
for j in range(10,24):
|
||||
for i in range(1, 6):
|
||||
for j in range(10, 24):
|
||||
T.append(float(j))
|
||||
D.append(float(i))
|
||||
L.append(float(3))
|
||||
for i in range(1,10):
|
||||
for j in range(10,21):
|
||||
for i in range(1, 10):
|
||||
for j in range(10, 21):
|
||||
T.append(float(j))
|
||||
D.append(float(i)*2)
|
||||
D.append(float(i) * 2)
|
||||
L.append(float(4))
|
||||
|
||||
self.T = T
|
||||
@@ -79,7 +79,7 @@ def get_fluid_constants(Ref):
|
||||
global indices
|
||||
indices = set()
|
||||
while len(indices) < 23:
|
||||
indices.add(random.randint(0, len(LIBRARY.T)-1))
|
||||
indices.add(random.randint(0, len(LIBRARY.T) - 1))
|
||||
print("%s %s" % (indices, len(LIBRARY.T)))
|
||||
|
||||
T0 = np.array([LIBRARY.T[i] for i in indices])
|
||||
@@ -95,13 +95,13 @@ def get_fluid_constants(Ref):
|
||||
|
||||
# values from R410A
|
||||
N0 = np.array([0.0, 0.987252, -1.03017, 1.17666, -0.138991, 0.00302373, -2.53639, -1.96680, -0.830480, 0.172477, -0.261116, -0.0745473, 0.679757, -0.652431, 0.0553849, -0.0710970, -0.000875332, 0.0200760, -0.0139761, -0.0185110, 0.0171939, -0.00482049])
|
||||
T0 = np.array([0.0,0.44,1.2,2.97,2.95,0.2,1.93,1.78,3.0,0.2,0.74,3.0,2.1,4.3,0.25,7.0,4.7,13.0,16.0,25.0,17.0,7.4])
|
||||
D0 = np.array([0,1.0,1,1,2,5,1,2,3,5,5,5,1,1,4,4,9,2,2,4,5,6])
|
||||
L0 = np.array([0,0.0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3])
|
||||
T0 = np.array([0.0, 0.44, 1.2, 2.97, 2.95, 0.2, 1.93, 1.78, 3.0, 0.2, 0.74, 3.0, 2.1, 4.3, 0.25, 7.0, 4.7, 13.0, 16.0, 25.0, 17.0, 7.4])
|
||||
D0 = np.array([0, 1.0, 1, 1, 2, 5, 1, 2, 3, 5, 5, 5, 1, 1, 4, 4, 9, 2, 2, 4, 5, 6])
|
||||
L0 = np.array([0, 0.0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3])
|
||||
|
||||
indices = set()
|
||||
while len(indices) < 5:
|
||||
indices.add(random.randint(0, len(LIBRARY.T)-1))
|
||||
indices.add(random.randint(0, len(LIBRARY.T) - 1))
|
||||
print("%s %s" % (indices, len(LIBRARY.T)))
|
||||
|
||||
T0 = np.append(T0, [LIBRARY.T[i] for i in indices])
|
||||
@@ -122,27 +122,27 @@ class IdealPartFitter(object):
|
||||
def __init__(self, Ref):
|
||||
self.Ref = Ref
|
||||
self.RefString, N0, T0, D0, L0 = get_fluid_constants(Ref)
|
||||
self.molemass = Props(self.RefString,'molemass')
|
||||
self.molemass = Props(self.RefString, 'molemass')
|
||||
self.Tc = Props(self.RefString, 'Tcrit')
|
||||
self.rhoc = Props(self.RefString, 'rhocrit')
|
||||
self.pc = Props(self.RefString, 'pcrit')
|
||||
self.T = np.linspace(100, 450, 200)
|
||||
self.tau = self.Tc/self.T
|
||||
self.tau = self.Tc / self.T
|
||||
self.C = Props('C', 'T', self.T, 'D', 1e-15, self.RefString)
|
||||
R = 8.314472/self.molemass
|
||||
self.cp0_R = self.C/R
|
||||
R = 8.314472 / self.molemass
|
||||
self.cp0_R = self.C / R
|
||||
|
||||
def cp0_R_from_fit(self, a_e):
|
||||
a = a_e[0:len(a_e)//2]
|
||||
e = a_e[len(a_e)//2::]
|
||||
u1 = e[1]/self.T
|
||||
u2 = e[2]/self.T
|
||||
u3 = e[3]/self.T
|
||||
return a[0]*self.T**e[0]+a[1]*u1**2*np.exp(u1)/(np.exp(u1)-1)**2+a[2]*u2**2*np.exp(u2)/(np.exp(u2)-1)**2+a[3]*u3**2*np.exp(u3)/(np.exp(u3)-1)**2
|
||||
a = a_e[0:len(a_e) // 2]
|
||||
e = a_e[len(a_e) // 2::]
|
||||
u1 = e[1] / self.T
|
||||
u2 = e[2] / self.T
|
||||
u3 = e[3] / self.T
|
||||
return a[0] * self.T**e[0] + a[1] * u1**2 * np.exp(u1) / (np.exp(u1) - 1)**2 + a[2] * u2**2 * np.exp(u2) / (np.exp(u2) - 1)**2 + a[3] * u3**2 * np.exp(u3) / (np.exp(u3) - 1)**2
|
||||
|
||||
def OBJECTIVE_cp0_R(self, a_e):
|
||||
cp0_R_fit = self.cp0_R_from_fit(a_e)
|
||||
RMS = np.sqrt(np.mean(np.power((self.cp0_R-cp0_R_fit)/self.cp0_R, 2)))
|
||||
RMS = np.sqrt(np.mean(np.power((self.cp0_R - cp0_R_fit) / self.cp0_R, 2)))
|
||||
return RMS
|
||||
|
||||
def fit(self):
|
||||
@@ -150,12 +150,12 @@ class IdealPartFitter(object):
|
||||
|
||||
a_e = scipy.optimize.minimize(self.OBJECTIVE_cp0_R, a_e).x
|
||||
|
||||
self.a = a_e[0:len(a_e)//2]
|
||||
self.e = a_e[len(a_e)//2::]
|
||||
self.a = a_e[0:len(a_e) // 2]
|
||||
self.e = a_e[len(a_e) // 2::]
|
||||
|
||||
cp0_over_R_check = 1-self.tau**2*self.d2phi0_dTau2(self.tau)
|
||||
cp0_over_R_check = 1 - self.tau**2 * self.d2phi0_dTau2(self.tau)
|
||||
|
||||
plt.plot(self.T, (self.cp0_R_from_fit(a_e)/self.cp0_R-1)*100, '-', self.T, (cp0_over_R_check/self.cp0_R-1)*100, '^')
|
||||
plt.plot(self.T, (self.cp0_R_from_fit(a_e) / self.cp0_R - 1) * 100, '-', self.T, (cp0_over_R_check / self.cp0_R - 1) * 100, '^')
|
||||
plt.xlabel('Temperature [K]')
|
||||
plt.ylabel('($c_{p0}/R$ (fit) / $c_{p0}/R$ (REFPROP) -1)*100 [%]')
|
||||
plt.savefig('cp0.pdf')
|
||||
@@ -164,10 +164,10 @@ class IdealPartFitter(object):
|
||||
def d2phi0_dTau2(self, tau):
|
||||
d = []
|
||||
for _tau in tau:
|
||||
#lead term is killed
|
||||
# lead term is killed
|
||||
d.append(helmholtz.phi0_logtau(-1.0).dTau2(_tau, _tau)
|
||||
+ helmholtz.phi0_cp0_poly(self.a[0],self.e[0],self.Tc,298.15).dTau2(_tau, _tau)
|
||||
+ helmholtz.phi0_Planck_Einstein(self.a,self.e/self.Tc,1,len(self.a)-1).dTau2(_tau, _tau)
|
||||
+ helmholtz.phi0_cp0_poly(self.a[0], self.e[0], self.Tc, 298.15).dTau2(_tau, _tau)
|
||||
+ helmholtz.phi0_Planck_Einstein(self.a, self.e / self.Tc, 1, len(self.a) - 1).dTau2(_tau, _tau)
|
||||
)
|
||||
return np.array(d)
|
||||
|
||||
@@ -178,10 +178,10 @@ class ResidualPartFitter(object):
|
||||
self.Ref = Ref
|
||||
self.IPF = IPF
|
||||
self.RefString, self.N0, self.T0, self.D0, self.L0 = get_fluid_constants(Ref)
|
||||
self.Tc = Props(self.RefString,'Tcrit')
|
||||
self.rhoc = Props(self.RefString,'rhocrit')
|
||||
molemass = Props(self.RefString,'molemass')
|
||||
self.R = 8.314472/ molemass
|
||||
self.Tc = Props(self.RefString, 'Tcrit')
|
||||
self.rhoc = Props(self.RefString, 'rhocrit')
|
||||
molemass = Props(self.RefString, 'molemass')
|
||||
self.R = 8.314472 / molemass
|
||||
|
||||
def termwise_Rsquared(self):
|
||||
|
||||
@@ -199,13 +199,13 @@ class ResidualPartFitter(object):
|
||||
|
||||
PPF = self.evaluate_EOS(np.array(list(n)))
|
||||
|
||||
R2 = rsquared(PPF.p,self.phir.dDeltaV(self.tauV,self.deltaV))
|
||||
R2 = rsquared(PPF.p, self.phir.dDeltaV(self.tauV, self.deltaV))
|
||||
|
||||
values.append((R2,i))
|
||||
values.append((R2, i))
|
||||
if R2 > 0.9:
|
||||
keepers.append(i)
|
||||
|
||||
values,indices = zip(*reversed(sorted(values)))
|
||||
values, indices = zip(*reversed(sorted(values)))
|
||||
|
||||
keepers = list(indices[0:30])
|
||||
|
||||
@@ -253,7 +253,7 @@ class ResidualPartFitter(object):
|
||||
print(VE)
|
||||
pass
|
||||
|
||||
for _rho in np.linspace(rhoc, 3.36*rhoc, 50):
|
||||
for _rho in np.linspace(rhoc, 3.36 * rhoc, 50):
|
||||
try:
|
||||
if _T > Tc:
|
||||
p = Props('P', 'T', _T, 'D', _rho, self.RefString)
|
||||
@@ -282,18 +282,18 @@ class ResidualPartFitter(object):
|
||||
print(VE)
|
||||
pass
|
||||
|
||||
h = h5py.File('T_rho_p.h5','w')
|
||||
h = h5py.File('T_rho_p.h5', 'w')
|
||||
grp = h.create_group(self.Ref)
|
||||
grp.create_dataset("T",data = np.array(TTT),compression = "gzip")
|
||||
grp.create_dataset("rho", data = np.array(RHO),compression = "gzip")
|
||||
grp.create_dataset("p", data = np.array(PPP),compression = "gzip")
|
||||
grp.create_dataset("cp", data = np.array(CPP),compression = "gzip")
|
||||
grp.create_dataset("cv", data = np.array(CVV),compression = "gzip")
|
||||
grp.create_dataset("speed_sound", data = np.array(AAA),compression = "gzip")
|
||||
grp.create_dataset("T", data=np.array(TTT), compression="gzip")
|
||||
grp.create_dataset("rho", data=np.array(RHO), compression="gzip")
|
||||
grp.create_dataset("p", data=np.array(PPP), compression="gzip")
|
||||
grp.create_dataset("cp", data=np.array(CPP), compression="gzip")
|
||||
grp.create_dataset("cv", data=np.array(CVV), compression="gzip")
|
||||
grp.create_dataset("speed_sound", data=np.array(AAA), compression="gzip")
|
||||
h.close()
|
||||
|
||||
def load_data(self):
|
||||
h = h5py.File('T_rho_p.h5','r')
|
||||
h = h5py.File('T_rho_p.h5', 'r')
|
||||
self.T = h.get(self.Ref + '/T').value
|
||||
self.rho = h.get(self.Ref + '/rho').value
|
||||
self.p = h.get(self.Ref + '/p').value
|
||||
@@ -301,8 +301,8 @@ class ResidualPartFitter(object):
|
||||
self.cv = h.get(self.Ref + '/cv').value
|
||||
self.speed_sound = h.get(self.Ref + '/speed_sound').value
|
||||
|
||||
self.tau = self.Tc/self.T
|
||||
self.delta = self.rho/self.rhoc
|
||||
self.tau = self.Tc / self.T
|
||||
self.delta = self.rho / self.rhoc
|
||||
self.tauV = helmholtz.vectord(self.tau)
|
||||
self.deltaV = helmholtz.vectord(self.delta)
|
||||
|
||||
@@ -319,22 +319,22 @@ class ResidualPartFitter(object):
|
||||
dDelta_dTau = self.phir.dDelta_dTauV(self.tauV, self.deltaV)
|
||||
|
||||
# Evaluate the pressure
|
||||
p = (self.rho*self.R*self.T)*(1 + self.delta*dDelta)
|
||||
p = (self.rho * self.R * self.T) * (1 + self.delta * dDelta)
|
||||
# Evaluate the specific heat at constant volume
|
||||
cv_over_R = -self.tau**2*(self.d2phi0_dTau2 + dTau2)
|
||||
cv = cv_over_R*self.R
|
||||
cv_over_R = -self.tau**2 * (self.d2phi0_dTau2 + dTau2)
|
||||
cv = cv_over_R * self.R
|
||||
# Evaluate the specific heat at constant pressure
|
||||
cp_over_R = cv_over_R+(1.0+self.delta*dDelta-self.delta*self.tau*dDelta_dTau)**2/(1+2*self.delta*dDelta+self.delta**2*dDelta2)
|
||||
cp = cp_over_R*self.R
|
||||
cp_over_R = cv_over_R + (1.0 + self.delta * dDelta - self.delta * self.tau * dDelta_dTau)**2 / (1 + 2 * self.delta * dDelta + self.delta**2 * dDelta2)
|
||||
cp = cp_over_R * self.R
|
||||
# Evaluate the speed of sound
|
||||
w = np.sqrt(1000*self.R*self.T*cp_over_R/cv_over_R*(1+2*self.delta*dDelta+self.delta**2*dDelta2))
|
||||
w = np.sqrt(1000 * self.R * self.T * cp_over_R / cv_over_R * (1 + 2 * self.delta * dDelta + self.delta**2 * dDelta2))
|
||||
|
||||
class stub: pass
|
||||
PPF = stub()
|
||||
PPF.p = np.array(p, ndmin = 1).T
|
||||
PPF.cp = np.array(cp, ndmin = 1).T
|
||||
PPF.cv = np.array(cv, ndmin = 1).T
|
||||
PPF.w = np.array(w, ndmin = 1).T
|
||||
PPF.p = np.array(p, ndmin=1).T
|
||||
PPF.cp = np.array(cp, ndmin=1).T
|
||||
PPF.cv = np.array(cv, ndmin=1).T
|
||||
PPF.w = np.array(w, ndmin=1).T
|
||||
|
||||
return PPF
|
||||
|
||||
@@ -349,16 +349,16 @@ class ResidualPartFitter(object):
|
||||
w_cv = 1.0
|
||||
w_w = 1.0
|
||||
w_cp = 1.0
|
||||
w_total = (w_p+w_cv+w_w+w_cp)/4
|
||||
w_total = (w_p + w_cv + w_w + w_cp) / 4
|
||||
|
||||
w_p_norm = w_p/w_total
|
||||
w_cv_norm = w_cv/w_total
|
||||
w_cp_norm = w_cp/w_total
|
||||
w_w_norm = w_w/w_total
|
||||
residuals = np.r_[(PPF.p/self.p-1),(PPF.cv/self.cv-1),(PPF.cp/self.cp-1)]#,(PPF.w**2/self.speed_sound**2-1)]
|
||||
w_p_norm = w_p / w_total
|
||||
w_cv_norm = w_cv / w_total
|
||||
w_cp_norm = w_cp / w_total
|
||||
w_w_norm = w_w / w_total
|
||||
residuals = np.r_[(PPF.p / self.p - 1), (PPF.cv / self.cv - 1), (PPF.cp / self.cp - 1)] # ,(PPF.w**2/self.speed_sound**2-1)]
|
||||
RMS = np.sqrt(np.mean(np.power(residuals, 2)))
|
||||
|
||||
print('RMS: %s %% Max %s %%' % (RMS*100, np.max(np.abs(residuals))*100))
|
||||
print('RMS: %s %% Max %s %%' % (RMS * 100, np.max(np.abs(residuals)) * 100))
|
||||
self.RMS = RMS
|
||||
self.MaxError = np.max(np.abs(residuals))
|
||||
return RMS
|
||||
@@ -366,53 +366,53 @@ class ResidualPartFitter(object):
|
||||
def fit(self):
|
||||
|
||||
# Kill off some not as good terms
|
||||
#self.termwise_Rsquared()
|
||||
# self.termwise_Rsquared()
|
||||
|
||||
# Load up the residual Helmholtz term with parameters
|
||||
n = helmholtz.vectord(self.N0)
|
||||
d = helmholtz.vectord(self.D0)
|
||||
t = helmholtz.vectord(self.T0)
|
||||
l = helmholtz.vectord(self.L0)
|
||||
self.phir = helmholtz.phir_power(n, d, t, l, 1, len(self.N0)-1)
|
||||
self.phir = helmholtz.phir_power(n, d, t, l, 1, len(self.N0) - 1)
|
||||
|
||||
# Solve for the coefficients
|
||||
Nbounds = [(-10,10) for _ in range(len(self.N0))]
|
||||
tbounds = [(-1,30) for _ in range(len(self.T0))]
|
||||
Nbounds = [(-10, 10) for _ in range(len(self.N0))]
|
||||
tbounds = [(-1, 30) for _ in range(len(self.T0))]
|
||||
print(self.OBJECTIVE(np.array(list(self.N0))))
|
||||
#self.N = self.N0
|
||||
#self.N = scipy.optimize.minimize(self.OBJECTIVE, np.array(list(self.N0)), bounds = Nbounds, options = dict(maxiter = 5)).x
|
||||
self.N = scipy.optimize.minimize(self.OBJECTIVE, np.array(list(self.N0)), method = 'L-BFGS-B', bounds = Nbounds, options = dict(maxiter = 100)).x
|
||||
self.N = scipy.optimize.minimize(self.OBJECTIVE, np.array(list(self.N0)), method='L-BFGS-B', bounds=Nbounds, options=dict(maxiter=100)).x
|
||||
|
||||
# Write the coefficients to HDF5 file
|
||||
h = h5py.File('fit_coeffs.h5','w')
|
||||
h = h5py.File('fit_coeffs.h5', 'w')
|
||||
grp = h.create_group(self.Ref)
|
||||
grp.create_dataset("n", data = np.array(self.N), compression = "gzip")
|
||||
grp.create_dataset("n", data=np.array(self.N), compression="gzip")
|
||||
print(self.N)
|
||||
#grp.create_dataset("t", data = np.array(self.N[len(self.N)//2::]), compression = "gzip")
|
||||
h.close()
|
||||
|
||||
def evaluate_REFPROP(self, Ref, T, rho):
|
||||
|
||||
p,cp,cv,w = [],[],[],[]
|
||||
R = 8.314472/Props(Ref,'molemass')
|
||||
for _T,_rho in zip(T, rho):
|
||||
p.append(Props("P",'T',_T,'D',_rho,Ref))
|
||||
cp.append(Props("C",'T',_T,'D',_rho,Ref))
|
||||
cv.append(Props("O",'T',_T,'D',_rho,Ref))
|
||||
w.append(Props("A",'T',_T,'D',_rho,Ref))
|
||||
p, cp, cv, w = [], [], [], []
|
||||
R = 8.314472 / Props(Ref, 'molemass')
|
||||
for _T, _rho in zip(T, rho):
|
||||
p.append(Props("P", 'T', _T, 'D', _rho, Ref))
|
||||
cp.append(Props("C", 'T', _T, 'D', _rho, Ref))
|
||||
cv.append(Props("O", 'T', _T, 'D', _rho, Ref))
|
||||
w.append(Props("A", 'T', _T, 'D', _rho, Ref))
|
||||
|
||||
class stub: pass
|
||||
PPF = stub()
|
||||
PPF.p = np.array(p, ndmin = 1).T
|
||||
PPF.cp = np.array(cp, ndmin = 1).T
|
||||
PPF.cv = np.array(cv, ndmin = 1).T
|
||||
PPF.w = np.array(w, ndmin = 1).T
|
||||
PPF.p = np.array(p, ndmin=1).T
|
||||
PPF.cp = np.array(cp, ndmin=1).T
|
||||
PPF.cv = np.array(cv, ndmin=1).T
|
||||
PPF.w = np.array(w, ndmin=1).T
|
||||
|
||||
return PPF
|
||||
|
||||
def check(self):
|
||||
# Load the coefficients from file
|
||||
h = h5py.File('fit_coeffs.h5','r')
|
||||
h = h5py.File('fit_coeffs.h5', 'r')
|
||||
grp = h.get(self.Ref)
|
||||
n = grp.get('n').value
|
||||
h.close()
|
||||
@@ -420,22 +420,22 @@ class ResidualPartFitter(object):
|
||||
print(n)
|
||||
|
||||
import matplotlib.colors as colors
|
||||
cNorm = colors.LogNorm(vmin=1e-3, vmax=50)
|
||||
cNorm = colors.LogNorm(vmin=1e-3, vmax=50)
|
||||
PPF = self.evaluate_EOS(np.array(list(n)))
|
||||
self.OBJECTIVE(np.array(list(n)))
|
||||
|
||||
print('max error (p) %s %%' % np.max(np.abs(PPF.p/self.p-1)*100))
|
||||
SC1 = plt.scatter(self.rho, self.T, s = 8, c = np.abs(PPF.p/self.p-1)*100, edgecolors = 'none', cmap = plt.get_cmap('jet'), norm = cNorm)
|
||||
print('max error (p) %s %%' % np.max(np.abs(PPF.p / self.p - 1) * 100))
|
||||
SC1 = plt.scatter(self.rho, self.T, s=8, c=np.abs(PPF.p / self.p - 1) * 100, edgecolors='none', cmap=plt.get_cmap('jet'), norm=cNorm)
|
||||
plt.gca().set_xscale('log')
|
||||
cb = plt.colorbar()
|
||||
cb.set_label('abs(PPF.p/self.p-1)*100')
|
||||
plt.savefig('pressure.png')
|
||||
plt.show()
|
||||
|
||||
print('max error (cp) %s %%' % np.max(np.abs(PPF.cp/self.cp-1)*100))
|
||||
SC1 = plt.scatter(self.rho, self.T, s = 8, c = np.abs(PPF.cp/self.cp-1)*100, edgecolors = 'none', cmap = plt.get_cmap('jet'), norm = cNorm)
|
||||
print('max error (cp) %s %%' % np.max(np.abs(PPF.cp / self.cp - 1) * 100))
|
||||
SC1 = plt.scatter(self.rho, self.T, s=8, c=np.abs(PPF.cp / self.cp - 1) * 100, edgecolors='none', cmap=plt.get_cmap('jet'), norm=cNorm)
|
||||
plt.gca().set_xscale('log')
|
||||
cb = plt.colorbar()
|
||||
cb = plt.colorbar()
|
||||
cb.set_label('abs(PPF.cp/self.cp-1)*100')
|
||||
plt.savefig('cp.png')
|
||||
plt.show()
|
||||
@@ -448,7 +448,7 @@ class ResidualPartFitter(object):
|
||||
|
||||
class PPFFitterClass(object):
|
||||
|
||||
def __init__(self, Ref, regenerate_data = True, fit = True):
|
||||
def __init__(self, Ref, regenerate_data=True, fit=True):
|
||||
|
||||
self.Ref = Ref
|
||||
|
||||
@@ -456,7 +456,7 @@ class PPFFitterClass(object):
|
||||
self.IPF.fit()
|
||||
for i in range(1):
|
||||
|
||||
self.RPF = ResidualPartFitter(Ref, IPF = self.IPF)
|
||||
self.RPF = ResidualPartFitter(Ref, IPF=self.IPF)
|
||||
if regenerate_data:
|
||||
self.RPF.generate_1phase_data()
|
||||
|
||||
@@ -465,7 +465,7 @@ class PPFFitterClass(object):
|
||||
if fit:
|
||||
self.RPF.fit()
|
||||
|
||||
f = open('results.txt','a+')
|
||||
f = open('results.txt', 'a+')
|
||||
print("%s %s %s" % (indices, self.RPF.RMS, self.RPF.MaxError), file=f)
|
||||
f.close()
|
||||
|
||||
@@ -480,7 +480,7 @@ class PPFFitterClass(object):
|
||||
values : iterable, same size as T and rho
|
||||
"""
|
||||
|
||||
plt.semilogx(self.RPF.rho,self.RPF.T,'o')
|
||||
plt.semilogx(self.RPF.rho, self.RPF.T, 'o')
|
||||
plt.show()
|
||||
|
||||
# Generate a regular grid to interpolate the data.
|
||||
@@ -488,24 +488,24 @@ class PPFFitterClass(object):
|
||||
yi = np.linspace(min(self.RPF.rho), max(self.RPF.rho), 100)
|
||||
xi, yi = np.meshgrid(xi, yi)
|
||||
# Interpolate using delaunay triangularization
|
||||
zi = mlab.griddata(np.array(self.RPF.T),np.array(self.RPF.rho),np.array(values),xi,yi)
|
||||
cont = plt.contourf(yi,xi,zi,30)
|
||||
zi = mlab.griddata(np.array(self.RPF.T), np.array(self.RPF.rho), np.array(values), xi, yi)
|
||||
cont = plt.contourf(yi, xi, zi, 30)
|
||||
plt.colorbar()
|
||||
plt.show()
|
||||
|
||||
def output_files(self):
|
||||
h = h5py.File('fit_coeffs.h5','r')
|
||||
n = h.get(self.Ref+'/n').value
|
||||
h = h5py.File('fit_coeffs.h5', 'r')
|
||||
n = h.get(self.Ref + '/n').value
|
||||
#t = h.get(self.Ref+'/t').value
|
||||
|
||||
# Output the header file
|
||||
header = PPF_h_template.format(Ref = self.Ref, RefUpper = self.Ref.upper())
|
||||
header = PPF_h_template.format(Ref=self.Ref, RefUpper=self.Ref.upper())
|
||||
|
||||
acoeffs = '0, '+', '.join(['{a:0.6f}'.format(a=_) for _ in self.IPF.a])
|
||||
acoeffs = '0, ' + ', '.join(['{a:0.6f}'.format(a=_) for _ in self.IPF.a])
|
||||
# First one doesn't get divided by critical temperature, later ones do
|
||||
bcoeffs = '0, '
|
||||
bcoeffs += str(self.IPF.e[0])+', '
|
||||
bcoeffs += ', '.join(['{b:0.4f}/{Tcrit:g}'.format(b=_,Tcrit = self.IPF.Tc) for _ in self.IPF.e[1::]])
|
||||
bcoeffs += str(self.IPF.e[0]) + ', '
|
||||
bcoeffs += ', '.join(['{b:0.4f}/{Tcrit:g}'.format(b=_, Tcrit=self.IPF.Tc) for _ in self.IPF.e[1::]])
|
||||
|
||||
ncoeffs = ', '.join(['{a:0.6g}'.format(a=_) for _ in n])
|
||||
tcoeffs = ', '.join(['{a:0.6g}'.format(a=_) for _ in self.RPF.T0])
|
||||
@@ -515,43 +515,43 @@ class PPFFitterClass(object):
|
||||
import sys
|
||||
sys.path.append('..')
|
||||
from fit_ancillary_ODRPACK import saturation_pressure, saturation_density
|
||||
pL = saturation_pressure(self.IPF.RefString, self.IPF.Ref, LV = 'L')
|
||||
pV = saturation_pressure(self.IPF.RefString, self.IPF.Ref, LV = 'V')
|
||||
rhoL = saturation_density(self.IPF.RefString, self.IPF.Ref, form='A', LV='L', add_critical = False)
|
||||
rhoV = saturation_density(self.IPF.RefString, self.IPF.Ref, form='B', LV='V', add_critical = False)
|
||||
pL = saturation_pressure(self.IPF.RefString, self.IPF.Ref, LV='L')
|
||||
pV = saturation_pressure(self.IPF.RefString, self.IPF.Ref, LV='V')
|
||||
rhoL = saturation_density(self.IPF.RefString, self.IPF.Ref, form='A', LV='L', add_critical=False)
|
||||
rhoV = saturation_density(self.IPF.RefString, self.IPF.Ref, form='B', LV='V', add_critical=False)
|
||||
|
||||
code = PPF_cpp_template.format(Ref = self.Ref,
|
||||
RefUpper = self.Ref.upper(),
|
||||
acoeffs = acoeffs,
|
||||
bcoeffs = bcoeffs,
|
||||
Ncoeffs = ncoeffs,
|
||||
tcoeffs = tcoeffs,
|
||||
dcoeffs = dcoeffs,
|
||||
Lcoeffs = lcoeffs,
|
||||
N_phir = len(n),
|
||||
N_cp0 = len(self.IPF.a),
|
||||
molemass = self.IPF.molemass,
|
||||
Ttriple = 200,
|
||||
accentric = 0.7,
|
||||
pcrit = self.IPF.pc,
|
||||
Tcrit = self.IPF.Tc,
|
||||
rhocrit = self.IPF.rhoc,
|
||||
pL = pL,
|
||||
pV = pV,
|
||||
rhoL = rhoL,
|
||||
rhoV = rhoV
|
||||
code = PPF_cpp_template.format(Ref=self.Ref,
|
||||
RefUpper=self.Ref.upper(),
|
||||
acoeffs=acoeffs,
|
||||
bcoeffs=bcoeffs,
|
||||
Ncoeffs=ncoeffs,
|
||||
tcoeffs=tcoeffs,
|
||||
dcoeffs=dcoeffs,
|
||||
Lcoeffs=lcoeffs,
|
||||
N_phir=len(n),
|
||||
N_cp0=len(self.IPF.a),
|
||||
molemass=self.IPF.molemass,
|
||||
Ttriple=200,
|
||||
accentric=0.7,
|
||||
pcrit=self.IPF.pc,
|
||||
Tcrit=self.IPF.Tc,
|
||||
rhocrit=self.IPF.rhoc,
|
||||
pL=pL,
|
||||
pV=pV,
|
||||
rhoL=rhoL,
|
||||
rhoV=rhoV
|
||||
)
|
||||
|
||||
f = open(self.IPF.Ref+'.h','w')
|
||||
f = open(self.IPF.Ref + '.h', 'w')
|
||||
f.write(header)
|
||||
f.close()
|
||||
|
||||
f = open(self.IPF.Ref+'.cpp','w')
|
||||
f = open(self.IPF.Ref + '.cpp', 'w')
|
||||
f.write(code)
|
||||
f.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
Ref = 'R407F'
|
||||
|
||||
PPFFitterClass(Ref)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
from distutils.core import setup
|
||||
from Cython.Build import cythonize
|
||||
|
||||
import sys,numpy
|
||||
import sys, numpy
|
||||
import Cython
|
||||
Cython.Compiler.Options.annotate = True
|
||||
sys.argv += ['build_ext','--inplace']
|
||||
sys.argv += ['build_ext', '--inplace']
|
||||
|
||||
setup(
|
||||
name = "",
|
||||
ext_modules = cythonize('summer.pyx'), # accepts a glob pattern
|
||||
include_dirs = [numpy.get_include()]
|
||||
name="",
|
||||
ext_modules=cythonize('summer.pyx'), # accepts a glob pattern
|
||||
include_dirs=[numpy.get_include()]
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import print_function
|
||||
|
||||
from math import sqrt,exp
|
||||
from math import sqrt, exp
|
||||
import CoolProp
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
@@ -8,18 +8,18 @@ import scipy.optimize
|
||||
from math import log
|
||||
|
||||
|
||||
def viscosity_dilute(fluid,T,e_k,sigma):
|
||||
def viscosity_dilute(fluid, T, e_k, sigma):
|
||||
"""
|
||||
T in [K], e_K in [K], sigma in [nm]
|
||||
viscosity returned is in [Pa-s]
|
||||
"""
|
||||
Tstar = T/e_k
|
||||
molemass = CoolProp.CoolProp.PropsSI(fluid,'molemass')*1000
|
||||
Tstar = T / e_k
|
||||
molemass = CoolProp.CoolProp.PropsSI(fluid, 'molemass') * 1000
|
||||
|
||||
# From Neufeld, 1972, Journal of Chemical Physics - checked coefficients
|
||||
OMEGA_2_2 = 1.16145*pow(Tstar,-0.14874)+ 0.52487*exp(-0.77320*Tstar)+2.16178*exp(-2.43787*Tstar)
|
||||
OMEGA_2_2 = 1.16145 * pow(Tstar, -0.14874) + 0.52487 * exp(-0.77320 * Tstar) + 2.16178 * exp(-2.43787 * Tstar)
|
||||
# Using the leading constant from McLinden, 2000 since the leading term from Huber 2003 gives crazy values
|
||||
eta_star = 26.692e-3*sqrt(molemass*T)/(pow(sigma,2)*OMEGA_2_2)/1e6
|
||||
eta_star = 26.692e-3 * sqrt(molemass * T) / (pow(sigma, 2) * OMEGA_2_2) / 1e6
|
||||
return eta_star
|
||||
|
||||
|
||||
@@ -35,24 +35,24 @@ def get_psi(fluid, ref_fluid, eta, T, rhomolar, e_k, sigma_nm):
|
||||
# Calculate the conformal state
|
||||
conformal_state = THIS.conformal_state(ref_fluid, -1, -1)
|
||||
# Calculate ESRR (which are based on the CONFORMAL state values)
|
||||
f = THIS.T()/conformal_state['T'];
|
||||
h = conformal_state['rhomolar']/THIS.rhomolar(); ## Must be the ratio of MOLAR densities!!
|
||||
f = THIS.T() / conformal_state['T'];
|
||||
h = conformal_state['rhomolar'] / THIS.rhomolar(); # Must be the ratio of MOLAR densities!!
|
||||
|
||||
# The F factor
|
||||
F_eta = sqrt(f)*pow(h, -2.0/3.0)*sqrt(THIS.molar_mass()/REF.molar_mass());
|
||||
F_eta = sqrt(f) * pow(h, -2.0 / 3.0) * sqrt(THIS.molar_mass() / REF.molar_mass());
|
||||
|
||||
# Dilute viscosity of fluid of interest
|
||||
eta_dilute = viscosity_dilute(fluid, T, e_k, sigma_nm)
|
||||
|
||||
# Required background contribution from reference fluid
|
||||
viscosity_background_required = (eta - eta_dilute)/F_eta
|
||||
viscosity_background_required = (eta - eta_dilute) / F_eta
|
||||
|
||||
REF.update(CoolProp.DmolarT_INPUTS, conformal_state['rhomolar']*psi, conformal_state['T'])
|
||||
REF.update(CoolProp.DmolarT_INPUTS, conformal_state['rhomolar'] * psi, conformal_state['T'])
|
||||
visc_ref = REF.viscosity_contributions()
|
||||
residual = visc_ref['initial_density'] + visc_ref['residual']
|
||||
return residual - viscosity_background_required
|
||||
|
||||
psi = scipy.optimize.newton(residual_for_psi, 1.0, args = (REF,))
|
||||
psi = scipy.optimize.newton(residual_for_psi, 1.0, args=(REF,))
|
||||
return psi
|
||||
|
||||
|
||||
@@ -84,38 +84,38 @@ def HFO():
|
||||
363.12 866.8 160.4 17.28 0.0924 1.35
|
||||
373.14 776.9 225.2 19.89 0.0817 0.54"""
|
||||
|
||||
for fluid, data, e_k, sigma_nm in zip(['R1234yf', 'R1234ze(E)'],[data_R1234yf, data_R1234zeE],[281.14, 292.11], [0.5328, 0.5017]):
|
||||
for fluid, data, e_k, sigma_nm in zip(['R1234yf', 'R1234ze(E)'], [data_R1234yf, data_R1234zeE], [281.14, 292.11], [0.5328, 0.5017]):
|
||||
xx, yy, RHO, ETA, ETACP, ETARP = [], [], [], [], [], []
|
||||
for line in data.split('\n'):
|
||||
T, rhoL, rhoV, etaV, nuL, sigma = line.strip().split(' ')
|
||||
rhoL = float(rhoL)
|
||||
T = float(T)
|
||||
nuL = float(nuL)
|
||||
rhomolar = rhoL/CoolProp.CoolProp.PropsSI(fluid,'molemass')
|
||||
eta = nuL/1000**2*rhoL
|
||||
rhomolar = rhoL / CoolProp.CoolProp.PropsSI(fluid, 'molemass')
|
||||
eta = nuL / 1000**2 * rhoL
|
||||
psi = get_psi(fluid, 'Propane', eta, T, rhomolar, e_k, sigma_nm)
|
||||
xx.append(T)
|
||||
yy.append(psi)
|
||||
RHO.append(rhomolar)
|
||||
ETA.append(eta)
|
||||
ETACP.append(CoolProp.CoolProp.PropsSI('V','T',T,'Q',0,fluid))
|
||||
ETARP.append(CoolProp.CoolProp.PropsSI('V','T',T,'Q',0,'REFPROP::' + CoolProp.CoolProp.get_fluid_param_string(fluid, 'REFPROP_name')))
|
||||
ETACP.append(CoolProp.CoolProp.PropsSI('V', 'T', T, 'Q', 0, fluid))
|
||||
ETARP.append(CoolProp.CoolProp.PropsSI('V', 'T', T, 'Q', 0, 'REFPROP::' + CoolProp.CoolProp.get_fluid_param_string(fluid, 'REFPROP_name')))
|
||||
|
||||
RHO, xx, ETA, ETACP, ETARP = arrayize(RHO, xx, ETA, ETACP, ETARP)
|
||||
rhor = RHO/CoolProp.CoolProp.PropsSI(fluid, 'rhomolar_critical')
|
||||
rhor = RHO / CoolProp.CoolProp.PropsSI(fluid, 'rhomolar_critical')
|
||||
|
||||
plt.plot(rhor, yy, 'o-',label='from experimental data')
|
||||
plt.plot(rhor, yy, 'o-', label='from experimental data')
|
||||
p = np.polyfit(rhor, yy, 2)
|
||||
print(p[::-1])
|
||||
plt.plot(rhor, np.polyval(p, rhor), 'o-',label = 'from correlation')
|
||||
plt.plot(rhor, np.polyval(p, rhor), 'o-', label='from correlation')
|
||||
plt.xlabel(r'$\rho_r$')
|
||||
plt.ylabel('$\psi$')
|
||||
plt.legend(loc='best')
|
||||
plt.show()
|
||||
|
||||
plt.title(fluid)
|
||||
plt.plot(xx, (ETACP/ETA-1)*100,'^', label = 'CoolProp')
|
||||
plt.plot(xx, (ETARP/ETA-1)*100,'o', label = 'REFPROP')
|
||||
plt.plot(xx, (ETACP / ETA - 1) * 100, '^', label='CoolProp')
|
||||
plt.plot(xx, (ETARP / ETA - 1) * 100, 'o', label='REFPROP')
|
||||
plt.xlabel('Temperature (K)')
|
||||
plt.ylabel('$100\\times(\eta_{calc}/\eta_{exp}-1)$ (%)')
|
||||
plt.legend(loc='best')
|
||||
@@ -140,44 +140,44 @@ def pentanes():
|
||||
|
||||
fluid = ''
|
||||
|
||||
def undelimit(args, delim = ''):
|
||||
def undelimit(args, delim=''):
|
||||
return [np.array([float(_) for _ in a.strip().split(delim)]) for a in args]
|
||||
|
||||
from CoolProp.CoolProp import PropsSI
|
||||
for fluid,e_k,sigma_nm in zip(['CycloPentane','Isopentane'],[406.33,341.06],[0.518,0.56232]):
|
||||
for fluid, e_k, sigma_nm in zip(['CycloPentane', 'Isopentane'], [406.33, 341.06], [0.518, 0.56232]):
|
||||
xx, yy, RHO, ETA, ETACP, ETARP = [], [], [], [], [], []
|
||||
for _T, _rhoLmass, _rhoVmass, _eta_mPas in zip(*undelimit(data_cyclopentane.split('\n'), delim = ' ')):
|
||||
for _T, _rhoLmass, _rhoVmass, _eta_mPas in zip(*undelimit(data_cyclopentane.split('\n'), delim=' ')):
|
||||
MM = PropsSI('molemass', fluid)
|
||||
rhomolar = _rhoLmass/MM
|
||||
eta = _eta_mPas/1000
|
||||
rhomolar = _rhoLmass / MM
|
||||
eta = _eta_mPas / 1000
|
||||
psi = get_psi(fluid, 'Propane', eta, _T, rhomolar, e_k, sigma_nm)
|
||||
xx.append(_T)
|
||||
yy.append(psi)
|
||||
RHO.append(rhomolar)
|
||||
try:
|
||||
ETACP.append(CoolProp.CoolProp.PropsSI('V','T',_T,'Q',0,fluid))
|
||||
ETACP.append(CoolProp.CoolProp.PropsSI('V', 'T', _T, 'Q', 0, fluid))
|
||||
except:
|
||||
ETACP.append(np.nan)
|
||||
ETA.append(eta)
|
||||
ETARP.append(CoolProp.CoolProp.PropsSI('V','T',_T,'Q',0,'REFPROP::' + CoolProp.CoolProp.get_fluid_param_string(fluid, 'REFPROP_name')))
|
||||
xx,yy,ETACP,ETARP, RHO, = arrayize(xx,yy,ETACP,ETARP,RHO)
|
||||
ETARP.append(CoolProp.CoolProp.PropsSI('V', 'T', _T, 'Q', 0, 'REFPROP::' + CoolProp.CoolProp.get_fluid_param_string(fluid, 'REFPROP_name')))
|
||||
xx, yy, ETACP, ETARP, RHO, = arrayize(xx, yy, ETACP, ETARP, RHO)
|
||||
rhored = CoolProp.CoolProp.PropsSI(fluid, 'rhomolar_critical')
|
||||
print('rhored',rhored)
|
||||
rhor = np.array(RHO)/rhored
|
||||
print('rhored', rhored)
|
||||
rhor = np.array(RHO) / rhored
|
||||
|
||||
plt.title(fluid)
|
||||
plt.plot(rhor, yy, 'o-',label='from experimental data')
|
||||
plt.plot(rhor, yy, 'o-', label='from experimental data')
|
||||
p = np.polyfit(rhor, yy, 2)
|
||||
print(p[::-1])
|
||||
plt.plot(rhor, np.polyval(p, rhor), 'o-',label = 'from correlation')
|
||||
plt.plot(rhor, np.polyval(p, rhor), 'o-', label='from correlation')
|
||||
plt.xlabel(r'$\rho_r$')
|
||||
plt.ylabel('$\psi$')
|
||||
plt.legend(loc='best')
|
||||
plt.show()
|
||||
|
||||
plt.title(fluid)
|
||||
plt.plot(xx, (ETACP/ETA-1)*100,'^', label = 'CoolProp')
|
||||
plt.plot(xx, (ETARP/ETA-1)*100,'o', label = 'REFPROP')
|
||||
plt.plot(xx, (ETACP / ETA - 1) * 100, '^', label='CoolProp')
|
||||
plt.plot(xx, (ETARP / ETA - 1) * 100, 'o', label='REFPROP')
|
||||
plt.xlabel('Temperature (K)')
|
||||
plt.ylabel('$100\\times(\eta_{calc}/\eta_{exp}-1)$ (%)')
|
||||
plt.legend(loc='best')
|
||||
|
||||
@@ -2,35 +2,35 @@ import matplotlib.pyplot as plt
|
||||
import CoolProp.CoolProp as CP
|
||||
import itertools, numpy as np
|
||||
|
||||
variables = ['T','P','H','S','U','D']
|
||||
variables = ['T', 'P', 'H', 'S', 'U', 'D']
|
||||
|
||||
for fluid in ['Water','CO2','n-Propane','MDM']:
|
||||
T = np.linspace(CP.PropsSI(fluid,'Tmin'),CP.PropsSI(fluid,'T_critical')-1e-5,1000)
|
||||
for fluid in ['Water', 'CO2', 'n-Propane', 'MDM']:
|
||||
T = np.linspace(CP.PropsSI(fluid, 'Tmin'), CP.PropsSI(fluid, 'T_critical') - 1e-5, 1000)
|
||||
|
||||
fig = plt.figure(1, figsize=(10, 10), dpi=100)
|
||||
for i, types in enumerate(itertools.combinations(variables,2)):
|
||||
ax = plt.subplot(5, 3, i+1)
|
||||
for i, types in enumerate(itertools.combinations(variables, 2)):
|
||||
ax = plt.subplot(5, 3, i + 1)
|
||||
|
||||
types = list(types)
|
||||
|
||||
if types[0] in ['T','P'] and types != ['T','P']:
|
||||
types[0],types[1] = types[1],types[0]
|
||||
if types[0] in ['T', 'P'] and types != ['T', 'P']:
|
||||
types[0], types[1] = types[1], types[0]
|
||||
|
||||
xL = CP.PropsSI(types[0],'T',T,'Q',0,fluid)
|
||||
yL = CP.PropsSI(types[1],'T',T,'Q',0,fluid)
|
||||
xV = CP.PropsSI(types[0],'T',T,'Q',1,fluid)
|
||||
yV = CP.PropsSI(types[1],'T',T,'Q',1,fluid)
|
||||
xL = CP.PropsSI(types[0], 'T', T, 'Q', 0, fluid)
|
||||
yL = CP.PropsSI(types[1], 'T', T, 'Q', 0, fluid)
|
||||
xV = CP.PropsSI(types[0], 'T', T, 'Q', 1, fluid)
|
||||
yV = CP.PropsSI(types[1], 'T', T, 'Q', 1, fluid)
|
||||
Tc = CP.PropsSI(fluid, 'T_critical')
|
||||
xc = CP.PropsSI(types[0],'T',Tc-1e-6,'Q',1,fluid)
|
||||
yc = CP.PropsSI(types[1],'T',Tc-1e-6,'Q',1,fluid)
|
||||
xc = CP.PropsSI(types[0], 'T', Tc - 1e-6, 'Q', 1, fluid)
|
||||
yc = CP.PropsSI(types[1], 'T', Tc - 1e-6, 'Q', 1, fluid)
|
||||
|
||||
ax.plot(xL,yL,'k')
|
||||
ax.plot(xV,yV,'k')
|
||||
ax.plot(xc,yc,'o')
|
||||
ax.plot(xL, yL, 'k')
|
||||
ax.plot(xV, yV, 'k')
|
||||
ax.plot(xc, yc, 'o')
|
||||
|
||||
if types[0] in ['P','D']:
|
||||
if types[0] in ['P', 'D']:
|
||||
ax.set_xscale('log')
|
||||
if types[1] in ['P','D']:
|
||||
if types[1] in ['P', 'D']:
|
||||
ax.set_yscale('log')
|
||||
|
||||
plt.title(' '.join(types))
|
||||
@@ -38,5 +38,5 @@ for fluid in ['Water','CO2','n-Propane','MDM']:
|
||||
plt.ylabel(types[1])
|
||||
|
||||
plt.tight_layout()
|
||||
plt.savefig('AllFlash'+fluid+'.pdf')
|
||||
plt.savefig('AllFlash' + fluid + '.pdf')
|
||||
plt.show()
|
||||
|
||||
@@ -8,31 +8,31 @@ else:
|
||||
compilers = ''
|
||||
extra = ''
|
||||
host = ''
|
||||
commons = dict(shell = True, stdout = sys.stdout, stderr = sys.stderr)
|
||||
commons = dict(shell=True, stdout=sys.stdout, stderr=sys.stderr)
|
||||
|
||||
if not os.path.exists('swig-matlab'):
|
||||
subprocess.call('git clone https://github.com/jaeandersson/swig swig-matlab', **commons)
|
||||
else:
|
||||
subprocess.call('git pull', shell = True, cwd = 'swig-matlab', stdout = sys.stdout, stderr = sys.stderr)
|
||||
subprocess.call('git pull', shell=True, cwd='swig-matlab', stdout=sys.stdout, stderr=sys.stderr)
|
||||
|
||||
os.chdir('swig-matlab')
|
||||
if '--no-pcre' not in sys.argv:
|
||||
if not glob.glob('pcre-*.tar.gz'):
|
||||
for rev in ['8.34','8.35','8.36']:
|
||||
for rev in ['8.34', '8.35', '8.36']:
|
||||
try:
|
||||
wget.download('ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-'+rev+'.tar.gz'); break
|
||||
wget.download('ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-' + rev + '.tar.gz'); break
|
||||
except:
|
||||
pass
|
||||
subprocess.check_call('Tools/pcre-build.sh'+compilers+host, **commons)
|
||||
subprocess.check_call('Tools/pcre-build.sh' + compilers + host, **commons)
|
||||
|
||||
prefix = '${PWD}/swig-matlab-bin'
|
||||
if '--prefix' in sys.argv:
|
||||
prefix = sys.argv[sys.argv.index('--prefix')+1]
|
||||
prefix = sys.argv[sys.argv.index('--prefix') + 1]
|
||||
|
||||
subprocess.check_call(compilers+'./autogen.sh', **commons)
|
||||
subprocess.check_call('./configure --disable-ccache --with-matlab=/usr/local/MATLAB/R2014a --prefix=' + prefix + extra + compilers+host, **commons)
|
||||
subprocess.check_call(compilers+'make', **commons)
|
||||
subprocess.check_call(compilers+'make install', **commons)
|
||||
subprocess.check_call(compilers + './autogen.sh', **commons)
|
||||
subprocess.check_call('./configure --disable-ccache --with-matlab=/usr/local/MATLAB/R2014a --prefix=' + prefix + extra + compilers + host, **commons)
|
||||
subprocess.check_call(compilers + 'make', **commons)
|
||||
subprocess.check_call(compilers + 'make install', **commons)
|
||||
|
||||
if '--windows' in sys.argv:
|
||||
subprocess.check_call('cp swig.exe swig3.0.exe', cwd='swig-matlab-bin/bin', **commons)
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import subprocess, wget, os, shutil, sys, glob
|
||||
|
||||
if not os.path.exists('swig-scilab'):
|
||||
subprocess.call('git clone https://github.com/swig/swig.git -b gsoc2012-scilab swig-scilab', shell = True, stdout = sys.stdout, stderr = sys.stderr)
|
||||
subprocess.call('git clone https://github.com/swig/swig.git -b gsoc2012-scilab swig-scilab', shell=True, stdout=sys.stdout, stderr=sys.stderr)
|
||||
else:
|
||||
subprocess.call('git pull', shell = True, cwd = 'swig-scilab', stdout = sys.stdout, stderr = sys.stderr)
|
||||
subprocess.call('git pull', shell=True, cwd='swig-scilab', stdout=sys.stdout, stderr=sys.stderr)
|
||||
os.chdir('swig-scilab')
|
||||
if not glob.glob('pcre-*.tar.gz'):
|
||||
for rev in ['8.34','8.35','8.36']:
|
||||
for rev in ['8.34', '8.35', '8.36']:
|
||||
try:
|
||||
wget.download('ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-'+rev+'.tar.gz'); break
|
||||
wget.download('ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-' + rev + '.tar.gz'); break
|
||||
except:
|
||||
pass
|
||||
|
||||
@@ -20,13 +20,13 @@ if '--windows' in sys.argv:
|
||||
else:
|
||||
compilers = ''
|
||||
host = ''
|
||||
commons = dict(shell = True, stdout = sys.stdout, stderr = sys.stderr)
|
||||
commons = dict(shell=True, stdout=sys.stdout, stderr=sys.stderr)
|
||||
|
||||
subprocess.check_call('Tools/pcre-build.sh'+compilers+host, **commons)
|
||||
subprocess.check_call(compilers+'./autogen.sh', **commons)
|
||||
subprocess.check_call('./configure --disable-ccache --with-scilab-inc=${SCILAB_HOME}/include --with-scilab=${SCILAB_HOME}/bin/scilab-cli'+' '+prefix+compilers+host, **commons)
|
||||
subprocess.check_call(compilers+'make', **commons)
|
||||
subprocess.check_call(compilers+'make install', **commons)
|
||||
subprocess.check_call('Tools/pcre-build.sh' + compilers + host, **commons)
|
||||
subprocess.check_call(compilers + './autogen.sh', **commons)
|
||||
subprocess.check_call('./configure --disable-ccache --with-scilab-inc=${SCILAB_HOME}/include --with-scilab=${SCILAB_HOME}/bin/scilab-cli' + ' ' + prefix + compilers + host, **commons)
|
||||
subprocess.check_call(compilers + 'make', **commons)
|
||||
subprocess.check_call(compilers + 'make install', **commons)
|
||||
|
||||
if '--windows' in sys.argv:
|
||||
subprocess.check_call('cp swig.exe swig3.0.exe', cwd='swig-scilab-bin/bin', **commons)
|
||||
|
||||
@@ -16,58 +16,58 @@ for Fluid in CoolProp.__fluids__:
|
||||
|
||||
ax.cla()
|
||||
|
||||
h_crit = Props('H','T',Props(Fluid,"Tcrit"),'D',Props(Fluid,"rhocrit"),Fluid)
|
||||
s_crit = Props('S','T',Props(Fluid,"Tcrit"),'D',Props(Fluid,"rhocrit"),Fluid)
|
||||
h_crit = Props('H', 'T', Props(Fluid, "Tcrit"), 'D', Props(Fluid, "rhocrit"), Fluid)
|
||||
s_crit = Props('S', 'T', Props(Fluid, "Tcrit"), 'D', Props(Fluid, "rhocrit"), Fluid)
|
||||
|
||||
hL_Tmin = Props('H','T',Props(Fluid,"Tmin"),'Q',0,Fluid)
|
||||
hV_Tmin = Props('H','T',Props(Fluid,"Tmin"),'Q',1,Fluid)
|
||||
sL_Tmin = Props('S','T',Props(Fluid,"Tmin"),'Q',0,Fluid)
|
||||
sV_Tmin = Props('S','T',Props(Fluid,"Tmin"),'Q',1,Fluid)
|
||||
hL_Tmin = Props('H', 'T', Props(Fluid, "Tmin"), 'Q', 0, Fluid)
|
||||
hV_Tmin = Props('H', 'T', Props(Fluid, "Tmin"), 'Q', 1, Fluid)
|
||||
sL_Tmin = Props('S', 'T', Props(Fluid, "Tmin"), 'Q', 0, Fluid)
|
||||
sV_Tmin = Props('S', 'T', Props(Fluid, "Tmin"), 'Q', 1, Fluid)
|
||||
|
||||
hs(Fluid, axis = ax)
|
||||
plt.plot(s_crit,h_crit,'rd')
|
||||
plt.plot([sL_Tmin,sV_Tmin],[hL_Tmin,hV_Tmin],'--')
|
||||
hs(Fluid, axis=ax)
|
||||
plt.plot(s_crit, h_crit, 'rd')
|
||||
plt.plot([sL_Tmin, sV_Tmin], [hL_Tmin, hV_Tmin], '--')
|
||||
plt.gca().axhline(h_crit)
|
||||
plt.gca().axhline(hV_Tmin)
|
||||
|
||||
# Two-Phase
|
||||
for T in np.linspace(Props(Fluid,"Tmin")+0.1,Props(Fluid,"Tcrit")-1e-3,30):
|
||||
for T in np.linspace(Props(Fluid, "Tmin") + 0.1, Props(Fluid, "Tcrit") - 1e-3, 30):
|
||||
for Q in np.linspace(0, 1, 30):
|
||||
try:
|
||||
h = Props("H",'Q',Q,'T',T,Fluid)
|
||||
s = Props("S",'Q',Q,'T',T,Fluid)
|
||||
T = Props("T",'S',s,'H',h,Fluid)
|
||||
#ax.plot(s,h,'o',mfc='none')
|
||||
h = Props("H", 'Q', Q, 'T', T, Fluid)
|
||||
s = Props("S", 'Q', Q, 'T', T, Fluid)
|
||||
T = Props("T", 'S', s, 'H', h, Fluid)
|
||||
# ax.plot(s,h,'o',mfc='none')
|
||||
except ValueError as VE:
|
||||
print(T, Q , '|||', '"T","S",',s,',"H",',h,',"'+Fluid+'"', '|||', VE)
|
||||
ax.plot(s,h,'o',mfc='none')
|
||||
print(T, Q, '|||', '"T","S",', s, ',"H",', h, ',"' + Fluid + '"', '|||', VE)
|
||||
ax.plot(s, h, 'o', mfc='none')
|
||||
|
||||
for h in np.linspace(hL_Tmin, hV_Tmin + 1500,100):
|
||||
for s in np.linspace(sL_Tmin+0.01,sV_Tmin,100):
|
||||
for h in np.linspace(hL_Tmin, hV_Tmin + 1500, 100):
|
||||
for s in np.linspace(sL_Tmin + 0.01, sV_Tmin, 100):
|
||||
try:
|
||||
h_pmax = Props('H','S',s,'P',6*Props(Fluid,'pcrit'),Fluid)
|
||||
h_pmax = Props('H', 'S', s, 'P', 6 * Props(Fluid, 'pcrit'), Fluid)
|
||||
except ValueError:
|
||||
h_pmax = 0
|
||||
htriple_s = (hV_Tmin-hL_Tmin)/(sV_Tmin-sL_Tmin)*(s-sL_Tmin)+hL_Tmin
|
||||
htriple_s = (hV_Tmin - hL_Tmin) / (sV_Tmin - sL_Tmin) * (s - sL_Tmin) + hL_Tmin
|
||||
if h < htriple_s or h > h_pmax: continue
|
||||
try:
|
||||
T = Props("T",'S',s,'H',h,Fluid)
|
||||
#ax.plot(s,h,'o',mfc='none',ms=6)
|
||||
T = Props("T", 'S', s, 'H', h, Fluid)
|
||||
# ax.plot(s,h,'o',mfc='none',ms=6)
|
||||
except ValueError:
|
||||
ax.plot(s,h,'s',mfc='none')
|
||||
ax.plot(s, h, 's', mfc='none')
|
||||
|
||||
|
||||
## if Fluid =='Propane':
|
||||
# if Fluid =='Propane':
|
||||
## ps = Props("P",'T',300,'Q',0,Fluid);
|
||||
## hL = Props("H",'Q',0,'T',300,Fluid);
|
||||
## sL = Props("S",'Q',0,'T',300,Fluid);
|
||||
## h = Props("H",'P',ps,'T',299.5,Fluid);
|
||||
## s = Props("S",'P',ps,'T',299.5,Fluid);
|
||||
## print s,h,sL,hL
|
||||
## plt.plot(s,h,'o')
|
||||
## plt.plot(sL,hL,'d')
|
||||
## plt.gca().axvline(s)
|
||||
## plt.gca().axhline(268.75968916316691)
|
||||
# print s,h,sL,hL
|
||||
# plt.plot(s,h,'o')
|
||||
# plt.plot(sL,hL,'d')
|
||||
# plt.gca().axvline(s)
|
||||
# plt.gca().axhline(268.75968916316691)
|
||||
|
||||
fig.savefig('figs/'+Fluid+'.png',dpi=200)
|
||||
fig.savefig('figs/'+Fluid+'.pdf')
|
||||
fig.savefig('figs/' + Fluid + '.png', dpi=200)
|
||||
fig.savefig('figs/' + Fluid + '.pdf')
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import CoolProp
|
||||
masses = {'Cl': 35.45, 'H':1.008,'C':12.011,'O':15.999,'N':14.007,'Ar':39.948,'S':32.06,'Si':28.085,'F':18.998,'D':2.01410,'He':4.0026,'Kr':83.798,'Ne':20.180,'I':126.90,'Xe':131.29}
|
||||
masses = {'Cl': 35.45, 'H': 1.008, 'C': 12.011, 'O': 15.999, 'N': 14.007, 'Ar': 39.948, 'S': 32.06, 'Si': 28.085, 'F': 18.998, 'D': 2.01410, 'He': 4.0026, 'Kr': 83.798, 'Ne': 20.180, 'I': 126.90, 'Xe': 131.29}
|
||||
for fluid in CoolProp.__fluids__:
|
||||
formula = CoolProp.CoolProp.get_fluid_param_string(fluid, "formula")
|
||||
if formula == 'N/A': continue
|
||||
bits = [_ for _ in formula.split('}') if _]
|
||||
m = 0
|
||||
for b in bits:
|
||||
el, c = b.replace('_','').split('{')
|
||||
m += masses[el]*int(c)/1000.0
|
||||
err = m/CoolProp.CoolProp.PropsSI(fluid,"M")-1
|
||||
el, c = b.replace('_', '').split('{')
|
||||
m += masses[el] * int(c) / 1000.0
|
||||
err = m / CoolProp.CoolProp.PropsSI(fluid, "M") - 1
|
||||
if abs(err) > 1e-3:
|
||||
print("%s %s" % (fluid, m/CoolProp.CoolProp.PropsSI(fluid,"M")-1))
|
||||
print("%s %s" % (fluid, m / CoolProp.CoolProp.PropsSI(fluid, "M") - 1))
|
||||
|
||||
@@ -10,29 +10,29 @@ def extract_coeffs(lines):
|
||||
assert(C_normal == 4)
|
||||
|
||||
chunk = []
|
||||
for line in lines[1:N_normal+1]:
|
||||
for line in lines[1:N_normal + 1]:
|
||||
ll = line.split('!')[0].strip()
|
||||
ll = [float(f) for f in ll.split(' ') if f]
|
||||
chunk.append(ll)
|
||||
n,t,d,l = zip(*chunk)
|
||||
n, t, d, l = zip(*chunk)
|
||||
|
||||
terms.append(
|
||||
dict(type = "ResidualHelmholtzPower",
|
||||
n = n, d = d, t = t, l = l)
|
||||
dict(type="ResidualHelmholtzPower",
|
||||
n=n, d=d, t=t, l=l)
|
||||
)
|
||||
|
||||
if N_critical > 0:
|
||||
chunk = []
|
||||
for line in lines[1+N_normal:N_normal+1+N_critical]:
|
||||
for line in lines[1 + N_normal:N_normal + 1 + N_critical]:
|
||||
ll = line.split('!')[0].strip()
|
||||
ll = [float(f) for f in ll.split(' ') if f]
|
||||
chunk.append(ll)
|
||||
n,t,d,l,dummy1,neg_eta,neg_beta,gamma,epsilon,dummy2,dummy3,dummy4 = zip(*chunk)
|
||||
n, t, d, l, dummy1, neg_eta, neg_beta, gamma, epsilon, dummy2, dummy3, dummy4 = zip(*chunk)
|
||||
eta, beta = [[-el for el in vec] for vec in [neg_eta, neg_beta]]
|
||||
|
||||
terms.append(
|
||||
dict(type = "ResidualHelmholtzGaussian",
|
||||
n = n, d = d, t = t, eta = eta, beta = beta, gamma = gamma, epsilon = epsilon)
|
||||
dict(type="ResidualHelmholtzGaussian",
|
||||
n=n, d=d, t=t, eta=eta, beta=beta, gamma=gamma, epsilon=epsilon)
|
||||
)
|
||||
|
||||
return terms
|
||||
@@ -45,7 +45,7 @@ def extract_active_EOS(file_name):
|
||||
|
||||
# Find the #EOS key
|
||||
iEOS = -1
|
||||
for i,line in enumerate(lines):
|
||||
for i, line in enumerate(lines):
|
||||
if line.startswith('#EOS'):
|
||||
if iEOS < 0:
|
||||
iEOS = i
|
||||
@@ -58,16 +58,16 @@ def extract_active_EOS(file_name):
|
||||
iEOS_end = i
|
||||
break
|
||||
|
||||
if i == len(lines) -1:
|
||||
if i == len(lines) - 1:
|
||||
raise KeyError("Could not find empty line at end of EOS block")
|
||||
|
||||
iEOS_start = iEOS
|
||||
for i in range(iEOS, iEOS_end +1):
|
||||
for i in range(iEOS, iEOS_end + 1):
|
||||
if lines[i].startswith('!'):
|
||||
iEOS_start = i
|
||||
break
|
||||
|
||||
for i in range(iEOS_start+1, iEOS_end +1):
|
||||
for i in range(iEOS_start + 1, iEOS_end + 1):
|
||||
print(lines[i].strip())
|
||||
|
||||
def unpack(line):
|
||||
@@ -77,11 +77,11 @@ def extract_active_EOS(file_name):
|
||||
except ValueError:
|
||||
return s
|
||||
|
||||
Tmin,Tmax,pmax,rhomax,CPP,MW,Tt,Pt,rhot,NBP,acentric,crit,reducing,R = [unpack(line) for line in lines[iEOS_start+1:iEOS_start+1+14]]
|
||||
Tmin, Tmax, pmax, rhomax, CPP, MW, Tt, Pt, rhot, NBP, acentric, crit, reducing, R = [unpack(line) for line in lines[iEOS_start + 1:iEOS_start + 1 + 14]]
|
||||
reducing = [float(f) for f in reducing.split(' ') if f]
|
||||
crit = [float(f) for f in crit.split(' ') if f]
|
||||
|
||||
alphar = extract_coeffs(lines[iEOS_start+15:iEOS_end+1])
|
||||
alphar = extract_coeffs(lines[iEOS_start + 15:iEOS_end + 1])
|
||||
|
||||
del file_name, iEOS, iEOS_start, iEOS_end, unpack, lines, line, i
|
||||
return locals().copy()
|
||||
@@ -101,31 +101,31 @@ def build_alphar(EOS):
|
||||
|
||||
def write(EOS, ALPHA0, json_file):
|
||||
|
||||
base = dict(BibTeX_CP0 = "",
|
||||
BibTeX_EOS = "XXXX TO BE FILLED IN XXX",
|
||||
STATES = build_states(),
|
||||
T_max = EOS['Tmax'],
|
||||
T_max_units = 'K',
|
||||
Ttriple = EOS['Tt'],
|
||||
Ttriple_units = 'K',
|
||||
acentric = EOS['acentric'],
|
||||
acentric_units = '-',
|
||||
alpha0 = build_alpha0(ALPHA0),
|
||||
alphar = EOS['alphar'],
|
||||
gas_constant = EOS['R'],
|
||||
gas_constant_units = 'J/mol/K',
|
||||
molar_mass = EOS['MW']/1000.0,
|
||||
molar_mass_units = 'kg/mol',
|
||||
p_max = EOS['pmax']*1000.0,
|
||||
p_max_units = 'Pa',
|
||||
pseudo_pure = 'XXX TO BE FILLED IN XXX'
|
||||
base = dict(BibTeX_CP0="",
|
||||
BibTeX_EOS="XXXX TO BE FILLED IN XXX",
|
||||
STATES=build_states(),
|
||||
T_max=EOS['Tmax'],
|
||||
T_max_units='K',
|
||||
Ttriple=EOS['Tt'],
|
||||
Ttriple_units='K',
|
||||
acentric=EOS['acentric'],
|
||||
acentric_units='-',
|
||||
alpha0=build_alpha0(ALPHA0),
|
||||
alphar=EOS['alphar'],
|
||||
gas_constant=EOS['R'],
|
||||
gas_constant_units='J/mol/K',
|
||||
molar_mass=EOS['MW'] / 1000.0,
|
||||
molar_mass_units='kg/mol',
|
||||
p_max=EOS['pmax'] * 1000.0,
|
||||
p_max_units='Pa',
|
||||
pseudo_pure='XXX TO BE FILLED IN XXX'
|
||||
)
|
||||
|
||||
with open(json_file, 'w') as fp:
|
||||
json.dump(base, fp, indent = 2, sort_keys = True)
|
||||
json.dump(base, fp, indent=2, sort_keys=True)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
EOS = extract_active_EOS('/Users/ian/Downloads/MDM.FLD')
|
||||
ALPHA0 = []
|
||||
write(EOS, ALPHA0, 'MDM.json')
|
||||
|
||||
@@ -2,68 +2,68 @@ from __future__ import division
|
||||
from CoolProp.CoolProp import Props, DerivTerms
|
||||
|
||||
|
||||
def finite_diff(Output,Input1,Val1,Input2,Val2,Fluid, index,deriv,order,type = 'centered',dx = 1e-3):
|
||||
def finite_diff(Output, Input1, Val1, Input2, Val2, Fluid, index, deriv, order, type='centered', dx=1e-3):
|
||||
def f(index, dx):
|
||||
if index == 1:
|
||||
return Props(Output,Input1,Val1+dx,Input2,Val2,Fluid)
|
||||
return Props(Output, Input1, Val1 + dx, Input2, Val2, Fluid)
|
||||
else:
|
||||
return Props(Output,Input1,Val1,Input2,Val2+dx,Fluid)
|
||||
return Props(Output, Input1, Val1, Input2, Val2 + dx, Fluid)
|
||||
|
||||
if deriv == 1:
|
||||
if order == 1:
|
||||
return (f(index,dx)-f(index,0))/(dx)
|
||||
return (f(index, dx) - f(index, 0)) / (dx)
|
||||
elif order == 2:
|
||||
return (f(index,dx)-f(index,-dx))/(2*dx)
|
||||
return (f(index, dx) - f(index, -dx)) / (2 * dx)
|
||||
elif order == 4:
|
||||
return (f(index,-2*dx)-8*f(index,-dx)+8*f(index,dx)-f(index,2*dx))/(12*dx)
|
||||
return (f(index, -2 * dx) - 8 * f(index, -dx) + 8 * f(index, dx) - f(index, 2 * dx)) / (12 * dx)
|
||||
elif deriv == 2:
|
||||
if order == 2:
|
||||
return (f(index,-dx)-2*f(index,0)+f(index,dx))/(dx**2)
|
||||
return (f(index, -dx) - 2 * f(index, 0) + f(index, dx)) / (dx**2)
|
||||
elif order == 4:
|
||||
return (-f(index,-2*dx)+16*f(index,-dx)-30*f(index,0)+16*f(index,dx)-f(index,2*dx))/(12*dx**2)
|
||||
return (-f(index, -2 * dx) + 16 * f(index, -dx) - 30 * f(index, 0) + 16 * f(index, dx) - f(index, 2 * dx)) / (12 * dx**2)
|
||||
else:
|
||||
raise ValueError
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
## fluid = 'Water'
|
||||
## T = 647.74374374374372#647#Props(fluid,'Tcrit')+1
|
||||
## rho = 322.32199999#358#Props(fluid,'rhocrit')+1
|
||||
# T = 647.74374374374372#647#Props(fluid,'Tcrit')+1
|
||||
# rho = 322.32199999#358#Props(fluid,'rhocrit')+1
|
||||
## H = Props('H','T',T,'D',rho,fluid)
|
||||
## P = Props('P','T',T,'D',rho,fluid)
|
||||
## print T,rho,H,P
|
||||
# print T,rho,H,P
|
||||
|
||||
|
||||
fluid = 'R125'
|
||||
T = 300
|
||||
rho = 1.5
|
||||
H = Props('H','T',T,'D',rho,fluid)
|
||||
P = Props('P','T',T,'D',rho,fluid)
|
||||
print("%s %s %s %s" % (T,rho,H,P))
|
||||
H = Props('H', 'T', T, 'D', rho, fluid)
|
||||
P = Props('P', 'T', T, 'D', rho, fluid)
|
||||
print("%s %s %s %s" % (T, rho, H, P))
|
||||
|
||||
dpdT__rho = DerivTerms('dpdT|rho',T,rho,fluid)
|
||||
dpdrho__T = DerivTerms('dpdrho|T',T,rho,fluid)
|
||||
dhdT__rho = DerivTerms('dhdT|rho',T,rho,fluid)
|
||||
dhdrho__T = DerivTerms('dhdrho|T',T,rho,fluid)
|
||||
dpdT__rho = DerivTerms('dpdT|rho', T, rho, fluid)
|
||||
dpdrho__T = DerivTerms('dpdrho|T', T, rho, fluid)
|
||||
dhdT__rho = DerivTerms('dhdT|rho', T, rho, fluid)
|
||||
dhdrho__T = DerivTerms('dhdrho|T', T, rho, fluid)
|
||||
print('*******************************************')
|
||||
print('CHECKING DERIVATIVES FROM EOS')
|
||||
print('*******************************************')
|
||||
dpdT__rho_num = finite_diff('P','T',T,'D',rho,fluid,1,1,4)
|
||||
dpdT__rho_num = finite_diff('P', 'T', T, 'D', rho, fluid, 1, 1, 4)
|
||||
print('dpdT|rho')
|
||||
print(dpdT__rho)
|
||||
print(dpdT__rho_num)
|
||||
|
||||
dpdrho__T_num = finite_diff('P','T',T,'D',rho,fluid,2,1,4)
|
||||
dpdrho__T_num = finite_diff('P', 'T', T, 'D', rho, fluid, 2, 1, 4)
|
||||
print('dpdrho|T')
|
||||
print(dpdrho__T)
|
||||
print(dpdrho__T_num)
|
||||
|
||||
dhdT__rho_num = finite_diff('H','T',T,'D',rho,fluid,1,1,4)
|
||||
dhdT__rho_num = finite_diff('H', 'T', T, 'D', rho, fluid, 1, 1, 4)
|
||||
print('dhdT|rho')
|
||||
print(dhdT__rho)
|
||||
print(dhdT__rho_num)
|
||||
|
||||
dhdrho__T_num = finite_diff('H','T',T,'D',rho,fluid,2,1,4)
|
||||
dhdrho__T_num = finite_diff('H', 'T', T, 'D', rho, fluid, 2, 1, 4)
|
||||
print('dhdrho|T')
|
||||
print(dhdrho__T)
|
||||
print(dhdrho__T_num)
|
||||
@@ -72,139 +72,139 @@ print('*******************************************')
|
||||
print('CHECKING HELMHOLTZ DERIVATIVES')
|
||||
print('*******************************************')
|
||||
dx = 1e-10
|
||||
Tc = Props(fluid,'Tcrit')
|
||||
rhoc = Props(fluid,'rhocrit')
|
||||
delta = rho/rhoc
|
||||
tau = Tc/T
|
||||
Tc = Props(fluid, 'Tcrit')
|
||||
rhoc = Props(fluid, 'rhocrit')
|
||||
delta = rho / rhoc
|
||||
tau = Tc / T
|
||||
|
||||
|
||||
def f(dx):
|
||||
rho = rhoc*(delta+dx)
|
||||
return DerivTerms('dphir_dDelta',T,rho,fluid)
|
||||
rho = rhoc * (delta + dx)
|
||||
return DerivTerms('dphir_dDelta', T, rho, fluid)
|
||||
|
||||
|
||||
print('d2phir_dDelta2')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d2phir_dDelta2',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d2phir_dDelta2', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
rho = rhoc*(delta+dx)
|
||||
return DerivTerms('d2phir_dDelta2',T,rho,fluid)
|
||||
rho = rhoc * (delta + dx)
|
||||
return DerivTerms('d2phir_dDelta2', T, rho, fluid)
|
||||
|
||||
|
||||
print('d3phir_dDelta3')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d3phir_dDelta3',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d3phir_dDelta3', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
rho = rhoc*(delta+dx)
|
||||
return DerivTerms('dphir_dTau',T,rho,fluid)
|
||||
rho = rhoc * (delta + dx)
|
||||
return DerivTerms('dphir_dTau', T, rho, fluid)
|
||||
|
||||
|
||||
print('d2phir_dDelta_dTau')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d2phir_dDelta_dTau',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d2phir_dDelta_dTau', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
rho = rhoc*(delta+dx)
|
||||
return DerivTerms('d2phir_dTau2',T,rho,fluid)
|
||||
rho = rhoc * (delta + dx)
|
||||
return DerivTerms('d2phir_dTau2', T, rho, fluid)
|
||||
|
||||
|
||||
print('d3phir_dDelta_dTau2')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d3phir_dDelta_dTau2',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d3phir_dDelta_dTau2', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
T = Tc/(tau+dx)
|
||||
return DerivTerms('d2phir_dDelta2',T,rho,fluid)
|
||||
T = Tc / (tau + dx)
|
||||
return DerivTerms('d2phir_dDelta2', T, rho, fluid)
|
||||
|
||||
|
||||
print('d3phir_dDelta2_dTau')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d3phir_dDelta2_dTau',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d3phir_dDelta2_dTau', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
T = Tc/(tau+dx)
|
||||
return DerivTerms('dphir_dTau',T,rho,fluid)
|
||||
T = Tc / (tau + dx)
|
||||
return DerivTerms('dphir_dTau', T, rho, fluid)
|
||||
|
||||
|
||||
print('d2phir_dTau2')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d2phir_dTau2',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d2phir_dTau2', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
T = Tc/(tau+dx)
|
||||
return DerivTerms('d2phir_dTau2',T,rho,fluid)
|
||||
T = Tc / (tau + dx)
|
||||
return DerivTerms('d2phir_dTau2', T, rho, fluid)
|
||||
|
||||
|
||||
print('d3phir_dTau3')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d3phir_dTau3',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d3phir_dTau3', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
T = Tc/(tau+dx)
|
||||
return DerivTerms('dphi0_dTau',T,rho,fluid)
|
||||
T = Tc / (tau + dx)
|
||||
return DerivTerms('dphi0_dTau', T, rho, fluid)
|
||||
|
||||
|
||||
print('d2phi0_dTau2')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d2phi0_dTau2',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d2phi0_dTau2', T, rho, fluid))
|
||||
|
||||
|
||||
def f(dx):
|
||||
T = Tc/(tau+dx)
|
||||
return DerivTerms('d2phi0_dTau2',T,rho,fluid)
|
||||
T = Tc / (tau + dx)
|
||||
return DerivTerms('d2phi0_dTau2', T, rho, fluid)
|
||||
|
||||
|
||||
print('d3phi0_dTau3')
|
||||
print((f(-2*dx)-8*f(-dx)+8*f(dx)-f(2*dx))/(12*dx))
|
||||
print(DerivTerms('d3phi0_dTau3',T,rho,fluid))
|
||||
print((f(-2 * dx) - 8 * f(-dx) + 8 * f(dx) - f(2 * dx)) / (12 * dx))
|
||||
print(DerivTerms('d3phi0_dTau3', T, rho, fluid))
|
||||
print("")
|
||||
print('*******************************************')
|
||||
print('CHECKING FIRST DERIVATIVES OF PROPERTIES')
|
||||
print('*******************************************')
|
||||
|
||||
A = dpdT__rho*dhdrho__T-dpdrho__T*dhdT__rho
|
||||
A = dpdT__rho * dhdrho__T - dpdrho__T * dhdT__rho
|
||||
|
||||
dT_dh_num = finite_diff('T','H',H,'P',P,fluid,1,1,4)
|
||||
dT_dh = 1/Props('C','T',T,'D',rho,fluid)
|
||||
dT_dh_num = finite_diff('T', 'H', H, 'P', P, fluid, 1, 1, 4)
|
||||
dT_dh = 1 / Props('C', 'T', T, 'D', rho, fluid)
|
||||
print('dTdh|p')
|
||||
print(dT_dh)
|
||||
print(dT_dh_num)
|
||||
|
||||
dT_dp_num = finite_diff('T','H',H,'P',P,fluid,2,1,4)
|
||||
dT_dp = 1/A*dhdrho__T
|
||||
dT_dp_num = finite_diff('T', 'H', H, 'P', P, fluid, 2, 1, 4)
|
||||
dT_dp = 1 / A * dhdrho__T
|
||||
print('dTdp|h')
|
||||
print(dT_dp)
|
||||
print(dT_dp_num)
|
||||
|
||||
drho_dh_num = finite_diff('D','H',H,'P',P,fluid,1,1,4)
|
||||
drho_dh = 1/A*dpdT__rho
|
||||
drho_dh_num = finite_diff('D', 'H', H, 'P', P, fluid, 1, 1, 4)
|
||||
drho_dh = 1 / A * dpdT__rho
|
||||
print('drhodh|p')
|
||||
print(drho_dh_num)
|
||||
print(drho_dh_num)
|
||||
|
||||
drho_dp_num = finite_diff('D','H',H,'P',P,fluid,2,1,4)
|
||||
drho_dp = -1/A*dhdT__rho
|
||||
drho_dp_num = finite_diff('D', 'H', H, 'P', P, fluid, 2, 1, 4)
|
||||
drho_dp = -1 / A * dhdT__rho
|
||||
print('drhodp|h')
|
||||
print(drho_dp)
|
||||
print(drho_dp_num)
|
||||
|
||||
ds_dh_num = finite_diff('S','H',H,'P',P,fluid,1,1,4)
|
||||
ds_dh = 1/T
|
||||
ds_dh_num = finite_diff('S', 'H', H, 'P', P, fluid, 1, 1, 4)
|
||||
ds_dh = 1 / T
|
||||
print('dsdh|p')
|
||||
print(ds_dh)
|
||||
print(ds_dh_num)
|
||||
|
||||
ds_dp_num = finite_diff('S','H',H,'P',P,fluid,2,1,4)
|
||||
ds_dp = -1/(T*rho)
|
||||
ds_dp_num = finite_diff('S', 'H', H, 'P', P, fluid, 2, 1, 4)
|
||||
ds_dp = -1 / (T * rho)
|
||||
print('dsdp|h')
|
||||
print(ds_dp)
|
||||
print(ds_dp_num)
|
||||
@@ -217,29 +217,29 @@ print('*******************************************')
|
||||
|
||||
## d2T_dh2_num = finite_diff('T','H',H,'P',P,fluid,1,2,4)
|
||||
## d2T_dh2 = 1/Props('C','T',T,'D',rho,fluid)
|
||||
## print 'dTdh|p'
|
||||
## print dT_dh
|
||||
## print dT_dh_num
|
||||
# print 'dTdh|p'
|
||||
# print dT_dh
|
||||
# print dT_dh_num
|
||||
|
||||
d2s_dh2 = -(1/T/T)*dT_dh
|
||||
d2s_dh2_num = finite_diff('S','H',H,'P',P,fluid,1,2,4,dx = 10)
|
||||
d2s_dh2 = -(1 / T / T) * dT_dh
|
||||
d2s_dh2_num = finite_diff('S', 'H', H, 'P', P, fluid, 1, 2, 4, dx=10)
|
||||
print('d2sdh2|p')
|
||||
print(d2s_dh2)
|
||||
print(d2s_dh2_num)
|
||||
|
||||
d2s_dp2 = 1/(T**2*rho)*dT_dp+1/(T*rho**2)*drho_dp
|
||||
d2s_dp2_num = finite_diff('S','H',H,'P',P,fluid,2,2,4,dx = 10)
|
||||
d2s_dp2 = 1 / (T**2 * rho) * dT_dp + 1 / (T * rho**2) * drho_dp
|
||||
d2s_dp2_num = finite_diff('S', 'H', H, 'P', P, fluid, 2, 2, 4, dx=10)
|
||||
print('d2sdp2|h')
|
||||
print(d2s_dp2)
|
||||
print(d2s_dp2_num)
|
||||
|
||||
d2s_dhdp = -(1/T/T)*dT_dp
|
||||
d2s_dhdp_num = finite_diff('S','H',H,'P',P,fluid,1,2,4)
|
||||
d2s_dhdp = -(1 / T / T) * dT_dp
|
||||
d2s_dhdp_num = finite_diff('S', 'H', H, 'P', P, fluid, 1, 2, 4)
|
||||
print('d2s_dhdp')
|
||||
print(d2s_dhdp)
|
||||
print(d2s_dhdp_num)
|
||||
|
||||
## d2s_dhdp = -(1/T/T)*dT_dp
|
||||
## print d2s_dhdp
|
||||
# print d2s_dhdp
|
||||
## d2s_dhdp = 1/(T**2*rho)*dT_dh+1/(T*rho**2)*drho_dh
|
||||
## print d2s_dhdp
|
||||
# print d2s_dhdp
|
||||
|
||||
@@ -7,25 +7,25 @@ import codecs
|
||||
|
||||
def tee_call(call, file, **kwargs):
|
||||
callee = subprocess.Popen(call,
|
||||
stdout = subprocess.PIPE,
|
||||
stderr = subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
**kwargs)
|
||||
stdout, stderr = callee.communicate()
|
||||
print(stdout, stderr)
|
||||
file.write(stdout.decode('utf-8'))
|
||||
file.write(stderr.decode('utf-8'))
|
||||
#if callee.poll() != 0:
|
||||
# if callee.poll() != 0:
|
||||
# raise ValueError('Return code is non-zero')
|
||||
|
||||
|
||||
def copyfiles(lang, ext):
|
||||
shutil.copy2(lang+'/Example.'+ext,'../../../Web/coolprop/wrappers/'+lang+'/Example.'+ext)
|
||||
shutil.copy2(lang+'/Example.out','../../../Web/coolprop/wrappers/'+lang+'/Example.out')
|
||||
shutil.copy2(lang + '/Example.' + ext, '../../../Web/coolprop/wrappers/' + lang + '/Example.' + ext)
|
||||
shutil.copy2(lang + '/Example.out', '../../../Web/coolprop/wrappers/' + lang + '/Example.out')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
|
||||
#C++
|
||||
# C++
|
||||
#kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True)
|
||||
#subprocess.check_call('cmake ../../../.. -DCOOLPROP_MY_MAIN=Example.cpp -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
#subprocess.check_call('cmake --build .', **kwargs)
|
||||
@@ -34,51 +34,51 @@ if __name__=='__main__':
|
||||
P = Python()
|
||||
code = P.parse()
|
||||
P.write('Python/Example.py', code)
|
||||
with codecs.open('Python/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call('python Example.py', fp, shell = True, cwd = 'Python')
|
||||
copyfiles('Python','py')
|
||||
with codecs.open('Python/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call('python Example.py', fp, shell=True, cwd='Python')
|
||||
copyfiles('Python', 'py')
|
||||
|
||||
if not os.path.exists('Octave'): os.mkdir('Octave')
|
||||
O = Octave()
|
||||
O.write('Octave/Example.m', O.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'Octave')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='Octave')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_OCTAVE_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
with codecs.open('Octave/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'octave Example.m', fp, shell = True, cwd = 'Octave')
|
||||
copyfiles('Octave','m')
|
||||
with codecs.open('Octave/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'octave Example.m', fp, shell=True, cwd='Octave')
|
||||
copyfiles('Octave', 'm')
|
||||
|
||||
if not os.path.exists('Java'): os.mkdir('Java')
|
||||
J = Java()
|
||||
J.write('Java/Example.java', J.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'Java')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='Java')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_JAVA_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
subprocess.check_call(r'javac *.java', **kwargs)
|
||||
with codecs.open('Java/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'java Example', fp, shell = True, cwd = 'Java')
|
||||
copyfiles('Java','java')
|
||||
with codecs.open('Java/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'java Example', fp, shell=True, cwd='Java')
|
||||
copyfiles('Java', 'java')
|
||||
|
||||
if not os.path.exists('Csharp'): os.mkdir('Csharp')
|
||||
C = Csharp()
|
||||
C.write('Csharp/Example.cs', C.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'Csharp')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='Csharp')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_CSHARP_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
subprocess.check_call(r'mcs -out:Example *.cs', **kwargs)
|
||||
with codecs.open('Csharp/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'mono Example', fp, shell = True, cwd = 'Csharp')
|
||||
copyfiles('Csharp','cs')
|
||||
with codecs.open('Csharp/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'mono Example', fp, shell=True, cwd='Csharp')
|
||||
copyfiles('Csharp', 'cs')
|
||||
|
||||
if not os.path.exists('R'): os.mkdir('R')
|
||||
RR = R()
|
||||
RR.write('R/Example.R', RR.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'R')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='R')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_R_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON -DR_BIN=/usr/bin', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
with codecs.open('R/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'DYLD_LIBRARY_PATH=/opt/refprop Rscript Example.R', fp, shell = True, cwd = 'R')
|
||||
copyfiles('R','R')
|
||||
with codecs.open('R/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'DYLD_LIBRARY_PATH=/opt/refprop Rscript Example.R', fp, shell=True, cwd='R')
|
||||
copyfiles('R', 'R')
|
||||
|
||||
#if not os.path.exists('MATLAB'): os.mkdir('MATLAB')
|
||||
#M = MATLAB()
|
||||
@@ -87,4 +87,4 @@ if __name__=='__main__':
|
||||
#subprocess.check_call('PATH=${HOME}/swig-matlab/bin:$PATH cmake ../../../.. -DCOOLPROP_MATLAB_SWIG_MODULE=ON -DSWIG_DIR=${HOME}/swig-matlab/bin -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
#subprocess.check_call('PATH=${HOME}/swig-matlab/bin:$PATH cmake --build .', **kwargs)
|
||||
#retcode = subprocess.call('matlab -nosplash -nojvm -nodesktop -nodisplay -r "result = runtests(\'Example\'); exit(result.Failed)" -logfile Example.out', shell = True, cwd = 'MATLAB')
|
||||
#copyfiles('MATLAB','m')
|
||||
# copyfiles('MATLAB','m')
|
||||
|
||||
@@ -7,25 +7,25 @@ import codecs
|
||||
|
||||
def tee_call(call, file, **kwargs):
|
||||
callee = subprocess.Popen(call,
|
||||
stdout = subprocess.PIPE,
|
||||
stderr = subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
**kwargs)
|
||||
stdout, stderr = callee.communicate()
|
||||
print(stdout, stderr)
|
||||
file.write(stdout.decode('utf-8'))
|
||||
file.write(stderr.decode('utf-8'))
|
||||
#if callee.poll() != 0:
|
||||
# if callee.poll() != 0:
|
||||
# raise ValueError('Return code is non-zero')
|
||||
|
||||
|
||||
def copyfiles(lang, ext):
|
||||
shutil.copy2(lang+'/Example.'+ext,'../../../Web/coolprop/wrappers/'+lang+'/Example.'+ext)
|
||||
shutil.copy2(lang+'/Example.out','../../../Web/coolprop/wrappers/'+lang+'/Example.out')
|
||||
shutil.copy2(lang + '/Example.' + ext, '../../../Web/coolprop/wrappers/' + lang + '/Example.' + ext)
|
||||
shutil.copy2(lang + '/Example.out', '../../../Web/coolprop/wrappers/' + lang + '/Example.out')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
|
||||
#C++
|
||||
# C++
|
||||
#kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True)
|
||||
#subprocess.check_call('cmake ../../../.. -DCOOLPROP_MY_MAIN=Example.cpp -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
#subprocess.check_call('cmake --build .', **kwargs)
|
||||
@@ -34,51 +34,51 @@ if __name__=='__main__':
|
||||
P = Python()
|
||||
code = P.parse()
|
||||
P.write('Python/Example.py', code)
|
||||
with codecs.open('Python/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call('python Example.py', fp, shell = True, cwd = 'Python')
|
||||
copyfiles('Python','py')
|
||||
with codecs.open('Python/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call('python Example.py', fp, shell=True, cwd='Python')
|
||||
copyfiles('Python', 'py')
|
||||
|
||||
if not os.path.exists('Octave'): os.mkdir('Octave')
|
||||
O = Octave()
|
||||
O.write('Octave/Example.m', O.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'Octave')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='Octave')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_OCTAVE_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
with codecs.open('Octave/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'octave Example.m', fp, shell = True, cwd = 'Octave')
|
||||
copyfiles('Octave','m')
|
||||
with codecs.open('Octave/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'octave Example.m', fp, shell=True, cwd='Octave')
|
||||
copyfiles('Octave', 'm')
|
||||
|
||||
if not os.path.exists('Java'): os.mkdir('Java')
|
||||
J = Java()
|
||||
J.write('Java/Example.java', J.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'Java')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='Java')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_JAVA_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
subprocess.check_call(r'javac *.java', **kwargs)
|
||||
with codecs.open('Java/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'java Example', fp, shell = True, cwd = 'Java')
|
||||
copyfiles('Java','java')
|
||||
with codecs.open('Java/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'java Example', fp, shell=True, cwd='Java')
|
||||
copyfiles('Java', 'java')
|
||||
|
||||
if not os.path.exists('Csharp'): os.mkdir('Csharp')
|
||||
C = Csharp()
|
||||
C.write('Csharp/Example.cs', C.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'Csharp')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='Csharp')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_CSHARP_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
subprocess.check_call(r'mcs -out:Example *.cs', **kwargs)
|
||||
with codecs.open('Csharp/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'mono Example', fp, shell = True, cwd = 'Csharp')
|
||||
copyfiles('Csharp','cs')
|
||||
with codecs.open('Csharp/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'mono Example', fp, shell=True, cwd='Csharp')
|
||||
copyfiles('Csharp', 'cs')
|
||||
|
||||
if not os.path.exists('R'): os.mkdir('R')
|
||||
RR = R()
|
||||
RR.write('R/Example.R', RR.parse())
|
||||
kwargs = dict(stdout = sys.stdout, stderr = sys.stderr, shell = True, cwd = 'R')
|
||||
kwargs = dict(stdout=sys.stdout, stderr=sys.stderr, shell=True, cwd='R')
|
||||
subprocess.check_call('cmake ../../../.. -DCOOLPROP_R_MODULE=ON -DCMAKE_VERBOSE_MAKEFILE=ON -DR_BIN=/usr/local/bin', **kwargs)
|
||||
subprocess.check_call('cmake --build .', **kwargs)
|
||||
with codecs.open('R/Example.out','w',encoding='utf-8') as fp:
|
||||
tee_call(r'DYLD_LIBRARY_PATH=/opt/refprop Rscript Example.R', fp, shell = True, cwd = 'R')
|
||||
copyfiles('R','R')
|
||||
with codecs.open('R/Example.out', 'w', encoding='utf-8') as fp:
|
||||
tee_call(r'DYLD_LIBRARY_PATH=/opt/refprop Rscript Example.R', fp, shell=True, cwd='R')
|
||||
copyfiles('R', 'R')
|
||||
|
||||
#if not os.path.exists('MATLAB'): os.mkdir('MATLAB')
|
||||
#M = MATLAB()
|
||||
@@ -87,4 +87,4 @@ if __name__=='__main__':
|
||||
#subprocess.check_call('PATH=${HOME}/swig-matlab/bin:$PATH cmake ../../../.. -DCOOLPROP_MATLAB_SWIG_MODULE=ON -DSWIG_DIR=${HOME}/swig-matlab/bin -DCMAKE_VERBOSE_MAKEFILE=ON', **kwargs)
|
||||
#subprocess.check_call('PATH=${HOME}/swig-matlab/bin:$PATH cmake --build .', **kwargs)
|
||||
#retcode = subprocess.call('matlab -nosplash -nojvm -nodesktop -nodisplay -r "result = runtests(\'Example\'); exit(result.Failed)" -logfile Example.out', shell = True, cwd = 'MATLAB')
|
||||
#copyfiles('MATLAB','m')
|
||||
# copyfiles('MATLAB','m')
|
||||
|
||||
@@ -70,7 +70,7 @@ high_level_interface = [
|
||||
{
|
||||
"type": "comment",
|
||||
"comment": "See http://www.coolprop.org/coolprop/HighLevelAPI.html#table-of-string-inputs-to-propssi-function for a list of inputs to high-level interface",
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
@@ -157,7 +157,7 @@ high_level_interface = [
|
||||
"",
|
||||
{
|
||||
"type": "print",
|
||||
"arguments": [ "'*********** HUMID AIR PROPERTIES *****************'" ],
|
||||
"arguments": ["'*********** HUMID AIR PROPERTIES *****************'"],
|
||||
"EOL":True
|
||||
},
|
||||
{
|
||||
@@ -200,7 +200,7 @@ high_level_interface = [
|
||||
"",
|
||||
{
|
||||
"type": "print",
|
||||
"arguments": [ "'*********** INCOMPRESSIBLE FLUID AND BRINES *****************'" ],
|
||||
"arguments": ["'*********** INCOMPRESSIBLE FLUID AND BRINES *****************'"],
|
||||
"EOL":True
|
||||
},
|
||||
{
|
||||
@@ -237,11 +237,11 @@ high_level_interface = [
|
||||
{
|
||||
"type": "comment",
|
||||
"comment": "If you don't have REFPROP installed, disable the following lines",
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
"arguments": [ "'*********** REFPROP *****************'" ],
|
||||
"arguments": ["'*********** REFPROP *****************'"],
|
||||
"EOL":True
|
||||
},
|
||||
{
|
||||
@@ -309,7 +309,7 @@ low_level_interface_with_mixtures = [
|
||||
"",
|
||||
{
|
||||
"type": "print",
|
||||
"arguments": [ "'*********** LOW-LEVEL INTERFACE *****************'" ],
|
||||
"arguments": ["'*********** LOW-LEVEL INTERFACE *****************'"],
|
||||
"EOL":True
|
||||
},
|
||||
{
|
||||
@@ -329,7 +329,7 @@ low_level_interface_with_mixtures = [
|
||||
"type": "custom_assignment",
|
||||
"variable_name": "z",
|
||||
"variable_type": "vector",
|
||||
"RHS":{
|
||||
"RHS": {
|
||||
"type": "vector",
|
||||
"arguments": [
|
||||
"0.5",
|
||||
@@ -365,7 +365,7 @@ low_level_interface_with_mixtures = [
|
||||
"101325", "1"
|
||||
]
|
||||
},
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
@@ -389,11 +389,11 @@ low_level_interface_with_mixtures = [
|
||||
{
|
||||
"type": "comment",
|
||||
"comment": "If you don't have REFPROP installed, disable the following block",
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
"arguments": [ "'*********** LOW-LEVEL INTERFACE (REFPROP) *****************'" ],
|
||||
"arguments": ["'*********** LOW-LEVEL INTERFACE (REFPROP) *****************'"],
|
||||
"EOL":True
|
||||
},
|
||||
{
|
||||
@@ -413,7 +413,7 @@ low_level_interface_with_mixtures = [
|
||||
"type": "custom_assignment",
|
||||
"variable_name": "z2",
|
||||
"variable_type": "vector",
|
||||
"RHS":{
|
||||
"RHS": {
|
||||
"type": "vector",
|
||||
"arguments": [
|
||||
"0.2",
|
||||
@@ -449,7 +449,7 @@ low_level_interface_with_mixtures = [
|
||||
"1", "120"
|
||||
]
|
||||
},
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
@@ -473,7 +473,7 @@ low_level_interface_with_mixtures = [
|
||||
},
|
||||
"'mol/m^3'"
|
||||
],
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
}
|
||||
]
|
||||
|
||||
@@ -481,7 +481,7 @@ low_level_interface = [
|
||||
"",
|
||||
{
|
||||
"type": "print",
|
||||
"arguments": [ "'*********** TABULAR BACKENDS *****************'" ],
|
||||
"arguments": ["'*********** TABULAR BACKENDS *****************'"],
|
||||
"EOL":True
|
||||
},
|
||||
{
|
||||
@@ -512,7 +512,7 @@ low_level_interface = [
|
||||
"101325", "300"
|
||||
]
|
||||
},
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
@@ -534,7 +534,7 @@ low_level_interface = [
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
"arguments": [ "'*********** SATURATION DERIVATIVES (LOW-LEVEL INTERFACE) ***************'" ],
|
||||
"arguments": ["'*********** SATURATION DERIVATIVES (LOW-LEVEL INTERFACE) ***************'"],
|
||||
"EOL":True
|
||||
},
|
||||
{
|
||||
@@ -565,7 +565,7 @@ low_level_interface = [
|
||||
"101325", "0"
|
||||
]
|
||||
},
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
},
|
||||
{
|
||||
"type": "print",
|
||||
@@ -594,7 +594,7 @@ low_level_interface = [
|
||||
},
|
||||
"'Pa/K'"
|
||||
],
|
||||
"EOL":True
|
||||
"EOL": True
|
||||
}
|
||||
]
|
||||
|
||||
@@ -632,8 +632,8 @@ class BaseParser(object):
|
||||
|
||||
class Python(BaseParser):
|
||||
|
||||
function_name_mapping = dict(Props1SI = 'PropsSI',
|
||||
factory = 'AbstractState')
|
||||
function_name_mapping = dict(Props1SI='PropsSI',
|
||||
factory='AbstractState')
|
||||
type_name_mapping = {'vector': None,
|
||||
'AbstractState': None}
|
||||
enum_name_mapping = {'input_pairs': "CoolProp", 'parameters': "CoolProp"}
|
||||
@@ -654,7 +654,7 @@ class Python(BaseParser):
|
||||
if d['type'] == 'comment':
|
||||
return '# ' + d['comment']
|
||||
elif d['type'] == 'function':
|
||||
return self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
return self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
elif d['type'] == 'print':
|
||||
return 'print(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
elif d['type'] == 'vector':
|
||||
@@ -684,16 +684,16 @@ class Python(BaseParser):
|
||||
|
||||
class Octave(BaseParser):
|
||||
|
||||
function_name_mapping = dict(Props1SI = 'CoolProp.Props1SI',
|
||||
PropsSI = 'CoolProp.PropsSI',
|
||||
PhaseSI = 'CoolProp.PhaseSI',
|
||||
HAPropsSI = 'CoolProp.HAPropsSI',
|
||||
get_global_param_string = 'CoolProp.get_global_param_string',
|
||||
factory = 'AbstractState.factory')
|
||||
function_name_mapping = dict(Props1SI='CoolProp.Props1SI',
|
||||
PropsSI='CoolProp.PropsSI',
|
||||
PhaseSI='CoolProp.PhaseSI',
|
||||
HAPropsSI='CoolProp.HAPropsSI',
|
||||
get_global_param_string='CoolProp.get_global_param_string',
|
||||
factory='AbstractState.factory')
|
||||
type_name_mapping = {'vector': None,
|
||||
'AbstractState': None}
|
||||
enum_name_mapping = {'input_pairs': "CoolProp", 'parameters': "CoolProp"}
|
||||
indentation = ' '*0
|
||||
indentation = ' ' * 0
|
||||
|
||||
def parse_arguments(self, arguments):
|
||||
out = []
|
||||
@@ -710,7 +710,7 @@ class Octave(BaseParser):
|
||||
if d['type'] == 'comment':
|
||||
l = '% ' + d['comment']
|
||||
elif d['type'] == 'function':
|
||||
l = self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
l = self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
elif d['type'] == 'print':
|
||||
args = self.parse_arguments(d['arguments'])
|
||||
args = ['num2str(' + arg + ')' for arg in args]
|
||||
@@ -731,8 +731,8 @@ class Octave(BaseParser):
|
||||
|
||||
if d['RHS']['type'] != 'vector':
|
||||
RHS = self.dict2string(d['RHS'])
|
||||
else: # Custom processing for vector assignment
|
||||
pushes = [d['variable_name']+'.push_back(' + arg +');' for arg in d['RHS']['arguments']]
|
||||
else: # Custom processing for vector assignment
|
||||
pushes = [d['variable_name'] + '.push_back(' + arg + ');' for arg in d['RHS']['arguments']]
|
||||
RHS = 'DoubleVector(); ' + ' '.join(pushes)
|
||||
|
||||
l = ' '.join([LHS, '=', RHS])
|
||||
@@ -749,11 +749,11 @@ class Octave(BaseParser):
|
||||
|
||||
class R(BaseParser):
|
||||
|
||||
function_name_mapping = dict(factory = 'AbstractState_factory')
|
||||
function_name_mapping = dict(factory='AbstractState_factory')
|
||||
type_name_mapping = {'vector': None,
|
||||
'AbstractState': None}
|
||||
enum_name_mapping = {'input_pairs': "CoolProp", 'parameters': "CoolProp"}
|
||||
indentation = ' '*0
|
||||
indentation = ' ' * 0
|
||||
|
||||
def parse_arguments(self, arguments):
|
||||
out = []
|
||||
@@ -770,7 +770,7 @@ class R(BaseParser):
|
||||
if d['type'] == 'comment':
|
||||
l = '# ' + d['comment']
|
||||
elif d['type'] == 'function':
|
||||
l = self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
l = self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
elif d['type'] == 'print':
|
||||
args = self.parse_arguments(d['arguments'])
|
||||
l = 'writeLines(paste(' + ', \' \', '.join(args) + '))'
|
||||
@@ -780,7 +780,7 @@ class R(BaseParser):
|
||||
elif d['type'] == 'class_dereference':
|
||||
l = d['name'] + '$' + self.dict2string(d['RHS'])
|
||||
elif d['type'] == 'enum':
|
||||
l = '"' + d['key'] + '"'
|
||||
l = '"' + d['key'] + '"'
|
||||
elif d['type'] == 'custom_assignment':
|
||||
type_name = self.type_name_mapping[d['variable_type']]
|
||||
if type_name:
|
||||
@@ -790,8 +790,8 @@ class R(BaseParser):
|
||||
|
||||
if d['RHS']['type'] != 'vector':
|
||||
RHS = self.dict2string(d['RHS'])
|
||||
else: # Custom processing for vector assignment
|
||||
pushes = [d['variable_name']+' <- ' + arg +';' for arg in d['RHS']['arguments']]
|
||||
else: # Custom processing for vector assignment
|
||||
pushes = [d['variable_name'] + ' <- ' + arg + ';' for arg in d['RHS']['arguments']]
|
||||
RHS = 'c(' + ', '.join([arg for arg in d['RHS']['arguments']]) + ')'
|
||||
|
||||
l = ' '.join([LHS, '=', RHS])
|
||||
@@ -808,12 +808,12 @@ class R(BaseParser):
|
||||
|
||||
class MATLAB(BaseParser):
|
||||
|
||||
function_name_mapping = dict(Props1SI = 'CoolProp.Props1SI',
|
||||
PropsSI = 'CoolProp.PropsSI',
|
||||
PhaseSI = 'CoolProp.PhaseSI',
|
||||
HAPropsSI = 'CoolProp.HAPropsSI',
|
||||
get_global_param_string = 'CoolProp.get_global_param_string',
|
||||
factory = 'CoolProp.AbstractState.factory')
|
||||
function_name_mapping = dict(Props1SI='CoolProp.Props1SI',
|
||||
PropsSI='CoolProp.PropsSI',
|
||||
PhaseSI='CoolProp.PhaseSI',
|
||||
HAPropsSI='CoolProp.HAPropsSI',
|
||||
get_global_param_string='CoolProp.get_global_param_string',
|
||||
factory='CoolProp.AbstractState.factory')
|
||||
enum_name_mapping = {'input_pairs': "CoolProp", 'parameters': "CoolProp"}
|
||||
type_name_mapping = {'vector': None,
|
||||
'AbstractState': None}
|
||||
@@ -834,7 +834,7 @@ class MATLAB(BaseParser):
|
||||
if d['type'] == 'comment':
|
||||
l = '% ' + d['comment']
|
||||
elif d['type'] == 'function':
|
||||
l = self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
l = self.map_function(d['function']) + '(' + ', '.join(self.parse_arguments(d['arguments'])) + ')'
|
||||
elif d['type'] == 'print':
|
||||
args = self.parse_arguments(d['arguments'])
|
||||
args = ['num2str(' + arg + ')' for arg in args]
|
||||
@@ -855,8 +855,8 @@ class MATLAB(BaseParser):
|
||||
# Custom processing for vector assignment
|
||||
if d['RHS']['type'] != 'vector':
|
||||
RHS = self.dict2string(d['RHS'])
|
||||
else: #vector
|
||||
pushes = [d['variable_name']+'.push_back(' + arg +');' for arg in d['RHS']['arguments']]
|
||||
else: # vector
|
||||
pushes = [d['variable_name'] + '.push_back(' + arg + ');' for arg in d['RHS']['arguments']]
|
||||
RHS = 'CoolProp.DoubleVector(); ' + ' '.join(pushes)
|
||||
|
||||
l = ' '.join([LHS, '=', RHS])
|
||||
@@ -873,16 +873,16 @@ class MATLAB(BaseParser):
|
||||
|
||||
class Java(BaseParser):
|
||||
|
||||
function_name_mapping = dict(Props1SI = 'CoolProp.Props1SI',
|
||||
PropsSI = 'CoolProp.PropsSI',
|
||||
PhaseSI = 'CoolProp.PhaseSI',
|
||||
HAPropsSI = 'CoolProp.HAPropsSI',
|
||||
get_global_param_string = 'CoolProp.get_global_param_string',
|
||||
factory = 'AbstractState.factory')
|
||||
function_name_mapping = dict(Props1SI='CoolProp.Props1SI',
|
||||
PropsSI='CoolProp.PropsSI',
|
||||
PhaseSI='CoolProp.PhaseSI',
|
||||
HAPropsSI='CoolProp.HAPropsSI',
|
||||
get_global_param_string='CoolProp.get_global_param_string',
|
||||
factory='AbstractState.factory')
|
||||
type_name_mapping = {'vector': 'DoubleVector',
|
||||
'AbstractState': 'AbstractState'}
|
||||
enum_name_mapping = {'input_pairs': "input_pairs", 'parameters': "parameters"}
|
||||
indentation = ' '*8
|
||||
indentation = ' ' * 8
|
||||
|
||||
def parse_arguments(self, arguments):
|
||||
out = []
|
||||
@@ -917,8 +917,8 @@ class Java(BaseParser):
|
||||
|
||||
if d['RHS']['type'] != 'vector':
|
||||
RHS = self.dict2string(d['RHS'])
|
||||
else: # Custom processing for vector assignment
|
||||
pushes = [d['variable_name']+'.add(' + arg +');' for arg in d['RHS']['arguments']]
|
||||
else: # Custom processing for vector assignment
|
||||
pushes = [d['variable_name'] + '.add(' + arg + ');' for arg in d['RHS']['arguments']]
|
||||
RHS = 'new DoubleVector(); ' + ' '.join(pushes)
|
||||
|
||||
l = ' '.join([LHS, '=', RHS])
|
||||
@@ -939,16 +939,16 @@ class Java(BaseParser):
|
||||
|
||||
class Csharp(BaseParser):
|
||||
|
||||
function_name_mapping = dict(Props1SI = 'CoolProp.Props1SI',
|
||||
PropsSI = 'CoolProp.PropsSI',
|
||||
PhaseSI = 'CoolProp.PhaseSI',
|
||||
HAPropsSI = 'CoolProp.HAPropsSI',
|
||||
get_global_param_string = 'CoolProp.get_global_param_string',
|
||||
factory = 'AbstractState.factory')
|
||||
function_name_mapping = dict(Props1SI='CoolProp.Props1SI',
|
||||
PropsSI='CoolProp.PropsSI',
|
||||
PhaseSI='CoolProp.PhaseSI',
|
||||
HAPropsSI='CoolProp.HAPropsSI',
|
||||
get_global_param_string='CoolProp.get_global_param_string',
|
||||
factory='AbstractState.factory')
|
||||
type_name_mapping = {'vector': "DoubleVector",
|
||||
'AbstractState': 'AbstractState'}
|
||||
enum_name_mapping = {'input_pairs': "input_pairs", 'parameters': "parameters"}
|
||||
indentation = ' '*12
|
||||
indentation = ' ' * 12
|
||||
|
||||
def parse_arguments(self, arguments):
|
||||
out = []
|
||||
@@ -996,7 +996,7 @@ class Csharp(BaseParser):
|
||||
return '\n }\n }\n}'
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
@@ -4,36 +4,36 @@ import requests
|
||||
|
||||
|
||||
def DownloadFile(url, outdir):
|
||||
fname = url.rsplit('/',1)[1]
|
||||
fname = url.rsplit('/', 1)[1]
|
||||
r = requests.get(url)
|
||||
f = open(os.path.join(outdir, fname), 'wb')
|
||||
for chunk in r.iter_content(chunk_size=512 * 1024):
|
||||
if chunk: # filter out keep-alive new chunks
|
||||
if chunk: # filter out keep-alive new chunks
|
||||
f.write(chunk)
|
||||
f.close()
|
||||
return
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
|
||||
P = Python()
|
||||
code = P.parse()
|
||||
P.write('Example.py', code)
|
||||
subprocess.call(r'python Example.py', stderr = sys.stderr, stdout = sys.stdout, cwd = '.')
|
||||
subprocess.call(r'python Example.py', stderr=sys.stderr, stdout=sys.stdout, cwd='.')
|
||||
|
||||
if not os.path.exists('Octave'): os.mkdir('Octave')
|
||||
O = Octave()
|
||||
code = O.parse()
|
||||
O.write('Octave\Example.m', code)
|
||||
DownloadFile('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/Octave/Octave3.8.2_Windows_32bit/CoolProp.oct', 'Octave')
|
||||
subprocess.call(r'c:\octave-3.8.2\bin\octave Example.m', stderr = sys.stderr, stdout = sys.stdout, cwd = 'Octave')
|
||||
subprocess.call(r'c:\octave-3.8.2\bin\octave Example.m', stderr=sys.stderr, stdout=sys.stdout, cwd='Octave')
|
||||
|
||||
if not os.path.exists('Java'): os.mkdir('Java')
|
||||
J = Java()
|
||||
code = J.parse()
|
||||
J.write('Java\Example.java', code)
|
||||
DownloadFile('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/Java/platform-independent.7z', 'Java')
|
||||
subprocess.call(r'7z platform-independent.7z', stderr = sys.stderr, stdout = sys.stdout, cwd = 'Java')
|
||||
subprocess.call(r'7z platform-independent.7z', stderr=sys.stderr, stdout=sys.stdout, cwd='Java')
|
||||
|
||||
DownloadFile('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/Java/platform-independent.7z', 'Java')
|
||||
|
||||
@@ -42,7 +42,7 @@ if __name__=='__main__':
|
||||
code = C.parse()
|
||||
C.write('Java\Example.cs', code)
|
||||
|
||||
#~ M = MATLAB()
|
||||
#~ code = M.parse()
|
||||
# ~ M = MATLAB()
|
||||
# ~ code = M.parse()
|
||||
#~ M.write('Example.m', code)
|
||||
#~ DownloadFile('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/MATLAB/CoolPropMATLAB_wrap.mexw64', 'Octave')
|
||||
|
||||
@@ -19,7 +19,7 @@ def rsquared(x, y):
|
||||
return r_value**2
|
||||
|
||||
|
||||
def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed = 0.3, fName = None, add_critical = True):
|
||||
def saturation_density(Ref, ClassName, form='A', LV='L', perc_error_allowed=0.3, fName=None, add_critical=True):
|
||||
"""
|
||||
|
||||
Parameters
|
||||
@@ -32,32 +32,32 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
"""
|
||||
|
||||
if fName is None:
|
||||
Tc = Props(Ref,'Tcrit')
|
||||
pc = Props(Ref,'pcrit')
|
||||
rhoc = Props(Ref,'rhocrit')
|
||||
Tmin = Props(Ref,'Tmin')
|
||||
print("%s %s %s" % (Ref,Tmin,Props(Ref,'Ttriple')))
|
||||
Tc = Props(Ref, 'Tcrit')
|
||||
pc = Props(Ref, 'pcrit')
|
||||
rhoc = Props(Ref, 'rhocrit')
|
||||
Tmin = Props(Ref, 'Tmin')
|
||||
print("%s %s %s" % (Ref, Tmin, Props(Ref, 'Ttriple')))
|
||||
|
||||
TT = np.linspace(Tmin, Tc-1, 1000)
|
||||
TT = np.linspace(Tmin, Tc - 1, 1000)
|
||||
TT = list(TT)
|
||||
# Add temperatures around the critical temperature
|
||||
if add_critical:
|
||||
for dT in [1e-10,1e-9,1e-8,1e-7,1e-6,1e-5,1e-4,1e-3,1e-2,1e-1]:
|
||||
TT.append(Tc-dT)
|
||||
for dT in [1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1]:
|
||||
TT.append(Tc - dT)
|
||||
TT = np.array(sorted(TT))
|
||||
|
||||
p = Props('P','T',TT,'Q',0,Ref)
|
||||
rhoL = Props('D','T',TT,'Q',0,Ref)
|
||||
rhoV = Props('D','T',TT,'Q',1,Ref)
|
||||
p = Props('P', 'T', TT, 'Q', 0, Ref)
|
||||
rhoL = Props('D', 'T', TT, 'Q', 0, Ref)
|
||||
rhoV = Props('D', 'T', TT, 'Q', 1, Ref)
|
||||
else:
|
||||
Tc = 423.27
|
||||
pc = 3533
|
||||
rhoc = 470
|
||||
Tmin = 273
|
||||
lines = open(fName,'r').readlines()
|
||||
TT,p,rhoL,rhoV = [],[],[],[]
|
||||
lines = open(fName, 'r').readlines()
|
||||
TT, p, rhoL, rhoV = [], [], [], []
|
||||
for line in lines:
|
||||
_T,_p,_rhoL,_rhoV = line.split(' ')
|
||||
_T, _p, _rhoL, _rhoV = line.split(' ')
|
||||
TT.append(float(_T))
|
||||
p.append(float(_p))
|
||||
rhoL.append(float(_rhoL))
|
||||
@@ -66,9 +66,9 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
TT = np.array(TT)
|
||||
|
||||
# Start with a large library of potential powers
|
||||
n = [i/6.0 for i in range(1,200)]#+[0.35+i/200.0 for i in range(1,70)]+[0.05+0.01*i for i in range(1,70)]
|
||||
n = [i / 6.0 for i in range(1, 200)] # +[0.35+i/200.0 for i in range(1,70)]+[0.05+0.01*i for i in range(1,70)]
|
||||
|
||||
x = 1.0-TT/Tc
|
||||
x = 1.0 - TT / Tc
|
||||
|
||||
if LV == 'L':
|
||||
rho_EOS = rhoL
|
||||
@@ -78,9 +78,9 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
raise ValueError
|
||||
|
||||
if form == 'A':
|
||||
y = np.array(rho_EOS)/rhoc-1
|
||||
y = np.array(rho_EOS) / rhoc - 1
|
||||
elif form == 'B':
|
||||
y = (np.log(rho_EOS)-np.log(rhoc))*TT/Tc
|
||||
y = (np.log(rho_EOS) - np.log(rhoc)) * TT / Tc
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
@@ -91,28 +91,28 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
def f_p(B, x):
|
||||
# B is a vector of the parameters.
|
||||
# x is an array of the current x values.
|
||||
return sum([_B*x**(_n) for _B,_n in zip(B,n)])
|
||||
return sum([_B * x**(_n) for _B, _n in zip(B, n)])
|
||||
|
||||
linear = Model(f_p)
|
||||
mydata = Data(x, y)
|
||||
myodr = ODR(mydata, linear, beta0=[0]*len(n))
|
||||
myodr = ODR(mydata, linear, beta0=[0] * len(n))
|
||||
myoutput = myodr.run()
|
||||
|
||||
beta = myoutput.beta
|
||||
sd = myoutput.sd_beta
|
||||
|
||||
if form == 'A':
|
||||
rho_fit = (f_p(myoutput.beta,x)+1)*rhoc
|
||||
rho_fit = (f_p(myoutput.beta, x) + 1) * rhoc
|
||||
elif form == 'B':
|
||||
rho_fit = np.exp(f_p(myoutput.beta,x)*Tc/TT)*rhoc
|
||||
rho_fit = np.exp(f_p(myoutput.beta, x) * Tc / TT) * rhoc
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
print('first,last %s %s %s %s %s %s' % (TT[0], TT[-1], rho_fit[0], rho_fit[-1], rho_EOS[0], rho_EOS[-1]))
|
||||
|
||||
max_abserror = np.max(np.abs(rho_fit/rho_EOS-1))*100
|
||||
max_abserror = np.max(np.abs(rho_fit / rho_EOS - 1)) * 100
|
||||
|
||||
dropped_indices = [i for i in range(len(n)) if abs(sd[i])<1e-15 ]
|
||||
dropped_indices = [i for i in range(len(n)) if abs(sd[i]) < 1e-15]
|
||||
if dropped_indices:
|
||||
for i in reversed(sorted(dropped_indices)):
|
||||
n.pop(i)
|
||||
@@ -120,7 +120,7 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
continue
|
||||
|
||||
if max_abserror > perc_error_allowed:
|
||||
break # The last good run will be used
|
||||
break # The last good run will be used
|
||||
else:
|
||||
print(max_abserror)
|
||||
Ncoeffs = str(list(myoutput.beta)).lstrip('[').rstrip(']')
|
||||
@@ -134,7 +134,7 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
summer += N[i]*pow(theta,t[i]);
|
||||
}}
|
||||
return reduce.rho*(summer+1);
|
||||
""".format(count = len(n))
|
||||
""".format(count=len(n))
|
||||
)
|
||||
elif form == 'B':
|
||||
code_template = textwrap.dedent(
|
||||
@@ -144,16 +144,16 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
summer += N[i]*pow(theta,t[i]);
|
||||
}}
|
||||
return reduce.rho*exp(reduce.T/T*summer);
|
||||
""".format(count = len(n))
|
||||
""".format(count=len(n))
|
||||
)
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
# Find the least significant entry (the one with the largest relative standard error)
|
||||
# and remove it
|
||||
n.pop(np.argmax(np.abs(sd/beta)))
|
||||
n.pop(np.argmax(np.abs(sd / beta)))
|
||||
|
||||
#Remove elements that are not
|
||||
# Remove elements that are not
|
||||
template = textwrap.dedent(
|
||||
"""
|
||||
double {name:s}Class::rhosat{LV:s}(double T)
|
||||
@@ -166,16 +166,16 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
\t{code:s}
|
||||
}}
|
||||
""")
|
||||
the_string = template.format(tcoeffs = tcoeffs,
|
||||
Ncoeffs = Ncoeffs,
|
||||
name = ClassName,
|
||||
Tmin = Tmin,
|
||||
Tmax = TT[-1],
|
||||
error = maxerror,
|
||||
code = code_template,
|
||||
LV = LV
|
||||
the_string = template.format(tcoeffs=tcoeffs,
|
||||
Ncoeffs=Ncoeffs,
|
||||
name=ClassName,
|
||||
Tmin=Tmin,
|
||||
Tmax=TT[-1],
|
||||
error=maxerror,
|
||||
code=code_template,
|
||||
LV=LV
|
||||
)
|
||||
f = open('anc.txt','a')
|
||||
f = open('anc.txt', 'a')
|
||||
f.write(the_string)
|
||||
f.close()
|
||||
return the_string
|
||||
@@ -183,84 +183,84 @@ def saturation_density(Ref, ClassName, form = 'A', LV = 'L', perc_error_allowed
|
||||
|
||||
def saturation_pressure_brute(Ref, ClassName):
|
||||
|
||||
Tc = Props(Ref,'Tcrit')
|
||||
pc = Props(Ref,'pcrit')
|
||||
rhoc = Props(Ref,'rhocrit')
|
||||
Tmin = Props(Ref,'Tmin')
|
||||
Tc = Props(Ref, 'Tcrit')
|
||||
pc = Props(Ref, 'pcrit')
|
||||
rhoc = Props(Ref, 'rhocrit')
|
||||
Tmin = Props(Ref, 'Tmin')
|
||||
|
||||
TT = np.linspace(Tmin+1e-6, Tc-0.00001, 300)
|
||||
p = np.array([Props('P','T',T,'Q',0,Ref) for T in TT])
|
||||
rhoL = np.array([Props('D','T',T,'Q',0,Ref) for T in TT])
|
||||
rhoV = np.array([Props('D','T',T,'Q',1,Ref) for T in TT])
|
||||
TT = np.linspace(Tmin + 1e-6, Tc - 0.00001, 300)
|
||||
p = np.array([Props('P', 'T', T, 'Q', 0, Ref) for T in TT])
|
||||
rhoL = np.array([Props('D', 'T', T, 'Q', 0, Ref) for T in TT])
|
||||
rhoV = np.array([Props('D', 'T', T, 'Q', 1, Ref) for T in TT])
|
||||
|
||||
Np = 10
|
||||
|
||||
max_abserror = 99999
|
||||
bbest = []
|
||||
|
||||
x = 1.0-TT/Tc
|
||||
y = (np.log(rhoL)-np.log(rhoc))*TT/Tc
|
||||
x = 1.0 - TT / Tc
|
||||
y = (np.log(rhoL) - np.log(rhoc)) * TT / Tc
|
||||
|
||||
def f_p(B, x):
|
||||
# B is a vector of the parameters.
|
||||
# x is an array of the current x values.
|
||||
return sum([_B*x**(_n) for _B,_n in zip(B,b)])
|
||||
return sum([_B * x**(_n) for _B, _n in zip(B, b)])
|
||||
|
||||
linear = Model(f_p)
|
||||
mydata = Data(x, y)
|
||||
|
||||
for attempt in range(300):
|
||||
|
||||
n = [i/6.0 for i in range(1,100)]+[0.35+i/200.0 for i in range(1,70)]+[0.05+0.01*i for i in range(1,70)]
|
||||
n = [i / 6.0 for i in range(1, 100)] + [0.35 + i / 200.0 for i in range(1, 70)] + [0.05 + 0.01 * i for i in range(1, 70)]
|
||||
b = []
|
||||
for _ in range(6):
|
||||
i = random.randint(0,len(n)-1)
|
||||
i = random.randint(0, len(n) - 1)
|
||||
b.append(n.pop(i))
|
||||
|
||||
myodr = ODR(mydata, linear, beta0 = [1]*len(b))
|
||||
myodr = ODR(mydata, linear, beta0=[1] * len(b))
|
||||
myoutput = myodr.run()
|
||||
|
||||
b = np.array(b)
|
||||
|
||||
keepers = np.abs(myoutput.sd_beta/myoutput.beta) < 0.1
|
||||
keepers = np.abs(myoutput.sd_beta / myoutput.beta) < 0.1
|
||||
if any(keepers):
|
||||
b = b[keepers]
|
||||
|
||||
myodr = ODR(mydata, linear, beta0 = [1]*len(b))
|
||||
myodr = ODR(mydata, linear, beta0=[1] * len(b))
|
||||
myoutput = myodr.run()
|
||||
|
||||
rho_fit = np.exp(f_p(myoutput.beta, x)*Tc/TT)*rhoc
|
||||
abserror = np.max(np.abs(rho_fit/rhoL-1))*100
|
||||
rho_fit = np.exp(f_p(myoutput.beta, x) * Tc / TT) * rhoc
|
||||
abserror = np.max(np.abs(rho_fit / rhoL - 1)) * 100
|
||||
print('.')
|
||||
if abserror < max_abserror:
|
||||
max_abserror = abserror
|
||||
bbest = b
|
||||
betabest = myoutput.beta
|
||||
print("%s %s %s" % (abserror, myoutput.sum_square, myoutput.sd_beta/myoutput.beta))
|
||||
print("%s %s %s" % (abserror, myoutput.sum_square, myoutput.sd_beta / myoutput.beta))
|
||||
|
||||
|
||||
def saturation_pressure(Ref, ClassName, fName = None, LV = None):
|
||||
def saturation_pressure(Ref, ClassName, fName=None, LV=None):
|
||||
|
||||
if fName is None:
|
||||
Tc = Props(Ref,'Tcrit')
|
||||
pc = Props(Ref,'pcrit')
|
||||
rhoc = Props(Ref,'rhocrit')
|
||||
Tmin = Props(Ref,'Tmin')
|
||||
Tc = Props(Ref, 'Tcrit')
|
||||
pc = Props(Ref, 'pcrit')
|
||||
rhoc = Props(Ref, 'rhocrit')
|
||||
Tmin = Props(Ref, 'Tmin')
|
||||
|
||||
TT = np.linspace(Tmin+1e-6, Tc-0.00001, 300)
|
||||
pL = Props('P','T',TT,'Q',0,Ref)
|
||||
pV = Props('P','T',TT,'Q',1,Ref)
|
||||
rhoL = Props('D','T',TT,'Q',0,Ref)
|
||||
rhoV = Props('D','T',TT,'Q',1,Ref)
|
||||
TT = np.linspace(Tmin + 1e-6, Tc - 0.00001, 300)
|
||||
pL = Props('P', 'T', TT, 'Q', 0, Ref)
|
||||
pV = Props('P', 'T', TT, 'Q', 1, Ref)
|
||||
rhoL = Props('D', 'T', TT, 'Q', 0, Ref)
|
||||
rhoV = Props('D', 'T', TT, 'Q', 1, Ref)
|
||||
else:
|
||||
Tc = 423.27
|
||||
pc = 3533
|
||||
rhoc = 470
|
||||
Tmin = 273
|
||||
lines = open(fName,'r').readlines()
|
||||
TT,p,rhoL,rhoV = [],[],[],[]
|
||||
lines = open(fName, 'r').readlines()
|
||||
TT, p, rhoL, rhoV = [], [], [], []
|
||||
for line in lines:
|
||||
_T,_p,_rhoL,_rhoV = line.split(' ')
|
||||
_T, _p, _rhoL, _rhoV = line.split(' ')
|
||||
TT.append(float(_T))
|
||||
p.append(float(_p))
|
||||
rhoL.append(float(_rhoL))
|
||||
@@ -269,46 +269,46 @@ def saturation_pressure(Ref, ClassName, fName = None, LV = None):
|
||||
TT = np.array(TT)
|
||||
|
||||
Np = 60
|
||||
n = range(1,Np)
|
||||
n = range(1, Np)
|
||||
max_abserror = 0
|
||||
while len(n) > 3:
|
||||
|
||||
def f_p(B, x):
|
||||
# B is a vector of the parameters.
|
||||
# x is an array of the current x values.
|
||||
return sum([_B*x**(_n/2.0) for _B,_n in zip(B,n)])
|
||||
return sum([_B * x**(_n / 2.0) for _B, _n in zip(B, n)])
|
||||
|
||||
x = 1.0-TT/Tc
|
||||
x = 1.0 - TT / Tc
|
||||
if LV == 'L':
|
||||
y = (np.log(pL)-np.log(pc))*TT/Tc
|
||||
y = (np.log(pL) - np.log(pc)) * TT / Tc
|
||||
elif LV == 'V' or LV is None:
|
||||
y = (np.log(pV)-np.log(pc))*TT/Tc
|
||||
y = (np.log(pV) - np.log(pc)) * TT / Tc
|
||||
|
||||
linear = Model(f_p)
|
||||
mydata = Data(x, y)
|
||||
myodr = ODR(mydata, linear, beta0=[0]*len(n))
|
||||
myodr = ODR(mydata, linear, beta0=[0] * len(n))
|
||||
myoutput = myodr.run()
|
||||
|
||||
beta = myoutput.beta
|
||||
sd = myoutput.sd_beta
|
||||
|
||||
p_fit = np.exp(f_p(myoutput.beta,x)*Tc/TT)*pc
|
||||
p_fit = np.exp(f_p(myoutput.beta, x) * Tc / TT) * pc
|
||||
if LV == 'L':
|
||||
max_abserror = np.max(np.abs((p_fit/pL)-1)*100)
|
||||
max_abserror = np.max(np.abs((p_fit / pL) - 1) * 100)
|
||||
elif LV == 'V' or LV is None:
|
||||
max_abserror = np.max(np.abs((p_fit/pV)-1)*100)
|
||||
max_abserror = np.max(np.abs((p_fit / pV) - 1) * 100)
|
||||
|
||||
print(max_abserror)
|
||||
psat_error = max_abserror
|
||||
|
||||
dropped_indices = [i for i in range(len(n)) if abs(sd[i])<1e-15 ]
|
||||
dropped_indices = [i for i in range(len(n)) if abs(sd[i]) < 1e-15]
|
||||
if dropped_indices:
|
||||
#for i in reversed(dropped_indices):
|
||||
# for i in reversed(dropped_indices):
|
||||
# randomly drop one of them
|
||||
n.pop(random.choice(dropped_indices))
|
||||
continue
|
||||
|
||||
if max_abserror < 0.5: #Max error is 0.5%
|
||||
if max_abserror < 0.5: # Max error is 0.5%
|
||||
Ncoeffs = str(list(myoutput.beta)).lstrip('[').rstrip(']')
|
||||
tcoeffs = str(n).lstrip('[').rstrip(']')
|
||||
maxerror = max_abserror
|
||||
@@ -320,7 +320,7 @@ def saturation_pressure(Ref, ClassName, fName = None, LV = None):
|
||||
# and remove it
|
||||
n.pop(np.argmax(sd))
|
||||
|
||||
#Remove elements that are not
|
||||
# Remove elements that are not
|
||||
import textwrap
|
||||
template = textwrap.dedent(
|
||||
"""
|
||||
@@ -338,28 +338,28 @@ def saturation_pressure(Ref, ClassName, fName = None, LV = None):
|
||||
return reduce.p.Pa*exp(reduce.T/T*summer);
|
||||
}}
|
||||
""")
|
||||
the_string = template.format(N = len(n)+1,
|
||||
tcoeffs = tcoeffs,
|
||||
Ncoeffs = Ncoeffs,
|
||||
name = ClassName,
|
||||
Tmin = Tmin,
|
||||
Tmax = TT[-1],
|
||||
psat_error = maxerror,
|
||||
LV = LV if LV in ['L','V'] else ''
|
||||
the_string = template.format(N=len(n) + 1,
|
||||
tcoeffs=tcoeffs,
|
||||
Ncoeffs=Ncoeffs,
|
||||
name=ClassName,
|
||||
Tmin=Tmin,
|
||||
Tmax=TT[-1],
|
||||
psat_error=maxerror,
|
||||
LV=LV if LV in ['L', 'V'] else ''
|
||||
)
|
||||
|
||||
f = open('anc.txt','a')
|
||||
f = open('anc.txt', 'a')
|
||||
f.write(the_string)
|
||||
f.close()
|
||||
return the_string
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
for RPFluid,Fluid in [('REFPROP-MIX:R32[0.47319469]&R125[0.2051091]&R134a[0.32169621]','R407F'),
|
||||
#for RPFluid,Fluid in [('R11','R11'),
|
||||
for RPFluid, Fluid in [('REFPROP-MIX:R32[0.47319469]&R125[0.2051091]&R134a[0.32169621]', 'R407F'),
|
||||
# for RPFluid,Fluid in [('R11','R11'),
|
||||
]:
|
||||
# saturation_pressure_brute(RPFluid, Fluid
|
||||
# saturation_pressure(RPFluid, Fluid, LV = 'L')
|
||||
# saturation_pressure(RPFluid, Fluid, LV = 'V')
|
||||
saturation_density(RPFluid, Fluid, form='A', LV='L')
|
||||
saturation_density(RPFluid, Fluid, form='B', LV='V', perc_error_allowed = 0.4)
|
||||
saturation_density(RPFluid, Fluid, form='B', LV='V', perc_error_allowed=0.4)
|
||||
|
||||
@@ -15,28 +15,28 @@ fluid = 'DimethylEther'
|
||||
Rfluid = 'REFPROP-DME'
|
||||
e_k = 329.72
|
||||
sigma = 0.5529
|
||||
molemass = CP.Props(fluid,'molemass')
|
||||
molemass = CP.Props(fluid, 'molemass')
|
||||
|
||||
Ttriple = CP.Props(fluid,'Ttriple')
|
||||
Tcrit = CP.Props(fluid,'Tcrit')
|
||||
rhocrit = CP.Props(fluid,'rhocrit')
|
||||
Ttriple = CP.Props(fluid, 'Ttriple')
|
||||
Tcrit = CP.Props(fluid, 'Tcrit')
|
||||
rhocrit = CP.Props(fluid, 'rhocrit')
|
||||
n = 6
|
||||
m = 3
|
||||
NP = 1
|
||||
Nb = 0
|
||||
N = (n-1)*(m+1)+3+Nb
|
||||
N = (n - 1) * (m + 1) + 3 + Nb
|
||||
|
||||
mu,mu_dilute,RHO,TTT = Collector(),Collector(),Collector(),Collector()
|
||||
mu, mu_dilute, RHO, TTT = Collector(), Collector(), Collector(), Collector()
|
||||
|
||||
rhomax = CP.Props('D','T',Ttriple,'Q',0,fluid)
|
||||
#Build a database of "experimental" data
|
||||
for T in np.linspace(Ttriple,Tcrit+30,400):
|
||||
for rho in np.linspace(1e-10,rhomax,400):
|
||||
muval = CP.Props('V','T',T,'D',rho,Rfluid)
|
||||
mudilute = CP.viscosity_dilute(fluid,T,rho,e_k,sigma)
|
||||
rhomax = CP.Props('D', 'T', Ttriple, 'Q', 0, fluid)
|
||||
# Build a database of "experimental" data
|
||||
for T in np.linspace(Ttriple, Tcrit + 30, 400):
|
||||
for rho in np.linspace(1e-10, rhomax, 400):
|
||||
muval = CP.Props('V', 'T', T, 'D', rho, Rfluid)
|
||||
mudilute = CP.viscosity_dilute(fluid, T, rho, e_k, sigma)
|
||||
|
||||
#Want positive value, and single-phase
|
||||
if (muval > 0 and T > Tcrit or rho > CP.rhosatL_anc(fluid,T) or rho < CP.rhosatV_anc(fluid,T)):
|
||||
# Want positive value, and single-phase
|
||||
if (muval > 0 and T > Tcrit or rho > CP.rhosatL_anc(fluid, T) or rho < CP.rhosatV_anc(fluid, T)):
|
||||
mu << muval
|
||||
mu_dilute << mudilute
|
||||
TTT << T
|
||||
@@ -44,74 +44,74 @@ for T in np.linspace(Ttriple,Tcrit+30,400):
|
||||
|
||||
from CoolProp.Plots.Plots import Trho
|
||||
Trho(fluid)
|
||||
plt.plot(RHO.vec,TTT.vec,'.')
|
||||
plt.plot(RHO.vec, TTT.vec, '.')
|
||||
plt.show()
|
||||
|
||||
#tau = np.array(TTT.vec)/Tcrit
|
||||
tau = np.array(TTT.vec)/Tcrit
|
||||
delta = np.array(RHO.vec)/rhocrit
|
||||
Tstar = np.array(TTT.vec)/e_k
|
||||
tau = np.array(TTT.vec) / Tcrit
|
||||
delta = np.array(RHO.vec) / rhocrit
|
||||
Tstar = np.array(TTT.vec) / e_k
|
||||
|
||||
#Define the objective function
|
||||
# Define the objective function
|
||||
|
||||
|
||||
def OBJECTIVE_fit(c,x):
|
||||
tau = x[0,:]
|
||||
delta = x[1,:]
|
||||
#Unpack the inputs into e matrix and f vector
|
||||
e = np.zeros((n+1,m+1))
|
||||
def OBJECTIVE_fit(c, x):
|
||||
tau = x[0, :]
|
||||
delta = x[1, :]
|
||||
# Unpack the inputs into e matrix and f vector
|
||||
e = np.zeros((n + 1, m + 1))
|
||||
|
||||
sum = 0
|
||||
k = 0
|
||||
for i in range(2,n+1):
|
||||
for j in range(0,m+1):
|
||||
for i in range(2, n + 1):
|
||||
for j in range(0, m + 1):
|
||||
e[i][j] = c[k]
|
||||
sum += e[i][j]*delta**i/tau**j
|
||||
sum += e[i][j] * delta**i / tau**j
|
||||
k += 1
|
||||
|
||||
for o in range(0,NP):
|
||||
f1 = c[k+o*3]
|
||||
g1 = c[k+1+o*3]
|
||||
g2 = c[k+2+o*3]
|
||||
for o in range(0, NP):
|
||||
f1 = c[k + o * 3]
|
||||
g1 = c[k + 1 + o * 3]
|
||||
g2 = c[k + 2 + o * 3]
|
||||
|
||||
delta_0 = g1*(1+g2*tau**0.5)
|
||||
sum += f1*(delta/(delta_0-delta)-delta/delta_0)
|
||||
delta_0 = g1 * (1 + g2 * tau**0.5)
|
||||
sum += f1 * (delta / (delta_0 - delta) - delta / delta_0)
|
||||
return sum + np.array(mu_dilute.vec)
|
||||
|
||||
|
||||
print('starting fit')
|
||||
XXX = np.r_[np.array(tau,ndmin = 2), np.array(delta,ndmin=2)]
|
||||
XXX = np.r_[np.array(tau, ndmin=2), np.array(delta, ndmin=2)]
|
||||
mod = Model(OBJECTIVE_fit)
|
||||
mydata = Data(XXX.copy(), np.array(mu.vec))
|
||||
beta0 = [1 for _ in range(N)]
|
||||
beta0 = [1 for _ in range(N)]
|
||||
myodr = ODR(mydata, mod, beta0=beta0)
|
||||
myoutput = myodr.run()
|
||||
myoutput.pprint()
|
||||
print(myoutput.sum_square)
|
||||
YFIT = OBJECTIVE_fit(myoutput.beta,XXX)
|
||||
plt.plot(np.array(mu.vec),YFIT/np.array(mu.vec),'o')
|
||||
YFIT = OBJECTIVE_fit(myoutput.beta, XXX)
|
||||
plt.plot(np.array(mu.vec), YFIT / np.array(mu.vec), 'o')
|
||||
plt.show()
|
||||
|
||||
rel_error = (YFIT)/np.array(mu.vec)-1
|
||||
MAE = np.mean(np.abs(rel_error))*100
|
||||
SSE = np.sum(np.power(YFIT-np.array(mu.vec),2))
|
||||
rel_error = (YFIT) / np.array(mu.vec) - 1
|
||||
MAE = np.mean(np.abs(rel_error)) * 100
|
||||
SSE = np.sum(np.power(YFIT - np.array(mu.vec), 2))
|
||||
print(SSE)
|
||||
|
||||
|
||||
def write_output(c):
|
||||
e = np.zeros((n+1,m+1))
|
||||
e = np.zeros((n + 1, m + 1))
|
||||
k = 0
|
||||
edata = ''
|
||||
for i in range(2,n+1):
|
||||
for i in range(2, n + 1):
|
||||
erow = ''
|
||||
for j in range(0,m+1):
|
||||
for j in range(0, m + 1):
|
||||
e[i][j] = c[k]
|
||||
erow += 'e[{i:d}][{j:d}] = {val:0.16g}; '.format(val = e[i][j],i=i,j=j)
|
||||
erow += 'e[{i:d}][{j:d}] = {val:0.16g}; '.format(val=e[i][j], i=i, j=j)
|
||||
k += 1
|
||||
edata += erow + '\n'
|
||||
f1 = c[k]
|
||||
g1 = c[k+1]
|
||||
g2 = c[k+2]
|
||||
g1 = c[k + 1]
|
||||
g2 = c[k + 2]
|
||||
|
||||
template = textwrap.dedent(
|
||||
"""
|
||||
@@ -156,14 +156,14 @@ def write_output(c):
|
||||
"""
|
||||
)
|
||||
|
||||
values = dict(f1 = f1,
|
||||
g1 = g1,
|
||||
g2 = g2,
|
||||
n = n,
|
||||
m = m,
|
||||
name = fluid,
|
||||
edata = edata,
|
||||
MAE = MAE)
|
||||
values = dict(f1=f1,
|
||||
g1=g1,
|
||||
g2=g2,
|
||||
n=n,
|
||||
m=m,
|
||||
name=fluid,
|
||||
edata=edata,
|
||||
MAE=MAE)
|
||||
|
||||
print(template.format(**values))
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import CoolProp
|
||||
import numpy as np
|
||||
import scipy.optimize
|
||||
import xalglib
|
||||
import os,sys
|
||||
import os, sys
|
||||
|
||||
|
||||
def fit_rational_polynomial(x, y, xfine, n, d):
|
||||
@@ -18,34 +18,34 @@ def fit_rational_polynomial(x, y, xfine, n, d):
|
||||
"""
|
||||
The objective function to be minimized
|
||||
"""
|
||||
A = AB[0:n+1]
|
||||
B = list(AB[n+1::])+[0]
|
||||
yfit = np.polyval(A,x)/(1+np.polyval(B,x))
|
||||
A = AB[0:n + 1]
|
||||
B = list(AB[n + 1::]) + [0]
|
||||
yfit = np.polyval(A, x) / (1 + np.polyval(B, x))
|
||||
return yfit
|
||||
|
||||
if d != 1:
|
||||
# n+d+1 coefficients to be solved for, select to distribute randomly
|
||||
indices = np.array(np.linspace(0,len(x)-1,n+d+1), dtype = int)
|
||||
indices = np.array(np.linspace(0, len(x) - 1, n + d + 1), dtype=int)
|
||||
xlin = x[indices]
|
||||
ylin = y[indices]
|
||||
|
||||
# Solve the linear problem where Lx=R where R is the vector y, x are the unknowns A and B joined together, and L is the set of column vectors
|
||||
# L = [x^n, ... , x^1, 1, x^n, -x^d*y, ..., -x*y]
|
||||
R = ylin[:]
|
||||
L = np.ones((n+d+1,n+d+1))
|
||||
for i in range(0,n+1):
|
||||
L[:,i] = xlin**(n-i)
|
||||
for j in range(0,d):
|
||||
L[:,n+1+j] = -xlin**(d-j)*ylin
|
||||
L = np.ones((n + d + 1, n + d + 1))
|
||||
for i in range(0, n + 1):
|
||||
L[:, i] = xlin**(n - i)
|
||||
for j in range(0, d):
|
||||
L[:, n + 1 + j] = -xlin**(d - j) * ylin
|
||||
|
||||
ABlin = np.linalg.solve(L, R)
|
||||
A = ABlin[0:n+1]
|
||||
B = list(ABlin[n+1::])+[0]
|
||||
yfitlin = np.polyval(A,x)/(1+np.polyval(B, x))
|
||||
A = ABlin[0:n + 1]
|
||||
B = list(ABlin[n + 1::]) + [0]
|
||||
yfitlin = np.polyval(A, x) / (1 + np.polyval(B, x))
|
||||
|
||||
AB = scipy.optimize.curve_fit(obj, x, y, p0 = ABlin)[0]
|
||||
AB = scipy.optimize.curve_fit(obj, x, y, p0=ABlin)[0]
|
||||
|
||||
poles = np.roots(list(AB[n+1::])+[1])
|
||||
poles = np.roots(list(AB[n + 1::]) + [1])
|
||||
poles = poles[np.isreal(poles)]
|
||||
poles = poles[poles > min(x)]
|
||||
poles = poles[poles < max(x)]
|
||||
@@ -53,28 +53,28 @@ def fit_rational_polynomial(x, y, xfine, n, d):
|
||||
else:
|
||||
# Find a pole that is not in the range of x
|
||||
def obj2(Tpole, x, y, AB):
|
||||
B = -1/Tpole
|
||||
A = np.polyfit(x, y*(x*B+1), n)
|
||||
yfit = np.polyval(A, x)/(x*B + 1)
|
||||
AB[:] = list(A) + [B] # Set so that it uses the AB passed in rather than making local variable
|
||||
rms = np.sqrt(np.sum(np.power(yfit-y, 2)))
|
||||
B = -1 / Tpole
|
||||
A = np.polyfit(x, y * (x * B + 1), n)
|
||||
yfit = np.polyval(A, x) / (x * B + 1)
|
||||
AB[:] = list(A) + [B] # Set so that it uses the AB passed in rather than making local variable
|
||||
rms = np.sqrt(np.sum(np.power(yfit - y, 2)))
|
||||
return rms
|
||||
|
||||
AB = []
|
||||
scipy.optimize.fminbound(obj2, Tc+0.1, 1.5*Tc, args = (x, y, AB))
|
||||
scipy.optimize.fminbound(obj2, Tc + 0.1, 1.5 * Tc, args=(x, y, AB))
|
||||
|
||||
return dict(max_abs_error = np.max(np.abs(obj(x, *AB)-y)),
|
||||
yfitnonlin = obj(xfine, *AB),
|
||||
A = AB[0:n+1],
|
||||
B = list(AB[n+1::]) + [1]
|
||||
return dict(max_abs_error=np.max(np.abs(obj(x, *AB) - y)),
|
||||
yfitnonlin=obj(xfine, *AB),
|
||||
A=AB[0:n + 1],
|
||||
B=list(AB[n + 1::]) + [1]
|
||||
)
|
||||
|
||||
|
||||
class SplineFitter(object):
|
||||
def __init__(self):
|
||||
self.Nconstraints = 0
|
||||
self.A = np.zeros((4,4))
|
||||
self.B = np.zeros((4,1))
|
||||
self.A = np.zeros((4, 4))
|
||||
self.B = np.zeros((4, 1))
|
||||
|
||||
def build(self):
|
||||
if (self.Nconstraints == 4):
|
||||
@@ -90,10 +90,10 @@ class SplineFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 4):
|
||||
return false;
|
||||
self.A[i,0] = x*x*x;
|
||||
self.A[i,1] = x*x;
|
||||
self.A[i,2] = x;
|
||||
self.A[i,3] = 1;
|
||||
self.A[i, 0] = x * x * x;
|
||||
self.A[i, 1] = x * x;
|
||||
self.A[i, 2] = x;
|
||||
self.A[i, 3] = 1;
|
||||
self.B[i] = y;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -101,25 +101,25 @@ class SplineFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 4):
|
||||
return false;
|
||||
self.A[i,0] = 3*x*x;
|
||||
self.A[i,1] = 2*x;
|
||||
self.A[i,2] = 1;
|
||||
self.A[i,3] = 0;
|
||||
self.A[i, 0] = 3 * x * x;
|
||||
self.A[i, 1] = 2 * x;
|
||||
self.A[i, 2] = 1;
|
||||
self.A[i, 3] = 0;
|
||||
self.B[i] = dydx;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
def evaluate(self, x):
|
||||
return self.a*x**3 + self.b*x**2 + self.c*x + self.d;
|
||||
return self.a * x**3 + self.b * x**2 + self.c * x + self.d;
|
||||
|
||||
# See http://stackoverflow.com/a/4983359
|
||||
|
||||
|
||||
def strictly_increasing(L):
|
||||
return all(x<y for x, y in zip(L, L[1:]))
|
||||
return all(x < y for x, y in zip(L, L[1:]))
|
||||
|
||||
|
||||
def strictly_decreasing(L):
|
||||
return all(x>y for x, y in zip(L, L[1:]))
|
||||
return all(x > y for x, y in zip(L, L[1:]))
|
||||
|
||||
|
||||
if not os.path.exists('hsancillaries.json'):
|
||||
@@ -129,18 +129,18 @@ if not os.path.exists('hsancillaries.json'):
|
||||
jj = {}
|
||||
for i, fluid in enumerate(sorted(CoolProp.__fluids__)):
|
||||
|
||||
fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2, 2)
|
||||
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
|
||||
|
||||
plt.suptitle(fluid)
|
||||
print(i,fluid)
|
||||
print(i, fluid)
|
||||
|
||||
N = 10000
|
||||
Tc = CP.PropsSI(fluid,'Tcrit')
|
||||
rhoc = CP.PropsSI(fluid,'rhocrit')
|
||||
Tc = CP.PropsSI(fluid, 'Tcrit')
|
||||
rhoc = CP.PropsSI(fluid, 'rhocrit')
|
||||
try:
|
||||
T = np.r_[np.linspace(Tc-0.1, CP.PropsSI(fluid,'Tmin'), N)]#, np.linspace(Tc-0.1, Tc-1e-8, N)]
|
||||
hfg = (np.array(CP.PropsSI('Hmolar','T',T,'Q',1,fluid)) - np.array(CP.PropsSI('Hmolar','T',T,'Q',0,fluid)))
|
||||
sfg = (np.array(CP.PropsSI('Smolar','T',T,'Q',1,fluid)) - np.array(CP.PropsSI('Smolar','T',T,'Q',0,fluid)))
|
||||
T = np.r_[np.linspace(Tc - 0.1, CP.PropsSI(fluid, 'Tmin'), N)] # , np.linspace(Tc-0.1, Tc-1e-8, N)]
|
||||
hfg = (np.array(CP.PropsSI('Hmolar', 'T', T, 'Q', 1, fluid)) - np.array(CP.PropsSI('Hmolar', 'T', T, 'Q', 0, fluid)))
|
||||
sfg = (np.array(CP.PropsSI('Smolar', 'T', T, 'Q', 1, fluid)) - np.array(CP.PropsSI('Smolar', 'T', T, 'Q', 0, fluid)))
|
||||
if np.any(np.isnan(hfg)):
|
||||
print('nan values in hfg')
|
||||
good_values = np.isfinite(hfg)
|
||||
@@ -153,58 +153,58 @@ if not os.path.exists('hsancillaries.json'):
|
||||
continue
|
||||
|
||||
try:
|
||||
p = CP.PropsSI('P','T',T,'Q',0,fluid)
|
||||
rho = CP.PropsSI('D','T',T,'Q',0,fluid)
|
||||
Tanchor = 1.1*Tc
|
||||
rhoanchor = 0.9*rhoc
|
||||
hanchor_molar = CP.PropsSI('Hmolar','T',Tanchor,'D',rhoanchor,fluid)
|
||||
sanchor_molar = CP.PropsSI('Smolar','T',Tanchor,'D',rhoanchor,fluid)
|
||||
sL = np.array(CP.PropsSI('Smolar','T',T,'Q',0,fluid)) - sanchor_molar
|
||||
hL = np.array(CP.PropsSI('Hmolar','T',T,'Q',0,fluid)) - hanchor_molar
|
||||
p = CP.PropsSI('P', 'T', T, 'Q', 0, fluid)
|
||||
rho = CP.PropsSI('D', 'T', T, 'Q', 0, fluid)
|
||||
Tanchor = 1.1 * Tc
|
||||
rhoanchor = 0.9 * rhoc
|
||||
hanchor_molar = CP.PropsSI('Hmolar', 'T', Tanchor, 'D', rhoanchor, fluid)
|
||||
sanchor_molar = CP.PropsSI('Smolar', 'T', Tanchor, 'D', rhoanchor, fluid)
|
||||
sL = np.array(CP.PropsSI('Smolar', 'T', T, 'Q', 0, fluid)) - sanchor_molar
|
||||
hL = np.array(CP.PropsSI('Hmolar', 'T', T, 'Q', 0, fluid)) - hanchor_molar
|
||||
|
||||
x = T
|
||||
xfine = np.linspace(np.min(x),np.max(x),5000)
|
||||
xfine = np.linspace(np.min(x), np.max(x), 5000)
|
||||
|
||||
n = 7
|
||||
d = 1
|
||||
|
||||
commons = dict(type = "rational_polynomial", Tmin = np.min(T), Tmax = np.max(T))
|
||||
commons = dict(type="rational_polynomial", Tmin=np.min(T), Tmax=np.max(T))
|
||||
|
||||
rp = fit_rational_polynomial(x, hL, xfine, n, d)
|
||||
ax1.plot(x, hL)
|
||||
ax1.plot(xfine, rp['yfitnonlin'],'r')
|
||||
ax1.plot(xfine, rp['yfitnonlin'], 'r')
|
||||
ax1.plot(xfine, rp['yfitnonlin'] + rp['max_abs_error'], 'k--')
|
||||
ax1.plot(xfine, rp['yfitnonlin'] - rp['max_abs_error'], 'k--')
|
||||
hLdict = dict(A = rp['A'][::-1], B = rp['B'][::-1], max_abs_error = rp['max_abs_error'], _note = "coefficients are in increasing order; input in K, output in J/mol; value is enthalpy minus hs_anchor enthalpy", max_abs_error_units = 'J/mol', **commons)
|
||||
hLdict = dict(A=rp['A'][::-1], B=rp['B'][::-1], max_abs_error=rp['max_abs_error'], _note="coefficients are in increasing order; input in K, output in J/mol; value is enthalpy minus hs_anchor enthalpy", max_abs_error_units='J/mol', **commons)
|
||||
if (np.any(np.isnan(hLdict['A']))):
|
||||
print('bad A for hL')
|
||||
continue
|
||||
|
||||
rp = fit_rational_polynomial(x, hfg, xfine, n, d)
|
||||
ax2.plot(x, hfg)
|
||||
ax2.plot(xfine, rp['yfitnonlin'],'r')
|
||||
ax2.plot(xfine, rp['yfitnonlin'], 'r')
|
||||
ax2.plot(xfine, rp['yfitnonlin'] + rp['max_abs_error'], 'k--')
|
||||
ax2.plot(xfine, rp['yfitnonlin'] - rp['max_abs_error'], 'k--')
|
||||
hLVdict = dict(A = rp['A'][::-1], B = rp['B'][::-1], max_abs_error = rp['max_abs_error'], _note = "coefficients are in increasing order; input in K, output in J/mol; value is enthalpy minus hs_anchor enthalpy", max_abs_error_units = 'J/mol', **commons)
|
||||
hLVdict = dict(A=rp['A'][::-1], B=rp['B'][::-1], max_abs_error=rp['max_abs_error'], _note="coefficients are in increasing order; input in K, output in J/mol; value is enthalpy minus hs_anchor enthalpy", max_abs_error_units='J/mol', **commons)
|
||||
|
||||
rp = fit_rational_polynomial(x, sL, xfine, n, d)
|
||||
ax3.plot(x, sL)
|
||||
ax3.plot(xfine, rp['yfitnonlin'],'r')
|
||||
ax3.plot(xfine, rp['yfitnonlin'], 'r')
|
||||
ax3.plot(xfine, rp['yfitnonlin'] + rp['max_abs_error'], 'k--')
|
||||
ax3.plot(xfine, rp['yfitnonlin'] - rp['max_abs_error'], 'k--')
|
||||
sLdict = dict(A = rp['A'][::-1], B = rp['B'][::-1], max_abs_error = rp['max_abs_error'], _note = "coefficients are in increasing order; input in K, output in J/mol/K; value is entropy minus hs_anchor entropy", max_abs_error_units = 'J/mol/K', **commons)
|
||||
sLdict = dict(A=rp['A'][::-1], B=rp['B'][::-1], max_abs_error=rp['max_abs_error'], _note="coefficients are in increasing order; input in K, output in J/mol/K; value is entropy minus hs_anchor entropy", max_abs_error_units='J/mol/K', **commons)
|
||||
if (np.any(np.isnan(sLdict['A']))):
|
||||
print('bad A for sL')
|
||||
continue
|
||||
|
||||
rp = fit_rational_polynomial(x, sfg, xfine, n, d)
|
||||
ax4.plot(x, sfg)
|
||||
ax4.plot(xfine, rp['yfitnonlin'],'r')
|
||||
ax4.plot(xfine, rp['yfitnonlin'], 'r')
|
||||
ax4.plot(xfine, rp['yfitnonlin'] + rp['max_abs_error'], 'k--')
|
||||
ax4.plot(xfine, rp['yfitnonlin'] - rp['max_abs_error'], 'k--')
|
||||
sLVdict = dict(A = rp['A'][::-1], B = rp['B'][::-1], max_abs_error = rp['max_abs_error'], _note = "coefficients are in increasing order; input in K, output in J/mol/K; value is entropy minus hs_anchor entropy", max_abs_error_units = 'J/mol/K', **commons)
|
||||
sLVdict = dict(A=rp['A'][::-1], B=rp['B'][::-1], max_abs_error=rp['max_abs_error'], _note="coefficients are in increasing order; input in K, output in J/mol/K; value is entropy minus hs_anchor entropy", max_abs_error_units='J/mol/K', **commons)
|
||||
|
||||
jj[fluid] = dict(hL = hLdict, hLV = hLVdict, sL = sLdict, sLV = sLVdict)
|
||||
jj[fluid] = dict(hL=hLdict, hLV=hLVdict, sL=sLdict, sLV=sLVdict)
|
||||
|
||||
except BaseException as E:
|
||||
continue
|
||||
@@ -216,7 +216,7 @@ if not os.path.exists('hsancillaries.json'):
|
||||
pp.close()
|
||||
|
||||
fp = open('hsancillaries.json', 'w')
|
||||
fp.write(json.dumps(jj, **{'indent' : 2, 'sort_keys' : True}))
|
||||
fp.write(json.dumps(jj, **{'indent': 2, 'sort_keys': True}))
|
||||
fp.close()
|
||||
else:
|
||||
# Inject
|
||||
@@ -226,7 +226,7 @@ else:
|
||||
|
||||
for fluid in ancillaries:
|
||||
|
||||
fluid_path = '../fluids/'+fluid+'.json'
|
||||
fluid_path = '../fluids/' + fluid + '.json'
|
||||
|
||||
# Open the fluid JSON file
|
||||
fp = open(fluid_path, 'r')
|
||||
@@ -244,4 +244,4 @@ else:
|
||||
fp.write(json.dumps(j, **json_options))
|
||||
fp.close()
|
||||
|
||||
print('writing '+ fluid)
|
||||
print('writing ' + fluid)
|
||||
|
||||
@@ -4,9 +4,9 @@ import matplotlib.pyplot as plt
|
||||
import numpy as np, os, json
|
||||
|
||||
# Turn off the critical splines using json
|
||||
jj = json.loads(CoolProp.CoolProp.get_config_as_json_string()) # Get the json values that are set already
|
||||
jj = json.loads(CoolProp.CoolProp.get_config_as_json_string()) # Get the json values that are set already
|
||||
jj['CRITICAL_SPLINES_ENABLED'] = False
|
||||
CoolProp.CoolProp.set_config_as_json_string(json.dumps(jj)) # Set the values using json
|
||||
CoolProp.CoolProp.set_config_as_json_string(json.dumps(jj)) # Set the values using json
|
||||
# Double check that it was set properly
|
||||
jj = json.loads(CoolProp.CoolProp.get_config_as_json_string()); print(jj)
|
||||
|
||||
@@ -14,8 +14,8 @@ jj = json.loads(CoolProp.CoolProp.get_config_as_json_string()); print(jj)
|
||||
class LinearFitter(object):
|
||||
def __init__(self):
|
||||
self.Nconstraints = 0
|
||||
self.A = np.zeros((2,2))
|
||||
self.B = np.zeros((2,1))
|
||||
self.A = np.zeros((2, 2))
|
||||
self.B = np.zeros((2, 1))
|
||||
|
||||
def build(self):
|
||||
if (self.Nconstraints == 2):
|
||||
@@ -29,8 +29,8 @@ class LinearFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 2):
|
||||
return false;
|
||||
self.A[i,0] = x;
|
||||
self.A[i,1] = 1;
|
||||
self.A[i, 0] = x;
|
||||
self.A[i, 1] = 1;
|
||||
self.B[i] = y;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -38,8 +38,8 @@ class LinearFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 2):
|
||||
return false;
|
||||
self.A[i,0] = 1;
|
||||
self.A[i,1] = 0;
|
||||
self.A[i, 0] = 1;
|
||||
self.A[i, 1] = 0;
|
||||
self.B[i] = dydx;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -50,8 +50,8 @@ class LinearFitter(object):
|
||||
class QuadraticFitter(object):
|
||||
def __init__(self):
|
||||
self.Nconstraints = 0
|
||||
self.A = np.zeros((3,3))
|
||||
self.B = np.zeros((3,1))
|
||||
self.A = np.zeros((3, 3))
|
||||
self.B = np.zeros((3, 1))
|
||||
|
||||
def build(self):
|
||||
if (self.Nconstraints == 3):
|
||||
@@ -65,9 +65,9 @@ class QuadraticFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 4):
|
||||
return false;
|
||||
self.A[i,0] = x*x;
|
||||
self.A[i,1] = x;
|
||||
self.A[i,2] = 1;
|
||||
self.A[i, 0] = x * x;
|
||||
self.A[i, 1] = x;
|
||||
self.A[i, 2] = 1;
|
||||
self.B[i] = y;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -75,9 +75,9 @@ class QuadraticFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 4):
|
||||
return false;
|
||||
self.A[i,0] = 2*x;
|
||||
self.A[i,1] = 1;
|
||||
self.A[i,2] = 0;
|
||||
self.A[i, 0] = 2 * x;
|
||||
self.A[i, 1] = 1;
|
||||
self.A[i, 2] = 0;
|
||||
self.B[i] = dydx;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -85,9 +85,9 @@ class QuadraticFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 3):
|
||||
return false;
|
||||
self.A[i,0] = 2;
|
||||
self.A[i,1] = 0;
|
||||
self.A[i,2] = 0;
|
||||
self.A[i, 0] = 2;
|
||||
self.A[i, 1] = 0;
|
||||
self.A[i, 2] = 0;
|
||||
self.B[i] = d2ydx2;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -98,8 +98,8 @@ class QuadraticFitter(object):
|
||||
class CubicFitter(object):
|
||||
def __init__(self):
|
||||
self.Nconstraints = 0
|
||||
self.A = np.zeros((4,4))
|
||||
self.B = np.zeros((4,1))
|
||||
self.A = np.zeros((4, 4))
|
||||
self.B = np.zeros((4, 1))
|
||||
|
||||
def build(self):
|
||||
if (self.Nconstraints == 4):
|
||||
@@ -113,10 +113,10 @@ class CubicFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 4):
|
||||
return false;
|
||||
self.A[i,0] = x*x*x;
|
||||
self.A[i,1] = x*x;
|
||||
self.A[i,2] = x;
|
||||
self.A[i,3] = 1;
|
||||
self.A[i, 0] = x * x * x;
|
||||
self.A[i, 1] = x * x;
|
||||
self.A[i, 2] = x;
|
||||
self.A[i, 3] = 1;
|
||||
self.B[i] = y;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -124,10 +124,10 @@ class CubicFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 4):
|
||||
return false;
|
||||
self.A[i,0] = 3*x*x;
|
||||
self.A[i,1] = 2*x;
|
||||
self.A[i,2] = 1;
|
||||
self.A[i,3] = 0;
|
||||
self.A[i, 0] = 3 * x * x;
|
||||
self.A[i, 1] = 2 * x;
|
||||
self.A[i, 2] = 1;
|
||||
self.A[i, 3] = 0;
|
||||
self.B[i] = dydx;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -135,10 +135,10 @@ class CubicFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 4):
|
||||
return false;
|
||||
self.A[i,0] = 6*x;
|
||||
self.A[i,1] = 2;
|
||||
self.A[i,2] = 0;
|
||||
self.A[i,3] = 0;
|
||||
self.A[i, 0] = 6 * x;
|
||||
self.A[i, 1] = 2;
|
||||
self.A[i, 2] = 0;
|
||||
self.A[i, 3] = 0;
|
||||
self.B[i] = d2ydx2;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -162,11 +162,11 @@ class QuarticFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 5):
|
||||
return false;
|
||||
self.A[i,0] = x*x*x*x;
|
||||
self.A[i,1] = x*x*x;
|
||||
self.A[i,2] = x*x;
|
||||
self.A[i,3] = x;
|
||||
self.A[i,4] = 1;
|
||||
self.A[i, 0] = x * x * x * x;
|
||||
self.A[i, 1] = x * x * x;
|
||||
self.A[i, 2] = x * x;
|
||||
self.A[i, 3] = x;
|
||||
self.A[i, 4] = 1;
|
||||
self.B[i] = y;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -174,11 +174,11 @@ class QuarticFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 5):
|
||||
return false;
|
||||
self.A[i,0] = 4*x*x*x;
|
||||
self.A[i,1] = 3*x*x;
|
||||
self.A[i,2] = 2*x;
|
||||
self.A[i,3] = 1;
|
||||
self.A[i,4] = 0;
|
||||
self.A[i, 0] = 4 * x * x * x;
|
||||
self.A[i, 1] = 3 * x * x;
|
||||
self.A[i, 2] = 2 * x;
|
||||
self.A[i, 3] = 1;
|
||||
self.A[i, 4] = 0;
|
||||
self.B[i] = dydx;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
@@ -186,16 +186,16 @@ class QuarticFitter(object):
|
||||
i = self.Nconstraints;
|
||||
if (i == 5):
|
||||
return false;
|
||||
self.A[i,0] = 12*x*x;
|
||||
self.A[i,1] = 6*x;
|
||||
self.A[i,2] = x;
|
||||
self.A[i,3] = 0;
|
||||
self.A[i,4] = 0;
|
||||
self.A[i, 0] = 12 * x * x;
|
||||
self.A[i, 1] = 6 * x;
|
||||
self.A[i, 2] = x;
|
||||
self.A[i, 3] = 0;
|
||||
self.A[i, 4] = 0;
|
||||
self.B[i] = d2ydx2;
|
||||
self.Nconstraints += 1;
|
||||
|
||||
def evaluate(self, x):
|
||||
return np.polyval(self.a,x)
|
||||
return np.polyval(self.a, x)
|
||||
|
||||
|
||||
CoolProp.CoolProp.set_debug_level(0)
|
||||
@@ -217,34 +217,34 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
perfect = False
|
||||
cL = None,
|
||||
cV = None,
|
||||
if fluid in ['R410A','R404A','R507A','R407C','SES36','Air','R407F']: continue
|
||||
if fluid in ['R410A', 'R404A', 'R507A', 'R407C', 'SES36', 'Air', 'R407F']: continue
|
||||
dT = 3
|
||||
plt.close('all')
|
||||
fig, (ax1, ax2) = plt.subplots(1,2)
|
||||
pc = CoolProp.CoolProp.PropsSI('pcrit',fluid)
|
||||
Tc = CoolProp.CoolProp.PropsSI('Tcrit',fluid)
|
||||
Tt = CoolProp.CoolProp.PropsSI('Ttriple',fluid)
|
||||
fig, (ax1, ax2) = plt.subplots(1, 2)
|
||||
pc = CoolProp.CoolProp.PropsSI('pcrit', fluid)
|
||||
Tc = CoolProp.CoolProp.PropsSI('Tcrit', fluid)
|
||||
Tt = CoolProp.CoolProp.PropsSI('Ttriple', fluid)
|
||||
print(fluid, Tc, Tt)
|
||||
try:
|
||||
|
||||
good_T = Tc-dT
|
||||
rhomolar_crit = CoolProp.CoolProp.PropsSI('rhomolar_critical',fluid)
|
||||
ok = False # Start assuming not ok
|
||||
good_T = Tc - dT
|
||||
rhomolar_crit = CoolProp.CoolProp.PropsSI('rhomolar_critical', fluid)
|
||||
ok = False # Start assuming not ok
|
||||
for i in np.linspace(np.log10(2), 6, 5000):
|
||||
dT = 10**(-i)
|
||||
bad_T = Tc-dT
|
||||
bad_T = Tc - dT
|
||||
|
||||
p = CoolProp.CoolProp.PropsSI('P', 'T', Tc - dT, 'Q', 0, fluid)
|
||||
|
||||
# If this run worked, good_T and good_dT are set to the working values
|
||||
good_dT = 10**(-(i-1))
|
||||
good_T = Tc-good_dT
|
||||
good_dT = 10**(-(i - 1))
|
||||
good_T = Tc - good_dT
|
||||
|
||||
# Set the flag saying this temperature was OK
|
||||
ok = True
|
||||
|
||||
good_dT = 10**(-17)
|
||||
good_T = Tc-good_dT
|
||||
good_T = Tc - good_dT
|
||||
|
||||
except ValueError as V:
|
||||
pass
|
||||
@@ -258,8 +258,8 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
# Cubic or quadratic fit
|
||||
DELTAT = 1e-5
|
||||
|
||||
dT_drhoL = DELTAT/(rhomolar_endL - CoolProp.CoolProp.PropsSI('Dmolar', 'T', good_T - DELTAT, 'Q', 0, fluid))
|
||||
dT_drhoV = DELTAT/(rhomolar_endV - CoolProp.CoolProp.PropsSI('Dmolar', 'T', good_T - DELTAT, 'Q', 1, fluid))
|
||||
dT_drhoL = DELTAT / (rhomolar_endL - CoolProp.CoolProp.PropsSI('Dmolar', 'T', good_T - DELTAT, 'Q', 0, fluid))
|
||||
dT_drhoV = DELTAT / (rhomolar_endV - CoolProp.CoolProp.PropsSI('Dmolar', 'T', good_T - DELTAT, 'Q', 1, fluid))
|
||||
|
||||
CFL = CubicFitter()
|
||||
CFL.add_value_constraint(rhomolar_crit, Tc)
|
||||
@@ -269,7 +269,7 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
CFL.build()
|
||||
|
||||
zeros = np.roots(np.polyder(CFL.a))
|
||||
monotonic_liq = not np.any(np.logical_and(zeros > 1.000000001*rhomolar_crit, zeros < 0.999999999*rhomolar_endL))
|
||||
monotonic_liq = not np.any(np.logical_and(zeros > 1.000000001 * rhomolar_crit, zeros < 0.999999999 * rhomolar_endL))
|
||||
print('monotonic_liq', monotonic_liq)
|
||||
|
||||
if not monotonic_liq:
|
||||
@@ -289,8 +289,8 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
CFV.build()
|
||||
|
||||
zeros = np.roots(np.polyder(CFV.a))
|
||||
monotonic_vap = not np.any(np.logical_and(zeros < 0.999999999*rhomolar_crit, zeros > 1.000000001*rhomolar_endV))
|
||||
print('monotonic_vap (cubic)',monotonic_vap)
|
||||
monotonic_vap = not np.any(np.logical_and(zeros < 0.999999999 * rhomolar_crit, zeros > 1.000000001 * rhomolar_endV))
|
||||
print('monotonic_vap (cubic)', monotonic_vap)
|
||||
|
||||
if not monotonic_vap:
|
||||
|
||||
@@ -301,24 +301,24 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
##CFV.add_second_derivative_constraint(rhomolar_endV, dT_drhoV)
|
||||
CFV.build()
|
||||
zeros = np.roots(np.polyder(CFV.a))
|
||||
monotonic_vap = not np.any(np.logical_and(zeros < 0.999999999*rhomolar_crit, zeros > 1.000000001*rhomolar_endV))
|
||||
monotonic_vap = not np.any(np.logical_and(zeros < 0.999999999 * rhomolar_crit, zeros > 1.000000001 * rhomolar_endV))
|
||||
print('monotonic_vap', monotonic_vap)
|
||||
|
||||
# Plot the cubic part on small axis
|
||||
ax1.plot(np.linspace(rhomolar_endL, rhomolar_crit), CFL.evaluate(np.linspace(rhomolar_endL, rhomolar_crit)),'r')
|
||||
ax1.plot(np.linspace(rhomolar_endV, rhomolar_crit), CFV.evaluate(np.linspace(rhomolar_endV, rhomolar_crit)),'r')
|
||||
ax1.plot(np.linspace(rhomolar_endL, rhomolar_crit), CFL.evaluate(np.linspace(rhomolar_endL, rhomolar_crit)), 'r')
|
||||
ax1.plot(np.linspace(rhomolar_endV, rhomolar_crit), CFV.evaluate(np.linspace(rhomolar_endV, rhomolar_crit)), 'r')
|
||||
# Plot the cubic part on big ais
|
||||
ax2.plot(np.linspace(rhomolar_endL, rhomolar_crit), CFL.evaluate(np.linspace(rhomolar_endL, rhomolar_crit)),'r')
|
||||
ax2.plot(np.linspace(rhomolar_endV, rhomolar_crit), CFV.evaluate(np.linspace(rhomolar_endV, rhomolar_crit)),'r')
|
||||
ax2.plot(np.linspace(rhomolar_endL, rhomolar_crit), CFL.evaluate(np.linspace(rhomolar_endL, rhomolar_crit)), 'r')
|
||||
ax2.plot(np.linspace(rhomolar_endV, rhomolar_crit), CFV.evaluate(np.linspace(rhomolar_endV, rhomolar_crit)), 'r')
|
||||
|
||||
# Evaluated from EOS
|
||||
TsL = np.linspace(good_T, good_T-good_dT, 100)
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [0]*len(TsL), fluid), TsL,'g')
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [1]*len(TsL), fluid), TsL,'g')
|
||||
TsL = np.linspace(good_T, good_T - good_dT, 100)
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [0] * len(TsL), fluid), TsL, 'g')
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [1] * len(TsL), fluid), TsL, 'g')
|
||||
|
||||
ax1.plot(rhomolar_endL, good_T, 'o')
|
||||
ax1.plot(rhomolar_endV, good_T, 'o')
|
||||
ax1.text(rhomolar_crit, good_T, '{T:0.2f} K'.format(T=good_T), va='top',ha='center')
|
||||
ax1.text(rhomolar_crit, good_T, '{T:0.2f} K'.format(T=good_T), va='top', ha='center')
|
||||
|
||||
print(fluid, ':::', dT, good_T, bad_T, CoolProp.CoolProp.PropsSI('P', 'T', good_T, 'Q', 0, fluid))
|
||||
|
||||
@@ -337,8 +337,8 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
LFL.add_value_constraint(rhomolar_endL, good_T)
|
||||
LFL.build()
|
||||
|
||||
ax1.plot(np.linspace(rhomolar_endL, rhomolar_crit), LFL.evaluate(np.linspace(rhomolar_endL, rhomolar_crit)),'r')
|
||||
ax1.plot(np.linspace(rhomolar_endV, rhomolar_crit), LFV.evaluate(np.linspace(rhomolar_endV, rhomolar_crit)),'r')
|
||||
ax1.plot(np.linspace(rhomolar_endL, rhomolar_crit), LFL.evaluate(np.linspace(rhomolar_endL, rhomolar_crit)), 'r')
|
||||
ax1.plot(np.linspace(rhomolar_endV, rhomolar_crit), LFV.evaluate(np.linspace(rhomolar_endV, rhomolar_crit)), 'r')
|
||||
|
||||
e['Tc'].append(Tc)
|
||||
e['Tt'].append(Tt)
|
||||
@@ -348,19 +348,19 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
cV = LFV.c
|
||||
else:
|
||||
# Evaluated from EOS
|
||||
TsL = np.linspace(0.999*Tc, Tc-1e-15, 100)
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [0]*len(TsL), fluid), TsL,'g')
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [1]*len(TsL), fluid), TsL,'g')
|
||||
TsL = np.linspace(0.999 * Tc, Tc - 1e-15, 100)
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [0] * len(TsL), fluid), TsL, 'g')
|
||||
ax1.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [1] * len(TsL), fluid), TsL, 'g')
|
||||
ax1.text(rhomolar_crit, Tc, 'PERFECT', ha='center', va='bottom')
|
||||
perfect = True
|
||||
|
||||
ax1.plot(rhomolar_crit, Tc, 'o')
|
||||
ax2.plot(rhomolar_crit, Tc, 'o', ms = 2)
|
||||
ax2.plot(rhomolar_crit, Tc, 'o', ms=2)
|
||||
|
||||
ax2.axhline(Tt+1, lw= 2)
|
||||
TsL = np.linspace(Tt+1, good_T, 10000)
|
||||
ax2.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [0]*len(TsL), fluid), TsL,'g')
|
||||
ax2.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [1]*len(TsL), fluid), TsL,'g')
|
||||
ax2.axhline(Tt + 1, lw=2)
|
||||
TsL = np.linspace(Tt + 1, good_T, 10000)
|
||||
ax2.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [0] * len(TsL), fluid), TsL, 'g')
|
||||
ax2.plot(CoolProp.CoolProp.PropsSI('Dmolar', 'T', TsL, 'Q', [1] * len(TsL), fluid), TsL, 'g')
|
||||
|
||||
plt.title(fluid)
|
||||
plt.xlabel(r'$\rho$ [mol/m$^3$]')
|
||||
@@ -369,13 +369,13 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
plt.close()
|
||||
|
||||
if not perfect:
|
||||
JSON[fluid] = dict(cL = cL,
|
||||
cV = cV,
|
||||
_note = "Coefficients for the critical cubic spline. T = c[0]*rho^3 + c[1]*rho^2 + c[2]*rho + c[3] with rho in mol/m^3 and T in K",
|
||||
T_min = good_T,
|
||||
T_max = Tc,
|
||||
rhomolar_min = rhomolar_endV,
|
||||
rhomolar_max = rhomolar_endL
|
||||
JSON[fluid] = dict(cL=cL,
|
||||
cV=cV,
|
||||
_note="Coefficients for the critical cubic spline. T = c[0]*rho^3 + c[1]*rho^2 + c[2]*rho + c[3] with rho in mol/m^3 and T in K",
|
||||
T_min=good_T,
|
||||
T_max=Tc,
|
||||
rhomolar_min=rhomolar_endV,
|
||||
rhomolar_max=rhomolar_endL
|
||||
)
|
||||
print('\tgood_dT', good_dT)
|
||||
else:
|
||||
@@ -385,25 +385,25 @@ if not os.path.exists('sat_spline_json.json'):
|
||||
|
||||
sat_crit_spline.close()
|
||||
|
||||
plt.semilogy(np.array(e['Tc'])/np.array(e['Tt']), e['dT'],'o',mfc='none')
|
||||
plt.semilogy(np.array(e['Tc']) / np.array(e['Tt']), e['dT'], 'o', mfc='none')
|
||||
plt.close()
|
||||
|
||||
fp = open('sat_spline_json.json','w')
|
||||
fp = open('sat_spline_json.json', 'w')
|
||||
json.dump(JSON, fp)
|
||||
fp.close()
|
||||
|
||||
else:
|
||||
# Load the generated JSON file
|
||||
jj = json.load(open('sat_spline_json.json','r'))
|
||||
jj = json.load(open('sat_spline_json.json', 'r'))
|
||||
|
||||
# Iterate over the list of fluids and inject into the fluid JSON files
|
||||
for fluid, v in jj.iteritems():
|
||||
fp = open(os.path.join('..', 'fluids', fluid + '.json'),'r')
|
||||
fp = open(os.path.join('..', 'fluids', fluid + '.json'), 'r')
|
||||
fluid_json = json.load(fp)
|
||||
if 'critical_region_spline' in fluid_json['EOS'][0]:
|
||||
del fluid_json['EOS'][0]['critical_region_spline']
|
||||
fluid_json['EOS'][0]['critical_region_splines'] = v
|
||||
fp.close()
|
||||
fp = open(os.path.join('..', 'fluids', fluid + '.json'),'w')
|
||||
fp = open(os.path.join('..', 'fluids', fluid + '.json'), 'w')
|
||||
json.dump(fluid_json, fp)
|
||||
fp.close()
|
||||
|
||||
@@ -7,154 +7,154 @@ from scipy.odr import *
|
||||
import textwrap
|
||||
|
||||
fluid_REF = 'Propane'
|
||||
Tcrit_REF = CP.Props(fluid_REF,'Tcrit')
|
||||
omega_REF = CP.Props(fluid_REF,"accentric")
|
||||
molemass_REF = CP.Props(fluid_REF,'molemass')
|
||||
rhocrit_REF = CP.Props(fluid_REF,'rhocrit')
|
||||
Zcrit_REF = CP.DerivTerms('Z',Tcrit_REF,rhocrit_REF,fluid_REF)
|
||||
Tcrit_REF = CP.Props(fluid_REF, 'Tcrit')
|
||||
omega_REF = CP.Props(fluid_REF, "accentric")
|
||||
molemass_REF = CP.Props(fluid_REF, 'molemass')
|
||||
rhocrit_REF = CP.Props(fluid_REF, 'rhocrit')
|
||||
Zcrit_REF = CP.DerivTerms('Z', Tcrit_REF, rhocrit_REF, fluid_REF)
|
||||
|
||||
fluid = 'DimethylEther'
|
||||
molemass = CP.Props(fluid,'molemass')
|
||||
Ttriple = CP.Props(fluid,'Ttriple')
|
||||
Tcrit = CP.Props(fluid,'Tcrit')
|
||||
omega = CP.Props(fluid,"accentric")
|
||||
rhocrit = CP.Props(fluid,'rhocrit')
|
||||
pcrit = CP.Props(fluid,'pcrit')
|
||||
Zcrit = CP.DerivTerms('Z',Tcrit,rhocrit,fluid)
|
||||
molemass = CP.Props(fluid, 'molemass')
|
||||
Ttriple = CP.Props(fluid, 'Ttriple')
|
||||
Tcrit = CP.Props(fluid, 'Tcrit')
|
||||
omega = CP.Props(fluid, "accentric")
|
||||
rhocrit = CP.Props(fluid, 'rhocrit')
|
||||
pcrit = CP.Props(fluid, 'pcrit')
|
||||
Zcrit = CP.DerivTerms('Z', Tcrit, rhocrit, fluid)
|
||||
|
||||
N = 12
|
||||
|
||||
RHO,TTT,RHO0,TTT0 = Collector(),Collector(),Collector(),Collector()
|
||||
RHO, TTT, RHO0, TTT0 = Collector(), Collector(), Collector(), Collector()
|
||||
|
||||
rhomax = CP.Props('D','T',Ttriple,'Q',0,fluid)
|
||||
#Build a database of "experimental" data
|
||||
for T in np.linspace(Ttriple,Tcrit+50,80):
|
||||
for rho in np.linspace(1e-10,rhomax,80):
|
||||
T0,rho0 = CP.conformal_Trho(fluid, fluid_REF, T, rho)
|
||||
rhomax = CP.Props('D', 'T', Ttriple, 'Q', 0, fluid)
|
||||
# Build a database of "experimental" data
|
||||
for T in np.linspace(Ttriple, Tcrit + 50, 80):
|
||||
for rho in np.linspace(1e-10, rhomax, 80):
|
||||
T0, rho0 = CP.conformal_Trho(fluid, fluid_REF, T, rho)
|
||||
|
||||
p = CP.Props('P', 'T', T, 'D', rho, fluid)
|
||||
|
||||
ar = CP.DerivTerms("phir",T,rho,fluid)
|
||||
ar_REF = CP.DerivTerms("phir",T0,rho0,fluid_REF)
|
||||
Z = CP.DerivTerms("Z",T,rho,fluid)
|
||||
Z_REF = CP.DerivTerms("Z",T0,rho0,fluid_REF)
|
||||
ar = CP.DerivTerms("phir", T, rho, fluid)
|
||||
ar_REF = CP.DerivTerms("phir", T0, rho0, fluid_REF)
|
||||
Z = CP.DerivTerms("Z", T, rho, fluid)
|
||||
Z_REF = CP.DerivTerms("Z", T0, rho0, fluid_REF)
|
||||
|
||||
#goodstate = ((T > Tcrit and p > pcrit) or (T<Tcrit and rho > CP.rhosatL_anc(fluid,T) ))
|
||||
goodstate = (T > Tcrit or rho > CP.rhosatL_anc(fluid,T) or rho < CP.rhosatV_anc(fluid,T) )
|
||||
goodstate = (T > Tcrit or rho > CP.rhosatL_anc(fluid, T) or rho < CP.rhosatV_anc(fluid, T))
|
||||
#goodstate = True
|
||||
|
||||
#Want positive value, and single-phase
|
||||
if ((T0/T)>0.1 and T/T0*Tcrit_REF/Tcrit < 3 and T0/T < 1e6 and goodstate):
|
||||
if abs((ar-ar_REF)*2+(Z-Z_REF)**2) > 1e-5:
|
||||
print("%s %s" %(ar-ar_REF,Z-Z_REF))
|
||||
# Want positive value, and single-phase
|
||||
if ((T0 / T) > 0.1 and T / T0 * Tcrit_REF / Tcrit < 3 and T0 / T < 1e6 and goodstate):
|
||||
if abs((ar - ar_REF) * 2 + (Z - Z_REF)**2) > 1e-5:
|
||||
print("%s %s" % (ar - ar_REF, Z - Z_REF))
|
||||
TTT << T
|
||||
RHO << rho
|
||||
TTT0 << T0
|
||||
RHO0 << rho0
|
||||
|
||||
tau = Tcrit/np.array(TTT.vec)
|
||||
delta = np.array(RHO.vec)/rhocrit
|
||||
THETA = np.array(TTT.vec)/np.array(TTT0.vec)*Tcrit_REF/Tcrit
|
||||
PHI = np.array(RHO0.vec)/np.array(RHO.vec)*rhocrit/rhocrit_REF #Ratio of MOLAR densities - here the molar masses cancel out to make phi non-dimensional
|
||||
tau = Tcrit / np.array(TTT.vec)
|
||||
delta = np.array(RHO.vec) / rhocrit
|
||||
THETA = np.array(TTT.vec) / np.array(TTT0.vec) * Tcrit_REF / Tcrit
|
||||
PHI = np.array(RHO0.vec) / np.array(RHO.vec) * rhocrit / rhocrit_REF # Ratio of MOLAR densities - here the molar masses cancel out to make phi non-dimensional
|
||||
|
||||
from CoolProp.Plots.Plots import Trho
|
||||
Trho(fluid)
|
||||
#plt.plot(RHO.vec,TTT.vec,'.')
|
||||
#plt.show()
|
||||
# plt.plot(RHO.vec,TTT.vec,'.')
|
||||
# plt.show()
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111, projection='3d')
|
||||
ax.scatter(np.array(RHO.vec),np.array(TTT.vec),THETA)
|
||||
ax.scatter(np.array(RHO.vec), np.array(TTT.vec), THETA)
|
||||
plt.close('all')
|
||||
|
||||
print('rhomin = %s' % np.min(RHO.vec))
|
||||
|
||||
#Define the objective function
|
||||
# Define the objective function
|
||||
|
||||
|
||||
def OBJECTIVE_theta(c,x):
|
||||
tau = x[0,:]
|
||||
delta = x[1,:]
|
||||
def OBJECTIVE_theta(c, x):
|
||||
tau = x[0, :]
|
||||
delta = x[1, :]
|
||||
|
||||
A1 = c[0]-c[1]*np.log(tau)
|
||||
A2 = c[2]-c[3]*np.log(tau)
|
||||
A3 = c[4]-c[5]*np.log(tau)
|
||||
A4 = c[6]-c[7]*np.log(tau)**2
|
||||
DELTA = (delta-1)**2+(tau-1)**2
|
||||
PSI_theta = c[8]*delta*np.exp(-c[9]*DELTA**2)
|
||||
return 1+(omega-omega_REF)*(A1+A2*np.exp(-delta**2)+A3*np.exp(-delta**c[10])+A4*np.exp(-delta**c[11])+PSI_theta)
|
||||
A1 = c[0] - c[1] * np.log(tau)
|
||||
A2 = c[2] - c[3] * np.log(tau)
|
||||
A3 = c[4] - c[5] * np.log(tau)
|
||||
A4 = c[6] - c[7] * np.log(tau)**2
|
||||
DELTA = (delta - 1)**2 + (tau - 1)**2
|
||||
PSI_theta = c[8] * delta * np.exp(-c[9] * DELTA**2)
|
||||
return 1 + (omega - omega_REF) * (A1 + A2 * np.exp(-delta**2) + A3 * np.exp(-delta**c[10]) + A4 * np.exp(-delta**c[11]) + PSI_theta)
|
||||
|
||||
#Define the objective function
|
||||
# Define the objective function
|
||||
|
||||
|
||||
def OBJECTIVE_phi(c,x):
|
||||
tau = x[0,:]
|
||||
delta = x[1,:]
|
||||
def OBJECTIVE_phi(c, x):
|
||||
tau = x[0, :]
|
||||
delta = x[1, :]
|
||||
|
||||
A1 = c[0]-c[1]*np.log(tau)
|
||||
A2 = c[2]-c[3]*np.log(tau)
|
||||
A3 = c[4]-c[5]*np.log(tau)
|
||||
A4 = c[6]-c[7]*np.log(tau)**2
|
||||
DELTA = (delta-1)**2+(tau-1)**2
|
||||
PSI_theta = c[8]*delta*np.exp(-c[9]*DELTA**2)
|
||||
return Zcrit_REF/Zcrit*(1+(omega-omega_REF)*(A1+A2*np.exp(-delta**2)+A3*np.exp(-delta**c[10])+A4*np.exp(-delta**c[11])+PSI_theta))
|
||||
A1 = c[0] - c[1] * np.log(tau)
|
||||
A2 = c[2] - c[3] * np.log(tau)
|
||||
A3 = c[4] - c[5] * np.log(tau)
|
||||
A4 = c[6] - c[7] * np.log(tau)**2
|
||||
DELTA = (delta - 1)**2 + (tau - 1)**2
|
||||
PSI_theta = c[8] * delta * np.exp(-c[9] * DELTA**2)
|
||||
return Zcrit_REF / Zcrit * (1 + (omega - omega_REF) * (A1 + A2 * np.exp(-delta**2) + A3 * np.exp(-delta**c[10]) + A4 * np.exp(-delta**c[11]) + PSI_theta))
|
||||
|
||||
|
||||
print('starting fit for theta')
|
||||
XXX = np.r_[np.array(tau,ndmin = 2), np.array(delta,ndmin=2)]
|
||||
XXX = np.r_[np.array(tau, ndmin=2), np.array(delta, ndmin=2)]
|
||||
|
||||
|
||||
def fit_theta():
|
||||
mod = Model(OBJECTIVE_theta)
|
||||
mydata = Data(XXX.copy(), THETA)
|
||||
beta0 = [100 for _ in range(N)]
|
||||
beta0 = [100 for _ in range(N)]
|
||||
myodr = ODR(mydata, mod, beta0=beta0)
|
||||
myoutput = myodr.run()
|
||||
myoutput.pprint()
|
||||
print(myoutput.sum_square)
|
||||
YFIT = OBJECTIVE_theta(myoutput.beta,XXX)
|
||||
plt.plot(THETA,YFIT,'o',mfc='none')
|
||||
YFIT = OBJECTIVE_theta(myoutput.beta, XXX)
|
||||
plt.plot(THETA, YFIT, 'o', mfc='none')
|
||||
plt.show()
|
||||
ERR = YFIT-THETA
|
||||
MAE = np.mean(np.abs(YFIT/THETA-1))*100
|
||||
ERR = YFIT - THETA
|
||||
MAE = np.mean(np.abs(YFIT / THETA - 1)) * 100
|
||||
from CoolProp.Plots.Plots import Trho
|
||||
Trho(fluid)
|
||||
plt.plot(np.array(RHO.vec)[np.abs(ERR)<5e-2],np.array(TTT.vec)[np.abs(ERR)<5e-2],'.')
|
||||
plt.plot(np.array(RHO.vec)[np.abs(ERR) < 5e-2], np.array(TTT.vec)[np.abs(ERR) < 5e-2], '.')
|
||||
plt.show()
|
||||
|
||||
return myoutput.beta,MAE
|
||||
return myoutput.beta, MAE
|
||||
|
||||
|
||||
def fit_phi():
|
||||
mod = Model(OBJECTIVE_phi)
|
||||
mydata = Data(XXX.copy(), PHI)
|
||||
beta0 = [100 for _ in range(N)]
|
||||
beta0 = [100 for _ in range(N)]
|
||||
myodr = ODR(mydata, mod, beta0=beta0)
|
||||
myoutput = myodr.run()
|
||||
myoutput.pprint()
|
||||
print(myoutput.sum_square)
|
||||
YFIT = OBJECTIVE_theta(myoutput.beta,XXX)
|
||||
plt.plot(PHI,YFIT,'o',mfc='none')
|
||||
YFIT = OBJECTIVE_theta(myoutput.beta, XXX)
|
||||
plt.plot(PHI, YFIT, 'o', mfc='none')
|
||||
plt.show()
|
||||
ERR = YFIT-PHI
|
||||
ERR = YFIT - PHI
|
||||
from CoolProp.Plots.Plots import Trho
|
||||
Trho(fluid)
|
||||
plt.plot(np.array(RHO.vec)[np.abs(ERR)<5e-2],np.array(TTT.vec)[np.abs(ERR)<5e-2],'.')
|
||||
MAE = np.mean(np.abs(YFIT/PHI-1))*100
|
||||
plt.plot(np.array(RHO.vec)[np.abs(ERR) < 5e-2], np.array(TTT.vec)[np.abs(ERR) < 5e-2], '.')
|
||||
MAE = np.mean(np.abs(YFIT / PHI - 1)) * 100
|
||||
plt.show()
|
||||
|
||||
return myoutput.beta,MAE
|
||||
return myoutput.beta, MAE
|
||||
|
||||
|
||||
c,theta_MAE = fit_theta()
|
||||
d,phi_MAE = fit_phi()
|
||||
c, theta_MAE = fit_theta()
|
||||
d, phi_MAE = fit_phi()
|
||||
|
||||
|
||||
def write_output(c,d, theta_MAE, phi_MAE):
|
||||
def write_output(c, d, theta_MAE, phi_MAE):
|
||||
import time
|
||||
from datetime import date
|
||||
cdata = ', '.join(['{val:0.16g}'.format(val = v) for v in c])
|
||||
ddata = ', '.join(['{val:0.16g}'.format(val = v) for v in d])
|
||||
cdata = ', '.join(['{val:0.16g}'.format(val=v) for v in c])
|
||||
ddata = ', '.join(['{val:0.16g}'.format(val=v) for v in d])
|
||||
name = fluid
|
||||
rhomin = np.min(RHO.vec)
|
||||
timestamp = date.fromtimestamp(time.time()).strftime("%A, %d. %B %Y")
|
||||
@@ -242,4 +242,4 @@ def write_output(c,d, theta_MAE, phi_MAE):
|
||||
print(template.format(**locals()))
|
||||
|
||||
|
||||
write_output(c,d,theta_MAE,phi_MAE)
|
||||
write_output(c, d, theta_MAE, phi_MAE)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import urllib, sys,CoolProp, json
|
||||
import urllib, sys, CoolProp, json
|
||||
|
||||
sys.path.append('C:\RDKit_2014_09_2')
|
||||
from rdkit import Chem
|
||||
@@ -12,9 +12,9 @@ for fluid in CoolProp.__fluids__:
|
||||
print('')
|
||||
continue
|
||||
|
||||
txt = urllib.urlretrieve('http://cactus.nci.nih.gov/chemical/structure/'+CAS+'/file?format=mol')
|
||||
txt = urllib.urlretrieve('http://cactus.nci.nih.gov/chemical/structure/' + CAS + '/file?format=mol')
|
||||
|
||||
with open(txt[0],'r') as fp:
|
||||
with open(txt[0], 'r') as fp:
|
||||
contents = fp.read()
|
||||
|
||||
if '<h1>Page not found (404)</h1>' in contents:
|
||||
@@ -27,7 +27,7 @@ for fluid in CoolProp.__fluids__:
|
||||
c = dict(Counter(atom.GetSymbol() for atom in mol.GetAtoms()))
|
||||
formula = ''.join([k + '_{' + str(c[k]) + '}' for k in sorted(c.keys())])
|
||||
|
||||
fname = '../fluids/'+fluid+'.json'
|
||||
fname = '../fluids/' + fluid + '.json'
|
||||
with open(fname, 'r') as fp:
|
||||
jj = json.load(fp)
|
||||
jj['FORMULA'] = formula
|
||||
|
||||
@@ -385,7 +385,7 @@ class GitArchiver(object):
|
||||
output = output.decode(encoding)
|
||||
|
||||
if p.returncode:
|
||||
if sys.version_info > (2,6):
|
||||
if sys.version_info > (2, 6):
|
||||
raise CalledProcessError(returncode=p.returncode, cmd=cmd, output=output)
|
||||
else:
|
||||
raise CalledProcessError(returncode=p.returncode, cmd=cmd)
|
||||
@@ -413,7 +413,7 @@ class GitArchiver(object):
|
||||
output = output.decode('unicode_escape').encode('raw_unicode_escape').decode('utf-8')
|
||||
|
||||
if p.returncode:
|
||||
if sys.version_info > (2,6):
|
||||
if sys.version_info > (2, 6):
|
||||
raise CalledProcessError(returncode=p.returncode, cmd=cmd, output=output)
|
||||
else:
|
||||
raise CalledProcessError(returncode=p.returncode, cmd=cmd)
|
||||
|
||||
@@ -15,7 +15,7 @@ class CurveTracer(object):
|
||||
self.AS = CoolProp.AbstractState(backend, fluid)
|
||||
|
||||
# Solve for Temperature for first point
|
||||
T = scipy.optimize.newton(self.objective_T, T0, args = (p0, -1))
|
||||
T = scipy.optimize.newton(self.objective_T, T0, args=(p0, -1))
|
||||
|
||||
self.T.append(T)
|
||||
|
||||
@@ -29,8 +29,8 @@ class CurveTracer(object):
|
||||
self.AS.update_with_guesses(CoolProp.PT_INPUTS, p, T, guesses)
|
||||
return self.objective()
|
||||
|
||||
def TPcoords(self, t, lnT, lnp, rlnT = 0.1, rlnp = 0.1):
|
||||
return np.exp(lnT + rlnT*np.cos(t)), np.exp(lnp + rlnp*np.sin(t))
|
||||
def TPcoords(self, t, lnT, lnp, rlnT=0.1, rlnp=0.1):
|
||||
return np.exp(lnT + rlnT * np.cos(t)), np.exp(lnp + rlnp * np.sin(t))
|
||||
|
||||
def obj_circle(self, t, lnT, lnp):
|
||||
T2, P2 = self.TPcoords(t, lnT, lnp)
|
||||
@@ -44,11 +44,11 @@ class CurveTracer(object):
|
||||
try:
|
||||
lnT = np.log(self.T[-1])
|
||||
lnp = np.log(self.P[-1])
|
||||
t = scipy.optimize.brentq(self.obj_circle, t-np.pi/2, t+np.pi/2, args = (lnT, lnp))
|
||||
t = scipy.optimize.brentq(self.obj_circle, t - np.pi / 2, t + np.pi / 2, args=(lnT, lnp))
|
||||
T2, P2 = self.TPcoords(t, lnT, lnp)
|
||||
self.T.append(T2)
|
||||
self.P.append(P2)
|
||||
if self.T[-1] < self.AS.keyed_output(CoolProp.iT_triple) or self.P[-1] > 1000*self.AS.keyed_output(CoolProp.iP_critical):
|
||||
if self.T[-1] < self.AS.keyed_output(CoolProp.iT_triple) or self.P[-1] > 1000 * self.AS.keyed_output(CoolProp.iP_critical):
|
||||
break
|
||||
except ValueError as VE:
|
||||
print(VE)
|
||||
@@ -67,7 +67,7 @@ class IdealCurveTracer(CurveTracer):
|
||||
|
||||
def starting_direction(self):
|
||||
""" Start searching directly up ( or calculate as orthogonal to gradient ) """
|
||||
return np.pi/2.0
|
||||
return np.pi / 2.0
|
||||
|
||||
|
||||
class BoyleCurveTracer(CurveTracer):
|
||||
@@ -76,13 +76,13 @@ class BoyleCurveTracer(CurveTracer):
|
||||
|
||||
def objective(self):
|
||||
""" dZ/dv|T = 0 """
|
||||
r = (self.AS.p() - self.AS.rhomolar()*self.AS.first_partial_deriv(CoolProp.iP, CoolProp.iDmolar, CoolProp.iT))/(self.AS.gas_constant()*self.AS.T())
|
||||
#print self.AS.T(), self.AS.p(), r
|
||||
r = (self.AS.p() - self.AS.rhomolar() * self.AS.first_partial_deriv(CoolProp.iP, CoolProp.iDmolar, CoolProp.iT)) / (self.AS.gas_constant() * self.AS.T())
|
||||
# print self.AS.T(), self.AS.p(), r
|
||||
return r
|
||||
|
||||
def starting_direction(self):
|
||||
""" Start searching directly up """
|
||||
return np.pi/2.0
|
||||
return np.pi / 2.0
|
||||
|
||||
|
||||
class JouleInversionCurveTracer(CurveTracer):
|
||||
@@ -91,13 +91,13 @@ class JouleInversionCurveTracer(CurveTracer):
|
||||
|
||||
def objective(self):
|
||||
""" dZ/dT|v = 0 """
|
||||
r = (self.AS.gas_constant()*self.AS.T()*1/self.AS.rhomolar()*self.AS.first_partial_deriv(CoolProp.iP, CoolProp.iT, CoolProp.iDmolar)-self.AS.p()*self.AS.gas_constant()/self.AS.rhomolar())/(self.AS.gas_constant()*self.AS.T())**2
|
||||
#print self.AS.T(), self.AS.p(), r
|
||||
r = (self.AS.gas_constant() * self.AS.T() * 1 / self.AS.rhomolar() * self.AS.first_partial_deriv(CoolProp.iP, CoolProp.iT, CoolProp.iDmolar) - self.AS.p() * self.AS.gas_constant() / self.AS.rhomolar()) / (self.AS.gas_constant() * self.AS.T())**2
|
||||
# print self.AS.T(), self.AS.p(), r
|
||||
return r
|
||||
|
||||
def starting_direction(self):
|
||||
""" Start searching directly up """
|
||||
return np.pi/2.0
|
||||
return np.pi / 2.0
|
||||
|
||||
|
||||
class JouleThomsonCurveTracer(CurveTracer):
|
||||
@@ -106,51 +106,51 @@ class JouleThomsonCurveTracer(CurveTracer):
|
||||
|
||||
def objective(self):
|
||||
""" dZ/dT|p = 0 """
|
||||
dvdT__constp = -self.AS.first_partial_deriv(CoolProp.iDmolar, CoolProp.iT, CoolProp.iP)/self.AS.rhomolar()**2
|
||||
r = self.AS.p()/(self.AS.gas_constant()*self.AS.T()**2)*(self.AS.T()*dvdT__constp - 1/self.AS.rhomolar())
|
||||
#print self.AS.T(), self.AS.p(), r
|
||||
dvdT__constp = -self.AS.first_partial_deriv(CoolProp.iDmolar, CoolProp.iT, CoolProp.iP) / self.AS.rhomolar()**2
|
||||
r = self.AS.p() / (self.AS.gas_constant() * self.AS.T()**2) * (self.AS.T() * dvdT__constp - 1 / self.AS.rhomolar())
|
||||
# print self.AS.T(), self.AS.p(), r
|
||||
return r
|
||||
|
||||
def starting_direction(self):
|
||||
""" Start searching directly up """
|
||||
return np.pi/2.0
|
||||
return np.pi / 2.0
|
||||
|
||||
|
||||
backend = 'HEOS'
|
||||
fluid = 'R125'
|
||||
|
||||
kwargs = dict(lw = 2)
|
||||
kwargs = dict(lw=2)
|
||||
print('Ideal')
|
||||
ICT = IdealCurveTracer(backend, fluid, p0 = 1e5, T0 = 900)
|
||||
ICT = IdealCurveTracer(backend, fluid, p0=1e5, T0=900)
|
||||
T, p = ICT.trace()
|
||||
plt.plot(T, p, '-', label = 'Ideal Curve', **kwargs)
|
||||
plt.plot(T, p, '-', label='Ideal Curve', **kwargs)
|
||||
|
||||
print('Boyle')
|
||||
BCT = BoyleCurveTracer(backend, fluid, p0 = 1e5, T0 = 800)
|
||||
BCT = BoyleCurveTracer(backend, fluid, p0=1e5, T0=800)
|
||||
T, p = BCT.trace()
|
||||
plt.plot(T, p, '-', label = 'Boyle Curve', **kwargs)
|
||||
plt.plot(T, p, '-', label='Boyle Curve', **kwargs)
|
||||
|
||||
print('Joule Inversion')
|
||||
JIT = JouleInversionCurveTracer(backend, fluid, p0 = 1e5, T0 = 1800)
|
||||
JIT = JouleInversionCurveTracer(backend, fluid, p0=1e5, T0=1800)
|
||||
T, p = JIT.trace()
|
||||
plt.plot(T, p, '-', label = 'Joule Inversion Curve', **kwargs)
|
||||
plt.plot(T, p, '-', label='Joule Inversion Curve', **kwargs)
|
||||
|
||||
print('Joule-Thomson')
|
||||
JTCT = JouleThomsonCurveTracer(backend, fluid, p0 = 1e5, T0 = 1800)
|
||||
JTCT = JouleThomsonCurveTracer(backend, fluid, p0=1e5, T0=1800)
|
||||
T, p = JTCT.trace()
|
||||
plt.plot(T, p, '-', label = 'Joule-Thomson Curve', **kwargs)
|
||||
plt.plot(T, p, '-', label='Joule-Thomson Curve', **kwargs)
|
||||
|
||||
print('Saturation Curve')
|
||||
Tt = ICT.AS.keyed_output(CoolProp.iT_triple)
|
||||
Tc = ICT.AS.keyed_output(CoolProp.iT_critical)
|
||||
Ts = np.linspace(Tt, Tc - 1.e-6)
|
||||
ps = CoolProp.CoolProp.PropsSI('P','T',Ts,'Q',0,backend + '::' + fluid)
|
||||
plt.plot(Ts, ps, '-', label = 'Saturation Curve', **kwargs)
|
||||
ps = CoolProp.CoolProp.PropsSI('P', 'T', Ts, 'Q', 0, backend + '::' + fluid)
|
||||
plt.plot(Ts, ps, '-', label='Saturation Curve', **kwargs)
|
||||
|
||||
plt.yscale('log')
|
||||
plt.xscale('log')
|
||||
plt.xlabel('T (K)')
|
||||
plt.ylabel('p (Pa)')
|
||||
plt.legend(loc = 'best')
|
||||
plt.legend(loc='best')
|
||||
plt.savefig('IdealCurves.png')
|
||||
plt.show()
|
||||
|
||||
@@ -3,44 +3,44 @@ import json
|
||||
|
||||
# From McLinden, IJR, 2000
|
||||
McLinden_sigma_ek_f_data = {
|
||||
'R11': [0.5447,363.61, 1.4000e-3],
|
||||
'R12': [0.5186,297.24, 1.3440e-3],
|
||||
'R13': [0.4909,233.36, 1.3200e-3],
|
||||
'R22': [0.4666, 284.72, 7.7817e-4,+1.2536e-6],
|
||||
'R23': [0.4430, 230.83, 6.0570e-4,+1.8604e-6],
|
||||
'R32': [0.4098, 289.65, 8.1980e-4,+2.2352e-7],
|
||||
'R11': [0.5447, 363.61, 1.4000e-3],
|
||||
'R12': [0.5186, 297.24, 1.3440e-3],
|
||||
'R13': [0.4909, 233.36, 1.3200e-3],
|
||||
'R22': [0.4666, 284.72, 7.7817e-4, +1.2536e-6],
|
||||
'R23': [0.4430, 230.83, 6.0570e-4, +1.8604e-6],
|
||||
'R32': [0.4098, 289.65, 8.1980e-4, +2.2352e-7],
|
||||
'R114': [0.5770, 323.26, 1.3200e-3],
|
||||
'R115': [0.5476, 272.53, 1.3200e-3],
|
||||
'R125': [0.5101, 261.39, 1.2565e-3,+2.2296e-6],
|
||||
'R125': [0.5101, 261.39, 1.2565e-3, +2.2296e-6],
|
||||
'R142b': [0.5320, 316.64, 1.3200e-3],
|
||||
'R143a': [0.5025, 267.10, 1.0066e-3,+1.3729e-6]
|
||||
'R143a': [0.5025, 267.10, 1.0066e-3, +1.3729e-6]
|
||||
}
|
||||
|
||||
# From McLinden, IJR, 2000
|
||||
McLinden_psi_cond_data = {
|
||||
'R11': [1.0724,-0.0226720],
|
||||
'R12': [0.9910,0.0029509],
|
||||
'R13': [1.4078,-0.2634600,0.037978],
|
||||
'R22': [1.0750,-0.0385740],
|
||||
'R23': [1.3801,-0.2797500,0.048798],
|
||||
'R32': [1.2325,-0.0883940],
|
||||
'R114': [1.0961,-0.0348990],
|
||||
'R115': [1.0338,-0.0020661],
|
||||
'R125': [1.0369,-0.0030368],
|
||||
'R142b': [1.6808,-0.8395440,0.321957,-0.039706],
|
||||
'R143a': [1.1779,-0.2054100,0.064870,-0.006473]}
|
||||
'R11': [1.0724, -0.0226720],
|
||||
'R12': [0.9910, 0.0029509],
|
||||
'R13': [1.4078, -0.2634600, 0.037978],
|
||||
'R22': [1.0750, -0.0385740],
|
||||
'R23': [1.3801, -0.2797500, 0.048798],
|
||||
'R32': [1.2325, -0.0883940],
|
||||
'R114': [1.0961, -0.0348990],
|
||||
'R115': [1.0338, -0.0020661],
|
||||
'R125': [1.0369, -0.0030368],
|
||||
'R142b': [1.6808, -0.8395440, 0.321957, -0.039706],
|
||||
'R143a': [1.1779, -0.2054100, 0.064870, -0.006473]}
|
||||
|
||||
# From Klein, 1997
|
||||
Klein_psi_visc_data = {
|
||||
'R11': [1.171,-0.0592],
|
||||
'R12': [1.087,-0.0379],
|
||||
'R113': [1.212,-0.0569],
|
||||
'R22': [1.106,-0.0491],
|
||||
'R32': [0.898,+0.0099],
|
||||
'R123': [1.155,-0.0513],
|
||||
'R125': [1.110,-0.0332],
|
||||
'R143a': [1.134,-0.0801],
|
||||
'R152a': [0.807,+0.0496]}
|
||||
'R11': [1.171, -0.0592],
|
||||
'R12': [1.087, -0.0379],
|
||||
'R113': [1.212, -0.0569],
|
||||
'R22': [1.106, -0.0491],
|
||||
'R32': [0.898, +0.0099],
|
||||
'R123': [1.155, -0.0513],
|
||||
'R125': [1.110, -0.0332],
|
||||
'R143a': [1.134, -0.0801],
|
||||
'R152a': [0.807, +0.0496]}
|
||||
|
||||
template = {
|
||||
"conductivity": {
|
||||
@@ -98,20 +98,20 @@ fluids = set(('R11,R12,R113,R22,R32,R123,R125,R143a,R152a'.split(','))).intersec
|
||||
|
||||
for fluid in fluids:
|
||||
try:
|
||||
v = CoolProp.CoolProp.PropsSI('V','T',300,'Q',0,fluid)
|
||||
l = CoolProp.CoolProp.PropsSI('L','T',300,'Q',0,fluid)
|
||||
#print 'GOOD', fluid, v, l
|
||||
v = CoolProp.CoolProp.PropsSI('V', 'T', 300, 'Q', 0, fluid)
|
||||
l = CoolProp.CoolProp.PropsSI('L', 'T', 300, 'Q', 0, fluid)
|
||||
# print 'GOOD', fluid, v, l
|
||||
except ValueError:
|
||||
|
||||
print('BAD %s' % fluid)
|
||||
|
||||
new = template.copy()
|
||||
new['viscosity']['sigma_eta'] = McLinden_sigma_ek_f_data[fluid][0]/1e9
|
||||
new['viscosity']['sigma_eta'] = McLinden_sigma_ek_f_data[fluid][0] / 1e9
|
||||
new['viscosity']['epsilon_over_k'] = McLinden_sigma_ek_f_data[fluid][1]
|
||||
a = Klein_psi_visc_data[fluid]
|
||||
new['viscosity']['psi']['a'] = a
|
||||
new['viscosity']['psi']['t'] = range(len(a))
|
||||
new['viscosity']['psi']['rhomolar_reducing'] = CoolProp.CoolProp.PropsSI(fluid,'rhomolar_reducing')
|
||||
new['viscosity']['psi']['rhomolar_reducing'] = CoolProp.CoolProp.PropsSI(fluid, 'rhomolar_reducing')
|
||||
|
||||
a = McLinden_sigma_ek_f_data[fluid][2::]
|
||||
new['conductivity']['f_int']['a'] = a
|
||||
@@ -119,9 +119,9 @@ for fluid in fluids:
|
||||
a = McLinden_psi_cond_data[fluid]
|
||||
new['conductivity']['psi']['a'] = a
|
||||
new['conductivity']['psi']['t'] = range(len(a))
|
||||
new['conductivity']['psi']['rhomolar_reducing'] = CoolProp.CoolProp.PropsSI(fluid,'rhomolar_reducing')
|
||||
new['conductivity']['psi']['rhomolar_reducing'] = CoolProp.CoolProp.PropsSI(fluid, 'rhomolar_reducing')
|
||||
|
||||
fname = '../fluids/'+fluid+'.json'
|
||||
fname = '../fluids/' + fluid + '.json'
|
||||
with open(fname, 'r') as fp:
|
||||
jj = json.load(fp)
|
||||
jj['TRANSPORT'] = new
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import CoolProp
|
||||
from chemspipy import ChemSpider
|
||||
from chemspipy_key import key # private file with the key (DO NOT COMMIT!!)
|
||||
from chemspipy_key import key # private file with the key (DO NOT COMMIT!!)
|
||||
import glob, json
|
||||
cs = ChemSpider(key)
|
||||
|
||||
@@ -24,7 +24,7 @@ c = cs.get_compound(2157)
|
||||
assert(c.inchikey == 'BSYNRYMUTXBXSQ-UHFFFAOYAW')
|
||||
|
||||
for fname in glob.glob('../fluids/*.json'):
|
||||
with open(fname,'r') as fp:
|
||||
with open(fname, 'r') as fp:
|
||||
jj = json.load(fp)
|
||||
|
||||
fluid = jj['INFO']['NAME']
|
||||
@@ -56,14 +56,14 @@ for fname in glob.glob('../fluids/*.json'):
|
||||
print('%s %s !!failure!! %s' % (fluid, CAS, len(results)))
|
||||
for result in results:
|
||||
spectra = cs.get_compound_spectra(result.csid)
|
||||
if spectra and '##CAS REGISTRY NO='+CAS in spectra[0].data:
|
||||
if spectra and '##CAS REGISTRY NO=' + CAS in spectra[0].data:
|
||||
doset(result)
|
||||
print ('GOT IT!!')
|
||||
print('GOT IT!!')
|
||||
break
|
||||
print(result.common_name, result.inchikey, result.stdinchi, cs.get_extended_compound_info(result.csid))
|
||||
print('')
|
||||
|
||||
with open(fname,'w') as fp:
|
||||
json.dump(jj, fp, indent = 2, sort_keys = True)
|
||||
with open(fname, 'w') as fp:
|
||||
json.dump(jj, fp, indent=2, sort_keys=True)
|
||||
|
||||
del jj, fp
|
||||
|
||||
@@ -6,11 +6,11 @@ CP = CoolProp.CoolProp
|
||||
|
||||
def inject_hsanchor(fluid, i, json_data):
|
||||
|
||||
Tanchor = 1.1*CoolProp.CoolProp.PropsSI('Tcrit',fluid)
|
||||
rhoanchor = 0.9*CoolProp.CoolProp.PropsSI('rhomolar_critical',fluid)
|
||||
hanchor_molar = CP.PropsSI('Hmolar','T',Tanchor,'Dmolar',rhoanchor,fluid)
|
||||
sanchor_molar = CP.PropsSI('Smolar','T',Tanchor,'Dmolar',rhoanchor,fluid)
|
||||
p = CP.PropsSI('P','T',Tanchor,'Dmolar',rhoanchor,fluid)
|
||||
Tanchor = 1.1 * CoolProp.CoolProp.PropsSI('Tcrit', fluid)
|
||||
rhoanchor = 0.9 * CoolProp.CoolProp.PropsSI('rhomolar_critical', fluid)
|
||||
hanchor_molar = CP.PropsSI('Hmolar', 'T', Tanchor, 'Dmolar', rhoanchor, fluid)
|
||||
sanchor_molar = CP.PropsSI('Smolar', 'T', Tanchor, 'Dmolar', rhoanchor, fluid)
|
||||
p = CP.PropsSI('P', 'T', Tanchor, 'Dmolar', rhoanchor, fluid)
|
||||
|
||||
json_data['EOS'][i]['STATES']['hs_anchor'] = {
|
||||
"T": Tanchor,
|
||||
@@ -33,25 +33,25 @@ def inject_triples(fluid, i, json_data):
|
||||
triple_liquid = {
|
||||
"T": Ttriple,
|
||||
"T_units": "K",
|
||||
"hmolar": CP.PropsSI('Hmolar','T',Ttriple,'Q',0,fluid),
|
||||
"hmolar": CP.PropsSI('Hmolar', 'T', Ttriple, 'Q', 0, fluid),
|
||||
"hmolar_units": "J/mol",
|
||||
"p": CP.PropsSI('P','T',Ttriple,'Q',0,fluid),
|
||||
"p": CP.PropsSI('P', 'T', Ttriple, 'Q', 0, fluid),
|
||||
"p_units": "Pa",
|
||||
"rhomolar": CP.PropsSI('Dmolar','T',Ttriple,'Q',0,fluid),
|
||||
"rhomolar": CP.PropsSI('Dmolar', 'T', Ttriple, 'Q', 0, fluid),
|
||||
"rhomolar_units": "mol/m^3",
|
||||
"smolar": CP.PropsSI('Smolar','T',Ttriple,'Q',0,fluid),
|
||||
"smolar": CP.PropsSI('Smolar', 'T', Ttriple, 'Q', 0, fluid),
|
||||
"smolar_units": "J/mol/K"
|
||||
}
|
||||
triple_vapor = {
|
||||
"T": Ttriple,
|
||||
"T_units": "K",
|
||||
"hmolar": CP.PropsSI('Hmolar','T',Ttriple,'Q',1,fluid),
|
||||
"hmolar": CP.PropsSI('Hmolar', 'T', Ttriple, 'Q', 1, fluid),
|
||||
"hmolar_units": "J/mol",
|
||||
"p": CP.PropsSI('P','T',Ttriple,'Q',1,fluid),
|
||||
"p": CP.PropsSI('P', 'T', Ttriple, 'Q', 1, fluid),
|
||||
"p_units": "Pa",
|
||||
"rhomolar": CP.PropsSI('Dmolar','T',Ttriple,'Q',1,fluid),
|
||||
"rhomolar": CP.PropsSI('Dmolar', 'T', Ttriple, 'Q', 1, fluid),
|
||||
"rhomolar_units": "mol/m^3",
|
||||
"smolar": CP.PropsSI('Smolar','T',Ttriple,'Q',1,fluid),
|
||||
"smolar": CP.PropsSI('Smolar', 'T', Ttriple, 'Q', 1, fluid),
|
||||
"smolar_units": "J/mol/K"
|
||||
}
|
||||
json_data['STATES']['triple_vapor'] = triple_vapor
|
||||
@@ -70,13 +70,13 @@ def inject_critical(fluid, json_data):
|
||||
json_data['STATES']['critical'] = {
|
||||
"T": T,
|
||||
"T_units": "K",
|
||||
"hmolar": CP.PropsSI('Hmolar','T',T,'Dmolar',D,fluid),
|
||||
"hmolar": CP.PropsSI('Hmolar', 'T', T, 'Dmolar', D, fluid),
|
||||
"hmolar_units": "J/mol",
|
||||
"p": CP.PropsSI('P','T',T,'Dmolar',D,fluid),
|
||||
"p": CP.PropsSI('P', 'T', T, 'Dmolar', D, fluid),
|
||||
"p_units": "Pa",
|
||||
"rhomolar": D,
|
||||
"rhomolar_units": "mol/m^3",
|
||||
"smolar": CP.PropsSI('Smolar','T',T,'Dmolar',D,fluid),
|
||||
"smolar": CP.PropsSI('Smolar', 'T', T, 'Dmolar', D, fluid),
|
||||
"smolar_units": "J/mol/K"
|
||||
}
|
||||
|
||||
@@ -91,13 +91,13 @@ def inject_reducing(fluid, i, json_data):
|
||||
json_data['EOS'][i]['STATES']['reducing'] = {
|
||||
"T": T,
|
||||
"T_units": "K",
|
||||
"hmolar": CP.PropsSI('Hmolar','T',T,'Dmolar',D,fluid),
|
||||
"hmolar": CP.PropsSI('Hmolar', 'T', T, 'Dmolar', D, fluid),
|
||||
"hmolar_units": "J/mol",
|
||||
"p": CP.PropsSI('P','T',T,'Dmolar',D,fluid),
|
||||
"p": CP.PropsSI('P', 'T', T, 'Dmolar', D, fluid),
|
||||
"p_units": "Pa",
|
||||
"rhomolar": D,
|
||||
"rhomolar_units": "mol/m^3",
|
||||
"smolar": CP.PropsSI('Smolar','T',T,'Dmolar',D,fluid),
|
||||
"smolar": CP.PropsSI('Smolar', 'T', T, 'Dmolar', D, fluid),
|
||||
"smolar_units": "J/mol/K"
|
||||
}
|
||||
|
||||
@@ -108,13 +108,13 @@ def inject_acentric(fluid, i, json_data):
|
||||
"""
|
||||
Tc = json_data['STATES']['critical']['T']
|
||||
pc = json_data['STATES']['critical']['p']
|
||||
p = CoolProp.CoolProp.PropsSI('P','T',Tc*0.7,"Q",0,fluid)
|
||||
p = CoolProp.CoolProp.PropsSI('P', 'T', Tc * 0.7, "Q", 0, fluid)
|
||||
import math
|
||||
json_data['EOS'][i]['acentric'] = -math.log10(p/pc)-1
|
||||
json_data['EOS'][i]['acentric'] = -math.log10(p / pc) - 1
|
||||
|
||||
|
||||
def inject_states(fluid):
|
||||
fluid_path = '../fluids/'+fluid+'.json'
|
||||
fluid_path = '../fluids/' + fluid + '.json'
|
||||
|
||||
# Open the fluid JSON file
|
||||
with open(fluid_path, 'r') as fp:
|
||||
@@ -134,9 +134,9 @@ def inject_states(fluid):
|
||||
fp.write(json.dumps(json_data, **json_options))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
#jj = json.loads(CP.get_config_as_json_string())
|
||||
#jj['DONT_CHECK_PROPERTY_LIMITS'] = True
|
||||
#CP.set_config_as_json_string(json.dumps(jj))
|
||||
# CP.set_config_as_json_string(json.dumps(jj))
|
||||
|
||||
inject_states('R40')
|
||||
|
||||
@@ -8,37 +8,37 @@ except ImportError:
|
||||
|
||||
|
||||
def get_milestones(milestone):
|
||||
fname = milestone+'-milestones.json'
|
||||
fname = milestone + '-milestones.json'
|
||||
if not os.path.exists(fname):
|
||||
# Find the milestone number for the given name
|
||||
milestones_json = json.loads(urlopen('https://api.github.com/repos/CoolProp/CoolProp/milestones').read())
|
||||
with open(fname,'w') as fp:
|
||||
fp.write(json.dumps(milestones_json, indent = 2))
|
||||
with open(fname,'r') as fp:
|
||||
with open(fname, 'w') as fp:
|
||||
fp.write(json.dumps(milestones_json, indent=2))
|
||||
with open(fname, 'r') as fp:
|
||||
return json.load(fp)
|
||||
|
||||
|
||||
def get_PR_JSON(milestone, number):
|
||||
# Get the merged pull requests associated with the milestone
|
||||
fname = milestone+'-PR.json'
|
||||
fname = milestone + '-PR.json'
|
||||
if not os.path.exists(fname):
|
||||
# Find the milestone number for the given name
|
||||
PR = json.loads(urlopen('https://api.github.com/repos/CoolProp/CoolProp/pulls?state=closed&per_page=1000&milestone='+str(number)).read())
|
||||
with open(fname,'w') as fp:
|
||||
fp.write(json.dumps(PR, indent = 2))
|
||||
with open(fname,'r') as fp:
|
||||
PR = json.loads(urlopen('https://api.github.com/repos/CoolProp/CoolProp/pulls?state=closed&per_page=1000&milestone=' + str(number)).read())
|
||||
with open(fname, 'w') as fp:
|
||||
fp.write(json.dumps(PR, indent=2))
|
||||
with open(fname, 'r') as fp:
|
||||
return json.load(fp)
|
||||
|
||||
|
||||
def get_issues_JSON(milestone, number):
|
||||
# Get the merged pull requests associated with the milestone
|
||||
fname = milestone+'-issues.json'
|
||||
fname = milestone + '-issues.json'
|
||||
if not os.path.exists(fname):
|
||||
# Find the milestone number for the given name
|
||||
issues = json.loads(urlopen('https://api.github.com/repos/CoolProp/CoolProp/issues?state=all&per_page=1000&milestone='+str(number)).read())
|
||||
with open(fname,'w') as fp:
|
||||
fp.write(json.dumps(issues, indent = 2))
|
||||
with open(fname,'r') as fp:
|
||||
issues = json.loads(urlopen('https://api.github.com/repos/CoolProp/CoolProp/issues?state=all&per_page=1000&milestone=' + str(number)).read())
|
||||
with open(fname, 'w') as fp:
|
||||
fp.write(json.dumps(issues, indent=2))
|
||||
with open(fname, 'r') as fp:
|
||||
return json.load(fp)
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ def generate_issues(milestone):
|
||||
pr_numbers = [issue['number'] for issue in PR]
|
||||
|
||||
# Get the issues associated with the milestone
|
||||
issues = get_issues_JSON(milestone, number)
|
||||
issues = get_issues_JSON(milestone, number)
|
||||
|
||||
# Make sure all issues are closed in this milestone
|
||||
l = 0
|
||||
@@ -68,7 +68,7 @@ def generate_issues(milestone):
|
||||
if issues[i]['number'] in pr_numbers:
|
||||
issues.pop(i)
|
||||
|
||||
rst = 'Issues Closed:\n\n'+'\n'.join(['* `#{n:d} <https://github.com/CoolProp/CoolProp/issues/{n:d}>`_ : {t:s}'.format(n = issue['number'], t = issue['title']) for issue in issues])
|
||||
rst = 'Issues Closed:\n\n' + '\n'.join(['* `#{n:d} <https://github.com/CoolProp/CoolProp/issues/{n:d}>`_ : {t:s}'.format(n=issue['number'], t=issue['title']) for issue in issues])
|
||||
|
||||
return rst
|
||||
|
||||
@@ -89,12 +89,12 @@ def generate_PR(milestone):
|
||||
rst = 'Pull Requests merged:\n\n'
|
||||
for issue in PR:
|
||||
if issue['milestone'] is not None and issue['milestone']['title'] == milestone:
|
||||
rst += '* `#{n:d} <https://github.com/CoolProp/CoolProp/pull/{n:d}>`_ : {t:s}\n'.format(n = issue['number'], t = issue['title'])
|
||||
rst += '* `#{n:d} <https://github.com/CoolProp/CoolProp/pull/{n:d}>`_ : {t:s}\n'.format(n=issue['number'], t=issue['title'])
|
||||
|
||||
return rst
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) != 2:
|
||||
raise ValueError('This script should be called like this: python milestone2rst.py v5')
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@ from __future__ import division
|
||||
from CoolProp import CoolProp as CP
|
||||
|
||||
Fluid = 'CO2'
|
||||
R = 8.314472/CP.Props(Fluid,'molemass')
|
||||
Tc = CP.Props(Fluid,'Tcrit')
|
||||
pc = CP.Props(Fluid,'pcrit')
|
||||
w = CP.Props(Fluid,'accentric')
|
||||
R = 8.314472 / CP.Props(Fluid, 'molemass')
|
||||
Tc = CP.Props(Fluid, 'Tcrit')
|
||||
pc = CP.Props(Fluid, 'pcrit')
|
||||
w = CP.Props(Fluid, 'accentric')
|
||||
|
||||
a = 0.457235*R**2*Tc**2/pc
|
||||
b = 0.077796*R*Tc/pc
|
||||
kappa = 0.37464+1.54226*w-0.26992*w**2
|
||||
a = 0.457235 * R**2 * Tc**2 / pc
|
||||
b = 0.077796 * R * Tc / pc
|
||||
kappa = 0.37464 + 1.54226 * w - 0.26992 * w**2
|
||||
|
||||
T = 298.15
|
||||
rho = 1000
|
||||
v = 1/rho
|
||||
Tr = T/Tc
|
||||
alpha = (1+kappa*(1-Tr**0.5))**2
|
||||
v = 1 / rho
|
||||
Tr = T / Tc
|
||||
alpha = (1 + kappa * (1 - Tr**0.5))**2
|
||||
|
||||
p = R*T/(v-b)-a*alpha/(v**2+2*b*v-b**2)
|
||||
p = R * T / (v - b) - a * alpha / (v**2 + 2 * b * v - b**2)
|
||||
print("%s %s" % (p, CP.Props('P', 'T', T, 'D', rho, Fluid)))
|
||||
|
||||
@@ -3,18 +3,18 @@ CPmod = CoolProp.CoolProp
|
||||
|
||||
|
||||
def get_offset_NBP(name):
|
||||
#CPmod.set_debug_level(10)
|
||||
CPmod.set_reference_state(name,"RESET")
|
||||
# CPmod.set_debug_level(10)
|
||||
CPmod.set_reference_state(name, "RESET")
|
||||
HEOS = CoolProp.AbstractState('HEOS', name)
|
||||
HEOS.update(CoolProp.PQ_INPUTS, 101325, 0)
|
||||
|
||||
gas_constant = HEOS.gas_constant()/HEOS.molar_mass()
|
||||
gas_constant = HEOS.gas_constant() / HEOS.molar_mass()
|
||||
|
||||
delta_a1 = HEOS.smass()/(gas_constant)
|
||||
delta_a2 = -HEOS.hmass()/(gas_constant*HEOS.keyed_output(CoolProp.iT_reducing))
|
||||
delta_a1 = HEOS.smass() / (gas_constant)
|
||||
delta_a2 = -HEOS.hmass() / (gas_constant * HEOS.keyed_output(CoolProp.iT_reducing))
|
||||
return delta_a1, delta_a2
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if __name__ == '__main__':
|
||||
name = 'MM'
|
||||
print(get_offset_NBP(name))
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
from distutils.core import setup
|
||||
from Cython.Build import cythonize
|
||||
|
||||
import sys,numpy
|
||||
import sys, numpy
|
||||
import Cython
|
||||
Cython.Compiler.Options.annotate = True
|
||||
sys.argv += ['build_ext','--inplace']
|
||||
sys.argv += ['build_ext', '--inplace']
|
||||
|
||||
setup(
|
||||
name = "My hello app",
|
||||
ext_modules = cythonize('summer.pyx'), # accepts a glob pattern
|
||||
include_dirs = [numpy.get_include()]
|
||||
name="My hello app",
|
||||
ext_modules=cythonize('summer.pyx'), # accepts a glob pattern
|
||||
include_dirs=[numpy.get_include()]
|
||||
)
|
||||
|
||||
@@ -5,18 +5,18 @@ from mpl_toolkits.mplot3d import Axes3D
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fluid = 'R245fa'
|
||||
Ttriple = CP.Props(fluid,'Ttriple')
|
||||
Tcrit = CP.Props(fluid,'Tcrit')
|
||||
Ttriple = CP.Props(fluid, 'Ttriple')
|
||||
Tcrit = CP.Props(fluid, 'Tcrit')
|
||||
|
||||
RHO,TTT,RHO0,TTT0,ERR = Collector(),Collector(),Collector(),Collector(),Collector()
|
||||
RHO, TTT, RHO0, TTT0, ERR = Collector(), Collector(), Collector(), Collector(), Collector()
|
||||
|
||||
rhomax = CP.Props('D','T',Ttriple,'Q',0,'R245fa')
|
||||
#Build a database of "experimental" data
|
||||
for T in np.linspace(Ttriple,Tcrit+50,80):
|
||||
for rho in np.linspace(1e-10,rhomax,80):
|
||||
if (T > Tcrit or rho > CP.rhosatL_anc(fluid,T) or rho < CP.rhosatV_anc(fluid,T) ):
|
||||
h = CP.Props('H','T',T,'D',rho,'R245fa')
|
||||
p = CP.Props('P','T',T,'D',rho,'R245fa')
|
||||
rhomax = CP.Props('D', 'T', Ttriple, 'Q', 0, 'R245fa')
|
||||
# Build a database of "experimental" data
|
||||
for T in np.linspace(Ttriple, Tcrit + 50, 80):
|
||||
for rho in np.linspace(1e-10, rhomax, 80):
|
||||
if (T > Tcrit or rho > CP.rhosatL_anc(fluid, T) or rho < CP.rhosatV_anc(fluid, T)):
|
||||
h = CP.Props('H', 'T', T, 'D', rho, 'R245fa')
|
||||
p = CP.Props('P', 'T', T, 'D', rho, 'R245fa')
|
||||
|
||||
RHO << rho
|
||||
TTT << T
|
||||
@@ -25,7 +25,7 @@ for T in np.linspace(Ttriple,Tcrit+50,80):
|
||||
|
||||
fig = plt.figure()
|
||||
ax1 = fig.add_subplot(121, projection='3d')
|
||||
ax1.scatter(np.array(RHO.vec),np.array(TTT.vec),ERR.vec)
|
||||
ax1.scatter(np.array(RHO.vec), np.array(TTT.vec), ERR.vec)
|
||||
ax2 = fig.add_subplot(122, projection='3d')
|
||||
ax2.scatter(np.array(RHO.vec),np.array(TTT.vec),TTT0.vec)
|
||||
ax2.scatter(np.array(RHO.vec), np.array(TTT.vec), TTT0.vec)
|
||||
plt.show()
|
||||
|
||||
@@ -1,42 +1,42 @@
|
||||
from math import sqrt,exp
|
||||
from math import sqrt, exp
|
||||
from CoolProp.CoolProp import Props
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from scipy.odr import *
|
||||
from math import log
|
||||
E_K = {'REFPROP-Ammonia':386,
|
||||
'REFPROP-Argon':143.2
|
||||
E_K = {'REFPROP-Ammonia': 386,
|
||||
'REFPROP-Argon': 143.2
|
||||
}
|
||||
SIGMA = {'REFPROP-Ammonia':0.2957,
|
||||
'REFPROP-Argon':0.335
|
||||
SIGMA = {'REFPROP-Ammonia': 0.2957,
|
||||
'REFPROP-Argon': 0.335
|
||||
}
|
||||
|
||||
E_K['REFPROP-Propane']=263.88
|
||||
SIGMA['REFPROP-Propane']=0.49748
|
||||
E_K['REFPROP-R32']=289.65
|
||||
SIGMA['REFPROP-R32']=0.4098
|
||||
E_K['REFPROP-Propane'] = 263.88
|
||||
SIGMA['REFPROP-Propane'] = 0.49748
|
||||
E_K['REFPROP-R32'] = 289.65
|
||||
SIGMA['REFPROP-R32'] = 0.4098
|
||||
E_K['REFPROP-R245fa'] = 329.72
|
||||
SIGMA['REFPROP-R245fa'] = 0.5529
|
||||
|
||||
|
||||
def viscosity_dilute(fluid,T,e_k,sigma):
|
||||
def viscosity_dilute(fluid, T, e_k, sigma):
|
||||
"""
|
||||
T in [K], e_k in [K], sigma in [nm]
|
||||
viscosity returned is in [Pa-s]
|
||||
"""
|
||||
|
||||
Tstar = T/e_k
|
||||
molemass = Props(fluid,'molemass')
|
||||
Tstar = T / e_k
|
||||
molemass = Props(fluid, 'molemass')
|
||||
if fluid == 'Propane' or fluid == 'REFPROP-Propane':
|
||||
a = [0.25104574,-0.47271238,0,0.060836515,0]
|
||||
theta_star = exp(a[0]*pow(log(Tstar),0)+a[1]*pow(log(Tstar),1)+a[3]*pow(log(Tstar),3));
|
||||
eta_star = 0.021357*sqrt(molemass*T)/(pow(sigma,2)*theta_star)/1e6;
|
||||
a = [0.25104574, -0.47271238, 0, 0.060836515, 0]
|
||||
theta_star = exp(a[0] * pow(log(Tstar), 0) + a[1] * pow(log(Tstar), 1) + a[3] * pow(log(Tstar), 3));
|
||||
eta_star = 0.021357 * sqrt(molemass * T) / (pow(sigma, 2) * theta_star) / 1e6;
|
||||
return eta_star
|
||||
|
||||
# From Neufeld, 1972, Journal of Chemical Physics - checked coefficients
|
||||
OMEGA_2_2 = 1.16145*pow(Tstar,-0.14874)+ 0.52487*exp(-0.77320*Tstar)+2.16178*exp(-2.43787*Tstar)
|
||||
OMEGA_2_2 = 1.16145 * pow(Tstar, -0.14874) + 0.52487 * exp(-0.77320 * Tstar) + 2.16178 * exp(-2.43787 * Tstar)
|
||||
# Using the leading constant from McLinden, 2000 since the leading term from Huber 2003 gives crazy values
|
||||
eta_star = 26.692e-3*sqrt(molemass*T)/(pow(sigma,2)*OMEGA_2_2)/1e6
|
||||
eta_star = 26.692e-3 * sqrt(molemass * T) / (pow(sigma, 2) * OMEGA_2_2) / 1e6
|
||||
return eta_star
|
||||
|
||||
|
||||
@@ -44,15 +44,15 @@ def viscosity_linear(fluid, T, rho, e_k, sigma):
|
||||
"""
|
||||
Implements the method of Vogel 1998 (Propane) for the linear part
|
||||
"""
|
||||
N_A=6.02214129e23
|
||||
molemass = Props(fluid,'molemass')
|
||||
Tstar = T/e_k
|
||||
b= [-19.572881,219.73999,-1015.3226,2471.01251,-3375.1717,2491.6597,-787.26086,14.085455,-0.34664158]
|
||||
s = sum([b[i]*pow(Tstar,-0.25*i) for i in range(7)])
|
||||
N_A = 6.02214129e23
|
||||
molemass = Props(fluid, 'molemass')
|
||||
Tstar = T / e_k
|
||||
b = [-19.572881, 219.73999, -1015.3226, 2471.01251, -3375.1717, 2491.6597, -787.26086, 14.085455, -0.34664158]
|
||||
s = sum([b[i] * pow(Tstar, -0.25 * i) for i in range(7)])
|
||||
|
||||
B_eta_star = s+b[7]*pow(Tstar,-2.5)+b[8]*pow(Tstar,-5.5) #//[no units]
|
||||
B_eta = N_A*pow(sigma/1e9,3)*B_eta_star #[m3/mol]
|
||||
return viscosity_dilute(fluid,T,e_k,sigma)*B_eta*rho/molemass*1000
|
||||
B_eta_star = s + b[7] * pow(Tstar, -2.5) + b[8] * pow(Tstar, -5.5) # //[no units]
|
||||
B_eta = N_A * pow(sigma / 1e9, 3) * B_eta_star # [m3/mol]
|
||||
return viscosity_dilute(fluid, T, e_k, sigma) * B_eta * rho / molemass * 1000
|
||||
|
||||
|
||||
from PDSim.misc.datatypes import Collector
|
||||
@@ -66,40 +66,40 @@ VV1 = Collector()
|
||||
VVH = Collector()
|
||||
|
||||
fluid = 'REFPROP-R32'
|
||||
Tc = Props(fluid,'Tcrit')
|
||||
rhoc = Props(fluid,'rhocrit')
|
||||
for T in np.linspace(290,Props(fluid,'Tcrit')-0.1,100):
|
||||
rhoV = Props('D','T',T,'Q',1,fluid)
|
||||
rhoL = Props('D','T',T,'Q',0,fluid)
|
||||
rhomax = Props('D','T',Props(fluid,'Tmin'),'Q',0,fluid)
|
||||
for rho in list(np.linspace(rhoL,rhomax,100)):#+list(np.linspace(rhoV,0.0001,100)):
|
||||
#for rho in list(np.linspace(rhoV,0.0001,100)):
|
||||
mu_0 = viscosity_dilute(fluid,T,E_K[fluid],SIGMA[fluid])
|
||||
mu_1 = viscosity_linear(fluid,T,rho,E_K[fluid],SIGMA[fluid])
|
||||
mu = Props('V','T',T,'D',rho,fluid)
|
||||
Tc = Props(fluid, 'Tcrit')
|
||||
rhoc = Props(fluid, 'rhocrit')
|
||||
for T in np.linspace(290, Props(fluid, 'Tcrit') - 0.1, 100):
|
||||
rhoV = Props('D', 'T', T, 'Q', 1, fluid)
|
||||
rhoL = Props('D', 'T', T, 'Q', 0, fluid)
|
||||
rhomax = Props('D', 'T', Props(fluid, 'Tmin'), 'Q', 0, fluid)
|
||||
for rho in list(np.linspace(rhoL, rhomax, 100)): # +list(np.linspace(rhoV,0.0001,100)):
|
||||
# for rho in list(np.linspace(rhoV,0.0001,100)):
|
||||
mu_0 = viscosity_dilute(fluid, T, E_K[fluid], SIGMA[fluid])
|
||||
mu_1 = viscosity_linear(fluid, T, rho, E_K[fluid], SIGMA[fluid])
|
||||
mu = Props('V', 'T', T, 'D', rho, fluid)
|
||||
VV << mu
|
||||
VV0 << mu_0
|
||||
VV1 << mu_1
|
||||
VVH << mu-mu_0-mu_1
|
||||
VVH << mu - mu_0 - mu_1
|
||||
TT << T
|
||||
RHO << rho
|
||||
DELTA << rho/rhoc
|
||||
TAU << Tc/T
|
||||
DELTA << rho / rhoc
|
||||
TAU << Tc / T
|
||||
|
||||
|
||||
def f_RHS(E, DELTA_TAU, VV):
|
||||
k = 0
|
||||
sum = 0
|
||||
DELTA = DELTA_TAU[0,:]
|
||||
TAU = DELTA_TAU[1,:]
|
||||
for i in range(2,5):
|
||||
DELTA = DELTA_TAU[0, :]
|
||||
TAU = DELTA_TAU[1, :]
|
||||
for i in range(2, 5):
|
||||
for j in range(3):
|
||||
sum += E[k]*DELTA**i/TAU**j
|
||||
sum += E[k] * DELTA**i / TAU**j
|
||||
k += 1
|
||||
# f1,f2,f3,g1,g2 = E[k],E[k+1],E[k+2],E[k+3],E[k+4]
|
||||
# DELTA0 = g1*(1+g2*np.sqrt(TAU))
|
||||
# sum += (f1+f2/TAU+f3/TAU/TAU)*(DELTA/(DELTA0-DELTA)-DELTA/DELTA0)
|
||||
print('%s %%' % np.mean(np.abs(((sum/VV-1)*100))))
|
||||
print('%s %%' % np.mean(np.abs(((sum / VV - 1) * 100))))
|
||||
return sum
|
||||
|
||||
|
||||
@@ -108,15 +108,15 @@ log_muH = np.log(VVH.v().T)
|
||||
x = np.c_[DELTA.v().T, TAU.v().T].T
|
||||
y = VVH.v()
|
||||
|
||||
linear = Model(f_RHS, extra_args = (y,) )
|
||||
linear = Model(f_RHS, extra_args=(y,))
|
||||
mydata = Data(x, y)
|
||||
myodr = ODR(mydata, linear, beta0=np.array([0.1]*17),)
|
||||
myodr = ODR(mydata, linear, beta0=np.array([0.1] * 17),)
|
||||
myoutput = myodr.run()
|
||||
E = myoutput.beta
|
||||
print(E)
|
||||
|
||||
#plt.plot(TT.vec, y,'b.',TT.vec, f_RHS(E, x, y),'r.')
|
||||
#plt.show()
|
||||
#plt.plot()
|
||||
plt.plot(y.T,f_RHS(E, x, y))
|
||||
# plt.show()
|
||||
# plt.plot()
|
||||
plt.plot(y.T, f_RHS(E, x, y))
|
||||
plt.show()
|
||||
|
||||
@@ -100,7 +100,7 @@ class BibTeXerClass(object):
|
||||
A function that always returns unicode. It also tries to recurse into
|
||||
lists and dicts, but be careful this is not thoroughly tested.
|
||||
"""
|
||||
table = { ord(u'{'): None, ord(u'}'): None }
|
||||
table = {ord(u'{'): None, ord(u'}'): None}
|
||||
|
||||
if isinstance(text, str): # ordinary string
|
||||
pass
|
||||
|
||||
@@ -374,7 +374,7 @@ class SaturationTable(wx.Frame):
|
||||
|
||||
#Add the headers
|
||||
for c in range(cols):
|
||||
data += str(self.tbl.GetColLabelValue(c).replace('\n',' ') )
|
||||
data += str(self.tbl.GetColLabelValue(c).replace('\n',' '))
|
||||
if c < cols - 1:
|
||||
data += '\t'
|
||||
data = data + '\n'
|
||||
|
||||
@@ -465,12 +465,12 @@ class IsoLine(Base2DObject):
|
||||
# Normally we calculate a sweep in x-dimensions, but
|
||||
# sometimes a sweep in y-dimensions is better.
|
||||
XY_SWITCH = {
|
||||
CoolProp.iDmass: { Base2DObject.TS:True , Base2DObject.PH:True , Base2DObject.HS:False, Base2DObject.PS:True , Base2DObject.PD:None , Base2DObject.TD:None , Base2DObject.PT:False},
|
||||
CoolProp.iHmass: { Base2DObject.TS:False, Base2DObject.PH:None , Base2DObject.HS:None , Base2DObject.PS:True , Base2DObject.PD:True , Base2DObject.TD:False, Base2DObject.PT:False},
|
||||
CoolProp.iP : { Base2DObject.TS:False, Base2DObject.PH:None , Base2DObject.HS:False, Base2DObject.PS:None , Base2DObject.PD:None , Base2DObject.TD:False, Base2DObject.PT:None },
|
||||
CoolProp.iSmass: { Base2DObject.TS:None , Base2DObject.PH:True , Base2DObject.HS:None , Base2DObject.PS:None , Base2DObject.PD:True , Base2DObject.TD:False, Base2DObject.PT:True },
|
||||
CoolProp.iT : { Base2DObject.TS:None , Base2DObject.PH:True , Base2DObject.HS:False, Base2DObject.PS:False, Base2DObject.PD:False, Base2DObject.TD:None , Base2DObject.PT:None },
|
||||
CoolProp.iQ : { Base2DObject.TS:True , Base2DObject.PH:True , Base2DObject.HS:True , Base2DObject.PS:True , Base2DObject.PD:True , Base2DObject.TD:True , Base2DObject.PT:False}
|
||||
CoolProp.iDmass: {Base2DObject.TS:True , Base2DObject.PH:True , Base2DObject.HS:False, Base2DObject.PS:True , Base2DObject.PD:None , Base2DObject.TD:None , Base2DObject.PT:False},
|
||||
CoolProp.iHmass: {Base2DObject.TS:False, Base2DObject.PH:None , Base2DObject.HS:None , Base2DObject.PS:True , Base2DObject.PD:True , Base2DObject.TD:False, Base2DObject.PT:False},
|
||||
CoolProp.iP : {Base2DObject.TS:False, Base2DObject.PH:None , Base2DObject.HS:False, Base2DObject.PS:None , Base2DObject.PD:None , Base2DObject.TD:False, Base2DObject.PT:None},
|
||||
CoolProp.iSmass: {Base2DObject.TS:None , Base2DObject.PH:True , Base2DObject.HS:None , Base2DObject.PS:None , Base2DObject.PD:True , Base2DObject.TD:False, Base2DObject.PT:True},
|
||||
CoolProp.iT : {Base2DObject.TS:None , Base2DObject.PH:True , Base2DObject.HS:False, Base2DObject.PS:False, Base2DObject.PD:False, Base2DObject.TD:None , Base2DObject.PT:None},
|
||||
CoolProp.iQ : {Base2DObject.TS:True , Base2DObject.PH:True , Base2DObject.HS:True , Base2DObject.PS:True , Base2DObject.PD:True , Base2DObject.TD:True , Base2DObject.PT:False}
|
||||
}
|
||||
|
||||
# Abort interpolation if there are not enough
|
||||
@@ -616,8 +616,8 @@ class IsoLine(Base2DObject):
|
||||
ipos,xpos,ypos,pair = self.get_update_pair()
|
||||
|
||||
order = [ipos,xpos,ypos]
|
||||
idxs = [v for (_,v) in sorted(zip(order,[self.i_index , self.x_index , self.y_index ]))]
|
||||
vals = [v for (_,v) in sorted(zip(order,[np.array(self.value), xvals , yvals ]))]
|
||||
idxs = [v for (_,v) in sorted(zip(order,[self.i_index , self.x_index , self.y_index]))]
|
||||
vals = [v for (_,v) in sorted(zip(order,[np.array(self.value), xvals , yvals]))]
|
||||
if vals[0] is None or vals[1] is None:
|
||||
raise ValueError("One required input is missing, make sure to supply the correct xvals ({0:s}) or yvals ({1:s}).".format(str(xvals),str(yvals)))
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ class PropertyPlot(BasePlot):
|
||||
# make sense, does it?
|
||||
while len(inVal) > len(output) and digits < limit:
|
||||
digits += 1
|
||||
val = ( np.around(np.log10(np.abs(inVal))) * -1) + digits + 1
|
||||
val = (np.around(np.log10(np.abs(inVal))) * -1) + digits + 1
|
||||
val = np.where(val < lim, val, lim)
|
||||
val = np.where(val >-lim, val, -lim)
|
||||
output = np.zeros(inVal.shape)
|
||||
|
||||
Reference in New Issue
Block a user