-
Notifications
You must be signed in to change notification settings - Fork 6
/
IOhelperFuncs.py
368 lines (292 loc) · 12.8 KB
/
IOhelperFuncs.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import yt
import numpy as np
from mpi4py import MPI
from mpi4py_fft import newDistArray
import FFTHelperFuncs
import sys
import h5py
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
def read_fields(args):
"""
Read all fields of a simulation snapshot
args : forwarded command line arguments from the main script
"""
# data dictionary
fields = {
'B' : None,
'Acc' : None,
'P' : None,
}
pressField = None
magFields = None
accFields = None
time_start = MPI.Wtime()
if args['data_type'] == 'Enzo':
rhoField = "Density"
velFields = ["x-velocity","y-velocity","z-velocity"]
if args['b']:
magFields = ["Bx","By","Bz"]
if args['forced']:
accFields = ['x-acceleration','y-acceleration','z-acceleration']
readAllFieldsWithYT(fields, args['data_path'], args['res'],
rhoField, velFields, magFields,
accFields, pressField)
elif args['data_type'][:8] == 'AthenaPP':
rhoField = ('athena_pp', 'rho')
velFields = [('athena_pp', 'vel1'), ('athena_pp', 'vel2'), ('athena_pp', 'vel3')]
if args['b']:
magFields = [('athena_pp', 'Bcc1'), ('athena_pp', 'Bcc2'), ('athena_pp', 'Bcc3')]
if args['forced']:
accFields = [('athena_pp', 'acceleration_x'),
('athena_pp', 'acceleration_y'),
('athena_pp', 'acceleration_z')]
if args['eos'] == 'adiabatic':
pressField = ('athena_pp', 'press')
if 'HDF' in args['data_type']:
readAllFieldsWithHDF(fields,'./Turb.prim.' + args['data_path'], args['res'],
rhoField, velFields, magFields,
None, pressField,'F',use_athena_hdf=True)
readAllFieldsWithHDF(fields,'./Turb.acc.' + args['data_path'], args['res'],
None, None, None,
accFields, None,'F',use_athena_hdf=True)
else:
readAllFieldsWithYT(fields,'./Turb.prim.' + args['data_path'], args['res'],
rhoField, velFields, magFields,
None, pressField)
readAllFieldsWithYT(fields,'./Turb.acc.' + args['data_path'], args['res'],
None, None, None,
accFields, None)
elif args['data_type'] == 'AthenaHDFC':
rhoField = 'density'
velFields = ['velocity_x', 'velocity_y', 'velocity_z']
if args['b']:
magFields = ['cell_centered_B_x', 'cell_centered_B_y', 'cell_centered_B_z']
if args['forced']:
accFields = ['acceleration_x', 'acceleration_y', 'acceleration_z']
if args['eos'] == 'adiabatic':
pressField = 'pressure'
order = 'C'
fields = readAllFieldsWithHDF(args['data_path'], args['res'],
rhoField, velFields, magFields,
accFields, pressField,order)
elif args['data_type'] == 'Athena':
rhoField = 'density'
velFields = ['velocity_x', 'velocity_y', 'velocity_z']
if args['b']:
magFields = ['cell_centered_B_x', 'cell_centered_B_y', 'cell_centered_B_z']
if args['forced']:
accFields = ['acceleration_x', 'acceleration_y', 'acceleration_z']
if args['eos'] == 'adiabatic':
pressField = 'pressure'
order = 'C'
readAllFieldsWithYT(fields, args['data_path'], args['res'],
rhoField, velFields, magFields,
accFields, pressField)
else:
raise SystemExit('Unknown data type: ', data_type)
time_elapsed = MPI.Wtime() - time_start
time_elapsed = comm.gather(time_elapsed)
if comm.Get_rank() == 0:
print("Reading data done in %.3g +/- %.3g" %
(np.mean(time_elapsed), np.std(time_elapsed)))
sys.stdout.flush()
return fields
def readAllFieldsWithYT(fields,loadPath,Res,
rhoField,velFields,magFields,accFields,pressField=None):
"""
Reads all fields using the yt frontend. Data is read in parallel.
"""
pencil_shape = FFTHelperFuncs.local_shape
if (np.array(FFTHelperFuncs.FFT.global_shape(), dtype=int) % pencil_shape != 0).any():
raise SystemExit(
'Data cannot be split evenly among processes. ' +
'Abort (for now) - fix me!')
ds = yt.load(loadPath)
left_edge = ds.domain_left_edge
right_edge = ds.domain_right_edge
n_proc = np.array(FFTHelperFuncs.FFT.global_shape(), dtype=int) // pencil_shape
gid_x_s = rank // n_proc[1] * pencil_shape[0] # global x start index
gid_y_s = rank % n_proc[1] * pencil_shape[1] # global y start index
start_pos = left_edge
start_pos[0] += gid_x_s / Res * (right_edge[0] - left_edge[0])
start_pos[1] += gid_y_s / Res * (right_edge[1] - left_edge[1])
if rank == 0:
print("Loading "+ loadPath)
print("Chunk dimensions = ", pencil_shape)
ad = ds.h.covering_grid(level=0, left_edge=start_pos,dims=FFTHelperFuncs.local_shape)
if rhoField is not None:
fields['rho'] = ad[rhoField].d
if pressField is not None:
fields['P'] = ad[pressField].d
else:
if rank == 0:
print("WARNING: assuming isothermal EOS with c_s = 1, i.e. P = rho")
fields['P'] = fields['rho']
if velFields is not None:
U = np.zeros((3,) + pencil_shape,dtype=np.float64)
U[0] = ad[velFields[0]].d
U[1] = ad[velFields[1]].d
U[2] = ad[velFields[2]].d
fields['U'] = U
if magFields is not None:
B = np.zeros((3,) + pencil_shape,dtype=np.float64)
B[0] = ad[magFields[0]].d
B[1] = ad[magFields[1]].d
B[2] = ad[magFields[2]].d
fields['B'] = B
if accFields is not None:
Acc = np.zeros((3,) + pencil_shape,dtype=np.float64)
Acc[0] = ad[accFields[0]].d
Acc[1] = ad[accFields[1]].d
Acc[2] = ad[accFields[2]].d
fields['Acc'] = Acc
def readOneFieldWithHDF(loadPath,FieldName,Res,order):
if order == 'F':
Filename = loadPath + '/' + FieldName + '-' + str(Res) + '.hdf5'
if rank == 0:
h5Data = h5py.File(Filename, 'r')[FieldName]
tmp = np.float64(h5Data[0,:,:,:]).T.reshape((size,int(Res/size),Res,Res))
data = comm.scatter(tmp)
else:
data = comm.scatter(None)
elif order == 'C':
Filename = loadPath + '/' + FieldName + '-' + str(Res) + '-C.hdf5'
chunkSize = Res/size
startIdx = int(rank * chunkSize)
endIdx = int((rank + 1) * chunkSize)
if endIdx == Res:
endIdx = None
h5Data = h5py.File(Filename, 'r')[FieldName]
data = np.float64(h5Data[0,startIdx:endIdx,:,:])
if rank == 0:
print("[%03d] done reading %s" % (rank,FieldName))
return np.ascontiguousarray(data)
def readOneFieldWithAthenaPPHDF(loadPath,FieldName,Res,order):
"""
reading (K-)Athena++ HDF data dumps
"""
# stripping the yt field type
FieldName = FieldName[1]
tmp = np.zeros(FFTHelperFuncs.local_shape, dtype=np.float64)
loc_slc = tmp.shape
n_proc = np.array(FFTHelperFuncs.FFT.global_shape(), dtype=int) // loc_slc
if h5py.h5.get_config().mpi:
h5py_kwargs = {
'driver' : 'mpio',
'comm' : comm,
}
else:
h5py_kwargs = {}
with h5py.File(loadPath,'r', **h5py_kwargs) as f:
mb_size = f.attrs['MeshBlockSize']
rg_size = f.attrs['RootGridSize']
if 'rho' == FieldName:
field_idx = 0
ds_name = 'prim'
elif 'press' == FieldName:
field_idx = 1
ds_name = 'prim'
elif 'vel' in FieldName:
field_idx = 1 + int(FieldName[-1])
ds_name = 'prim'
elif 'Bcc' in FieldName:
field_idx = int(FieldName[-1]) - 1
ds_name = 'B'
elif 'acc' in FieldName:
# translate from ..._x, _y, _z to index 0, 1, 2
field_idx = ord(FieldName[-1]) - 120
ds_name = 'hydro'
else:
raise SystemExit(
'Unknown field: ', FieldName)
if not ((loc_slc[0] % mb_size[0] == 0 or mb_size[0] % loc_slc[0] == 0) and
(loc_slc[1] % mb_size[1] == 0 or mb_size[1] % loc_slc[1] == 0)):
raise SystemExit(
'Error: local data size ', loc_slc,
'cannot be matched to meshblock size of ', mb_size)
gid_x_s = rank // n_proc[1] * tmp.shape[0] # global x start index
gid_x_e = rank // n_proc[1] * tmp.shape[0] + tmp.shape[0] # global x end index
gid_y_s = rank % n_proc[1] * tmp.shape[1] # global y start index
gid_y_e = rank % n_proc[1] * tmp.shape[1] + tmp.shape[1] # global y end index
log_loc_all = np.copy(f['LogicalLocations']) # all logical meshblock locations
for i, loc in enumerate(log_loc_all):
gid_mb = loc * mb_size # index of meshblock
# make sure meshblock belong to this MPI proc
if not ((gid_mb[0] <= gid_x_s < gid_mb[0] + mb_size[0] or
gid_x_s <= gid_mb[0] < gid_x_e) and
(gid_mb[1] <= gid_y_s < gid_mb[1] + mb_size[1] or
gid_y_s <= gid_mb[1] < gid_y_e)):
continue
try:
data = f[ds_name][field_idx,i,:,:,:] # actual meshblock data
except KeyError:
raise SystemExit(
'Cannot find data in dataset: ', ds_name, field_idx
)
# if local x pencil dim smaller than a meshblock use entire local pencil
if mb_size[0] >= loc_slc[0]:
loc_x_s = 0
loc_x_e = tmp.shape[0]
else:
loc_x_s = loc[0]*mb_size[0] - gid_x_s
loc_x_e = (loc[0]+1)*mb_size[0] - gid_x_s
sl_x = slice(gid_x_s % mb_size[0],gid_x_s % mb_size[0] + tmp.shape[0])
# if local y pencil dim smaller than a meshblock use entire local pencil
if mb_size[1] >= loc_slc[1]:
loc_y_s = 0
loc_y_e = tmp.shape[1]
else:
loc_y_s = loc[1]*mb_size[1] - gid_y_s
loc_y_e = (loc[1] + 1)*mb_size[1] - gid_y_s
sl_y = slice(gid_y_s % mb_size[1],gid_y_s % mb_size[1] + tmp.shape[1])
tmp[loc_x_s: loc_x_e,
loc_y_s: loc_y_e,
loc[2]*mb_size[2] : (loc[2] + 1)*mb_size[2]] = data.T[sl_x,sl_y,:]
return np.ascontiguousarray(np.float64(tmp))
def readAllFieldsWithHDF(fields,loadPath,Res,
rhoField,velFields,magFields,accFields,pField,order,use_athena_hdf=False):
"""
Reads all fields using the HDF5. Data is read in parallel.
"""
FinalShape = FFTHelperFuncs.local_shape
if (FinalShape[0] * FFTHelperFuncs.FFT.subcomm[0].Get_size() != Res or
FinalShape[1] * FFTHelperFuncs.FFT.subcomm[1].Get_size() != Res):
print("Data cannot be split evenly among processes. Abort (for now) - fix me!")
sys.exit(1)
if order is not "C" and order is not "F":
print("For safety reasons you have to specify the order (row or column major) for your data.")
sys.exit(1)
if use_athena_hdf:
readOneFieldWithX = readOneFieldWithAthenaPPHDF
else:
readOneFieldWithX = readOneFieldWithHDF
if rhoField is not None:
fields['rho'] = readOneFieldWithX(loadPath,rhoField,Res,order)
if velFields is not None:
U = np.zeros((3,) + FinalShape,dtype=np.float64)
U[0] = readOneFieldWithX(loadPath,velFields[0],Res,order)
U[1] = readOneFieldWithX(loadPath,velFields[1],Res,order)
U[2] = readOneFieldWithX(loadPath,velFields[2],Res,order)
fields['U'] = U
if magFields is not None:
B = np.zeros((3,) + FinalShape,dtype=np.float64)
B[0] = readOneFieldWithX(loadPath,magFields[0],Res,order)
B[1] = readOneFieldWithX(loadPath,magFields[1],Res,order)
B[2] = readOneFieldWithX(loadPath,magFields[2],Res,order)
fields['B'] = B
if accFields is not None:
Acc = np.zeros((3,) + FinalShape,dtype=np.float64)
Acc[0] = readOneFieldWithX(loadPath,accFields[0],Res,order)
Acc[1] = readOneFieldWithX(loadPath,accFields[1],Res,order)
Acc[2] = readOneFieldWithX(loadPath,accFields[2],Res,order)
fields['Acc'] = Acc
if pField is not None:
fields['P'] = readOneFieldWithX(loadPath,pField,Res,order)
#TODO FIXME for new layout
# else:
# # CAREFUL assuming isothermal EOS here with c_s = 1 -> P = rho in code units
# if rank == 0:
# print("WARNING: remember assuming isothermal EOS with c_s = 1, i.e. P = rho")
# P = rho