-
Notifications
You must be signed in to change notification settings - Fork 6
/
OpenFASTutil.py
309 lines (281 loc) · 10.8 KB
/
OpenFASTutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#!/usr/bin/env python
#
# Copyright (c) 2022, Alliance for Sustainable Energy
#
# This software is released under the BSD 3-clause license. See LICENSE file
# for more details.
#
import sys, os, re
from collections import OrderedDict
import numpy as np
import fileinput
scriptpath = os.path.dirname(os.path.realpath(__file__))
utilpath = os.path.join(scriptpath, 'utilities')
sys.path.insert(1, utilpath)
import findOFversion as findOFversion
def is_number(s):
try:
complex(s) # for int, long, float and complex
except ValueError:
return False
return True
def editFASTfile(FASTfile, replacedict):
commentchars = ['=', '#']
OutListCount = 0
for line in fileinput.input(FASTfile, inplace=True, backup='.bak'):
#sys.stdout.write("# "+line)
linesplit=re.split('[, ;]+', line.strip())
outline=""
# Check to make sure the line doesn't start with comment char
firstchar = ""
if len(line.strip())>0: firstchar = line.strip()[0]
if firstchar in commentchars:
outline=str(line)
# Edit the Outlist if applicable
if (linesplit[0]=='OutList'):
if ('OutList' in replacedict.keys()) or ('OutList'+repr(OutListCount) in replacedict.keys()):
targetkey = 'OutList' if 'OutList' in replacedict.keys() else 'OutList'+repr(OutListCount)
sys.stderr.write('Adding %s to OutList\n'%(repr(replacedict[targetkey])))
outline = str(line)
outline += replacedict[targetkey]+'\n'
OutListCount += 1
else:
# Ignore any lines with less than two items
if len(linesplit)<2:
outline=str(line)
# Check to make sure line is not all numbers
allnums = [is_number(x) for x in linesplit]
if False not in allnums:
outline=str(line)
# Handle list of nodes
if outline=="":
idx = 1
if is_number(linesplit[idx]):
# Find the right keyword
idx = allnums.index(False)
keyword = linesplit[idx]
if keyword in replacedict.keys():
replacestring = repr(replacedict[keyword]).replace("'",'')
outline = '%10s '%replacestring
outline += ' '.join(linesplit[idx:])
outline += ' [EDITED]\n'
sys.stderr.write(outline)
else:
outline=line
# Write out the line
sys.stdout.write(outline)
return
def editDISCONfile(DISCONfile, replacedict):
"""
Edits a value in the DISCON file
"""
findsubstring = lambda s, start, end: s.split(start)[1].split(end)[0]
commentchars = ['!']
iline = 0
for line in fileinput.input(DISCONfile, inplace=True, backup='.bak'):
outline=""
# Ignore the line if it starts with a comment
if len(line.strip())>0: firstchar = line.strip()[0]
if firstchar in commentchars:
outline=str(line)
# Replace the line by number
linekey = 'line'+str(iline)
if linekey in replacedict.keys():
outline = replacedict[linekey]+'\n'
sys.stderr.write('replacing line %i with \n%s'%(iline, outline))
# Look for a keyword in the discon file
keystart = '!'
keyend = '-'
try:
keyword = findsubstring(line, keystart, keyend).strip()
except:
keyword = None
if (keyword is not None) and keyword in replacedict.keys():
# Replace everything in the beginning of the line
linesplit = line.split(keystart, 1)
endline = linesplit[1].strip()
outline = str(replacedict[keyword])+' ! '+endline+' [EDITED]\n'
sys.stderr.write(outline)
# If nothing needs to be modified in the line, keep it original
if outline=="":
outline=line
# Write out the line
sys.stdout.write(outline)
iline += 1
return
def FASTfile2dict(FASTfile):
"""
Reads the file FASTfile and returns a dictionary with parameters
"""
commentchars = ['=', '#']
d = OrderedDict()
# go through the file line-by-line
with open(FASTfile) as fp:
line=fp.readline()
while line:
# Check to make sure the line doesn't start with comment char
firstchar = ""
if len(line.strip())>0: firstchar = line.strip()[0]
if firstchar in commentchars:
line=fp.readline()
continue
#linesplit=line.strip().split(", ")
linesplitX=re.split('[, ;]+', line.strip())
# Remove any empty tokens in linesplit
linesplit=[x.strip() for x in linesplitX if x.strip() != '']
# Ignore any lines with less than two items
if len(linesplit)<2:
line=fp.readline()
continue
# Check to make sure line is not all numbers
allnums = [is_number(x) for x in linesplit]
if False not in allnums:
line=fp.readline()
continue
# Handle the outlist
if linesplit[0]=="OutList":
outlistline = fp.readline()
outlistlinesplit = outlistline.strip().split()
firstword = "" if len(outlistlinesplit)==0 else outlistlinesplit[0]
outlist = []
while firstword != "END":
outlist.append(outlistline.strip())
outlistline = fp.readline()
outlistlinesplit = outlistline.strip().split()
firstword = "" if len(outlistlinesplit)==0 else outlistlinesplit[0]
# Check how many other Outlists there are:
keylist = [k for k,g in d.items()]
numOutList=len([x for x in keylist if x.startswith('OutList')])
suffix = repr(numOutList) if numOutList>0 else ''
d["OutList"+suffix] = outlist
line = fp.readline()
continue
# Handle list of nodes
idx = 1
if is_number(linesplit[idx]):
# Find the right keyword
idx = allnums.index(False)
keyword = linesplit[idx]
if idx==1:
d[keyword] = linesplit[0]
else:
d[keyword] = linesplit[:idx]
line=fp.readline()
return d
def getFileFromFST(fstfile, key, fstdict=None):
"""
Get the file referenced by key in fstfile
"""
if fstdict is None:
fstdict=FASTfile2dict(fstfile)
keyfile = fstdict[key].strip('"').strip("'")
# Now set up the path to keyfile correctly
fstpath = os.path.dirname(os.path.abspath(fstfile))
return os.path.join(fstpath, keyfile)
def getVarFromFST(fstfile, key, fstdict=None):
"""
Get the file referenced by key in fstfile
"""
if fstdict is None:
fstdict=FASTfile2dict(fstfile)
return fstdict[key]
def loadoutfile(filename):
"""
Loads the FAST output file
"""
# load the data file
dat=np.loadtxt(filename, skiprows=8)
# get the headers and units
with open(filename) as fp:
fp.readline() # blank
fp.readline() # When FAST was run
fp.readline() # linked with...
fp.readline() # blank
fp.readline() # Description of FAST input file
fp.readline() # blank
varsline=fp.readline()
unitline=fp.readline()
headers=varsline.strip().split()
units =unitline.strip().split()
return dat, headers, units
def loadalldata(allfiles):
"""
Load all data files given in allfiles
"""
adat=[]
header0=[]
units0=[]
names=[]
for ifile, file in enumerate(allfiles):
names.append(file)
print("Loading file "+file)
dat, headers, units = loadoutfile(file)
adat.append(dat)
if ifile==0:
header0 = headers
units0 = units
else:
if ((len(header0) != len(headers)) or (len(units0)!=len(units))):
print("Data sizes doesn't match")
sys.exit(1)
return adat, header0, units0, names
def getDensity(fstfile, verbose=False):
"""
Gets the density in OpenFAST input file
"""
# Get the version of the fstfile
ver, match = findOFversion.findversion(fstfile)
if verbose: print("Version: "+repr(ver))
if (match != findOFversion.versionmatch.MATCH):
print("No matching version found for "+fstfile)
sys.exit(1)
return
# Get the AeroFile
AeroFile = getVarFromFST(fstfile, 'AeroFile').strip('"')
AeroFileWPath = os.path.join(os.path.dirname(fstfile), AeroFile)
AirDens = getVarFromFST(AeroFileWPath,'AirDens')
verindex = findOFversion.convertversiontoindex((ver['major'], ver['minor']))
ver31index = findOFversion.convertversiontoindex((3,1))
if verindex < ver31index:
# Just get density from the AeroFile
if verbose: print("Density from aerofile: %f"%float(AirDens))
return float(AirDens)
else:
# Check the density from AeroFile
AirDensString = AirDens.replace('"', '').replace("'",'').lower()
if verbose: print("Density from aerofile: %s"%AirDensString)
if AirDensString == "default":
# Get density from fst file
fstdensity = getVarFromFST(fstfile, 'AirDens')
if verbose: print("Using density from fst file: %s"%fstdensity)
return float(fstdensity)
else:
return float(AirDensString)
return
def setDensity(fstfile, density, verbose=False):
"""
Sets the density in OpenFAST input file
"""
# Get the version of the fstfile
ver, match = findOFversion.findversion(fstfile)
if verbose: print("Version: "+repr(ver))
if (match != findOFversion.versionmatch.MATCH):
print("No matching version found for "+fstfile)
sys.exit(1)
return
verindex = findOFversion.convertversiontoindex((ver['major'], ver['minor']))
ver31index = findOFversion.convertversiontoindex((3,1))
if verindex < ver31index:
# Set density in the AeroFile
# Get the AeroFile
AeroFile = getVarFromFST(fstfile, 'AeroFile').strip('"')
AeroFileWPath = os.path.join(os.path.dirname(fstfile), AeroFile)
editFASTfile(AeroFileWPath, {'AirDens':density})
if verbose:
print("Set AirDens in %s: %f"%(AeroFile, float(AirDens)))
else:
# Set density in the FST file
editFASTfile(fstfile, {'AirDens':density})
if verbose:
print("Set AirDens in %s: %f"%(fstfile, float(AirDens)))
return