-
Notifications
You must be signed in to change notification settings - Fork 7
/
pytipsy.py
executable file
·364 lines (323 loc) · 12.8 KB
/
pytipsy.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
import os
import re
import struct
import numpy as np
def rtipsy(filename, return_STANDARD=False, VERBOSE=False):
"""rtipsy Reads tipsy files detecting the format:
big endian, little endian, padded (standard) or non-padded header
Usage:
rtipsy(filename, return_STANDARD=False, VERBOSE=False)
Input parameters:
filename filename string
VERBOSE print messages (optional)
return_STANDARD do we return a boolean indicating the endianness?
Return values:
(header,g,d,s), [return_STANDARD]
header tipsy header struct
g,d,s gas, dark and star structures
return_STANDARD optional, boolean indicating endianness
Please read rtipsy.py for the structure definitions
Example:
h,g,d,s = rtipsy('/home/wadsley/usr5/mihos/mihos.std')
print, h['ndark']
plt.plot(d['x'], d['y'], 'k,')"""
f,header,endianswap = checktipsy(filename, VERBOSE=VERBOSE)
ng,nd,ns = (header['ngas'], header['ndark'], header['nstar'])
endian = ">" if endianswap else "<"
catg = {'mass':np.zeros(ng), 'pos':np.zeros((ng,3)),
'vel':np.zeros((ng,3)), 'dens':np.zeros(ng),
'tempg':np.zeros(ng), 'h':np.zeros(ng), 'zmetal':np.zeros(ng),
'phi':np.zeros(ng)}
catd = {'mass':np.zeros(nd), 'pos':np.zeros((nd,3)),
'vel':np.zeros((nd,3)), 'eps':np.zeros(nd),
'phi':np.zeros(nd)}
cats = {'mass':np.zeros(ns), 'pos':np.zeros((ns,3)),
'vel':np.zeros((ns,3)), 'metals':np.zeros(ns),
'tform':np.zeros(ns), 'eps':np.zeros(ns), 'phi':np.zeros(ns)}
for cat in ['g','d','s']:
j = 0
for qty in ['x','y','z']:
locals()['cat'+cat][qty] = locals()['cat'+cat]['pos'][:,j]
locals()['cat'+cat]['v'+qty] = locals()['cat'+cat]['vel'][:,j]
j += 1
if (ng > 0):
for i in range(ng):
mass, x, y, z, vx, vy, vz, dens, tempg, h, zmetal, phi = \
struct.unpack(endian+"ffffffffffff", f.read(48))
catg['mass'][i] = mass
catg['x'][i] = x
catg['y'][i] = y
catg['z'][i] = z
catg['vx'][i] = vx
catg['vy'][i] = vy
catg['vz'][i] = vz
catg['dens'][i] = dens
catg['tempg'][i] = tempg
catg['h'][i] = h
catg['zmetal'][i] = zmetal
catg['phi'][i] = phi
if (nd > 0):
for i in range(nd):
mass, x, y, z, vx, vy, vz, eps, phi = \
struct.unpack(endian+"fffffffff", f.read(36))
catd['mass'][i] = mass
catd['x'][i] = x
catd['y'][i] = y
catd['z'][i] = z
catd['vx'][i] = vx
catd['vy'][i] = vy
catd['vz'][i] = vz
catd['eps'][i] = eps
catd['phi'][i] = phi
if (ns > 0):
for i in range(ns):
mass, x, y, z, vx, vy, vz, metals, tform, eps, phi = \
struct.unpack(endian+"fffffffffff", f.read(44))
cats['mass'][i] = mass
cats['x'][i] = x
cats['y'][i] = y
cats['z'][i] = z
cats['vx'][i] = vx
cats['vy'][i] = vy
cats['vz'][i] = vz
cats['metals'][i] = metals
cats['tform'][i] = tform
cats['eps'][i] = eps
cats['phi'][i] = phi
if return_STANDARD:
return (header,catg,catd,cats), endianswap
else:
return (header,catg,catd,cats)
def checktipsy(filename, VERBOSE=False):
"""checktipsy Checks tipsy files detecting the format:
big endian, little endian, padded (standard) or non-padded header
but does not read the data
Usage:
checktipsy(filename, VERBOSE=False)
Input parameters:
filename filename string
VERBOSE print messages (optional)
Return values:
(file,header,endianswap)
"""
try:
f = open(filename, 'rb')
except:
print("TIPSY ERROR: Can't open file",filename)
fs = os.fstat(f.fileno()).st_size
#Read in the header
t, n, ndim, ng, nd, ns = struct.unpack("<diiiii", f.read(28))
endianswap = False
#Check Endianness
if (ndim < 1 or ndim > 3):
endianswap = True
f.seek(0)
t, n, ndim, ng, nd, ns = struct.unpack(">diiiii", f.read(28))
if VERBOSE:
print("SWAP_ENDIAN")
if VERBOSE:
print("Header: time,n,ngas,ndark,nstar: ", t, n, ng, nd, ns)
#Catch for 4 byte padding
if (fs == 32+48*ng+36*nd+44*ns):
f.read(4)
#File is borked if this is true
elif (fs != 28+48*ng+36*nd+44*ns):
print("TIPSY ERROR: Header and file size inconsistent")
print("Estimates: Header bytes: 28 or 32 (either is OK)")
print(" ngas: ",ng," bytes:",48*ng)
print(" ndark: ",nd," bytes:",36*nd)
print(" nstar: ",ns," bytes:",44*ns)
print("Actual File bytes:",fs," not one of:",28+48*ng+36*nd+44*ns,32+48*ng+36*nd+44*ns)
f.close()
return(f,{'time':t, 'n':n, 'ndim':ndim, 'ngas':ng, 'ndark':nd, 'nstar':ns}, endianswap)
def wtipsy(filename, header, catg, catd, cats, STANDARD=True, VERBOSE=False):
"""wtipsy Write tipsy files in selected format
big endian, little endian, padded (standard) or non-padded header
Usage:
wtipsy(filename, header, g, d, s, STANDARD=True, VERBOSE=False)
Input parameters:
filename filename string
header tipsy header struct
g,d,s gas, dark and star structures
STANDARD True for standard big endian
VERBOSE print messages (optional)
Please read pytipsy.py for the structure definitions
"""
try:
f = open(filename, 'wb')
except:
print("WTIPSY ERROR: Can't open file")
endian='>' if STANDARD else '<'
f.write(struct.pack(endian+"diiiii", header['time'], header['n'],
header['ndim'], header['ngas'], header['ndark'],
header['nstar']))
if STANDARD:
f.write(struct.pack("xxxx"))
if VERBOSE:
print("STANDARD Write. Header: ",header)
elif VERBOSE:
print("Native Write. Header: ",header)
for i in range(header['ngas']):
f.write(struct.pack(endian+"ffffffffffff", catg['mass'][i],
catg['x'][i], catg['y'][i], catg['z'][i],
catg['vx'][i], catg['vy'][i], catg['vz'][i],
catg['dens'][i], catg['tempg'][i], catg['h'][i],
catg['zmetal'][i], catg['phi'][i]))
for i in range(header['ndark']):
f.write(struct.pack(endian+"fffffffff", catd['mass'][i], catd['x'][i],
catd['y'][i], catd['z'][i], catd['vx'][i],
catd['vy'][i], catd['vz'][i], catd['eps'][i],
catd['phi'][i]))
for i in range(header['nstar']):
f.write(struct.pack(endian+"fffffffffff", cats['mass'][i],
cats['x'][i], cats['y'][i], cats['z'][i],
cats['vx'][i], cats['vy'][i], cats['vz'][i],
cats['metals'][i], cats['tform'][i],
cats['eps'][i], cats['phi'][i]))
f.close()
def checkarray(filename, VERBOSE=True):
"""checkarray Checks tipsy array files detecting the format:
big endian, little endian, number
but does not read the data
Usage:
checkarray(filename, VERBOSE=False)
Input parameters:
filename filename string
VERBOSE print messages (optional)
Return values:
(file,header,endianswap)
"""
try:
f = open(filename, 'rb')
except:
print("array ERROR: Can't open file",filename)
fs = os.fstat(f.fileno()).st_size
#Read in the header
n, = struct.unpack("<i", f.read(4))
endianswap = False
#Confirm Endianness
if (fs != 4+4*n):
endianswap = True
f.seek(0)
nswap, = struct.unpack(">i", f.read(4))
if (fs != 4+4*nswap):
f.close()
print("RARRAY ERROR: Header (native: %d std: %d) and file size n (%d) inconsistent" % (n,nswap,(fs-4)//4) )
n=nswap
return(f,n,endianswap)
def rarray(filename, return_STANDARD=False, INTEGER=False, VERBOSE=False ):
"""rarray reads tipsy array files detecting the format:
big endian, little endian, number and returns the data
Usage:
rarray(filename, return_STANDARD=False, INTEGER=False, VERBOSE=False)
Input parameters:
filename filename string
return_STANDARD do we return the endianness?
INTEGER assume integer data
VERBOSE print messages (optional)
Return values:
read array, possibly the endianness as well.
"""
f,n,endianswap = checkarray(filename, VERBOSE=VERBOSE)
readformat = '>%s' % (n) if endianswap else '<%s' % (n)
readformat += 'i' if INTEGER else 'f'
data = np.array(struct.unpack(readformat, f.read(n*4)))
if (len(data)!=n):
print("Failed to read all data",len(data),n)
elif (VERBOSE):
print("Succesfully read all data",len(data),n)
f.close()
if return_STANDARD:
return data, endianswap
else:
return data
def warray(filename, data, STANDARD=True, VERBOSE=False):
"""warray writes tipsy array files using the given format
default (STANDARD big endian)
Usage:
warray(filename, data, [STANDARD=True/False,] [VERBOSE=True/False])
Input parameters:
filename filename string
data is a numpy array of floats or ints
STANDARD=True means write standard big endian
VERBOSE=True reports success
Return values:
0 success 1 fail
"""
try:
f = open(filename, 'wb')
except:
print("warray ERROR: Can't open file")
if (STANDARD):
f.write(struct.pack(">i", len(data)))
writeformat = '>'
else:
f.write(struct.pack("<i", len(data)))
writeformat = '<'
if (len(data)>0):
writeformat += '%s' % (len(data))
writeformat += 'i' if 'int' in str(type(data[0])) else 'f'
f.write(struct.pack(writeformat, *data))
if (VERBOSE):
print("Wrote all data",len(data))
f.close()
class gaslog(dict):
def __init__(self, fname):
self.rawdata = np.genfromtxt(fname, comments='#', dtype=None,
names=['dTime', 'z', 'E', 'T', 'U', 'Eth',
'Lx', 'Ly', 'Lz',
'WallTime', 'dwMax', 'dIMax', 'dEMax', 'dMultiEff'])
for name in self.rawdata.dtype.names:
self[name] = self.rawdata[name]
self.units = {'erg':
float(re.findall(r'dErgPerGmUnit:\s*[0-9,.,e,+,-]*',
open(fname).read())[0].split()[1]) *
float(re.findall(r'dMsolUnit:\s*[0-9,.,e,+,-]*',
open(fname).read())[0].split()[1]) *
1.9891e33, 'yr':
float(re.findall(r'dSecUnit:\s*[0-9,.,e,+,-]*',
open(fname).read())[0].split()[1]) /
3.1557e7}
self['dTime'] *= self.units['yr']
self['E'] *= self.units['erg']
self['T'] *= self.units['erg']
self['U'] *= self.units['erg']
self['Eth'] *= self.units['erg']
class starlog(dict):
def __init__(self, fname):
try:
f = open(fname, 'rb')
except:
print("Cannot open starlog!")
return 1
# Calculate number of entries
n_sf = int((f.seek(0, os.SEEK_END)-4)/96)
self['iOrdStar'] = np.zeros(n_sf, dtype=np.int64)
self['iOrdGas'] = np.zeros(n_sf, dtype=np.int64)
self['timeForm'] = np.zeros(n_sf)
self['xForm'] = np.zeros(n_sf)
self['yForm'] = np.zeros(n_sf)
self['zForm'] = np.zeros(n_sf)
self['vxForm'] = np.zeros(n_sf)
self['vyForm'] = np.zeros(n_sf)
self['vzForm'] = np.zeros(n_sf)
self['massForm'] = np.zeros(n_sf)
self['rhoForm'] = np.zeros(n_sf)
self['TForm'] = np.zeros(n_sf)
f.seek(4) # Remove 4-byte pad
for i in range(n_sf):
iOrdStar, iOrdGas, timeForm, xForm, yForm, zForm, vxForm, vyForm, \
vzForm, massForm, rhoForm, Tform = struct.unpack('>qqdddddddddd',
f.read(96))
self['iOrdStar'][i] = iOrdStar
self['iOrdGas'][i] = iOrdGas
self['timeForm'][i] = timeForm
self['xForm'][i] = xForm
self['yForm'][i] = yForm
self['zForm'][i] = zForm
self['vxForm'][i] = vxForm
self['vyForm'][i] = vyForm
self['vzForm'][i] = vzForm
self['massForm'][i] = massForm
self['rhoForm'][i] = rhoForm
self['TForm'][i] = Tform