-
Notifications
You must be signed in to change notification settings - Fork 1
/
fld-read.jl
314 lines (244 loc) · 8.45 KB
/
fld-read.jl
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
310
311
312
313
314
#=
fld-read.jl
Jeff Fessler and David Hong
=#
export fld_open, fld_header, fld_read
"""
head, is_external_file, fid = fld_open(file ; dir::String="", chat=false)
Read header data from AVS format `.fld` file.
Leaves file open for more reading.
# In
- `file::String` file name, usually ending in `.fld`
# Option
- `dir::String` prepend file name with this directory; default ""
- `chat::Bool` verbose? default: `false`
# Out
- `head::String` array of header information
- `is_external_file::Bool` true if AVS external format
- `fid::IOstream`
"""
function fld_open(
file::AbstractString ;
dir::String = "",
chat::Bool = false,
)
file = joinpath(dir, file)
fid = open(file)
formfeed = '\f' # form feed
newline = '\n'
is_external_file = false
# read header until we find the end of file or the 1st form feed
header = ""
while true
# end of file means external file (or error)
if eof(fid)
if occursin("file=", header)
is_external_file = true
break # end of header file!
else
chat && @info(header)
throw("end of file before form feeds?")
end
end
inchar = read(fid, Char) # read one character
# form feed means embedded file
if inchar == formfeed
eof(fid) && throw("end of file before 2nd form feed?")
inchar = read(fid, Char)
(inchar != formfeed) && throw("not two form feeds?")
chat && @info("embedded data file")
break
end
# otherwise append this character to header string
header *= inchar
end
header = string_to_array(header) # convert to array
chat && @info(header)
return header, is_external_file, fid
end
"""
head = fld_header(file::String ; dir::String="", chat=false)
Read header data from AVS format `.fld` file, then close file.
# In
- `file::String` file name, usually ending in `.fld`
# Option
- `dir::String` prepend file name with this directory; default ""
- `chat::Bool` verbose? default: `false`
# Out
- `head::String` array of header information
"""
function fld_header(file::AbstractString ; kwargs...)
header, _, fid = fld_open(file ; kwargs...)
close(fid)
return header
end
# todo:
# + [ ] 'raw' 0|1 1: return raw data class (default), 0: return doubles
# + [ ] 'slice' int specify which slice to read from 3D file. (0 ... nz-1)
# + [ ] 'chat' 0|1 enable verbosity
# + [ ] 'dim_only' 0|1 returns dims. data and coord are equal to [].
# + [ ] 'coord' 0|1 returns coordinates too (default: 0)
# + [ ] 'coord_format' default: 'n'; see fopen() for machine format options
# (needed for some UM .fld files with 'vaxd' coordinates)
# + [ ] multi files
# + [ ] short datatype
"""
data = fld_read(file::String ; dir::String="", chat=false)
Read data from AVS format `.fld` file
# In
- `file` file name, usually ending in `.fld`
# Option
- `dir::String` prepend file name with this directory; default ""
- `chat::Bool` verbose?
# Out
- `data` Array (1D - 5D) in the data type of the file itself
"""
function fld_read(
file::AbstractString ;
dir::String = "",
chat::Bool = false,
)
file = joinpath(dir, file)
header, is_external_file, fid = fld_open(file ; chat)
chat && @info("is_external_file = $is_external_file")
# parse header to determine data dimensions and type
ndim = arg_get(header, "ndim")
dims = [arg_get(header, "dim$ii") for ii in 1:ndim]
fieldtype = arg_get(header, "field", false)
datatype = arg_get(header, "data", false)
(arg_get(header, "veclen") != 1) && throw("only veclen=1 done")
chat && @info("ndim=$ndim")
chat && @info("dims=$dims")
# external file (binary data in another file)
_skip = 0
if is_external_file
close(fid)
extfile = arg_get(header, "file", false)
filetype = arg_get(header, "filetype", false)
chat && @info("Current file = '$file', External file = '$extfile', type='$filetype'")
_skip = occursin("skip=",prod(header)) ?
arg_get([prod(header)], "skip", false) : 0
if filetype == "ascii"
tmp = dirname(file)
extfile = joinpath(tmp, extfile)
chat && @info("extfile = $extfile")
isfile(extfile) || throw("no ascii file $extfile")
format, _, _ = datatype_fld_to_mat(datatype)
return fld_read_ascii(extfile, (dims...,), format)
elseif filetype != "multi"
if !isfile(extfile)
fdir = file
slash = findlast(isequal('/'), fdir) # todo: windows?
isnothing(slash) && throw("cannot find external file $extfile")
fdir = fdir[1:slash]
extfile = fdir * extfile # add directory
!isfile(extfile) && throw("no external ref file $extfile")
end
else
throw("multi not supported yet") # todo
end
else
filetype = ""
extfile = ""
end
# finally, read the binary data
format, endian, bytes = datatype_fld_to_mat(datatype)
# single file reading
data = fld_read_single(file, fid, dims, datatype, fieldtype,
is_external_file, extfile, format, endian, bytes, _skip)
close(fid)
return data
end
# todo: currently supports only one entry per line (see fld_read.m)
function fld_read_ascii(extfile::AbstractString, dims::Dims, datatype::Type{<:Real})
data = zeros(datatype, dims)
open(extfile, "r") do fid
for i in 1:length(data)
tmp = readline(fid)
data[i] = parse(Float64, tmp)
end
end
return data
end
function fld_read_single(
file, fid, dims, datatype, fieldtype,
is_external_file, extfile, format::Type{<:Real}, endian, bytes, _skip,
)
# reopen file to same position, with appropriate endian too.
if is_external_file
fid = open(extfile)
end
skip(fid,_skip)
rdims = dims # from handling slice option
# read binary data and reshape appropriately
data = Array{format}(undef, rdims...)
try
read!(fid, data)
catch
@info("rdims=$rdims")
throw("file count != data count")
end
return endian === :le ? htol.(data) :
endian === :be ? hton.(data) :
throw("bug $endian")
end
"""
header = string_to_array(header_lines)
Convert long string with embedded newlines into string array.
"""
function string_to_array(header_lines::String)
newline = '\n'
# ensure there is a newline at end, since dumb editors can forget...
if header_lines[end] != newline
header_lines *= newline
end
ends = findall(isequal(newline), header_lines)
(length(ends) <= 0) && throw("no newlines?")
header = split(header_lines, newline, keepempty=false)
# strip comments (lines that begin with #)
header = filter(line -> line[1] != '#', header)
return header
end
"""
arg_get(head, name, toint)
Parse an argument from header, of the `name=value` form
"""
function arg_get(head::Array{<:AbstractString}, name::String, toint::Bool=true)
for line in head
start = findfirst(name * '=',line)
if !isnothing(start)
!isnothing(findnext(name*'=',line,start[end]+1)) && throw("bug: multiples?")
line = line[(start[end]+1):end]
arg = split(line)[1]
toint && (arg = parse(Int,arg))
return arg
end
end
throw("could not find $name in header")
end
"""
format, endian, bytes = datatype_fld_to_mat(datatype)
Determine data format from `.fld` header datatype.
"""
function datatype_fld_to_mat(datatype::AbstractString)
dict = Dict([
("byte", (UInt8, :be, 1)), # :be irrelevant
("short_be", (UInt16, :be, 2)),
("short_sun", (UInt16, :be, 2)),
("xdr_short", (UInt16, :be, 2)),
("short_le", (UInt16, :le, 2)),
("int", (Int32, "", 4)), # native int - not portable
("int_le", (Int32, :le, 4)),
("int_be", (Int32, :be, 4)),
("xdr_int", (Int32, :be, 4)),
("float", (Float32, "", 4)), # native float - not portable
("float_le", (Float32, :le, 4)),
("float_be", (Float32, :be, 4)),
("xdr_float", (Float32, :be, 4)),
("double", (Float64, "", 8)), # native 64oat - not portable
("double_le", (Float64, :le, 8)),
("double_be", (Float64, :be, 8)),
("xdr_double", (Float64, :be, 8)),
])
return dict[datatype] # format, endian, bytes
end