Skip to content
This repository was archived by the owner on Nov 27, 2023. It is now read-only.

Commit a01f819

Browse files
committed
IO: misc updates from welib
1 parent e1617f5 commit a01f819

File tree

8 files changed

+70
-21
lines changed

8 files changed

+70
-21
lines changed

pyFAST/input_output/converters.py

+38-8
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,44 @@
44
# --------------------------------------------------------------------------------
55
# --- Writing pandas DataFrame to different formats
66
# --------------------------------------------------------------------------------
7-
# The
7+
def writeDataFrameToFormat(df, filename, fformat):
8+
"""
9+
Write a dataframe to disk based on user-specified fileformat
10+
- df: pandas dataframe
11+
- filename: filename
12+
- fformat: fileformat in: ['csv', 'outb', 'parquet']
13+
"""
14+
15+
if fformat=='outb':
16+
dataFrameToOUTB(df, filename)
17+
elif fformat=='parquet':
18+
dataFrameToParquet(df, filename)
19+
elif fformat=='csv':
20+
dataFrameToCSV(df, filename, sep=',', index=False)
21+
else:
22+
raise Exception('File format not supported for dataframe export `{}`'.format(fformat))
23+
24+
def writeDataFrameAutoFormat(df, filename, fformat=None):
25+
"""
26+
Write a dataframe to disk based on extension
27+
- df: pandas dataframe
28+
- filename: filename
29+
"""
30+
if fformat is not None:
31+
raise Exception()
32+
base, ext = os.path.splitext(filename)
33+
ext = ext.lower()
34+
if ext in ['.outb']:
35+
fformat = 'outb'
36+
elif ext in ['.parquet']:
37+
fformat = 'parquet'
38+
elif ext in ['.csv']:
39+
fformat = 'csv'
40+
else:
41+
print('[WARN] defaulting to csv, extension unknown: `{}`'.format(ext))
42+
fformat = 'csv'
43+
44+
writeDataFrameToFormat(df, filename, fformat)
845

946
def writeFileDataFrames(fileObject, writer, extension='.conv', filename=None, **kwargs):
1047
"""
@@ -35,7 +72,6 @@ def writeFileDataFrames(fileObject, writer, extension='.conv', filename=None, **
3572
else:
3673
writeDataFrame(df=dfs, writer=writer, filename=filename, **kwargs)
3774

38-
3975
def writeDataFrame(df, writer, filename, **kwargs):
4076
"""
4177
Write a dataframe to disk based on a "writer" function.
@@ -47,16 +83,10 @@ def writeDataFrame(df, writer, filename, **kwargs):
4783

4884
# --- Low level writers
4985
def dataFrameToCSV(df, filename, sep=',', index=False, **kwargs):
50-
base, ext = os.path.splitext(filename)
51-
if len(ext)==0:
52-
filename = base='.csv'
5386
df.to_csv(filename, sep=sep, index=index, **kwargs)
5487

5588
def dataFrameToOUTB(df, filename, **kwargs):
5689
from .fast_output_file import writeDataFrame as writeDataFrameToOUTB
57-
base, ext = os.path.splitext(filename)
58-
if len(ext)==0:
59-
filename = base='.outb'
6090
writeDataFrameToOUTB(df, filename, binary=True)
6191

6292
def dataFrameToParquet(df, filename, **kwargs):

pyFAST/input_output/excel_file.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,10 @@ def __repr__(self):
7575

7676

7777
def _toDataFrame(self):
78-
#cols=['Alpha_[deg]','Cl_[-]','Cd_[-]','Cm_[-]']
79-
#dfs[name] = pd.DataFrame(data=..., columns=cols)
80-
#df=pd.DataFrame(data=,columns=)
81-
return self.data
78+
if len(self.data)==1:
79+
# Return a single dataframe
80+
return self.data[list(self.data.keys())[0]]
81+
else:
82+
# Return dictionary
83+
return self.data
8284

pyFAST/input_output/fast_output_file.py

+17-6
Original file line numberDiff line numberDiff line change
@@ -235,23 +235,30 @@ def isBinary(filename):
235235

236236

237237

238-
def load_ascii_output(filename, method='numpy'):
238+
def load_ascii_output(filename, method='numpy', encoding='ascii'):
239239

240240

241241
if method in ['forLoop','pandas']:
242242
from .file import numberOfLines
243243
nLines = numberOfLines(filename, method=2)
244244

245-
with open(filename) as f:
245+
with open(filename, encoding=encoding, errors='ignore') as f:
246246
info = {}
247247
info['name'] = os.path.splitext(os.path.basename(filename))[0]
248248
# Header is whatever is before the keyword `time`
249-
in_header = True
250249
header = []
251-
while in_header:
250+
maxHeaderLines=35
251+
headerRead = False
252+
for i in range(maxHeaderLines):
252253
l = f.readline()
253254
if not l:
254255
raise Exception('Error finding the end of FAST out file header. Keyword Time missing.')
256+
# Check for utf-16
257+
if l[:3] == '\x00 \x00':
258+
f.close()
259+
encoding=''
260+
print('[WARN] Attempt to re-read the file with encoding utf-16')
261+
return load_ascii_output(filename=filename, method=method, encoding='utf-16')
255262
first_word = (l+' dummy').lower().split()[0]
256263
in_header= (first_word != 'time') and (first_word != 'alpha')
257264
if in_header:
@@ -260,6 +267,10 @@ def load_ascii_output(filename, method='numpy'):
260267
info['description'] = header
261268
info['attribute_names'] = l.split()
262269
info['attribute_units'] = [unit[1:-1] for unit in f.readline().split()]
270+
headerRead=True
271+
break
272+
if not headerRead:
273+
raise WrongFormatError('Could not find the keyword "Time" or "Alpha" in the first {} lines of the file'.format(maxHeaderLines))
263274

264275
nHeader = len(header)+1
265276
nCols = len(info['attribute_names'])
@@ -285,13 +296,13 @@ def load_ascii_output(filename, method='numpy'):
285296
data = np.zeros((nRows, nCols))
286297
for i in range(nRows):
287298
l = f.readline().strip()
288-
sp = np.array(l.split()).astype(np.float)
299+
sp = np.array(l.split()).astype(float)
289300
data[i,:] = sp[:nCols]
290301

291302
elif method == 'listCompr':
292303
# --- Method 4 - List comprehension
293304
# Data, up to end of file or empty line (potential comment line at the end)
294-
data = np.array([l.strip().split() for l in takewhile(lambda x: len(x.strip())>0, f.readlines())]).astype(np.float)
305+
data = np.array([l.strip().split() for l in takewhile(lambda x: len(x.strip())>0, f.readlines())]).astype(float)
295306
else:
296307
raise NotImplementedError()
297308

pyFAST/input_output/file_formats.py

+2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ def isRightFormat(fileformat, filename, **kwargs):
1111
except WrongFormatError:
1212
return False,None
1313
except:
14+
# We Raise the Exception.
15+
# It's the responsability of all the file classes to Return a WrongFormatError
1416
raise
1517

1618
class FileFormat():

pyFAST/input_output/flex_out_file.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def read_flex_res(filename, dtype=np.float32):
134134

135135

136136
def read_flex_sensor(sensor_file):
137-
with open(sensor_file, encoding="utf-8") as fid:
137+
with open(sensor_file, 'r') as fid:
138138
sensor_info_lines = fid.readlines()[2:]
139139
sensor_info = []
140140
d=dict({ 'ID':[],'Gain':[],'Offset':[],'Unit':[],'Name':[],'Description':[]});

pyFAST/input_output/matlabmat_file.py

-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ def read(self, filename=None, **kwargs):
6363
raise EmptyFileError('File is empty:',self.filename)
6464

6565
mfile = scipy.io.loadmat(self.filename)
66-
import pdb; pdb.set_trace()
6766

6867
def write(self, filename=None):
6968
""" Rewrite object to file, or write object to `filename` if provided """

pyFAST/input_output/pickle_file.py

+6
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,12 @@ def _setData(self, data):
6565
else:
6666
self['data'] = data
6767

68+
def addDict(self, data):
69+
self._setData(data)
70+
71+
def additem(self, key, data):
72+
self[key]=data
73+
6874
def read(self, filename=None, **kwargs):
6975
""" Reads the file self.filename, or `filename` if provided """
7076
# --- Standard tests and exceptions (generic code)

pyFAST/input_output/wetb/hawc2/htc_file.py

-1
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,6 @@ def unix_path(self, filename):
591591
if "__main__" == __name__:
592592
f = HTCFile(r"C:/Work/BAR-Local/Hawc2ToBeamDyn/sim.htc", ".")
593593
print(f.input_files())
594-
import pdb; pdb.set_trace()
595594
# f.save(r"C:\mmpe\HAWC2\models\DTU10MWRef6.0\htc\DTU_10MW_RWT_power_curve.htc")
596595
#
597596
# f = HTCFile(r"C:\mmpe\HAWC2\models\DTU10MWRef6.0\htc\DTU_10MW_RWT.htc", "../")

0 commit comments

Comments
 (0)