-
Notifications
You must be signed in to change notification settings - Fork 76
/
tipsy.py
1714 lines (1366 loc) · 62 KB
/
tipsy.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""tipsy
=====
Implements classes and functions for handling tipsy files. You rarely
need to access this module directly as it will be invoked
automatically via pynbody.load.
**Input**:
*filename*: file name string
**Optional Keywords**:
*paramfile*: string specifying the parameter file to load. If not
specified, the loader will look for a file `*.param` in the current and
parent directories.
"""
# for py2.5
import copy
import glob
import logging
import math
import os
import struct
import sys
import warnings
import numpy as np
from .. import array, chunk, config, config_parser, family, units, util
from . import SimSnap, nchilada
logger = logging.getLogger('pynbody.snapshot.tipsy')
class TipsySnap(SimSnap):
_basic_loadable_keys = {family.dm: {'phi', 'pos', 'eps', 'mass', 'vel'},
family.gas: {'phi', 'temp', 'pos', 'metals', 'eps',
'mass', 'rho', 'vel'},
family.star: {'phi', 'tform', 'pos', 'metals',
'eps', 'mass', 'vel'},
None: {'phi', 'pos', 'eps', 'mass', 'vel'}}
def __init__(self, filename, **kwargs):
global config
super().__init__()
only_header = kwargs.get('only_header', False)
if only_header:
warnings.warn(
"only_header kwarg is deprecated: all loading in TipsySnap is now lazy by default", RuntimeWarning)
must_have_paramfile = kwargs.get('must_have_paramfile', False)
take = kwargs.get('take', None)
verbose = kwargs.get('verbose', config['verbose'])
self.partial_load = take is not None
self._filename = util.cutgz(filename)
f = util.open_(filename, 'rb')
if not only_header:
logger.info("Loading %s", filename)
t, n, ndim, ng, nd, ns = struct.unpack("diiiii", f.read(28))
if (ndim > 3 or ndim < 1):
self._byteswap = True
f.seek(0)
t, n, ndim, ng, nd, ns = struct.unpack(">diiiii", f.read(28))
else:
self._byteswap = False
assert ndim == 3
self._header_t = t
f.read(4)
disk_family_slice = dict({family.gas: slice(0, ng),
family.dm: slice(ng, nd + ng),
family.star: slice(nd + ng, ng + nd + ns)})
self._load_control = chunk.LoadControl(disk_family_slice, 10240, take)
self._family_slice = self._load_control.mem_family_slice
self._num_particles = self._load_control.mem_num_particles
self._paramfilename = kwargs.get('paramfile', None)
self._decorate()
# describe the file structure as list of (num_parts, [list_of_properties])
# by default all fields are floats -- we look at the param file to determine
# whether we should expect some doubles
if self._paramfile.get('bDoublePos', 0):
ptype = 'd'
else:
ptype = 'f'
if self._paramfile.get('bDoubleVel', 0):
vtype = 'd'
else:
vtype = 'f'
self._g_dtype = np.dtype({'names': ("mass", "x", "y", "z", "vx", "vy", "vz", "rho", "temp", "eps", "metals", "phi"),
'formats': ('f', ptype, ptype, ptype, vtype, vtype, vtype, 'f', 'f', 'f', 'f', 'f')})
self._d_dtype = np.dtype({'names': ("mass", "x", "y", "z", "vx", "vy", "vz", "eps", "phi"),
'formats': ('f', ptype, ptype, ptype, vtype, vtype, vtype, 'f', 'f')})
self._s_dtype = np.dtype({'names': ("mass", "x", "y", "z", "vx", "vy", "vz", "metals", "tform", "eps", "phi"),
'formats': ('f', ptype, ptype, ptype, vtype, vtype, vtype, 'f', 'f', 'f', 'f')})
if 'dKpcUnit' not in self._paramfile:
if must_have_paramfile:
raise RuntimeError("Could not find .param file for this run. Place it in the run's directory or parent directory.")
else:
warnings.warn(
"No readable param file in the run directory or parent directory: using defaults.", RuntimeWarning)
self._file_units_system = [
units.Unit(x) for x in ('G', '1 kpc', '1e10 Msol')]
time_unit = None
try:
time_unit = self.infer_original_units('yr')
except units.UnitsException:
pass
if time_unit is not None:
self.properties['time'] *= time_unit
del f
def _load_main_file(self):
logger.info("Loading data from main file %s", self._filename)
f = util.open_(self._filename, 'rb')
f.seek(32)
write = []
for w, ndim in ("pos", 3), ("vel", 3), ("mass", 1), ("eps", 1), ("phi", 1):
if w not in list(self.keys()):
self._create_array(w, ndim, zeros=False)
write.append(w)
for w in "rho", "temp":
if w not in list(self.gas.keys()):
self.gas._create_array(w, zeros=False)
write.append(w)
if ("metals" not in list(self.gas.keys())) and ("metals" not in list(self.star.keys())):
self.gas._create_array("metals", zeros=False)
self.star._create_array("metals", zeros=False)
write.append("metals")
if "tform" not in list(self.star.keys()):
self.star._create_array("tform", zeros=False)
write.append("tform")
if "temp" in write:
self.gas["temp"].units = "K"
for k in "pos", "vel", "mass", "eps", "phi":
if k in write:
self[k].set_default_units(quiet=True)
# only do this for cosmo runs
if "phi" in write and 'h' in self.properties:
self['phi'].units = self['phi'].units * units.a ** -3 # messy :-(
for k in "rho", "temp", "metals":
if k in write:
self.gas[k].set_default_units(quiet=True)
for k in "metals", "tform":
if k in write:
self.star[k].set_default_units(quiet=True)
if "pos" in write:
write += ['x', 'y', 'z']
if "vel" in write:
write += ['vx', 'vy', 'vz']
max_item_size = max(
q.itemsize for q in (self._g_dtype, self._d_dtype, self._s_dtype))
tbuf = bytearray(max_item_size * 10240)
for fam, dtype in ((family.gas, self._g_dtype), (family.dm, self._d_dtype), (family.star, self._s_dtype)):
self_fam = self[fam]
st_len = dtype.itemsize
for readlen, buf_index, mem_index in self._load_control.iterate([fam], [fam], multiskip=True):
# Read in the block
if mem_index is None:
f.seek(st_len * readlen, 1)
continue
buf = np.fromstring(f.read(st_len * readlen), dtype=dtype)
if self._byteswap:
buf = buf.byteswap()
if mem_index is not None:
# Copy into the correct arrays
for name in dtype.names:
if name in write:
self_fam[name][mem_index] = buf[name][buf_index]
def _update_loadable_keys(self):
def is_readable_array(x):
try:
f = util.open_(x, 'r')
return int(f.readline()) == len(self)
except ValueError:
# could be a binary file
f = util.open_(x, 'rb')
header = f.read(4)
if len(header)!=4:
return False
if self._byteswap:
buflen = struct.unpack(">i", header)[0]
else:
buflen = struct.unpack("i", header)[0]
ourlen_1 = (self._load_control.disk_num_particles)& 0xffffffff
ourlen_3 = (self._load_control.disk_num_particles*3)& 0xffffffff
if buflen == ourlen_1: # it's a vector
return True
elif buflen == ourlen_3: # it's an array
return True
else:
return False
except OSError:
return False
fs = list(map(util.cutgz, glob.glob(self._filename + ".*")))
res = [q[len(self._filename) + 1:] for q in list(filter(is_readable_array, fs))]
# Create an empty dictionary of sets to store the loadable
# arrays for each family
rdict = {x: set() for x in self.families()}
rdict.update({a: copy.copy(b)
for a, b in self._basic_loadable_keys.items() if a is not None})
# Now work out which families can load which arrays
# according to the stored metadata
for r in res:
fams = self._get_loadable_array_metadata(r)[1]
for x in fams or list(rdict.keys()):
rdict[x].add(r)
self._loadable_keys_registry = rdict
def loadable_keys(self, fam=None):
"""Produce and return a list of loadable arrays for this TIPSY file."""
if len(self._loadable_keys_registry) == 0:
self._update_loadable_keys()
if fam is not None:
# Return what is loadable for this family
return list(self._loadable_keys_registry[fam])
else:
# Return what is loadable to all families
return list(set.intersection(*list(self._loadable_keys_registry.values())))
def _update_snapshot(self, arrays, filename=None, fam_out=[family.gas, family.dm, family.star]):
"""
Write a TIPSY file, but only updating the requested information and leaving the
rest intact on disk.
"""
if self.partial_load:
raise RuntimeError("Writing back to partially loaded files not yet supported")
global config
# make arrays be a list
if isinstance(arrays, str):
arrays = [arrays]
# check if arrays includes a 3D array
if 'pos' in arrays:
arrays.remove('pos')
for arr in ['x', 'y', 'z']:
arrays.append(arr)
if 'vel' in arrays:
arrays.remove('vel')
for arr in ['vx', 'vy', 'vz']:
arrays.append(arr)
with self.lazy_off:
fin = util.open_(self.filename, "rb")
fout = util.open_(self.filename + ".tmp", "wb")
if self._byteswap:
t, n, ndim, ng, nd, ns = struct.unpack(">diiiii", fin.read(28))
fout.write(struct.pack(">diiiiii", t, n, ndim, ng, nd, ns, 0))
else:
t, n, ndim, ng, nd, ns = struct.unpack("diiiii", fin.read(28))
fout.write(struct.pack("diiiiii", t, n, ndim, ng, nd, ns, 0))
fin.read(4)
if family.gas in fam_out:
assert(ng == len(self[family.gas]))
if family.dm in fam_out:
assert(nd == len(self[family.dm]))
if family.star in fam_out:
assert(ns == len(self[family.star]))
max_block_size = 1024 ** 2 # particles
# describe the file structure as list of (num_parts,
# [list_of_properties])
file_structure = ((ng, family.gas, ["mass", "x", "y", "z", "vx", "vy", "vz", "rho", "temp", "eps", "metals", "phi"]),
(nd, family.dm, [
"mass", "x", "y", "z", "vx", "vy", "vz", "eps", "phi"]),
(ns, family.star, ["mass", "x", "y", "z", "vx", "vy", "vz", "metals", "tform", "eps", "phi"]))
# do the read/write -- at each block, replace the relevant array
for n_left, fam, st in file_structure:
n_done = 0
self_fam = self[fam]
while n_left > 0:
n_block = min(n_left, max_block_size)
# Read in the block
if(self._byteswap):
g = np.fromstring(
fin.read(len(st) * n_block * 4), 'f').byteswap().reshape((n_block, len(st)))
else:
g = np.fromstring(
fin.read(len(st) * n_block * 4), 'f').reshape((n_block, len(st)))
if fam in fam_out:
self_sub = self[fam][n_done:n_done + n_block]
# write over the relevant data
with self_sub.immediate_mode:
for i, name in enumerate(st):
if name in arrays:
ar = self_sub[name]
try:
if ar.units != 1 and ar.units != units.NoUnit():
g[:, i] = ar.in_original_units().view(
np.ndarray)
else:
g[:, i] = ar.view(np.ndarray)
except KeyError:
pass
# Write out the block
if self._byteswap:
g.byteswap().tofile(fout)
else:
g.tofile(fout)
# Increment total ptcls read in, decrement ptcls left of
# this type
n_left -= n_block
n_done += n_block
fin.close()
fout.close()
os.system("mv " + self.filename + ".tmp " + self.filename)
@staticmethod
def _write(self, filename=None, double_pos=None, double_vel=None, binary_aux_arrays=None, cosmological=True):
"""
Write a TIPSY (standard) formatted file.
Additionally, you can specify whether you want position and/or
velocity arrays written out in double precision. If you are
writing out a snapshot that was originally in tipsy format and
the bDoublePos/bDoubleVel flags are set in the parameter file,
then the write routine will follow those choices. If you are
writing a snapshot other than a tipsy snapshot, then you have
to specify these by hand.
**Optional Keywords**
*filename* (None): name of the file to be written out. If
None, the original file is overwritten.
*double_pos* (False): set to 'True' if you want to write out positions as doubles
*double_vel* (False): set to 'True' if you want to write out velocities as doubles
*binary_aux_arrays* (None): set to 'True' to write auxiliary
arrays in binary format; if left 'None', the preference is
taken from the param file
*cosmological* (True): if True (default), the header will store the self.properties['a'];
otherwise it will store self.properties['time']
"""
global config
if filename is None:
filename = self._filename
logger.info("Writing main file %s", filename)
f = util.open_(filename, 'wb')
t = 0.0
try:
if cosmological:
t = self.properties['a']
else:
t = self.properties['time']
except KeyError:
warnings.warn(
"Time is unknown: writing zero in header", RuntimeWarning)
n = len(self)
ndim = 3
ng = len(self.gas)
nd = len(self.dark)
ns = len(self.star)
if n != ng + nd + ns:
warnings.warn("Snapshot contains extra particles than DM, stars and gas (extra families?). "
"Tipsy writing is not set up to handle those. Reverting Tipsy header ntot to ng + nd + ns")
n = ng + nd + ns
byteswap = getattr(self, "_byteswap", sys.byteorder == "little")
if byteswap:
f.write(struct.pack(">diiiiii", t, n, ndim, ng, nd, ns, 0))
else:
f.write(struct.pack("diiiiii", t, n, ndim, ng, nd, ns, 0))
# needs to be done in blocks like reading
# describe the file structure as list of (num_parts,
# [list_of_properties])
if type(self) is not TipsySnap:
if double_pos is None:
double_pos = False
if double_vel is None:
double_vel = False
ptype = 'd' if double_pos else 'f'
vtype = 'd' if double_vel else 'f'
else:
dpos_param = self._paramfile.get('bDoublePos', False)
dvel_param = self._paramfile.get('bDoubleVel', False)
if double_pos:
ptype = 'd'
elif not double_pos:
ptype = 'f'
else:
ptype = 'd' if dpos_param else 'f'
if double_vel:
vtype = 'd'
elif not double_vel:
vtype = 'f'
else:
vtype = 'd' if dvel_param else 'f'
g_dtype = np.dtype({'names': ("mass", "x", "y", "z", "vx", "vy", "vz", "rho", "temp", "eps", "metals", "phi"),
'formats': ('f', ptype, ptype, ptype, vtype, vtype, vtype, 'f', 'f', 'f', 'f', 'f')})
d_dtype = np.dtype({'names': ("mass", "x", "y", "z", "vx", "vy", "vz", "eps", "phi"),
'formats': ('f', ptype, ptype, ptype, vtype, vtype, vtype, 'f', 'f')})
s_dtype = np.dtype({'names': ("mass", "x", "y", "z", "vx", "vy", "vz", "metals", "tform", "eps", "phi"),
'formats': ('f', ptype, ptype, ptype, vtype, vtype, vtype, 'f', 'f', 'f', 'f')})
file_structure = ((ng, family.gas, g_dtype),
(nd, family.dm, d_dtype),
(ns, family.star, s_dtype))
max_block_size = 1024 ** 2 # particles
with self.lazy_derive_off:
for n_left, fam, dtype in file_structure:
n_done = 0
self_type = self[fam]
while n_left > 0:
n_block = min(n_left, max_block_size)
#g = np.zeros((n_block,len(st)),dtype=np.float32)
g = np.empty(n_block, dtype=dtype)
self_type_block = self_type[n_done:n_done + n_block]
with self_type_block.immediate_mode:
# Copy from the correct arrays
for i, name in enumerate(dtype.names):
try:
g[name] = self_type_block[name]
except KeyError:
pass
# Write out the block
if byteswap:
g.byteswap().tofile(f)
else:
g.tofile(f)
# Increment total ptcls written, decrement ptcls left of
# this type
n_left -= n_block
n_done += n_block
f.close()
logger.info("Writing auxiliary arrays")
with self.lazy_off: # prevent any lazy reading or evaluation
for x in set(self.keys()).union(self.family_keys()):
if not self.is_derived_array(x) and x not in ["mass", "pos", "x", "y", "z", "vel", "vx", "vy", "vz", "rho", "temp",
"eps", "metals", "phi", "tform"]:
TipsySnap._write_array(
self, x, filename=filename + "." + x, binary=binary_aux_arrays)
@staticmethod
def __get_write_dtype(stored_dtype):
if issubclass(stored_dtype.type, np.integer):
return np.int32
else:
return np.float32
@staticmethod
def __write_block(f, ar, binary, byteswap):
ar = np.asarray(ar, dtype=TipsySnap.__get_write_dtype(ar.dtype))
if binary:
if byteswap:
ar.byteswap().tofile(f)
else:
ar.tofile(f)
else:
if issubclass(ar.dtype.type, np.integer):
fmt = "%d"
else:
fmt = "%e"
np.savetxt(f, ar, fmt=fmt)
def _get_loadable_array_metadata(self, array_name):
"""Given an array name, returns the metadata consisting of
the tuple units, families.
Returns:
*units*: the units of this data on disk
*families*: a list of family objects for which data is on disk
for this array, or None if this cannot be determined"""
try:
f = open(self.filename + "." + array_name + ".pynbody-meta")
except OSError:
return self._default_units_for(array_name), None, None
res = {}
for l in f:
X = l.split(":")
if len(X) == 2:
res[X[0].strip()] = X[1].strip()
try:
u = units.Unit(res['units'])
except:
u = None
try:
fams = [family.get_family(x.strip())
for x in res['families'].split(" ")]
except:
fams = None
try:
dtype = np.dtype(res['dtype'])
except:
dtype = None
return u, fams, dtype
@staticmethod
def _write_array_metafile(self, filename, units, families, dtype):
f = open(filename + ".pynbody-meta", "w")
print("# This file automatically created by pynbody", file=f)
if not hasattr(units, "_no_unit"):
print("units:", units, file=f)
print("families:", end=' ', file=f)
for x in families:
print(x.name, end=' ', file=f)
print(file=f)
if dtype is not None:
print("dtype:", TipsySnap.__get_write_dtype(dtype), file=f)
f.close()
if isinstance(self, TipsySnap):
# update the loadable keys if this operation is likely to have
# changed them
self._update_loadable_keys()
@staticmethod
def _families_in_main_file(array_name, fam=None):
fam_for_default = [fX for fX, ars in TipsySnap._basic_loadable_keys.items(
) if array_name in ars and fX in fam]
return fam_for_default
def _update_array(self, array_name, fam=None,
filename=None, binary=None, byteswap=None):
assert fam is not None
if self.partial_load:
raise RuntimeError("Writing back to partially loaded files not yet supported")
fam_in_main = self._families_in_main_file(array_name, fam)
if len(fam_in_main) > 0:
self._update_snapshot(array_name, fam_out=fam_in_main)
fam = list(set(fam).difference(fam_in_main))
if len(fam) == 0:
return
# If we have disk units for this array, check we can convert into them
aux_u, aux_f, aux_type = self._get_loadable_array_metadata(array_name)
if aux_f is None:
aux_f = self.families()
if aux_u is not None:
for f in fam:
if array_name in self[f]:
# check convertible
try:
self[f][array_name].units.in_units(aux_u)
except units.UnitsException:
raise OSError(
"Units must match the existing auxiliary array on disk.")
try:
data = self.__read_array_from_disk(array_name, filename=filename)
except OSError:
# doesn't really exist, probably because the other data on disk was
# in the main snapshot
self._write_array(self, array_name, fam, filename=filename, binary=binary,
byteswap=byteswap)
return
for f in fam:
if aux_u is not None:
data[self._get_family_slice(f)] = self[f][
array_name].in_units(aux_u)
else:
data[self._get_family_slice(f)] = self[f][array_name]
fam = list(set(aux_f).union(fam))
self._write_array(self, array_name, fam=fam, contents=data, binary=binary,
byteswap=byteswap, filename=filename)
@staticmethod
def _write_array(self, array_name, fam=None, contents=None,
filename=None, binary=None, byteswap=None):
"""Write the array to file."""
fam_in_main = TipsySnap._families_in_main_file(array_name, fam)
if len(fam_in_main) > 0:
if isinstance(self, TipsySnap):
self._update_snapshot(array_name, fam_out=fam_in_main)
fam = list(set(fam).difference(fam_in_main))
if len(fam) == 0:
return
else:
raise RuntimeError("Cannot call static _write_array to write into main tipsy file.")
units_out = None
dtype = None
if binary is None:
binary = getattr(self.ancestor, "_tipsy_arrays_binary", False)
if binary and (byteswap is None):
byteswap = getattr(self.ancestor, "_byteswap", False)
with self.lazy_off: # prevent any lazy reading or evaluation
if filename is None:
if self._filename[-3:] == '.gz':
filename = self._filename[:-3] + "." + array_name + ".gz"
else:
filename = self._filename + "." + array_name
if binary:
fhand = util.open_(filename, 'wb')
if byteswap:
fhand.write(struct.pack(">i", len(self)))
else:
fhand.write(struct.pack("i", len(self)))
else:
fhand = util.open_(filename, 'wb')
fhand.write((str(len(self)) + '\n').encode('utf-8'))
if contents is None:
if array_name in self.family_keys():
for f in [family.gas, family.dm, family.star]:
try:
dtype = self[f][array_name].dtype
ar = self[f][array_name]
units_out = ar.units
except KeyError:
ar = np.zeros(len(self[f]), dtype=int)
TipsySnap.__write_block(fhand, ar, binary, byteswap)
else:
ar = self[array_name]
dtype = self[array_name].dtype
units_out = ar.units
TipsySnap.__write_block(fhand, ar, binary, byteswap)
else:
TipsySnap.__write_block(fhand, contents, binary, byteswap)
units_out = contents.units
fhand.close()
if fam is None:
fam = [family.gas, family.dm, family.star]
TipsySnap._write_array_metafile(self, filename, units_out, fam, dtype)
def _load_array(self, array_name, fam=None, filename=None,
packed_vector=None):
if array_name in self._basic_loadable_keys[fam]:
self._load_main_file()
return
fams = self._get_loadable_array_metadata(
array_name)[1] or self.families()
if (fam is None and fams is not None and len(fams) != len(self.families())) or \
(fam is not None and fam not in fams):
# Top line says 'you requested all families but at least one isn't available'
# Bottom line says 'you requested one family, but that one's not
# available'
raise OSError("This array is marked as available only for families %s" % fams)
data = self.__read_array_from_disk(array_name, fam=fam,
filename=filename,
packed_vector=packed_vector)
if fam is None:
self[array_name] = data
else:
self[fam][array_name] = data
def __read_array_from_disk(self, array_name, fam=None, filename=None,
packed_vector=None):
"""Read a TIPSY-ASCII or TIPSY-BINARY auxiliary file with the
specified name. If fam is not None, read only the particles of
the specified family."""
starlog_keys = ['rhoform', 'tempform', 'phiform', 'nsmooth',
'xform', 'yform', 'zform', 'vxform', 'vyform', 'vzform',
'posform', 'velform','h2form']
# if massform available as auxiliary array, faster to load it instead
if array_name == 'massform' and 'massform' not in self.loadable_keys():
starlog_keys += ['massform']
if filename is None and array_name in starlog_keys:
try:
self.read_starlog()
if fam is not None:
return self[fam][array_name]
else:
return self[array_name]
except OSError:
pass
# N.B. this code is a bit inefficient for loading
# family-specific arrays, because it reads in the whole array
# then slices it. But of course the memory is only wasted
# while still inside this routine, so it's only really the
# wasted time that's a problem.
# determine whether the array exists in a file
if filename is None:
if self._filename[-3:] == '.gz':
filename = self._filename[:-3] + "." + array_name
else:
filename = self._filename + "." + array_name
f = util.open_(filename, 'r')
logger.info("Attempting to load auxiliary array %s", filename)
# if we get here, we've got the file - try loading it
units, _, dtype = self._get_loadable_array_metadata(array_name)
if dtype is None:
dtype = self._get_preferred_dtype(array_name)
try:
l = int(f.readline())
binary = False
if l != self._load_control.disk_num_particles:
raise OSError("Incorrect file format")
if not dtype:
# Inspect the first line to see whether it's float or int
l = "0\n"
while l == "0\n":
l = f.readline()
if "." in l or "e" in l or l[:-1] == "inf":
dtype = float
else:
dtype = int
# Restart at head of file
f.seek(0)
f.readline()
loadblock = lambda count: np.fromfile(
f, dtype=dtype, sep="\n", count=count)
# data = np.fromfile(f, dtype=tp, sep="\n")
except ValueError:
# this is probably a binary file
binary = True
f = util.open_(filename, 'rb')
# Read header and check endianness
if self._byteswap:
l = struct.unpack(">i", f.read(4))[0]
else:
l = struct.unpack("i", f.read(4))[0]
if l != self._load_control.disk_num_particles:
raise OSError("Incorrect file format")
if dtype is None:
# Set data format to be read (float or int) based on config
int_arrays = list(map(
str.strip, config_parser.get('tipsy', 'binary-int-arrays').split(",")))
if array_name in int_arrays:
dtype = 'i'
else:
dtype = 'f'
# Read longest data array possible.
# Assume byteswap since most will be.
if self._byteswap:
loadblock = lambda count: np.fromstring(
f.read(count * 4), dtype=dtype, count=count).byteswap()
# data = np.fromstring(f.read(3*len(self)*4),dtype).byteswap()
else:
loadblock = lambda count: np.fromstring(
f.read(count * 4), dtype=dtype, count=count)
# data = np.fromstring(f.read(3*len(self)*4),dtype)
ndim = 1
self.ancestor._tipsy_arrays_binary = binary
all_fam = [family.dm, family.gas, family.star]
if fam is None:
fam = all_fam
r = np.empty(len(self), dtype=dtype).view(array.SimArray)
else:
r = np.empty(len(self[fam]), dtype=dtype).view(array.SimArray)
for readlen, buf_index, mem_index in self._load_control.iterate(all_fam, fam):
buf = loadblock(readlen)
if mem_index is not None:
r[mem_index] = buf[buf_index]
if units is not None:
r.units = units
return r
def read_starlog(self, fam=None):
"""Read a TIPSY-starlog file."""
import pynbody.bridge
x = os.path.abspath(self._filename)
done = False
filename = None
x = os.path.dirname(x)
# Attempt the loading of information
l = glob.glob(os.path.join(x, "*.starlog"))
if (len(l)):
for filename in l:
sl = StarLog(filename)
else:
l = glob.glob(os.path.join(x, "../*.starlog"))
if (len(l) == 0):
raise OSError("Couldn't find starlog file")
for filename in l:
sl = StarLog(filename)
logger.info("Bridging starlog into SimSnap")
b = pynbody.bridge.OrderBridge(self, sl)
b(b(b(sl))).star['iorderGas'] = b(b(sl)).star['iorderGas']
b(b(b(sl))).star['massform'] = b(b(sl)).star['massform']
b(b(b(sl))).star['rhoform'] = b(b(sl)).star['rhoform']
b(b(b(sl))).star['tempform'] = b(b(sl)).star['tempform']
b(b(b(sl)))['posform'] = b(b(sl))['pos']
b(b(b(sl)))['velform'] = b(b(sl))['vel']
#b(sl).star['iorderGas'] = sl.star['iorderGas'][:len(self.star)]
#b(sl).star['massform'] = sl.star['massform'][:len(self.star)]
#b(sl).star['rhoform'] = sl.star['rhoform'][:len(self.star)]
#b(sl).star['tempform'] = sl.star['tempform'][:len(self.star)]
#b(sl)['posform'] = sl['pos'][:len(self.star), :]
#b(sl)['velform'] = sl['vel'][:len(self.star), :]
if 'h2form' in list(sl.star.keys()):
b(b(b(sl))).star['h2form'] = b(b(sl)).star['h2form']
else: print("No H2 data found in StarLog file")
for i, x in enumerate(['x', 'y', 'z']):
self._arrays[x + 'form'] = self['posform'][:, i]
for i, x in enumerate(['vx', 'vy', 'vz']):
self._arrays[x + 'form'] = self['velform'][:, i]
@staticmethod
def _can_load(f):
try:
check = TipsySnap(f, verbose=False)
del check
except:
return False
return True
# caculate the number fraction YH, YHe as a function of metalicity. Cosmic
# production rate of helium relative to metals (in mass)
# delta Y/delta Z = 2.1 and primordial He Yp = 0.236 (Jimenez et al. 2003,
# Science 299, 5612.
# piecewise linear
# Y = Yp + dY/dZ*ZMetal up to ZMetal = 0.1, then linear decrease to 0 at Z=1)
# SUM_Metal = sum(ni/nH *mi),it is a fixed number for cloudy abundance.
# Massfraction fmetal = Z*SUM_metal/(1 + 4*nHe/nH + Z*SUM_metal) (1)
# 4*nHe/nH = mHe/mH = fHe/fH
# also fH + fHe + fMetal = 1 (2)
# if fHe specified, combining the 2 eq above will solve for
# fH and fMetal
def _abundance_estimator(metal):
Y_He = ((0.236 + 2.1 * metal) / 4.0) * (metal <= 0.1)
Y_He += ((-0.446 * (metal - 0.1) / 0.9 + 0.446) / 4.0) * (metal > 0.1)
Y_H = 1.0 - Y_He * 4. - metal
return Y_H, Y_He
@TipsySnap.derived_quantity
def HII(sim):
"""Number of HII ions per proton mass"""
Y_H, Y_He = _abundance_estimator(sim["metals"])
try:
return Y_H - sim["HI"] - 2 * sim["H2"]
except KeyError:
return Y_H - sim["HI"]
@TipsySnap.derived_quantity
def HeIII(sim):
"""Number of HeIII ions per proton mass"""
Y_H, Y_He = _abundance_estimator(sim["metals"])
return Y_He - sim["HeII"] - sim["HeI"]
@TipsySnap.derived_quantity
def ne(sim):
"""Number of electrons per proton mass"""