/
halo.py
1944 lines (1563 loc) · 75 KB
/
halo.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
"""
halo
====
Implements halo catalogue functions. If you have a supported halo
catalogue on disk or a halo finder installed and correctly configured,
you can access a halo catalogue through f.halos() where f is a
SimSnap.
See the `halo tutorial
<http://pynbody.github.io/pynbody/tutorials/halos.html>`_ for some
examples.
"""
import numpy as np
import weakref
import os.path
import glob
import re
import copy
import sys
from array import SimArray
import gzip
import logging
from . import snapshot, util, config, config_parser, units
from .snapshot import gadget
logger = logging.getLogger("pynbody.halo")
class DummyHalo(object):
def __init__(self):
self.properties = {}
class Halo(snapshot.IndexedSubSnap):
"""
Generic class representing a halo.
"""
def __init__(self, halo_id, halo_catalogue, *args):
super(Halo, self).__init__(*args)
self._halo_catalogue = halo_catalogue
self._halo_id = halo_id
self._descriptor = "halo_" + str(halo_id)
self.properties = copy.copy(self.properties)
self.properties['halo_id'] = halo_id
def is_subhalo(self, otherhalo):
"""
Convenience function that calls the corresponding function in
a halo catalogue.
"""
return self._halo_catalogue.is_subhalo(self._halo_id, otherhalo._halo_id)
# ----------------------------#
# General HaloCatalogue class #
#-----------------------------#
class HaloCatalogue(object):
"""
Generic halo catalogue object.
"""
def __init__(self, sim):
self._base = weakref.ref(sim)
self._halos = {}
self.lazy_off = util.ExecutionControl()
def calc_item(self, i):
if i in self._halos: # and self._halos[i]() is not None :
return self._halos[i] # ()
else:
h = self._get_halo(i)
self._halos[i] = h # weakref.ref(h)
return h
def __len__(self):
return len(self._halos)
def __iter__(self):
return self._halo_generator()
def __getitem__(self, item):
if isinstance(item, slice):
for x in self._halo_generator(item.start,item.stop) : pass
indices = item.indices(len(self._halos))
res = [self.calc_item(i) for i in range(*indices)]
return res
else:
return self.calc_item(item)
@property
def base(self):
return self._base()
def _halo_generator(self, i_start=None, i_stop=None) :
if len(self) == 0 : return
if i_start is None :
try :
self[0]
i = 0
except KeyError :
i = 1
else :
i = i_start
if i_stop is None :
i_stop = len(self)
while True:
try:
yield self[i]
i+=1
if len(self[i]) == 0: continue
except RuntimeError:
break
if i == i_stop: raise StopIteration
def _init_iord_to_fpos(self):
if not hasattr(self, "_iord_to_fpos"):
self._iord_to_fpos = np.empty(self.base['iord'].max()+1,dtype=np.int64)
self._iord_to_fpos[self.base['iord']] = np.arange(len(self.base))
def is_subhalo(self, childid, parentid):
"""Checks whether the specified 'childid' halo is a subhalo
of 'parentid' halo.
"""
if (childid in self._halos[parentid].properties['children']):
return True
else:
return False
def contains(self, haloid):
if (haloid in self._halos):
return True
else:
return False
def __contains__(self, haloid):
return self.contains(haloid)
def get_group_array(self):
"""Return an array with an integer for each particle in the simulation
indicating which halo that particle is associated with. If there are multiple
levels (i.e. subhalos), the number returned corresponds to the lowest level, i.e.
the smallest subhalo."""
raise NotImplementedError
@staticmethod
def _can_load(self):
return False
@staticmethod
def _can_run(self):
return False
class RockstarIntermediateCatalogue(HaloCatalogue):
"""Reader for Rockstar intermediate catalogues as generated by
Michael Tremmel's tool"""
_halo_type = np.dtype([('id',np.int64),('num_p',np.int64),('indstart',np.int64)])
_part_type = np.dtype('int64')
def __init__(self, sim, sort=True, correct=False):
assert isinstance(sim,snapshot.SimSnap)
self._correct=correct
HaloCatalogue.__init__(self, sim)
self._halos = {}
self._index_filename = sim.filename+".rockstar.halos"
self._particles_filename = sim.filename+".rockstar.halo_particles_fpos"
self._init_index()
if sort:
self._sort_index()
def __len__(self):
return self._nhalos
def _get_particles_for_halo(self, num):
halo_info = self._halo_info[num]
with util.open_(self._particles_filename) as f:
f.seek(halo_info['indstart']*self._part_type.itemsize)
halo_ptcls=np.fromfile(f,dtype=self._part_type,count=halo_info['num_p']-1)
halo_ptcls.sort()
return halo_ptcls
def _add_halo_id(self, halo, num):
halo.properties['rockstar_halo_id']=self._halo_info[num]['id']
if self._correct is True:
with util.open_(self._particles_filename) as f:
f.seek(self._halo_info['indstart'][num]*self._part_type.itemsize)
one_ptcl = np.fromfile(f,dtype=self._part_type,count=1)
from . import load
onep = load(self.base.filename, take = one_ptcl)
while not onep['grpid']:
one_ptcl = np.fromfile(f,dtype=self._part_type,count=1)
onep = load(self.base.filename, take = one_ptcl)
halo.properties['rockstar_halo_id'] = onep['grpid'][0]
def _get_halo(self, i):
if self.base is None:
raise RuntimeError("Parent SimSnap has been deleted")
halo_ptcls = self._get_particles_for_halo(i)
h = Halo(i, self, self.base, halo_ptcls)
self._add_halo_id(h,i)
return h
def load_copy(self, i):
"""Load a fresh SimSnap with only the particles in halo i"""
if i>=len(self):
raise KeyError, "No such halo"
from . import load
halo = load(self.base.filename, take=self._get_particles_for_halo(i))
self._add_halo_id(halo, i)
return halo
@staticmethod
def _can_load(sim,*args,**kwargs):
return os.path.exists(sim.filename+".rockstar.halos") and \
os.path.exists(sim.filename+".rockstar.halo_particles_fpos")
def _init_index(self):
with open(self._index_filename,"rb") as f:
self._nhalos = np.fromfile(f,np.int64,1)[0]
#self._halo_info = np.fromfile(f,self._halo_type,self._nhalos)
self._halo_info = np.fromfile(f,self._halo_type,-1)
ok, = np.where(self._halo_info['indstart']>=0)
self._halo_info = self._halo_info[ok]
def _sort_index(self):
self._halo_info[::-1].sort(order='num_p')
def get_fam_group_array(self, family='star'):
if family == 'star':
target = self.base.star
if family == 'gas':
target = self.base.gas
if family == 'dark':
target = self.base.dark
if family == 'BH':
temptarget = self.base.star
target = temptarget[(temptarget['tform']<0)]
if family not in ['star','gas','dark', 'BH']:
raise TypeError("family input not understood. Must be star, gas, or dark")
ar = -1 * np.ones(len(target))
if family != 'dark':
fpos_ar = target.get_index_list(self.base)
ngas = len(self.base.gas)
ndark = len(self.base.dark)
with util.open_(self._particles_filename) as f:
for i in range(len(self._halo_info)):
#print i, len(self._halo_info)
#if i%100 == 0: print float(i)/float(len(self._halo_info))*100, "% done"
f.seek(self._halo_info[i]['indstart']*self._part_type.itemsize)
halo_ptcls=np.fromfile(f,dtype=self._part_type,count=self._halo_info[i]['num_p']-1)
if family == 'gas':
halo_ptcls = halo_ptcls[(halo_ptcls>=ndark)&(halo_ptcls<ndark+ngas)]
if family == 'dark':
halo_ptcls = halo_ptcls[(halo_ptcls<ndark)]
if family == 'star' or family == 'BH':
halo_ptcls = halo_ptcls[(halo_ptcls>=ndark+ngas)]
if family != 'dark':
match, = np.where(np.in1d(fpos_ar, halo_ptcls))
ar[match] = i
else:
ar[halo_ptcls] = i
return ar.astype(np.int)
class RockstarCatalogue(HaloCatalogue):
def __init__(self, sim, dummy=False, filename=None, sort=False):
"""Initialize a RockstarCatalogue.
**kwargs** :
*dummy*: if True, the particle file is not loaded, and all
halos returned are just dummies (with the correct
properties dictionary loaded). Use load_copy to get
the actual data in this case.
*sort*: if True, resort the halos into descending order of
particle number. Otherwise, leave in RockStar output order.
"""
HaloCatalogue.__init__(self, sim)
self._dummy = dummy
if filename is not None:
self._files = filename
else:
self._files = glob.glob(os.path.join(os.path.dirname(sim.filename),'halos*.bin'))
self._cpus = [RockstarCatalogueOneCpu(sim,dummy,file_i) for file_i in self._files]
self._prune_files_from_wrong_scalefactor()
self._cpus[0]._init_iord_to_fpos()
for cpu in self._cpus:
cpu._iord_to_fpos = self._cpus[0]._iord_to_fpos
self._init_index_ar()
if sort:
self._sort_index_ar()
def _prune_files_from_wrong_scalefactor(self):
new_cpus = []
for cpu in self._cpus:
if abs(self.base.properties['a']-cpu._head['scale'])<1e-6:
new_cpus.append(cpu)
self._cpus = new_cpus
def _pass_on(self, function, *args, **kwargs):
if self._index_ar is not None:
cpui, hi = self._cpus[self._index_ar[args[0],0]], self._index_ar[args[0],1]
return function(cpui,hi,*args[1:],**kwargs)
for i in self._cpus:
try:
return function(i,*args,**kwargs)
except KeyError:
pass
def __getitem__(self, k):
return self._pass_on(RockstarCatalogueOneCpu.__getitem__, k)
def load_copy(self, k):
return self._pass_on(RockstarCatalogueOneCpu.load_copy, k)
def __len__(self):
return sum([len(x) for x in self._cpus])
def _run_rockstar(self, sim):
import pynbody
fileformat = 'TIPSY'
if (sim is pynbody.gadget.GadgetSnap):
fileformat = 'GADGET'
import pynbody.units as units
# find AHFstep
groupfinder = config_parser.get('RockstarCatalogue', 'Path')
if groupfinder == 'None':
for directory in os.environ["PATH"].split(os.pathsep):
ahfs = glob.glob(os.path.join(directory, "rockstar-galaxies"))
for iahf, ahf in enumerate(ahfs):
if ((len(ahfs) > 1) & (iahf != len(ahfs)-1) &
(os.path.basename(ahf) == 'rockstar-galaxies')):
continue
else:
groupfinder = ahf
break
if not os.path.exists(groupfinder):
raise RuntimeError("Path to Rockstar (%s) is invalid" % groupfinder)
f = open('quickstart.cfg', 'w')
print >>f, config_parser.get('RockstarCatalogue', 'Config', vars={
'format': fileformat,
'partmass': sim.d['mass'].in_units('Msol h^-1',**sim.conversion_context()).min(),
'expfac': sim.properties['a'],
'hub': sim.properties['h'],
'omega0': sim.properties['omegaM0'],
'lambda0': sim.properties['omegaL0'],
'boxsize': sim['pos'].units.ratio('Mpc a h^-1', **sim.conversion_context()),
'vunit': sim['vel'].units.ratio('km s^-1 a', **sim.conversion_context()),
'munit': sim['mass'].units.ratio('Msol h^-1', **sim.conversion_context()),
'softening': sim.s['eps'].in_units('Mpc a h^-1', **sim.conversion_context()).min()
})
f.close()
if (not os.path.exists(sim._filename)):
os.system("gunzip "+sim._filename+".gz")
# determine parallel possibilities
if os.path.exists(groupfinder):
# run it
if config['verbose']:
print "RockstarCatalogue: running %s"%groupfinder
os.system(groupfinder+" -c quickstart.cfg "+sim._filename)
return
def _init_index_ar(self):
index_ar = np.empty((len(self),2),dtype=np.int32)
for cpu_id, cpu in enumerate(self._cpus):
i0 = cpu._halo_min
i1 = cpu._halo_max
index_ar[i0:i1,0]=cpu_id
index_ar[i0:i1,1]=np.arange(i0,i1,dtype=np.int32)
self._index_ar = index_ar
def _sort_index_ar(self):
num_ar = np.empty(len(self))
for cpu_id, cpu in enumerate(self._cpus):
i0 = cpu._halo_min
i1 = cpu._halo_max
num_ar[i0:i1]=self._cpus[cpu_id]._halo_lens
num_ar = np.argsort(num_ar)[::-1]
self._index_ar = self._index_ar[num_ar]
@staticmethod
def _can_run(sim):
if config_parser.getboolean('RockstarCatalogue', 'AutoRun'):
if config_parser.get('RockstarCatalogue', 'Path') == 'None':
for directory in os.environ["PATH"].split(os.pathsep):
if (len(glob.glob(os.path.join(directory, "rockstar-galaxies"))) > 0):
return True
else:
path = config_parser.get('RockstarCatalogue', 'Path')
return os.path.exists(path)
return False
class RockstarCatalogueOneCpu(HaloCatalogue):
"""
Class to handle catalogues produced by Rockstar
"""
head_type = np.dtype([('magic',np.uint64),('snap',np.int64),
('chunk',np.int64),('scale','f'),
('Om','f'),('Ol','f'),('h0','f'),
('bounds','f',6),('num_halos',np.int64),
('num_particles',np.int64),('box_size','f'),
('particle_mass','f'),('particle_type',np.int64),
('format_revision',np.int32),
('rockstar_version',np.str_,12)])
halo_type = np.dtype([('id',np.int64),('pos','f',3),('vel','f',3),
('corevel','f',3),('bulkvel','f',3),('m','f'),
('r','f'),
('child_r','f'),('vmax_r','f'),('mgrav','f'),
('vmax','f'),('rvmax','f'),('rs','f'),
('klypin_rs','f'),('vrms','f'),('J','f',3),
('energy','f'),('spin','f'),('alt_m','f',4),
('Xoff','f'),('Voff','f'),('b_to_a','f'),
('c_to_a','f'),('A','f',3),('b_to_a2','f'),
('c_to_a2','f'),('A2','f',3),('bullock_spin','f'),
('kin_to_pot','f'),('m_pe_b','f'),('m_pe_d','f'),
('dum',np.str_,4),
('num_p',np.int64),('num_child_particles',np.int64),
('p_start',np.int64),('desc',np.int64),
('flags',np.int64),('n_core',np.int64),
('min_pos_err','f'),('min_vel_err','f'),
('min_bulkvel_err','f'),('type',np.int32),
('sm','f'),('gas','f'),('bh','f'),
('peak_density','f'),('av_density','f'),
('odum',np.str_,4)])
def __init__(self, sim, dummy=False, filename=None):
"""Initialize a RockstarCatalogue.
**kwargs** :
*dummy*: if True, the particle file is not loaded, and all
halos returned are just dummies (with the correct
properties dictionary loaded). Use load_copy to get
the actual data in this case.
"""
import os.path
if not self._can_load(sim):
self._run_rockstar(sim)
HaloCatalogue.__init__(self,sim)
self._dummy = dummy
if filename is not None: self._rsFilename = filename
else:
self._rsFilename = util.cutgz(glob.glob('halos*.bin')[0])
try :
f = util.open_(self._rsFilename)
except IOError:
raise IOError("Halo catalogue not found -- check the file name of catalogue data or try specifying a catalogue using the filename keyword")
with f:
self._head = np.fromstring(f.read(self.head_type.itemsize),
dtype=self.head_type)
unused = f.read(256 - self._head.itemsize)
self._nhalos = self._head['num_halos'][0]
self._load_rs_halos(f,sim)
def __len__(self):
return len(self._halo_lens)
def calc_item(self, i):
if self.base is None:
raise RuntimeError("Parent SimSnap has been deleted")
self._load_rs_halo_if_required(i)
self._load_rs_particles_for_halo_if_required(i)
return self._halos[i]
def load_copy(self, i):
"""Load a fresh SimSnap with only the particles in halo i"""
if i<self._halo_min or i>=self._halo_max:
raise KeyError, "No such halo"
from . import load
return load(self.base.filename, take=self._get_particles_for_halo(i))
@staticmethod
def _can_load(sim,**kwargs):
for file in glob.glob('halos*.bin'):
if os.path.exists(file):
return True
return False
def make_grp(self):
"""
Creates a 'grp' array which labels each particle according to
its parent halo.
"""
try:
self.base['grp']
except:
self.base['grp'] = np.zeros(len(self.base),dtype='i')
for halo in self._halos.values():
halo[name][:] = halo._halo_id
if config['verbose']: print "writing %s"%(self._base().filename+'.grp')
self._base().write_array('grp',overwrite=True,binary=False)
def _setup_children(self):
"""
Creates a 'children' array inside each halo's 'properties'
listing the halo IDs of its children. Used in case the reading
of substructure data from the AHF-supplied _substructure file
fails for some reason.
"""
for i in xrange(self._nhalos):
self._halos[i+1].properties['children'] = []
for i in xrange(self._nhalos):
host = self._halos[i+1].properties.get('hostHalo', -2)
if host > -1:
try:
self._halos[host+1].properties['children'].append(i+1)
except KeyError:
pass
def _load_rs_halo_if_required(self, i):
if i not in self._halos:
self._halos[i] = self._get_dummy_for_halo(i)
def _get_dummy_for_halo(self, n):
if n<self._halo_min or n>=self._halo_max:
raise KeyError, "No such halo"
with util.open_(self._rsFilename) as f:
f.seek(self._haloprops_offset+(n-self._halo_min)*self.halo_type.itemsize)
halo_data = np.fromfile(f, dtype=self.halo_type, count=1)
hn = DummyHalo()
# TODO: properties are in Msun / h, Mpc / h
hn.properties = dict(zip(halo_data.dtype.names,halo_data[0]))
return hn
def _load_rs_halos(self, f, sim):
self._haloprops_offset = f.tell()
self._halo_offsets = np.empty(self._head['num_halos'],dtype=np.int64)
self._halo_lens = np.empty(self._head['num_halos'],dtype=np.int64)
offset = self._haloprops_offset+self.halo_type.itemsize*self._head['num_halos']
self._halo_min = int(np.fromfile(f, dtype=self.halo_type, count=1)['id'])
self._halo_max = self._halo_min+self._head['num_halos']
f.seek(self._haloprops_offset)
this_id = self._halo_min
for h in xrange(self._head['num_halos']):
halo_data =np.fromfile(f, dtype=self.halo_type, count=1)
self._halo_offsets[this_id-self._halo_min] = int(offset)
self._halo_lens[this_id-self._halo_min] = int(halo_data['num_p'])
offset+=halo_data['num_p']*np.dtype('int64').itemsize
this_id+=1
def _get_particles_for_halo(self, num):
self._init_iord_to_fpos()
with util.open_(self._rsFilename) as f:
f.seek(self._halo_offsets[num-self._halo_min])
halo_ptcls=np.fromfile(f,dtype=np.int64,count=self._halo_lens[num-self._halo_min])
halo_ptcls = self._iord_to_fpos[halo_ptcls]
halo_ptcls.sort()
return halo_ptcls
def _load_rs_particles_for_halo(self, num):
halo_ptcls = self._get_particles_for_halo(num)
properties_from_proxy = self._halos[num].properties
self._halos[num]=Halo(num, self, self.base, halo_ptcls)
self._halos[num]._descriptor = "halo_"+str(num)
self._halos[num].properties.update(properties_from_proxy)
def _load_rs_particles_for_halo_if_required(self, num):
if isinstance(self._halos[num], DummyHalo) and not self._dummy:
self._load_rs_particles_for_halo(num)
def _load_ahf_substructure(self, filename):
f = util.open_(filename)
for i in xrange(len(self._halos)):
haloid, nsubhalos = [int(x) for x in f.readline().split()]
self._halos[haloid+1].properties['children'] = [
int(x)+1 for x in f.readline().split()]
f.close()
def writestat(self, outfile=None, hubble=None):
"""
write a condensed skid.stat style ascii file from ahf_halos
file. header + 1 halo per line. should reproduce `Alyson's
idl script' except does not do last 2 columns (Is it a
satellite?) and (Is central halo is `false'ly split?). output
units are set to Mpc Msun, km/s.
user can specify own hubble constant hubble=(H0/(100
km/s/Mpc)), ignoring the snaphot arg for hubble constant
(which sometimes has a large roundoff error).
"""
s = self._base()
mindarkmass = min(s.dark['mass'])
if hubble is None:
hubble = s.properties['h']
if outfile is None: outfile = self._base().filename+'.stat'
print "write stat file to ", outfile
fpout = open(outfile, "w")
header = "#Grp N_tot N_gas N_star N_dark Mvir(M_sol) Rvir(kpc) GasMass(M_sol) StarMass(M_sol) DarkMass(M_sol) V_max R@V_max VelDisp Xc Yc Zc VXc VYc VZc Contam Satellite? False? ID_A"
print >> fpout, header
for ii in np.arange(self._nhalos)+1:
print '%d '%ii,
sys.stdout.flush()
h = self[ii].properties # halo index starts with 1 not 0
## 'Contaminated'? means multiple dark matter particle masses in halo)"
icontam = np.where(self[ii].dark['mass'] > mindarkmass)
if (len(icontam[0]) > 0):
contam = "contam"
else:
contam = "clean"
## may want to add implement satellite test and false central breakup test.
ss = " " # can adjust column spacing
outstring = str(ii)+ss
outstring += str(len(self[ii]))+ss+str(len(self[ii].g))+ss
outstring += str(len(self[ii].s)) + ss+str(len(self[ii].dark))+ss
outstring += str(h['m']/hubble)+ss+str(h['r']/hubble)+ss
outstring += str(self[ii].g['mass'].in_units('Msol').sum())+ss
outstring += str(self[ii].s['mass'].in_units('Msol').sum())+ss
outstring += str(self[ii].d['mass'].in_units('Msol').sum())+ss
outstring += str(h['vmax'])+ss+str(h['vmax_r']/hubble)+ss
outstring += str(h['vrms'])+ss
## pos: convert kpc/h to mpc (no h).
outstring += str(h['pos'][0][0]/hubble)+ss
outstring += str(h['pos'][0][1]/hubble)+ss
outstring += str(h['pos'][0][2]/hubble)+ss
outstring += str(h['vel'][0][0])+ss+str(h['vel'][0][1])+ss
outstring += str(h['vel'][0][2])+ss
outstring += contam+ss
outstring += "unknown" + \
ss # unknown means sat. test not implemented.
outstring += "unknown"+ss # false central breakup.
print >> fpout, outstring
fpout.close()
def writetipsy(self, outfile=None, hubble=None):
"""
write halos to tipsy file (write as stars) from ahf_halos
file. returns a shapshot where each halo is a star particle.
user can specify own hubble constant hubble=(H0/(100
km/s/Mpc)), ignoring the snaphot arg for hubble constant
(which sometimes has a large roundoff error).
"""
from . import analysis
from . import tipsy
from .analysis import cosmology
from snapshot import _new as new
import math
s = self._base()
if outfile is None: outfile = s.filename+'.gtp'
print "write tipsy file to ", outfile
sout = new(star=self._nhalos) # create new tipsy snapshot written as halos.
sout.properties['a'] = s.properties['a']
sout.properties['z'] = s.properties['z']
sout.properties['boxsize'] = s.properties['boxsize']
if hubble is None: hubble = s.properties['h']
sout.properties['h'] = hubble
### ! dangerous -- rho_crit function and unit conversions needs simplifying
rhocrithhco = cosmology.rho_crit(s, z=0, unit="Msol Mpc^-3 h^2")
lboxkpc = sout.properties['boxsize'].ratio("kpc a")
lboxkpch = lboxkpc*sout.properties['h']
lboxmpch = lboxkpc*sout.properties['h']/1000.
tipsyvunitkms = lboxmpch * 100. / (math.pi * 8./3.)**.5
tipsymunitmsun = rhocrithhco * lboxmpch**3 / sout.properties['h']
print "transforming ", self._nhalos, " halos into tipsy star particles"
for ii in xrange(self._nhalos):
h = self[ii+1].properties
sout.star[ii]['mass'] = h['m']/hubble / tipsymunitmsun
## tipsy units: box centered at 0. (assume 0<=x<=1)
sout.star[ii]['x'] = h['pos'][0][0]/lboxmpch - 0.5
sout.star[ii]['y'] = h['pos'][0][1]/lboxmpch - 0.5
sout.star[ii]['z'] = h['pos'][0][2]/lboxmpch - 0.5
sout.star[ii]['vx'] = h['vel'][0][0]/tipsyvunitkms
sout.star[ii]['vy'] = h['vel'][0][1]/tipsyvunitkms
sout.star[ii]['vz'] = h['vel'][0][2]/tipsyvunitkms
sout.star[ii]['eps'] = h['r']/lboxkpch
sout.star[ii]['metals'] = 0.
sout.star[ii]['phi'] = 0.
sout.star[ii]['tform'] = 0.
print "writing tipsy outfile %s"%outfile
sout.write(fmt=tipsy.TipsySnap, filename=outfile)
return sout
def writehalos(self, hubble=None, outfile=None):
s = self._base()
if outfile is None:
statoutfile = s.filename+".rockstar.stat"
tipsyoutfile = s.filename+".rockstar.gtp"
else:
statoutfile = outfile+'.stat'
gtpoutfile = outfile+'.gtp'
self.make_grp()
self.writestat(statoutfile, hubble=hubble)
shalos = self.writetipsy(gtpoutfile, hubble=hubble)
return shalos
#--------------------------#
# AHF Halo Catalogue class #
#--------------------------#
class AHFCatalogue(HaloCatalogue):
"""
Class to handle catalogues produced by Amiga Halo Finder (AHF).
"""
def __init__(self, sim, make_grp=None, dummy=False, use_iord=None, ahf_basename=None):
"""Initialize an AHFCatalogue.
**kwargs** :
*make_grp*: if True a 'grp' array is created in the underlying
snapshot specifying the lowest level halo that any
given particle belongs to. If it is False, no such
array is created; if None, the behaviour is
determined by the configuration system.
*dummy*: if True, the particle file is not loaded, and all
halos returned are just dummies (with the correct
properties dictionary loaded). Use load_copy to get
the actual data in this case.
*use_iord*: if True, the particle IDs in the Amiga catalogue
are taken to refer to the iord array. If False,
they are the particle offsets within the file. If
None, the parameter defaults to True for
GadgetSnap, False otherwise.
*ahf_basename*: specify the basename of the AHF halo catalog
files - the code will append 'halos',
'particles', and 'substructure' to this
basename to load the catalog data.
"""
import os.path
if not self._can_load(sim):
self._run_ahf(sim)
HaloCatalogue.__init__(self,sim)
if use_iord is None:
use_iord = isinstance(sim.ancestor, gadget.GadgetSnap)
self._use_iord = use_iord
self._dummy = dummy
if ahf_basename is not None:
self._ahfBasename = ahf_basename
else:
self._ahfBasename = util.cutgz(
glob.glob(sim._filename + '*z*AHF_halos*')[0])[:-5]
try:
f = util.open_(self._ahfBasename + 'halos')
except IOError:
raise IOError(
"Halo catalogue not found -- check the base name of catalogue data or try specifying a catalogue using the ahf_basename keyword")
for i, l in enumerate(f):
pass
self._nhalos = i
f.close()
logger.info("AHFCatalogue loading particles")
self._load_ahf_particles(self._ahfBasename + 'particles')
logger.info("AHFCatalogue loading halos")
self._load_ahf_halos(self._ahfBasename + 'halos')
if os.path.isfile(self._ahfBasename + 'substructure'):
logger.info("AHFCatalogue loading substructure")
self._load_ahf_substructure(self._ahfBasename + 'substructure')
else:
self._setup_children()
if make_grp is None:
make_grp = config_parser.getboolean('AHFCatalogue', 'AutoGrp')
if make_grp:
self.make_grp()
if config_parser.getboolean('AHFCatalogue', 'AutoPid'):
sim['pid'] = np.arange(0, len(sim))
logger.info("AHFCatalogue loaded")
def make_grp(self, name='grp'):
"""
Creates a 'grp' array which labels each particle according to
its parent halo.
"""
self.base[name] = self.get_group_array()
def get_group_array(self, top_level=False):
ar = np.zeros(len(self.base), dtype=int)
if top_level is False:
for halo in self._halos.values():
ar[halo.get_index_list(self.base)] = halo._halo_id
else:
for halo in self._halos.values()[::-1]:
ar[halo.get_index_list(self.base)] = halo._halo_id
return ar
def _setup_children(self):
"""
Creates a 'children' array inside each halo's 'properties'
listing the halo IDs of its children. Used in case the reading
of substructure data from the AHF-supplied _substructure file
fails for some reason.
"""
for i in xrange(self._nhalos):
self._halos[i + 1].properties['children'] = []
for i in xrange(self._nhalos):
host = self._halos[i + 1].properties.get('hostHalo', -2)
if host > -1:
try:
self._halos[host + 1].properties['children'].append(i + 1)
except KeyError:
pass
def _get_halo(self, i):
if self.base is None:
raise RuntimeError("Parent SimSnap has been deleted")
return self._halos[i]
@property
def base(self):
return self._base()
def load_copy(self, i):
"""Load the a fresh SimSnap with only the particle in halo i"""
from . import load
f = util.open_(self._ahfBasename + 'particles')
if self.isnew:
nhalos = int(f.readline())
else:
nhalos = self._nhalos
for h in xrange(i):
ids = self._load_ahf_particle_block(f)
f.close()
return load(self.base.filename, take=ids)
def _load_ahf_particle_block(self, f):
"""Load the particles for the next halo described in particle file f"""
ng = len(self.base.gas)
nds = len(self.base.dark) + len(self.base.star)
nparts = int(f.readline().split()[0])
if self.isnew:
if not isinstance(f, gzip.GzipFile):
data = (np.fromfile(
f, dtype=int, sep=" ", count=nparts * 2).reshape(nparts, 2))[:, 0]
else:
# unfortunately with gzipped files there does not
# seem to be an efficient way to load nparts lines
data = np.zeros(nparts, dtype=int)
for i in xrange(nparts):
data[i] = int(f.readline().split()[0])
if self._use_iord:
data = self._iord_to_fpos[data]
else:
hi_mask = data >= nds
data[np.where(hi_mask)] -= nds
data[np.where(~hi_mask)] += ng
else:
if not isinstance(f, gzip.GzipFile):
data = np.fromfile(f, dtype=int, sep=" ", count=nparts)
else:
# see comment above on gzipped files
data = np.zeros(nparts, dtype=int)
for i in xrange(nparts):
data[i] = int(f.readline())
data.sort()
return data
def _load_ahf_particles(self, filename):
if self._use_iord:
self._iord_to_fpos = np.zeros(self.base['iord'].max()+1,dtype=int)
self._iord_to_fpos[self.base['iord']] = np.arange(len(self._base()))
f = util.open_(filename)
if filename.split("z")[-2][-1] is ".":
self.isnew = True
else:
self.isnew = False
if self.isnew:
nhalos = int(f.readline())
else:
nhalos = self._nhalos
if not self._dummy:
for h in xrange(nhalos):
self._halos[h + 1] = Halo(
h + 1, self, self.base, self._load_ahf_particle_block(f))
self._halos[h + 1]._descriptor = "halo_" + str(h + 1)
else: