forked from OpenFAST/openfast_toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tecplot_file.py
222 lines (193 loc) · 7.24 KB
/
tecplot_file.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
"""
Read/Write TecPto ascii files
sea read_tecplot documentation below
Part of weio library: https://github.com/ebranlard/weio
"""
import pandas as pd
import numpy as np
import os
import struct
try:
from .file import File, EmptyFileError, WrongFormatError, BrokenFormatError
except:
EmptyFileError = type('EmptyFileError', (Exception,),{})
WrongFormatError = type('WrongFormatError', (Exception,),{})
BrokenFormatError = type('BrokenFormatError', (Exception,),{})
File=dict
Keywords=['title','variables','zone','text','geometry','datasetauxdata','customlabels','varauxdata']
# --------------------------------------------------------------------------------}
# --- Helper functions
# --------------------------------------------------------------------------------{
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def _process_merged_line(line, section, dict_out):
n = len(section)
line = line[n:].strip()
if section=='title':
dict_out[section]=line
elif section=='variables':
line = line.replace('=','').strip()
line = line.replace(',',' ').strip()
line = line.replace(' ',' ').strip()
line = line.replace('[','_[').strip()
line = line.replace('(','_(').strip()
line = line.replace('__','_').strip()
if line.find('"')==0:
line = line.replace('" "',',')
line = line.replace('"','')
sp=line.split(',')
else:
sp=line.split()
dict_out[section]=sp
elif section=='datasetauxdata':
if section not in dict_out.keys():
dict_out[section]={} # initialixe an empty directory
sp = line.split('=')
key = sp[0]
value = sp[1].replace('"','').strip()
if is_number(value):
value=float(value)
dict_out[section][key]=value
elif section=='zone':
if section not in dict_out.keys():
dict_out[section]={} # initialixe an empty directory
sp = line.split('=')
key = sp[0]
value = sp[1].replace('"','').strip()
if is_number(value):
value=float(value)
dict_out[section][key]=value
else:
print('!!! Reading of section not implemented:')
print('Processing section {}:'.format(section),line)
dict_out[section]=line
def read_tecplot(filename, dict_out={}):
""" Reads a tecplot file
Limited support:
- title optional
- variables mandatory
- Lines may be continued to next line, stopping when a predefined keyword is detected
For now, assumes that only one section of numerical data is present
"""
merged_line=''
current_section=''
variables=[]
with open(filename, "r") as f:
dfs = [] # list of dataframes
iline=0
while True:
line= f.readline().strip()
iline+=1
if not line:
break
l=line.lower().strip()
# Comment
if l[0]=='#':
continue
new_section = [k for k in Keywords if l.find(k)==0 ]
if len(new_section)==1:
# --- Start of a new section
# First, process the previous section
if len(merged_line)>0:
_process_merged_line(merged_line, current_section, dict_out)
# Then start the new section
current_section=new_section[0]
merged_line =line
elif len(current_section)==0:
raise WrongFormatError('No section detected')
else:
if current_section=='title' or current_section=='variables':
# OK
pass
else:
if 'variables' not in dict_out.keys():
raise WrongFormatError('The `variables` section should be present')
sp = l.split()
if is_number(sp[0]):
if len(merged_line)>0:
_process_merged_line(merged_line, current_section, dict_out)
# --- Special case of numerical values outside of zone
f.close()
M = np.loadtxt(filename, skiprows = iline-1)
if M.shape[1]!=len(dict_out['variables']):
raise BrokenFormatError('Number of columns of data does not match number of variables')
dict_out['data']=M
break
else:
# --- Continuation of previous section
merged_line +=' '+line
return dict_out
class TecplotFile(File):
@staticmethod
def defaultExtensions():
return ['.dat']
@staticmethod
def formatName():
return 'Tecplot ASCII file'
def __init__(self,filename=None,**kwargs):
self.filename = None
if filename:
self.read(filename=filename,**kwargs)
def read(self, filename=None):
""" read a tecplot ascii file
sea `read_tecplot` documentation above
"""
if filename:
self.filename = filename
if not self.filename:
raise Exception('No filename provided')
if not os.path.isfile(self.filename):
raise OSError(2,'File not found:',self.filename)
if os.stat(self.filename).st_size == 0:
raise EmptyFileError('File is empty:',self.filename)
try:
read_tecplot(filename,self)
except BrokenFormatError:
raise
except WrongFormatError:
raise
except Exception as e:
raise WrongFormatError('Tecplot dat File {}: '.format(self.filename)+e.args[0])
def write(self, filename=None, precision=None):
""" Write tecplot ascii file """
if filename:
self.filename = filename
if not self.filename:
raise Exception('No filename provided')
with open(self.filename, mode='w') as f:
if 'title' in self.keys():
f.write('TITLE = {}\n'.format(self['title']))
f.write('VARIABLES = ' + ','.join(['"{}"'.format(col) for col in self['variables'] ]) + '\n')
for k in Keywords[2:]:
if k in self.keys():
f.write('{} = {}\n'.format(k,self[k]))
# Data
if 'data' in self.keys():
for row in self['data']:
srow = np.array2string(row, edgeitems=0, separator=' ', precision=precision)
f.write(srow[1:-1]+'\n')
def __repr__(self):
s='<{} object> with keys:\n'.format(type(self).__name__)
for k,v in self.items():
s+=' - {}: {}\n'.format(k,v)
return s
def toDataFrame(self):
return pd.DataFrame(data=self['data'],columns=self['variables'])
if __name__=='__main__':
mb = MannBoxFile('mann_bin/mini-u.bin', N=(2,4,8))
F1=mb['field'].ravel()
mb.write('mann_bin/mini-u-out.bin')
mb2= MannBoxFile('mann_bin/mini-u-out.bin', N=(2,4,8))
F2=mb2['field'].ravel()
# print(F1-F2)