Skip to content

Commit 68920ea

Browse files
adrpoOpenModelica-Hudson
authored andcommitted
update the buildings2csv script
1 parent 8c0a156 commit 68920ea

File tree

1 file changed

+123
-29
lines changed

1 file changed

+123
-29
lines changed

Examples/ConvertBuildingsReferenceToCSV.py

Lines changed: 123 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,127 @@
44
import sys
55
from optparse import OptionParser
66

7+
########################################################################
8+
# Adrian.Pop@liu.se 2016-12-10
9+
# parts of this script were taken from the building library here:
10+
# https://github.com/lbl-srg/modelica-buildings/*/buildingspy_to_csv.py
11+
########################################################################
12+
# This script converts a reference result file
13+
# from the format used by BuildingsPy to the
14+
# csv format used by the Modelica Association.
15+
#
16+
# This script is provided for tools that compare the
17+
# reference results with the csv compare tool
18+
# from the Modelica Association.
19+
#
20+
# MWetter@lbl.gov 2016-08-31
21+
########################################################################
22+
23+
def _read_reference_result(file_name):
24+
''' Read the reference results and write them as a csv file
25+
with the same base file name.
26+
27+
:param file_name: The name of the reference file.
28+
:return: A dictionary with the reference results.
29+
30+
This function is based on buildingspy.development.regressiontest:_readReferenceResults()
31+
but provided as a stand-alone function to avoid dependency on
32+
BuildingsPy.
33+
34+
'''
35+
f=open(file_name,'r')
36+
lines = f.readlines()
37+
f.close()
38+
39+
# Compute the number of the first line that contains the results
40+
iSta=0
41+
for iLin in range(min(2, len(lines))):
42+
if "svn-id" in lines[iLin]:
43+
iSta=iSta+1
44+
if "last-generated" in lines[iLin]:
45+
iSta=iSta+1
46+
47+
# Dictionary that stores the reference results
48+
r = dict()
49+
iLin = iSta
50+
while iLin < len(lines):
51+
lin = lines[iLin].strip('\n')
52+
try:
53+
(key, value) = lin.split("=")
54+
# Check if this is a statistics-* entry.
55+
if key.startswith("statistics-"):
56+
while (iLin < len(lines)-1 and lines[iLin+1].find('=') == -1):
57+
iLin += 1
58+
else:
59+
s = (value[value.find('[')+1: value.rfind(']')]).strip()
60+
numAsStr=s.split(',')
61+
val = []
62+
for num in numAsStr:
63+
# We need to use numpy.float64 here for the comparison to work
64+
# val.append(numpy.float64(num))
65+
val.append(num)
66+
r[key] = val
67+
except ValueError as detail:
68+
s = "%s could not be parsed.\n" % file_name
69+
sys.stderr.write(s)
70+
raise TypeError(detail)
71+
iLin += 1
72+
return r
73+
74+
def _write_csv(file_name, d):
75+
""" Writes the dictionary with the reference results to a csv file.
76+
77+
:param file_name: The name of the csv reference file.
78+
:param: A dictionary with the reference results.
79+
"""
80+
import numpy as np
81+
# Get the length of the data series
82+
83+
# Check if time is a key, as FMU export has no time series
84+
found_time = False
85+
for key in d.keys():
86+
if key == 'time':
87+
found_time = True
88+
break
89+
if not found_time:
90+
return
91+
92+
n = 2
93+
for key in d.keys():
94+
# Parameters and time have two entries. Hence, we search
95+
# to see if there are data with more entries.
96+
if len(d[key]) > 2:
97+
n = len(d[key])
98+
break
99+
# Set all series to have the same length
100+
for key in d.keys():
101+
if len(d[key]) != n:
102+
if key == 'time':
103+
d[key] = np.linspace( \
104+
np.float64(d[key][0]), \
105+
np.float64(d[key][-1]), n).tolist()
106+
else:
107+
d[key] = [d[key][0] for x in range(n)]
108+
109+
# Write data as csv file
110+
with open(file_name, 'w') as f:
111+
# Write header
112+
f.write("time")
113+
for key in d.keys():
114+
if key != 'time':
115+
f.write(", %s" % key)
116+
f.write("\n")
117+
# Write data
118+
for i in range(n):
119+
vals = d['time']
120+
f.write(str(vals[i]))
121+
for key in d.keys():
122+
if key != 'time':
123+
vals = d[key]
124+
f.write(", %s" % vals[i])
125+
f.write("\n")
126+
127+
7128
def convertDir(indir,outdir):
8129
for fil in os.listdir(indir):
9130
print "Converting file: %s\n" % indir+"/"+fil
@@ -14,35 +135,8 @@ def convertDir(indir,outdir):
14135
continue
15136
else:
16137
f.seek(0)
17-
v = {}
18-
for line in f.readlines():
19-
line = line.strip().split('=')
20-
# print "Line %s \n" % line
21-
if (line is not None) and (len(line) == 2) and (line[1] != ''):
22-
if (line[1][0] == '['):
23-
l = [str(float(s)) for s in line[1].strip('[]').split(',')]
24-
if len(l)==2:
25-
diff = float(l[1])-float(l[0])
26-
l = [str(float(l[0])+x*diff) for x in range(101)]
27-
if len(l)<>101:
28-
raise Exception("Assumed buildings result format has exactly 101 data points")
29-
v[line[0]] = l
30-
keys = v.keys()
31-
#for key in keys :
32-
# print key + "\n"
33-
#try:
34-
keys.remove('time')
35-
#except ValueError:
36-
# pass # no nothing
37-
keys.sort()
38-
keys = ['time'] + keys
39-
values = [v[key] for key in keys]
40-
# Transpose
41-
rows = map(list, zip(*values))
42-
o = open(outdir+"/"+fil[0:-4]+'.csv', 'w')
43-
o.write(','.join(keys) + '\n')
44-
for row in rows:
45-
o.write(','.join(row) + '\n')
138+
d = _read_reference_result(indir+"/"+fil)
139+
_write_csv(outdir+"/"+fil[0:-4]+'.csv', d)
46140

47141
def main():
48142
parser = OptionParser()

0 commit comments

Comments
 (0)