-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvelociraptor_python_tools.py
6493 lines (5999 loc) · 313 KB
/
velociraptor_python_tools.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
# Make backwards compatible with python 2, ignored in python 3
from __future__ import print_function
import sys
import os
import subprocess
import struct
import os.path
import string
import time
import re
import math
import operator
import numpy as np
import h5py
# import hdf5 interface
# import tables as pytb #import pytables
#import pandas as pd
import copy
from collections import deque
import itertools
import scipy.interpolate as scipyinterp
import scipy.spatial as spatial
import multiprocessing as mp
#import mpi4py as mpi
from collections import deque
import pandas as pd
#import cython
#from cython.parallel import prange, parallel
# would be good to compile these routines with cython
# try to speed up search
# cimport numpy as np
"""
Routines for reading velociraptor output
"""
"""
IO Routines
"""
def ReadPropertyFile(basefilename, ibinary=0, iseparatesubfiles=0, iverbose=0, desiredfields=[], isiminfo=True, iunitinfo=True, iconfiginfo=True):
"""
VELOCIraptor/STF files in various formats
for example ascii format contains
a header with
filenumber number_of_files
numhalos_in_file nnumhalos_in_total
followed by a header listing the information contain. An example would be
ID(1) ID_mbp(2) hostHaloID(3) numSubStruct(4) npart(5) Mvir(6) Xc(7) Yc(8) Zc(9) Xcmbp(10) Ycmbp(11) Zcmbp(12) VXc(13) VYc(14) VZc(15) VXcmbp(16) VYcmbp(17) VZcmbp(18) Mass_tot(19) Mass_FOF(20) Mass_200mean(21) Mass_200crit(22) Mass_BN97(23) Efrac(24) Rvir(25) R_size(26) R_200mean(27) R_200crit(28) R_BN97(29) R_HalfMass(30) Rmax(31) Vmax(32) sigV(33) veldisp_xx(34) veldisp_xy(35) veldisp_xz(36) veldisp_yx(37) veldisp_yy(38) veldisp_yz(39) veldisp_zx(40) veldisp_zy(41) veldisp_zz(42) lambda_B(43) Lx(44) Ly(45) Lz(46) q(47) s(48) eig_xx(49) eig_xy(50) eig_xz(51) eig_yx(52) eig_yy(53) eig_yz(54) eig_zx(55) eig_zy(56) eig_zz(57) cNFW(58) Krot(59) Ekin(60) Epot(61) n_gas(62) M_gas(63) Xc_gas(64) Yc_gas(65) Zc_gas(66) VXc_gas(67) VYc_gas(68) VZc_gas(69) Efrac_gas(70) R_HalfMass_gas(71) veldisp_xx_gas(72) veldisp_xy_gas(73) veldisp_xz_gas(74) veldisp_yx_gas(75) veldisp_yy_gas(76) veldisp_yz_gas(77) veldisp_zx_gas(78) veldisp_zy_gas(79) veldisp_zz_gas(80) Lx_gas(81) Ly_gas(82) Lz_gas(83) q_gas(84) s_gas(85) eig_xx_gas(86) eig_xy_gas(87) eig_xz_gas(88) eig_yx_gas(89) eig_yy_gas(90) eig_yz_gas(91) eig_zx_gas(92) eig_zy_gas(93) eig_zz_gas(94) Krot_gas(95) T_gas(96) Zmet_gas(97) SFR_gas(98) n_star(99) M_star(100) Xc_star(101) Yc_star(102) Zc_star(103) VXc_star(104) VYc_star(105) VZc_star(106) Efrac_star(107) R_HalfMass_star(108) veldisp_xx_star(109) veldisp_xy_star(110) veldisp_xz_star(111) veldisp_yx_star(112) veldisp_yy_star(113) veldisp_yz_star(114) veldisp_zx_star(115) veldisp_zy_star(116) veldisp_zz_star(117) Lx_star(118) Ly_star(119) Lz_star(120) q_star(121) s_star(122) eig_xx_star(123) eig_xy_star(124) eig_xz_star(125) eig_yx_star(126) eig_yy_star(127) eig_yz_star(128) eig_zx_star(129) eig_zy_star(130) eig_zz_star(131) Krot_star(132) tage_star(133) Zmet_star(134)
then followed by data
Note that a file will indicate how many files the total output has been split into
Not all fields need be read in. If only want specific fields, can pass a string of desired fields like
['ID', 'Mass_FOF', 'Krot']
#todo still need checks to see if fields not present and if so, not to include them or handle the error
"""
# this variable is the size of the char array in binary formated data that stores the field names
CHARSIZE = 40
start = time.process_time()
inompi = True
if (iverbose):
print("reading properties file", basefilename)
filename = basefilename+".properties"
# load header
if (os.path.isfile(filename) == True):
numfiles = 0
else:
filename = basefilename+".properties"+".0"
inompi = False
if (os.path.isfile(filename) == False):
print("Could not find VELOCIraptor file as either",basefilename+".properties or",filename)
return []
byteoffset = 0
# used to store fields, their type, etc
fieldnames = []
fieldtype = []
fieldindex = []
if (ibinary == 0):
# load ascii file
halofile = open(filename, 'r')
# read header information
[filenum, numfiles] = halofile.readline().split()
filenum = int(filenum)
numfiles = int(numfiles)
[numhalos, numtothalos] = halofile.readline().split()
numhalos = np.uint64(numhalos)
numtothalos = np.uint64(numtothalos)
names = ((halofile.readline())).split()
# remove the brackets in ascii file names
fieldnames = [fieldname.split("(")[0] for fieldname in names]
for i in np.arange(fieldnames.__len__()):
fieldname = fieldnames[i]
if fieldname in ["ID", "numSubStruct", "npart", "n_gas", "n_star", "Structuretype"]:
fieldtype.append(np.uint64)
elif fieldname in ["ID_mbp", "hostHaloID"]:
fieldtype.append(np.int64)
else:
fieldtype.append(np.float64)
halofile.close()
# if desiredfields is NULL load all fields
# but if this is passed load only those fields
if (len(desiredfields) > 0):
lend = len(desiredfields)
fieldindex = np.zeros(lend, dtype=int)
desiredfieldtype = [[] for i in range(lend)]
for i in range(lend):
fieldindex[i] = fieldnames.index(desiredfields[i])
desiredfieldtype[i] = fieldtype[fieldindex[i]]
fieldtype = desiredfieldtype
fieldnames = desiredfields
# to store the string containing data format
fieldtypestring = ''
for i in np.arange(fieldnames.__len__()):
if fieldtype[i] == np.uint64:
fieldtypestring += 'u8, '
elif fieldtype[i] == np.int64:
fieldtypestring += 'i8, '
elif fieldtype[i] == np.float64:
fieldtypestring += 'f8, '
elif (ibinary == 1):
# load binary file
halofile = open(filename, 'rb')
[filenum, numfiles] = np.fromfile(halofile, dtype=np.int32, count=2)
[numhalos, numtothalos] = np.fromfile(
halofile, dtype=np.uint64, count=2)
headersize = np.fromfile(halofile, dtype=np.int32, count=1)[0]
byteoffset = np.dtype(np.int32).itemsize*3 + \
np.dtype(np.uint64).itemsize*2+4*headersize
for i in range(headersize):
fieldnames.append(struct.unpack('s', halofile.read(CHARSIZE)).strip())
for i in np.arange(fieldnames.__len__()):
fieldname = fieldnames[i]
if fieldname in ["ID", "numSubStruct", "npart", "n_gas", "n_star", "Structuretype"]:
fieldtype.append(np.uint64)
elif fieldname in ["ID_mbp", "hostHaloID"]:
fieldtype.append(np.int64)
else:
fieldtype.append(np.float64)
halofile.close()
# if desiredfields is NULL load all fields
# but if this is passed load only those fields
if (len(desiredfields) > 0):
lend = len(desiredfields)
fieldindex = np.zeros(lend, dtype=int)
desiredfieldtype = [[] for i in range(lend)]
for i in range(lend):
fieldindex[i] = fieldnames.index(desiredfields[i])
desiredfieldtype[i] = fieldtype[fieldindex[i]]
fieldtype = desiredfieldtype
fieldnames = desiredfields
# to store the string containing data format
fieldtypestring = ''
for i in np.arange(fieldnames.__len__()):
if fieldtype[i] == np.uint64:
fieldtypestring += 'u8, '
elif fieldtype[i] == np.int64:
fieldtypestring += 'i8, '
elif fieldtype[i] == np.float64:
fieldtypestring += 'f8, '
elif (ibinary == 2):
# load hdf file
halofile = h5py.File(filename, 'r')
filenum = int(halofile["File_id"][0])
numfiles = int(halofile["Num_of_files"][0])
numhalos = np.uint64(halofile["Num_of_groups"][0])
numtothalos = np.uint64(halofile["Total_num_of_groups"][0])
#atime = np.float(halofile.attrs["Time"])
fieldnames = [str(n) for n in halofile.keys()]
# clean of header info
fieldnames.remove("File_id")
fieldnames.remove("Num_of_files")
fieldnames.remove("Num_of_groups")
fieldnames.remove("Total_num_of_groups")
if ('Configuration' in fieldnames): fieldnames.remove('Configuration')
if ('SimulationInfo' in fieldnames): fieldnames.remove('SimulationInfo')
if ('UnitInfo' in fieldnames): fieldnames.remove('UnitInfo')
fieldtype = [halofile[fieldname].dtype for fieldname in fieldnames]
# if the desiredfields argument is passed only these fieds are loaded
if (len(desiredfields) > 0):
if (iverbose):
print("Loading subset of all fields in property file ",
len(desiredfields), " instead of ", len(fieldnames))
fieldnames = desiredfields
fieldtype = [halofile[fieldname].dtype for fieldname in fieldnames]
halofile.close()
# allocate memory that will store the halo dictionary
catalog = {fieldnames[i]: np.zeros(
numtothalos, dtype=fieldtype[i]) for i in range(len(fieldnames))}
noffset = np.uint64(0)
for ifile in range(numfiles):
if (inompi == True):
filename = basefilename+".properties"
else:
filename = basefilename+".properties"+"."+str(ifile)
if (iverbose):
print("reading ", filename)
if (ibinary == 0):
halofile = open(filename, 'r')
halofile.readline()
numhalos = np.uint64(halofile.readline().split()[0])
halofile.close()
if (numhalos > 0):
htemp = np.loadtxt(filename, skiprows=3, usecols=fieldindex,
dtype=fieldtypestring, unpack=True, ndmin=1)
elif(ibinary == 1):
halofile = open(filename, 'rb')
np.fromfile(halofile, dtype=np.int32, count=2)
numhalos = np.fromfile(halofile, dtype=np.uint64, count=2)[0]
# halofile.seek(byteoffset);
if (numhalos > 0):
htemp = np.fromfile(
halofile, usecols=fieldindex, dtype=fieldtypestring, unpack=True)
halofile.close()
elif(ibinary == 2):
# here convert the hdf information into a numpy array
halofile = h5py.File(filename, 'r')
numhalos = np.uint64(halofile["Num_of_groups"][0])
if (numhalos > 0):
htemp = [np.array(halofile[catvalue])
for catvalue in fieldnames]
halofile.close()
#numhalos = len(htemp[0])
for i in range(len(fieldnames)):
catvalue = fieldnames[i]
if (numhalos > 0):
catalog[catvalue][noffset:noffset+numhalos] = htemp[i]
noffset += numhalos
# if subhalos are written in separate files, then read them too
if (iseparatesubfiles == 1):
for ifile in range(numfiles):
if (inompi == True):
filename = basefilename+".sublevels"+".properties"
else:
filename = basefilename+".sublevels" + \
".properties"+"."+str(ifile)
if (iverbose):
print("reading ", filename)
if (ibinary == 0):
halofile = open(filename, 'r')
halofile.readline()
numhalos = np.uint64(halofile.readline().split()[0])
halofile.close()
if (numhalos > 0):
htemp = np.loadtxt(
filename, skiprows=3, usecols=fieldindex, dtype=fieldtypestring, unpack=True, ndmin=1)
elif(ibinary == 1):
halofile = open(filename, 'rb')
# halofile.seek(byteoffset);
np.fromfile(halofile, dtype=np.int32, count=2)
numhalos = np.fromfile(halofile, dtype=np.uint64, count=2)[0]
if (numhalos > 0):
htemp = np.fromfile(
halofile, usecols=fieldindex, dtype=fieldtypestring, unpack=True)
halofile.close()
elif(ibinary == 2):
halofile = h5py.File(filename, 'r')
numhalos = np.uint64(halofile["Num_of_groups"][0])
if (numhalos > 0):
htemp = [np.array(halofile[catvalue])
for catvalue in fieldnames]
halofile.close()
#numhalos = len(htemp[0])
for i in range(len(fieldnames)):
catvalue = fieldnames[i]
if (numhalos > 0):
catalog[catvalue][noffset:noffset+numhalos] = htemp[i]
noffset += numhalos
# load associated simulation info, time, units and configuration options
if (isiminfo):
if(iverbose):
print("reading ",basefilename+".siminfo")
catalog['SimulationInfo'] = ReadSimInfo(basefilename)
if (iunitinfo):
if(iverbose):
print("reading ",basefilename+".unitinfo")
catalog['UnitInfo'] = ReadUnitInfo(basefilename)
if (iconfiginfo):
if(iverbose):
print("reading ",basefilename+".configuration")
catalog['ConfigurationInfo'] = ReadConfigInfo(basefilename)
if (iverbose):
print("done reading properties file ", time.process_time()-start)
return catalog, numtothalos
def ReadPropertyFileMultiWrapper(basefilename, index, halodata, numhalos, atime, ibinary=0, iseparatesubfiles=0, iverbose=0, desiredfields=[]):
"""
Wrapper for multithreaded reading
"""
# call read routine and store the data
halodata[index], numhalos[index] = ReadPropertyFile(
basefilename, ibinary, iseparatesubfiles, iverbose, desiredfields)
def ReadPropertyFileMultiWrapperNamespace(index, basefilename, ns, ibinary=0, iseparatesubfiles=0, iverbose=0, desiredfields=[]):
# call read routine and store the data
ns.hdata[index], ns.ndata[index] = ReadPropertyFile(
basefilename, ibinary, iseparatesubfiles, iverbose, desiredfields)
def ReadHaloMergerTree(treefilename, ibinary=0, iverbose=0, imerit=False, inpart=False):
"""
VELOCIraptor/STF merger tree in ascii format contains
a header with
number_of_snapshots
a description of how the tree was built
total number of halos across all snapshots
then followed by data
for each snapshot
snapshotvalue numhalos
haloid_1 numprogen_1
progenid_1
progenid_2
...
progenid_numprogen_1
haloid_2 numprogen_2
.
.
.
one can also have an output format that has an additional field for each progenitor, the meritvalue
"""
start = time.process_time()
tree = {}
if (iverbose):
print("reading Tree file", treefilename, os.path.isfile(treefilename))
if (os.path.isfile(treefilename) == False):
print("Error, file not found")
return tree
# if ascii format
if (ibinary == 0):
treefile = open(treefilename, 'r')
numsnap = int(treefile.readline())
treefile.close()
elif(ibinary == 2):
if (iverbose):
print("Reading HDF5 input")
snaptreelist = open(treefilename, 'r')
snaptreename = snaptreelist.readline().strip()+".tree"
numsnaplist = sum(1 for line in snaptreelist) +1
treedata = h5py.File(snaptreename, "r")
numsnap = treedata.attrs['Number_of_snapshots']
#Check if the treefrog number of snapshots and the number of files in the list is consistent
if(numsnap!=numsnaplist):
print("Error, the number of snapshots reported by the TreeFrog output is different to the number of filenames supplied. \nPlease update this.")
return tree
#Lets extract te header information
tree["Header"] = dict()
for field in treedata.attrs.keys():
tree["Header"][field] = treedata.attrs[field]
treedata.close()
snaptreelist.close()
else:
print("Unknown format, returning null")
numsnap = 0
return tree
tree.update({i: {"haloID": [], "Num_progen": [], "Progen": []}
for i in range(numsnap)})
if (imerit):
for i in range(numsnap):
tree[i]['Merit'] = []
if (inpart):
for i in range(numsnap):
tree[i]['Npart'] = []
tree[i]['Npart_progen'] = []
# if ascii format
if (ibinary == 0):
treefile = open(treefilename, 'r')
numsnap = int(treefile.readline())
descrip = treefile.readline().strip()
tothalos = int(treefile.readline())
offset = 0
totalnumprogen = 0
for i in range(numsnap):
[snapval, numhalos] = treefile.readline().strip().split('\t')
snapval = int(snapval)
numhalos = int(numhalos)
# if really verbose
if (iverbose == 2):
print(snapval, numhalos)
tree[i]["haloID"] = np.zeros(numhalos, dtype=np.int64)
tree[i]["Num_progen"] = np.zeros(numhalos, dtype=np.uint32)
tree[i]["Progen"] = [[] for j in range(numhalos)]
if (imerit):
tree[i]["Merit"] = [[] for j in range(numhalos)]
if (inpart):
tree[i]["Npart"] = np.zeros(numhalos, dtype=np.uint32)
tree[i]["Npart_progen"] = [[] for j in range(numhalos)]
for j in range(numhalos):
data = treefile.readline().strip().split('\t')
hid = np.int64(data[0])
nprog = np.uint32(data[1])
tree[i]["haloID"][j] = hid
tree[i]["Num_progen"][j] = nprog
if (inpart):
tree[i]["Npart"][j] = np.uint32(data[2])
totalnumprogen += nprog
if (nprog > 0):
tree[i]["Progen"][j] = np.zeros(nprog, dtype=np.int64)
if (imerit):
tree[i]["Merit"][j] = np.zeros(nprog, dtype=np.float32)
if (inpart):
tree[i]["Npart_progen"][j] = np.zeros(
nprog, dtype=np.uint32)
for k in range(nprog):
data = treefile.readline().strip().split(' ')
tree[i]["Progen"][j][k] = np.int64(data[0])
if (imerit):
tree[i]["Merit"][j][k] = np.float32(data[1])
if (inpart):
tree[i]["Npart_progen"][j][k] = np.uint32(data[2])
elif(ibinary == 2):
if("HaloID_snapshot_offset" in tree["Header"]):
snapshotoffset = tree["Header"]["HaloID_snapshot_offset"]
else:
print("Warning: you are using older TreeFrog output (version<=1.2) which does not contain information about which snapshot the halo catalog starts at\nAssuming that it starts at snapshot = 0.\nPlease use a TreeFrog version>1.2 if you require this feature")
snapshotoffset = 0
snaptreelist = open(treefilename, 'r')
for snap in range(snapshotoffset,snapshotoffset+numsnap):
snaptreename = snaptreelist.readline().strip()+".tree"
if (iverbose):
print("Reading", snaptreename)
treedata = h5py.File(snaptreename, "r")
tree[snap]["haloID"] = np.asarray(treedata["ID"])
tree[snap]["Num_progen"] = np.asarray(treedata["NumProgen"])
if(inpart):
tree[snap]["Npart"] = np.asarray(treedata["Npart"])
# See if the dataset exits
if("ProgenOffsets" in treedata.keys()):
# Find the indices to split the array
split = np.add(np.asarray(
treedata["ProgenOffsets"]), tree[snap]["Num_progen"], dtype=np.uint64, casting="unsafe")
# Read in the progenitors, splitting them as reading them in
tree[snap]["Progen"] = np.split(
treedata["Progenitors"][:], split[:-1])
if(inpart):
tree[snap]["Npart_progen"] = np.split(
treedata["ProgenNpart"], split[:-1])
if(imerit):
tree[snap]["Merit"] = np.split(
treedata["Merits"], split[:-1])
snaptreelist.close()
if (iverbose):
print("done reading tree file ", time.process_time()-start)
return tree
class MinStorageList():
"""
This uses two smaller arrays to access a large contiguous array and return subchunks
"""
Num,Offset=None,None
Data=None
def __init__(self,nums,offsets,rawdata):
self.Num=nums
self.Offset=offsets
self.Data=rawdata
def __getitem__(self, index):
if self.Num[index] == 0 :
return np.array([])
else :
return self.Data[self.Offset[index]:self.Offset[index]+self.Num[index]]
def GetBestRanks(self, ):
return np.array(self.Data[self.Offset],copy=True)
def ReadHaloMergerTreeDescendant(treefilename, ireverseorder=False, ibinary=0,
iverbose=0, imerit=False, inpart=False,
ireducedtobestranks=False, meritlimit=0.025,
ireducemem=True,iprimarydescen=False):
"""
VELOCIraptor/STF descendant based merger tree in ascii format contains
a header with
number_of_snapshots
a description of how the tree was built
total number of halos across all snapshots
then followed by data
for each snapshot
snapshotvalue numhalos
haloid_1 numprogen_1
progenid_1
progenid_2
...
progenid_numprogen_1
haloid_2 numprogen_2
.
.
.
one can also have an output format that has an additional field for each progenitor, the meritvalue
"""
start = time.process_time()
tree = {}
if (iverbose):
print("reading Tree file", treefilename, os.path.isfile(treefilename))
if (os.path.isfile(treefilename) == False):
print("Error, file not found")
return tree
# fine out how many snapshots there are
# if ascii format
if (ibinary == 0):
if (iverbose):
print("Reading ascii input")
treefile = open(treefilename, 'r')
numsnap = int(treefile.readline())
treefile.close()
# hdf format, input file is a list of filenames can also extract the header info
elif(ibinary == 2):
if (iverbose):
print("Reading HDF5 input")
snaptreelist = open(treefilename, 'r')
snaptreename = snaptreelist.readline().strip()+".tree"
numsnap = sum(1 for line in snaptreelist) +1
treedata = h5py.File(snaptreename, "r")
#Lets extract te header information
tree["Header"] = dict()
for field in treedata.attrs.keys():
tree["Header"][field] = treedata.attrs[field]
treedata.close()
snaptreelist.close()
else:
print("Unknown format, returning null")
numsnap = 0
return tree
#Check for flag compatibility
if(ireducemem & iprimarydescen):
print("Warning: Both the ireducemem and iprimarydescen are set to True. The ireducemem is not needed for iprimarydescen flag \nas it already had reduced memory footprint, due to only primiary descendants being extracted")
ireducemem=False
#Update the dictionary with the tree information
tree.update({i: {"haloID": [], "Num_descen": [], "Descen": [], "Rank": []}
for i in range(numsnap)})
if (imerit):
for i in range(numsnap):
tree[i]['Merit'] = []
if (inpart):
for i in range(numsnap):
tree[i]['Npart'] = []
tree[i]['Npart_descen'] = []
if (ibinary == 0):
treefile = open(treefilename, 'r')
numsnap = int(treefile.readline())
descrip = treefile.readline().strip()
tothalos = int(treefile.readline())
offset = 0
totalnumdescen = 0
for i in range(numsnap):
ii = i
if (ireverseorder):
ii = numsnap-1-i
[snapval, numhalos] = treefile.readline().strip().split('\t')
snapval = int(snapval)
numhalos = int(numhalos)
# if really verbose
if (iverbose == 2):
print(snapval, numhalos)
tree[ii]["haloID"] = np.zeros(numhalos, dtype=np.int64)
tree[ii]["Num_descen"] = np.zeros(numhalos, dtype=np.uint32)
tree[ii]["Descen"] = [[] for j in range(numhalos)]
tree[ii]["Rank"] = [[] for j in range(numhalos)]
if (imerit):
tree[ii]["Merit"] = [[] for j in range(numhalos)]
if (inpart):
tree[i]["Npart"] = np.zeros(numhalos, dtype=np.uint32)
tree[ii]["Npart_descen"] = [[] for j in range(numhalos)]
for j in range(numhalos):
data = treefile.readline().strip().split('\t')
hid = np.int64(data[0])
ndescen = np.uint32(data[1])
tree[ii]["haloID"][j] = hid
tree[ii]["Num_descen"][j] = ndescen
if (inpart):
tree[ii]["Npart"][j] = np.uint32(data[2])
totalnumdescen += ndescen
if (ndescen > 0):
tree[ii]["Descen"][j] = np.zeros(ndescen, dtype=np.int64)
tree[ii]["Rank"][j] = np.zeros(ndescen, dtype=np.uint32)
if (imerit):
tree[ii]["Merit"][j] = np.zeros(
ndescen, dtype=np.float32)
if (inpart):
tree[ii]["Npart_descen"][j] = np.zeros(
ndescen, dtype=np.float32)
for k in range(ndescen):
data = treefile.readline().strip().split(' ')
tree[ii]["Descen"][j][k] = np.int64(data[0])
tree[ii]["Rank"][j][k] = np.uint32(data[1])
if (imerit):
tree[ii]["Merit"][j][k] = np.float32(data[2])
if (inpart):
tree[ii]["Npart_descen"][j][k] = np.uint32(data[3])
if (ireducedtobestranks):
halolist=np.where(tree[ii]["Num_descen"]>1)[0]
for ihalo in halolist:
numdescen = 1
if (imerit):
numdescen = np.int32(np.max([1,np.argmax(tree[ii]["Merit"][ihalo]<meritlimit)]))
tree[ii]["Num_descen"][ihalo] = numdescen
tree[ii]["Descen"][ihalo] = np.array([tree[ii]["Descen"][ihalo][:numdescen]])
tree[ii]["Rank"][ihalo] = np.array([tree[ii]["Rank"][ihalo][:numdescen]])
if (imerit):
tree[ii]["Merit"][ihalo] = np.array([tree[ii]["Merit"][ihalo][:numdescen]])
if (inpart):
tree[ii]["Npart_descen"][ihalo] = np.array([tree[ii]["Npart_descen"][ihalo][:numdescen]])
# hdf format
elif(ibinary == 2):
snaptreelist = open(treefilename, 'r')
snaptreenames=[[] for snap in range(numsnap)]
for snap in range(numsnap):
snaptreenames[snap] = snaptreelist.readline().strip()+".tree"
snaptreelist.close()
if("HaloID_snapshot_offset" in tree["Header"]):
snapshotoffset = tree["Header"]["HaloID_snapshot_offset"]
else:
print("Warning: you are using older TreeFrog output (version<=1.2) which does not contain information about which snapshot the halo catalog starts at\nAssuming that it starts at snapshot = 0.\nPlease use a TreeFrog version>1.2 if you require this feature")
snapshotoffset = 0
if (iverbose):
snaptreename = snaptreenames[0]
treedata = h5py.File(snaptreename, "r")
numhalos = treedata.attrs["Total_number_of_halos"]
memsize = np.uint64(1).nbytes*2.0+np.uint16(0).nbytes*2.0
if (inpart):
memsize += np.int32(0).nbytes*2.0
if (imerit):
memsize += np.float32(0).nbytes
memsize *= numhalos
if (ireducemem):
print("Reducing memory, changes api.")
print("Data contains ", numhalos, "halos and will likley need a minimum of", memsize/1024.**3.0, "GB of memory")
elif(iprimarydescen):
print("Extracting just the primary descendants")
print("Data contains ", numhalos, "halos and will likley need a minimum of", memsize/1024.**3.0, "GB of memory")
else:
print("Contains ", numhalos, "halos and will likley minimum ", memsize/1024.**3.0, "GB of memory")
print("Plus overhead to store list of arrays, with likely need a minimum of ",100*numhalos/1024**3.0, "GB of memory ")
treedata.close()
for snap in range(snapshotoffset,snapshotoffset+numsnap):
snaptreename = snaptreenames[snap]
if (iverbose):
print("Reading", snaptreename)
treedata = h5py.File(snaptreename, "r")
tree[snap]["haloID"] = np.asarray(treedata["ID"])
tree[snap]["Num_descen"] = np.asarray(treedata["NumDesc"],np.uint16)
numhalos=tree[snap]["haloID"].size
if(inpart):
tree[snap]["Npart"] = np.asarray(treedata["Npart"],np.int32)
# See if the dataset exits
if("DescOffsets" in treedata.keys()):
# Find the indices to split the array
if (ireducemem):
tree[snap]["_Offsets"] = np.asarray(treedata["DescOffsets"],dtype=np.uint64)
elif(iprimarydescen):
offsets = np.asarray(treedata["DescOffsets"],dtype=np.uint64)
#Only include the offset for the last halo in the array if it has a descendant
if(offsets.size):
if(tree[snap]["Num_descen"][-1]==0): offsets = offsets[:-1]
else:
descenoff=np.asarray(treedata["DescOffsets"],dtype=np.uint64)
split = np.add(descenoff, tree[snap]["Num_descen"], dtype=np.uint64, casting="unsafe")[:-1]
descenoff=None
# Read in the data splitting it up as reading it in
# if reducing memory then store all the values in the _ keys
# and generate class that returns the appropriate subchunk as an array when using the [] operaotor
# otherwise generate lists of arrays
if (ireducemem):
tree[snap]["_Ranks"] = np.asarray(treedata["Ranks"],dtype=np.int16)
tree[snap]["_Descens"] = np.asarray(treedata["Descendants"],dtype=np.uint64)
tree[snap]["Rank"] = MinStorageList(tree[snap]["Num_descen"],tree[snap]["_Offsets"],tree[snap]["_Ranks"])
tree[snap]["Descen"] = MinStorageList(tree[snap]["Num_descen"],tree[snap]["_Offsets"],tree[snap]["_Descens"])
elif(iprimarydescen):
tree[snap]["Rank"] = np.asarray(treedata["Ranks"],dtype=np.uint16)[offsets]
tree[snap]["Descen"] = np.asarray(treedata["Descendants"],dtype=np.uint64)[offsets]
else:
tree[snap]["Rank"] = np.split(np.asarray(treedata["Ranks"],dtype=np.uint16), split)
tree[snap]["Descen"] = np.split(np.asarray(treedata["Descendants"],dtype=np.uint64), split)
if(inpart):
if (ireducemem):
tree[snap]["_Npart_descens"] = np.asarray(treedata["DescenNpart"],np.uint64)
tree[snap]["Npart_descen"] = MinStorageList(tree[snap]["Num_descen"],tree[snap]["_Offsets"],tree[snap]["_Npart_descens"])
elif(iprimarydescen):
tree[snap]["Npart_descen"] = np.asarray(treedata["DescenNpart"],np.uint64)[offsets]
else:
tree[snap]["Npart_descen"] = np.split(np.asarray(treedata["DescenNpart"],np.uint64), split)
if(imerit):
if (ireducemem):
tree[snap]["_Merits"] = np.asarray(treedata["Merits"],np.float32)
tree[snap]["Merit"] = MinStorageList(tree[snap]["Num_descen"],tree[snap]["_Offsets"],tree[snap]["_Merits"])
elif(iprimarydescen):
tree[snap]["Merit"] = np.asarray(treedata["Merits"],np.float32)[offsets]
else:
tree[snap]["Merit"] = np.split(np.asarray(treedata["Merits"],np.float32), split)
#if reducing stuff down to best ranks, then only keep first descendant
#unless also reading merit and then keep first descendant and all other descendants that are above a merit limit
if (ireducedtobestranks==True and ireducemem==False and iprimarydescen==False):
halolist = np.where(tree[snap]["Num_descen"]>1)[0]
if (iverbose):
print('Reducing memory needed. At snap ', snap, ' with %d total halos and alter %d halos. '% (len(tree[snap]['Num_descen']), len(halolist)))
print(np.percentile(tree[snap]['Num_descen'][halolist],[50.0,99.0]))
for ihalo in halolist:
numdescen = 1
if (imerit):
numdescen = np.int32(np.max([1,np.argmax(tree[snap]["Merit"][ihalo]<meritlimit)]))
tree[snap]["Num_descen"][ihalo] = numdescen
tree[snap]["Descen"][ihalo] = np.asarray([tree[snap]["Descen"][ihalo][:numdescen]])
tree[snap]["Rank"][ihalo] = np.asarray([tree[snap]["Rank"][ihalo][:numdescen]])
if (imerit):
tree[snap]["Merit"][ihalo] = np.asarray([tree[snap]["Merit"][ihalo][:numdescen]])
if (inpart):
tree[snap]["Npart_descen"][ihalo] = np.asarray([tree[snap]["Npart_descen"][ihalo][:numdescen]])
split=None
treedata.close()
if (iverbose):
print("done reading tree file ", time.process_time()-start)
return tree
def ReadHaloPropertiesAcrossSnapshots(numsnaps, snaplistfname, inputtype, iseperatefiles, iverbose=0, desiredfields=[]):
"""
read halo data from snapshots listed in file with snaplistfname file name
"""
halodata = [dict() for j in range(numsnaps)]
ngtot = [0 for j in range(numsnaps)]
atime = [0 for j in range(numsnaps)]
start = time.process_time()
print("reading data")
# if there are a large number of snapshots to read, read in parallel
# only read in parallel if worthwhile, specifically if large number of snapshots and snapshots are ascii
iparallel = (numsnaps > 20 and inputtype == 2)
if (iparallel):
# determine maximum number of threads
nthreads = min(mp.cpu_count(), numsnaps)
nchunks = int(np.ceil(numsnaps/float(nthreads)))
print("Using", nthreads, "threads to parse ",
numsnaps, " snapshots in ", nchunks, "chunks")
# load file names
snapnamelist = open(snaplistfname, 'r')
catfilename = ["" for j in range(numsnaps)]
for j in range(numsnaps):
catfilename[j] = snapnamelist.readline().strip()
# allocate a manager
manager = mp.Manager()
# use manager to specify the dictionary and list that can be accessed by threads
hdata = manager.list([manager.dict() for j in range(numsnaps)])
ndata = manager.list([0 for j in range(numsnaps)])
adata = manager.list([0 for j in range(numsnaps)])
# now for each chunk run a set of proceses
for j in range(nchunks):
offset = j*nthreads
# if last chunk then must adjust nthreads
if (j == nchunks-1):
nthreads = numsnaps-offset
# when calling a process pass manager based proxies, which then are used to copy data back
processes = [mp.Process(target=ReadPropertyFileMultiWrapper, args=(catfilename[offset+k], k+offset,
hdata, ndata, adata, inputtype, iseperatefiles, iverbose, desiredfields)) for k in range(nthreads)]
# start each process
# store the state of each thread, alive or not, and whether it has finished
activethreads = [[True, False] for k in range(nthreads)]
count = 0
for p in processes:
print("reading", catfilename[offset+count])
p.start()
# space threads apart (join's time out is 0.25 seconds
p.join(0.2)
count += 1
totactivethreads = nthreads
while(totactivethreads > 0):
count = 0
for p in processes:
# join thread and see if still active
p.join(0.5)
if (p.is_alive() == False):
# if thread nolonger active check if its been processed
if (activethreads[count][1] == False):
# make deep copy of manager constructed objects that store data
#halodata[i][offset+count] = copy.deepcopy(hdata[offset+count])
# try instead init a dictionary
halodata[offset+count] = dict(hdata[offset+count])
ngtot[offset+count] = ndata[offset+count]
atime[offset+count] = adata[offset+count]
# effectively free the data in manager dictionary
hdata[offset+count] = []
activethreads[count][0] = False
activethreads[count][1] = True
totactivethreads -= 1
count += 1
# terminate threads
for p in processes:
p.terminate()
else:
snapnamelist = open(snaplistfname, 'r')
for j in range(0, numsnaps):
catfilename = snapnamelist.readline().strip()
print("reading ", catfilename)
halodata[j], ngtot[j], atime[j] = ReadPropertyFile(
catfilename, inputtype, iseperatefiles, iverbose, desiredfields)
print("data read in ", time.process_time()-start)
return halodata, ngtot, atime
def ReadCrossCatalogList(fname, meritlim=0.1, iverbose=0):
"""
Reads a cross catalog produced by halomergertree,
also allows trimming of cross catalog using a higher merit threshold than one used to produce catalog
"""
return []
"""
start = time.process_time()
if (iverbose):
print("reading cross catalog")
dfile = open(fname, "r")
dfile.readline()
dfile.readline()
dataline = (dfile.readline().strip()).split('\t')
ndata = np.int32(dataline[1])
pdata = CrossCatalogList(ndata)
for i in range(0, ndata):
data = (dfile.readline().strip()).split('\t')
nmatches = np.int32(data[1])
for j in range(0, nmatches):
data = (dfile.readline().strip()).split(' ')
meritval = np.float32(data[1])
nsharedval = np.float32(data[2])
if(meritval > meritlim):
nmatchid = np.int64(data[0])
pdata.matches[i].append(nmatchid)
pdata.matches[i].append(meritval)
pdata.nsharedfrac[i].append(nsharedval)
pdata.nmatches[i] += 1
dfile.close()
if (iverbose):
print("done reading cross catalog ", time.process_time()-start)
return pdata
"""
def ReadSimInfo(basefilename):
"""
Reads in the information in the .siminfo file and returns it as a dictionary
"""
filename = basefilename + ".siminfo"
if (os.path.isfile(filename) == False):
print(filename,"not found")
return {}
cosmodata = {}
siminfofile = open(filename, "r")
for i,l in enumerate(siminfofile):
line = l.strip()
#See if this a comment
if(line==""):
continue
if(line[0]=="#"):
continue
try:
field, value = line.replace(" ","").split(':')
except ValueError:
print("Cannot read line",i,"of",filename,"continuing")
continue
#See if the datatype is present
if("#" in value):
value, datatype = value.split("#")
try:
typefunc = np.dtype(datatype).type
except:
print("Cannot interpret",datatype,"for field",field,"on line",i,"in",filename,"as a valid datatype, interpreting the value as float64")
typefunc = np.float64
else:
typefunc = np.float64
try:
#Find if the value is a list of values
if("," in value):
value = value.split(",")
#Remove any empty strings
value = list(filter(None,value))
cosmodata[field] = np.array(value,dtype=typefunc)
else:
cosmodata[field] = typefunc(value)
except ValueError:
print("Cannot interpret",value,"as a",np.dtype(typefunc))
siminfofile.close()
return cosmodata
def ReadUnitInfo(basefilename):
"""
Reads in the information in the .units file and returns it as a dictionary
"""
filename = basefilename + ".units"
if (os.path.isfile(filename) == False):
print(filename,"not found")
return {}
unitsfile = open(filename, 'r')
unitdata = dict()
for i,l in enumerate(unitsfile):
line = l.strip()
#See if this a comment
if(line==""):
continue
if(line[0]=="#"):
continue
try:
field, value = line.replace(" ","").split(':')
except ValueError:
print("Cannot read line",i,"of",filename,"continuing")
continue
#See if the datatype is present
if("#" in value):
value, datatype = value.split("#")
try:
typefunc = np.dtype(datatype).type
except:
print("Cannot interpret",datatype,"for field",field,"on line",i,"in",filename,"as a valid datatype, interpreting the value as float64")
typefunc = np.float64
else:
typefunc = np.float64
try:
#Find if the value is a list of values
if("," in value):
value = value.split(",")
#Remove any empty strings
value = list(filter(None,value))
unitdata[field] = np.array(value,dtype=typefunc)
else:
unitdata[field] = typefunc(value)
except ValueError:
print("Cannot interpret",value,"as a",np.dtype(typefunc))
unitsfile.close()
return unitdata