-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild_core_trees.py
1650 lines (1433 loc) · 81 KB
/
build_core_trees.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
import sys
import os
import h5py
import re
import psutil
import glob
import math
import numpy as np
#import numba
from time import time
import struct
from struct import pack
from struct import unpack, calcsize
from copy import deepcopy
import pygio
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import matplotlib.colors as colors
from matplotlib.colors import ListedColormap
#import pydot
import pydotplus as pydot
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
default_sim = 'SV'
filenames = {'AQ':'',
'SV':'m000p-',
'HM':'',
}
cc_template = {'AQ':'{}{}.corepropertiesextend.hdf5',
'SV':'{}{}.corepropertiesextend.hdf5',
'HM':'{}{}.coreproperties',
}
gio_template = {'AQ':'{}{}.coreproperties',
'SV':'{}{}.coreproperties',
'HM':'{}{}.coreproperties',
}
binfile_template = 'trees_099.{}'
mkeys = {'AQ':'m_evolved_0.9_0.005',
'SV':'m_evolved_1.1_0.1',
'HM':'m_evolved',
}
# trees are built in 2 formats: 'core' and 'lgal'
core = 'core'
lgal = 'lgal'
# mode is serial or vector
# define properties from core catalog; also used as names for 'core' tree format
coretag = 'core_tag'
coremass = 'coremass'
infall_tree_node_mass = 'infall_tree_node_mass'
tree_node_mass = 'tree_node_mass'
fof_halo_mass = 'fof_halo_mass'
sod_halo_mass = 'sod_halo_mass'
sod_node_mass = 'sod_node_mass'
tree_node_index = 'tree_node_index'
fof_halo_tag = 'fof_halo_tag'
foftag = tree_node_index #used to sort fof groups; uses halo fragments
infall_tree_node_index = 'infall_tree_node_index'
infall_fof_halo_mass = 'infall_fof_halo_mass'
infall_sod_halo_mass = 'infall_sod_halo_mass'
infall_sod_halo_cdelta = 'infall_sod_halo_cdelta'
infall_sod_halo_radius = 'infall_sod_halo_radius'
infall_fof_halo_angmom = 'infall_fof_halo_angmom_'
infall_sod_halo_angmom = 'infall_sod_halo_angmom_'
infall_sod_halo_1d_vdisp = 'infall_sod_halo_1d_vdisp'
infall_fof_halo_1d_vel_disp = 'infall_fof_halo_1D_vel_disp'
infall_fof_halo_vel_disp = 'infall_fof_halo_vel_disp' #same as 1d
infall_sod_halo_vel_disp = 'infall_sod_halo_vel_disp' #same as 1d
infall_fof_halo_max_cir_vel = 'infall_fof_halo_max_cir_vel'
infall_sod_halo_max_cir_vel = 'infall_sod_halo_max_cir_vel'
central = 'central'
timestep = 'timestep'
infall_step = 'infall_step'
radius = 'radius'
#define frequently used names for L-Galaxies
Descendent = 'Descendent'
FirstProgenitor = 'FirstProgenitor'
NextProgenitor = 'NextProgenitor'
FirstHaloInFOFGroup = 'FirstHaloInFOFGroup'
NextHaloInFOFGroup = 'NextHaloInFOFGroup'
MostBoundID_Coretag = 'MostBoundID->Coretag'
SubhaloIndex = 'SubhaloIndex'
ParentHaloTag = 'ParentHaloTag'
Offset = 'Offset'
DescendentOffset = Descendent + Offset
FirstProgenitorOffset = FirstProgenitor + Offset
NextProgenitorOffset = NextProgenitor + Offset
FirstHaloInFOFGroupOffset = FirstHaloInFOFGroup + Offset
NextHaloInFOFGroupOffset = NextHaloInFOFGroup + Offset
Len = 'Len'
SnapNum = 'SnapNum'
M_Crit200 = 'M_Crit200'
Zero = 'Zero'
first_snap = 499
last_snap = 43
#last_snap = 475
first_row = 0
last_row = 100 #101 snapshots between 499 and 43
#last_row = 2
#properties available in core catalogs
#central, core_tag, fof_halo_tag, infall_sod_halo_mass, infall_fof_halo_angmom_x,y,z
#infall_fof_halo_mass, infall_step, infall_fof_halo_max_cir_vel, infall_fof_halo_tag,
#infall_sod_halo_angmom_x,y,z, infall_sod_halo_max_cir_vel, infall_tree_node_index,
#infall_tree_node_mass, tree_node_index, vel_disp, vx,y,z, x,y,z, m_evolved_*_*
#host_core?, radius, merged?
#properties not available in Imran's core catalaogs + core tag to check ordering
gio_quantities = [coretag, infall_sod_halo_1d_vdisp, infall_fof_halo_1d_vel_disp]
# properties for storing in dict or matrices
core_pointers = {lgal: [Descendent, DescendentOffset, FirstProgenitor, NextProgenitor,
FirstProgenitorOffset, NextProgenitorOffset],
core: [Descendent, FirstProgenitor, NextProgenitor]
}
#core_pointers = [Descendent, DescendentOffset, FirstProgenitor, FirstProgenitorOffset]
sibling_pointers = {lgal: [FirstHaloInFOFGroup, NextHaloInFOFGroup, FirstHaloInFOFGroupOffset, NextHaloInFOFGroupOffset],
core: [FirstHaloInFOFGroup, NextHaloInFOFGroup],
}
#sibling_pointers = []
read_properties_float = {lgal: {'Pos_x':'x', 'Pos_y':'y', 'Pos_z':'z',
'Vel_x':'vx', 'Vel_y':'vy', 'Vel_z':'vz',
'VelDisp': infall_fof_halo_1d_vel_disp,
'Vmax': infall_fof_halo_max_cir_vel,
M_Crit200: tree_node_mass,
'M_Mean200': Zero,
'M_TopHat': Zero,
'Spin_x': 'infall_fof_halo_angmom_x',
'Spin_y': 'infall_fof_halo_angmom_y',
'Spin_z': 'infall_fof_halo_angmom_z',
'SubHalfMass': Zero,
},
core: {'Pos_x':'x', 'Pos_y':'y', 'Pos_z':'z',
'Vel_x':'vx', 'Vel_y':'vy', 'Vel_z':'vz',
'VelDisp':'vel_disp',
'Vmax_fof': 'infall_fof_halo_max_cir_vel',
'Vmax_sod': 'infall_sod_halo_max_cir_vel',
infall_tree_node_mass: infall_tree_node_mass,
infall_fof_halo_mass: infall_fof_halo_mass,
infall_sod_halo_mass: infall_sod_halo_mass,
infall_sod_halo_cdelta: infall_sod_halo_cdelta,
infall_sod_halo_radius: infall_sod_halo_radius,
infall_fof_halo_angmom+'x': infall_fof_halo_angmom+'x',
infall_fof_halo_angmom+'y': infall_fof_halo_angmom+'y',
infall_fof_halo_angmom+'z': infall_fof_halo_angmom+'z',
coremass: coremass,
radius: radius,
tree_node_mass: tree_node_mass,
fof_halo_mass: fof_halo_mass,
sod_halo_mass: sod_halo_mass,
sod_node_mass: sod_node_mass,
},
}
derived_properties_float = {lgal: [],
core: [],
}
read_properties_int = {lgal: {MostBoundID_Coretag:coretag,
'FileNr': Zero,
SubhaloIndex: Zero,
fof_halo_tag: fof_halo_tag,
},
core: {coretag:coretag,
central: central,
fof_halo_tag: fof_halo_tag,
tree_node_index: tree_node_index,
infall_tree_node_index: infall_tree_node_index,
infall_step: infall_step,
},
}
derived_properties_int = {lgal: [SnapNum, Len, ParentHaloTag],
core: [timestep],
}
properties_int32 = [SnapNum, timestep, infall_step, central]
def assemble_properties(fmt, vector=True):
properties = {}
properties['read'] = deepcopy(read_properties_float[fmt]) #need deepcopy so that update doesn't change original dict
properties['read'].update(read_properties_int[fmt])
properties['derived'] = derived_properties_int[fmt] + derived_properties_float[fmt]
properties['float'] = derived_properties_float[fmt] + list(read_properties_float[fmt].keys())
properties['int'] = core_pointers[fmt] + sibling_pointers[fmt] + derived_properties_int[fmt] + list(read_properties_int[fmt].keys())
properties['pointers'] = core_pointers[fmt] + sibling_pointers[fmt]
mode = 'vector' if vector else 'serial'
print('Using {} format; assembling {} properties'.format(fmt, mode))
print(properties)
return properties
no_int = -999
no_float = -999.
no_mass = -101.
M_Crit_norm = 1.e10
#masses in #M_sun/h
particle_numbers = {'LJ':10752,
'SV':1024,
'HM':3072,
'AQ':1024,
}
box_size = {'LJ':3400,
'SV':250,
'HM':250,
'AQ':256,
}
planck_cdm = 0.26067
planck_wb = 0.02242
planck_h = .6766
wmap_cdm = .220
wmap_wb = 0.02258
wmap_h = 0.71
G_SI = 6.67430e-11 #SI m^3 kg^-1 s^-2
Msun = 1.989e30 #kg
Mpc = 3.086e22 #m
#G = 4.3e-9 #Mpc km^2 s^-2 M⊙^-1
G = G_SI*1e-6*Msun/Mpc
#rho_c = 3*1e4/(8.*np.pi*G) #Msun/h Mpc^-3 h^3
rho_c = 2.77536627e11
Omega_m = {'LJ':planck_cdm + planck_wb/planck_h**2,
'SV':planck_cdm + planck_wb/planck_h**2,
'HM':planck_cdm + planck_wb/planck_h**2,
'AQ':wmap_cdm + wmap_wb/wmap_h**2,
}
# 8.6e8 Msun/h for Millennium I, 6.9e6 Msun/h for Millennium II
particle_masses = {'MTII':6.88e6,
'MTI':2.6e8,
'SV':1.3e9,
'LJ':2.7e9,
'AQ':1.2e9,
}
def get_particle_mass(sim):
if sim in Omega_m.keys():
Om_0 = Omega_m[sim]
mass = Om_0*rho_c*(float(box_size[sim])/float(particle_numbers[sim]))**3
print('Using derived {} particle mass = {:.9e}\n'.format(sim, mass))
else:
mass = particle_masses[sim]
print('Cannot compute mass exactly; using approximate assigned value for {} = {:.2e}\n'.format(sim, mass))
return mass
def get_a(step, nsteps=500, z_in=200, a_fin=1):
a_ini = (1./(1.+z_in))
a = a_ini + (a_fin-a_ini)/nsteps * (step + 1)
#z = 1./a - 1.
return a
a_scaling = {lgal: {'VelDisp':1.,
'Vmax': -0.5,
'Vel_x':1.,
'Vel_y':1.,
'Vel_z':1.,
'Spin_x': 2.,
'Spin_y': 2.,
'Spin_z': 2.,
},
core: {},
}
fragment_replace = {lgal: ['Vmax', 'Spin_x', 'Spin_y', 'Spin_z', 'VelDisp'],
core: ['Vmax_fof', 'Vmax_sod', infall_sod_halo_cdelta,
infall_sod_halo_radius,
infall_fof_halo_angmom+'x', infall_fof_halo_angmom+'y',
infall_fof_halo_angmom+'z'],
}
# header file contains Ntrees, totNHalos, TreeNHalos
header_format = "<{}i"
struct_keys = [DescendentOffset, FirstProgenitorOffset, NextProgenitorOffset,
FirstHaloInFOFGroupOffset, NextHaloInFOFGroupOffset,
Len, 'M_Mean200', M_Crit200, 'M_TopHat',
'Pos_x', 'Pos_y', 'Pos_z', 'Vel_x', 'Vel_y', 'Vel_z',
'VelDisp', 'Vmax', 'Spin_x', 'Spin_y', 'Spin_z',
MostBoundID_Coretag, SnapNum, 'FileNr',
SubhaloIndex, 'SubHalfMass',
]
struct_format = "<iiiiiiffffffffffffffqiiif"
"""
#test
struct_keys = [DescendentOffset, FirstProgenitorOffset, NextProgenitorOffset,
FirstHaloInFOFGroupOffset, NextHaloInFOFGroupOffset,
Len, M_Crit200, MostBoundID_Coretag,
# SnapNum, SubhaloIndex,
]
#struct_format = "<iiiiiifqii"
struct_format = "<iiiiiifq"
"""
# corecat = build_core_trees.get_core_snapshot( '../CoreCatalogs_SV', snapshot)
def get_core_snapshot(coredir, snapshot, template=cc_template[default_sim], sim=default_sim):
fn = os.path.join(coredir, template.format(filenames[sim], snapshot))
data= {}
if os.path.exists(fn):
if sim == 'HM':
coredata = pygio.read_genericio(fn)
else:
h5 = h5py.File(fn, 'r')
coredata = h5['coredata']
keys = [k for k in list(coredata.keys()) if 'm_evolved' not in k]
for k in keys + [mkeys[sim]]:
data[k] = coredata[k][()]
else:
print('{} not found'.format(fn))
return data
def add_mass_columns(corecat, sim=default_sim):
mask = (corecat['central']==1) # get centrals
central_mass = corecat[infall_tree_node_mass][mask] # get fof mass (possibly fragment)
if mkeys[sim] in corecat.keys():
corecat[coremass] = corecat[mkeys[sim]] # get evolved masses
# the mass of centrals are not modeled by mass model
central_massmodel = corecat[coremass][mask]
check_mass = np.count_nonzero(~np.isclose(central_mass, central_massmodel)) #check if any entries don't agree
if check_mass > 0:
print('Mass model != tree-node mass for central cores in {}/{} entries'.format(check_mass,
np.count_nonzero(mask)))
corecat[coremass][mask] = central_mass #force mass for centrals = tree-node mass
# now add tree_node masses and fof masses
corecat = add_treenode_fof_sod_mass(corecat, mask)
return corecat
def add_treenode_fof_sod_mass(corecat, mask):
tree_index, inverse = np.unique(corecat[tree_node_index], return_inverse=True)
assert np.sum(mask)==len(tree_index), 'number of unique halos not equal to number of centrals'
#get order of tree_node_indexes for centrals (mask selects centrals)
central_tree_index, cindex = np.unique(corecat[tree_node_index][mask], return_index=True)
assert np.array_equal(tree_index, central_tree_index), 'Mismatch in tree_node_indexes of centrals'
# use cindex to reorder central masses in (ascending) unique order
for key in [tree_node_mass, fof_halo_mass, sod_halo_mass]:
mass = corecat['infall_' + key][mask]
unique_ordered_masses = mass[cindex]
# reconstruct full array of central-only masses using inverse
corecat[key] = unique_ordered_masses[inverse]
print('Adding column {} to corecat'.format(key))
#check
assert np.array_equal(corecat[key][mask], corecat['infall_' + key][mask]), 'Mismatch in masses of centrals'
#now assign sod masses if available; otherwise use -101 (change from using tree_node mass because this would mix fof and sod quantities)
corecat[sod_node_mass] = corecat[sod_halo_mass].copy() #need to copy otherwise column gets overwritten
mask_sod = corecat[sod_halo_mass] > 0 #select valid sod masses
nofrag_mask = corecat[fof_halo_tag] > 0
mask_sod_nofrag = mask_sod & nofrag_mask
mask_sod_frag = mask_sod & ~nofrag_mask
#overwrite with valid sod masses multiplied by ratio of fragment mass to fof_halo mass
corecat[sod_node_mass][mask_sod_frag] = corecat[sod_halo_mass][mask_sod_frag]*corecat[tree_node_mass][mask_sod_frag]/corecat[fof_halo_mass][mask_sod_frag]
print('Adding column {} to corecat'.format(sod_node_mass))
return corecat
#eg data= get_gio_core_snapshot(coredir_gio, snapshot, template=cc_template['SV'], sim='SV')
def get_gio_core_snapshot(coredir, snapshot, gio_quantities_list=gio_quantities, template=gio_template[default_sim], sim=default_sim):
fn = os.path.join(coredir, template.format(filenames[sim], snapshot))
data = {}
if os.path.exists(fn):
data = pygio.read_genericio(fn, gio_quantities_list, print_stats=False)
print(' Read in quantities {}'.format(', '.join(data.keys())))
else:
print('{} not found'.format(fn))
return data
def add_gio_quantities(corecat, coredir, snapshot, gio_quantities_list=gio_quantities, template=gio_template[default_sim], sim=default_sim):
# get dict of required extra columns
data= get_gio_core_snapshot(coredir, snapshot, gio_quantities_list=gio_quantities_list, template=template, sim=sim)
if np.array_equal(corecat[coretag], data[coretag]):
print(' Core tag arrays match between core catalog and gio catalog: proceeding')
cols_to_add = [k for k in data.keys() if coretag not in k]
for k in cols_to_add:
corecat[k] = data[k]
print(' Adding column {} to corecat'.format(k))
else:
print('Mismatch in coretag columns between extended core catalogs and gio catalogs; not adding columns')
return corecat
def clean(corecat, sorted_coretags):
mask = np.in1d(corecat[coretag], sorted_coretags, assume_unique=True)
print('Truncating core catlog to {}/{} entries'.format(np.count_nonzero(mask),
len(corecat[coretag])))
for p in list(corecat.keys()):
corecat[p] = corecat[p][mask]
return corecat
def add_snapshot_to_trees(coretrees, corecat, properties, current_snap, sim, snap_index=0,
print_int=100, coretags_fofm=None, argsorted_fofm=None,
sorted_indices=None, fmt=core,
ncore_min=0, ncore_max=None, vector=False):
assert coretags_fofm is not None, "No sibling-ordered tags supplied"
assert sorted_indices is not None, "No sibling-ordered sorted indices supplied"
#mass_order = np.flip(corecat[coremass].argsort()) #args in descending order
# sort indices in this snapshot in decreasing foftag-mass order
if current_snap < first_snap:
sorted_indices_this = np.flip(np.lexsort(((corecat[coremass], corecat[foftag]))))
coretags_fofm_this = corecat[coretag][sorted_indices_this]
else:
sorted_indices_this = sorted_indices
coretags_fofm_this = coretags_fofm
foftags_fofm_this = corecat[foftag][sorted_indices_this]
# get unique parents; index points to first occurence of tag; inverse reconstructs array
parent_halos, index, inverse, counts = np.unique(foftags_fofm_this,
return_index=True, return_inverse=True,
return_counts=True)
# initialize times
stimes = []
atimes = []
if vector:
assert argsorted_fofm is not None, "No sibling-ordered argsorted indices supplied"
# get required reordering of coretags in current snapshot for insertion into matrix
# cannot assume cortetags will be in the same order as in last snapshot
if current_snap < first_snap:
# argsorted_fofm = coretags_fofm.argsort()
insertions = np.searchsorted(coretags_fofm[argsorted_fofm], coretags_fofm_this)
locations_this = argsorted_fofm[insertions]
else:
locations_this = np.arange(0, len(coretags_fofm))
print('Number of cores in snapshot {} (row {}) = {}'.format(current_snap, snap_index,
len(locations_this)))
# get siblings as vectors in sorted-indices order
stime1 = time()
first_siblings, next_siblings = get_sibling_vectors(coretags_fofm_this, index, inverse)
stimes.append((time()-stime1)/60.)
ptime1 = time()
# loop over property matrices in coretree dict
for p, v in coretrees.items():
#define/reorder property
atime1 = time()
prop_values = get_ordered_property(p, corecat, sorted_indices_this,
snap_index, current_snap, properties,
first_siblings, next_siblings, foftags_fofm_this,
fmt=fmt, particle_mass=particle_masses[sim])
atimes.append((time()-atime1)/60.)
#fill row of property matrix with values for selected entries
v[snap_index][locations_this] = prop_values
#print('Sample value {}: {}'.format(p, v[snap_index][locations_this[0]]))
# fix first progenitors
coretrees[FirstProgenitor] = fix_firstprogenitor_vector(coretrees[FirstProgenitor], snap_index)
if fmt == lgal:
coretrees[FirstProgenitorOffset] = fix_firstprogenitor_vector(coretrees[FirstProgenitorOffset], snap_index)
print('Time to fill coretree arrays = {:.2g} minutes'.format((time() - ptime1)/60.))
else: #serial code runs over parents of selected cores
htime = time()
if not coretrees: #first pass
selected_cores = coretags_fofm_this[ncore_min:ncore_max]
selected_parents = np.unique(foftags_fofm_this[ncore_min:ncore_max])
else:
#find parents belonging to selected cores being followed in tree dicts
selected_cores = list(coretrees.keys())
maskc = np.in1d(coretags_fofm_this, np.asarray(selected_cores)) #get mask for this coretag array
selected_parents = np.unique(foftags_fofm_this[maskc])
mask = np.in1d(parent_halos, selected_parents)
# truncate parent halo arrays
parent_halos = parent_halos[mask]
counts = counts[mask]
index = index[mask]
if current_snap < first_snap:
assert np.sum(counts) == np.count_nonzero(maskc), "Mismatch in selected core numbers"
if np.count_nonzero(mask) > 0:
msg = '{} <= ncores <= {}'.format(np.min(counts), np.max(counts))
print('Selecting {} parents with {}'.format(np.count_nonzero(mask), msg))
print('Time to find selected parents = {:.2g} minutes'.format((time() - htime)/60.))
# loop over parent halos and process siblings together
ptime1 = time()
#numba attempts
#coretrees = process_parent_halos(coretrees, parent_halos, index, counts, sorted_indices_this)
#stimes.append(stime)
#atimes.append(atime)
for npar, (p, indx, cnt) in enumerate(zip(parent_halos, index, counts)):
# get sibling tags, array locations and masses
stime1 = time()
siblings = coretags_fofm_this[indx:indx+cnt] # values from sorted array
locations = sorted_indices_this[indx:indx+cnt] # locations in corecat arrays
stimes.append((time()-stime1)/60.)
atime1 = time()
for ns, (s, loc) in enumerate(zip(siblings, locations)):
next_sibling = siblings[ns+1] if ns < len(siblings)-1 else -1
if not coretrees or s not in list(coretrees.keys()): #first snapshot or first instance of s
coretrees[s] = {}
coretrees[s] = add_properties_to_tree(s, loc, coretrees[s], corecat, properties,
next_sibling, siblings[0],
snap_index, current_snap, p,
fmt=fmt, particle_mass=particle_masses[sim])
atimes.append((time()-atime1)/60.)
if npar % print_int == 0 and npar > 0:
print('Time to loop over {} parents = {:.2g} minutes'.format(npar, (time() - ptime1)/60.))
print('Time to loop over selected parents = {:.2g} minutes'.format((time() - ptime1)/60.))
# fix first progenitors if no core in this step
coretags_not_this = get_coretags_not_this(selected_cores, coretags_fofm_this.tolist())
#coretags_not_this = get_coretags_not_this(np.asarray(selected_cores), coretags_fofm_this)
coretrees = fix_first_progenitors(coretrees, coretags_not_this, snap_index)
return coretrees, atimes, stimes
#@numba.jit(nopython=True)
def get_coretags_not_this(selected_cores, coretags_fofm_this):
#coretags_not_this = [c for c in selected_cores if c not in coretags_fofm_this.tolist()]
coretags_not_this = []
for c in selected_cores:
if c not in coretags_fofm_this:
coretags_not_this.append(c)
return coretags_not_this
#@numba.jit(nopython=True)
def process_parent_halos(coretrees, parent_halos, index, counts, sorted_indices_this):
for npar, (p, indx, cnt) in enumerate(zip(parent_halos, index, counts)):
# get sibling tags, array locations and masses
#stime1 = time()
siblings = coretags_fofm_this[indx:indx+cnt] # values from sorted array
locations = sorted_indices_this[indx:indx+cnt] # locations in corecat arrays
#stime = (time()-stime1)/60.
#atime1 = time()
for ns, (s, loc) in enumerate(zip(siblings, locations)):
next_sibling = siblings[ns+1] if ns < len(siblings)-1 else -1
if not coretrees or s not in list(coretrees.keys()): #first snapshot or first instance of s
coretrees[s] = {}
coretrees[s] = add_properties_to_tree(s, loc, coretrees[s], corecat,
next_sibling, siblings[0],
snap_index, current_snap, p)
#atime = (time()-atime1)/60.
#if npar % print_int == 0 and npar > 0:
#print('Time to loop over {} parents = {:.2g} minutes'.format(npar, (time() - ptime1)/60.))
return coretrees
def get_sibling_vectors(coretags, index, inverse):
"""
coretags: array sorted in decreasing tag, mass order
index, inverse, counts: output of np.unique
"""
# find most massive core corresponding to parent halos
first_sibling_coretags = coretags[index]
# use inverse to reconstruct first-sibling array
first_siblings = first_sibling_coretags[inverse]
# initialize array and pointers for next siblings
ncores = len(coretags)
nparents = len(index)
next_siblings = np.array([-1]*ncores) #null pointer
last_sibling_loc = np.zeros(nparents - 1).astype(int)
# shift coretag array by 1 argument to the left; last element is left as -1
next_siblings[0:ncores-1] = coretags[1:ncores]
# shift index locations by -1 to point to last sibling in each group
last_sibling_loc[0:nparents-1] = index[1:nparents] - 1
next_siblings[last_sibling_loc] = -1
return first_siblings, next_siblings
# fix first progenitors
def fix_firstprogenitor_vector(first_progenitor, row):
if row > 0:
mask_this = (first_progenitor[row] == no_int) #no entry in this snap
mask_prev = (first_progenitor[row-1] != no_int) #entry in previous snap
mask = mask_this & mask_prev
first_progenitor[row-1][mask] = -1 #overwrite
return first_progenitor
def get_ordered_property(p, corecat, sorted_indices_this, row, current_snap, properties,
first_siblings, next_siblings, parent_tags,
fmt=core, particle_mass=particle_masses[default_sim]):
ncores = len(corecat[coretag]) # = len(sorted_indices_this)
if fmt == lgal:
a = get_a(current_snap)
# assign pointers
if Descendent in p:
prop_values = np.array([row - 1]*ncores) #row = row of matrix array
elif FirstProgenitor in p:
prop_values = np.array([row + 1]*ncores) if row != last_row else np.array([-1]*ncores)
elif NextProgenitor in p:
prop_values = np.array([-1]*ncores)
elif FirstHaloInFOFGroup in p:
prop_values = first_siblings
elif NextHaloInFOFGroup in p:
prop_values = next_siblings
# assign derived properties
elif SnapNum in p:
#prop_values = np.array([current_snap]*ncores)
prop_values = np.array([last_row - row]*ncores) #L-galaxies needs consecutive integers
elif timestep in p:
prop_values = np.array([current_snap]*ncores)
elif ParentHaloTag in p:
prop_values = parent_tags
elif Len in p:
prop_values = np.round(corecat[coremass][sorted_indices_this]/particle_mass).astype(int) #truncate
mask = (prop_values == 0)
prop_values[mask] = 1 #ensure non-zero values
elif p in properties['int']:
if Zero in properties['read'][p]:
prop_values = np.zeros(ncores).astype(int)
else:
prop_values = corecat[properties['read'][p]][sorted_indices_this] # reorder into sorted coretag order
#print('Prop values for {}: {} {} from corecat {} {}'.format(p, prop_values.dtype, prop_values[0],
# corecat[properties['read'][p]].dtype,
# corecat[properties['read'][p]][0]))
elif p in properties['float']:
if Zero in properties['read'][p]: #zero values
prop_values = np.zeros(ncores)
else:
prop_values = corecat[properties['read'][p]][sorted_indices_this] # reorder into sorted coretag order
#fix normalizations for L-Galaxies
if 'M_Crit' in p:
print(' Normalizing M_Crit by {:.2g}'.format(M_Crit_norm))
mask = (corecat['central'][sorted_indices_this]==0) # select non-centrals
prop_values[mask] = 0. # set satellite masses to 0.
prop_values[~mask] /= M_Crit_norm
if 'Spin' in p: #normalize by appropriate mass (infall_sod_halo mass or infall_fof_halo_mass)
if 'sod' in properties['read'][p]:
sod_mask = corecat[infall_sod_halo_mass][sorted_indices_this] > 0 #find valid mass entries
print(' Normalizing {} by {}/{} valid SOD masses'.format(p, np.count_nonzero(sod_mask), len(sod_mask)))
prop_values[sod_mask] /= corecat[infall_sod_halo_mass][sorted_indices_this][sod_mask]
prop_values[~sod_mask] = no_mass
else:
print(' Normalizing {} by infall FOF masses'.format(p))
prop_values /= corecat[infall_fof_halo_mass][sorted_indices_this]
if fmt == lgal and p in list(a_scaling[fmt].keys()):
afactor = a**(a_scaling[fmt][p])
print(' a-scaling {} values by {:.4f}**{:.1f}={:.4g}'.format(p, a, a_scaling[fmt][p], afactor))
if 'sod' in properties['read'][p]:
sod_mask = corecat[infall_sod_halo_mass][sorted_indices_this] > 0 #find valid entries
print(' Rescaling {}/{} infall_SOD-validated {} values '.format(np.count_nonzero(sod_mask), len(sod_mask)), properties['read'][p])
check_mask = (prop_values != no_mass) #valid prop values
if not np.array_equal(check_mask, sod_mask):
print(' Mismatch: {} array has {} valid entries; infall_sod_halo_mass array has {} valid entries'.format(p,
np.count_nonzero(check_mask),
np.count_nonzero(sod_mask)))
prop_values[sod_mask] *= afactor
prop_values[~sod_mask] = no_mass
else:
prop_values *= afactor
else:
print('Unknown property {}'.format(p))
return prop_values
# fix serial trees first progenitors
#@numba.jit(nopython=True)
def fix_first_progenitors(coretrees, coretags_not_this, snap_index, fmt=core):
for s in coretags_not_this: #loop thru trees without entry in this snapshot
if len(coretrees[s][FirstProgenitor]) == snap_index: #but have entry in last snapshot
coretrees[s][FirstProgenitor][-1] = -1 #overwrite last element in list
if fmt == lgal:
coretrees[s][FirstProgenitorOffset][-1] = -1
return coretrees
#@numba.jit(nopython=True)
def add_properties_to_tree(core_tag, location, coretree, corecat, properties,
next_sibling, first_sibling, snap_index,
current_snap, parent_fof_tag,
fmt=core, particle_mass=particle_masses[default_sim]):
if not coretree: # empty - first entry
coretree[Descendent] = [-1] # no descendent for first halo
coretree[FirstProgenitor] = [1] # will be next element (if it exists)
coretree[NextProgenitor] = [-1] # no Next_Progenitor since cores are unmerged
if fmt == lgal:
coretree[DescendentOffset] = [-1] # no descendent for first halo
coretree[FirstProgenitorOffset] = [1] # will be next element (if it exists)
coretree[NextProgenitorOffset] = [-1] # no Next_Progenitor since cores are unmerged
# initialize empty lists for properties
for p in sibling_pointers + list(properties['read'].keys()) + derived_properties:
coretree[p] = []
else:
# descendent will be next core unless in snap 499
array_len = len(coretree[Descendent])
coretree[Descendent].append(array_len - 1)
coretree[DescendentOffset].append(array_len - 1)
# now fill in location of next element in tree
if current_snap != last_snap:
coretree[FirstProgenitor].append(array_len + 1)
coretree[FirstProgenitorOffset].append(array_len + 1)
else:
coretree[FirstProgenitor].append(-1)
coretree[FirstProgenitorOffset].append(-1)
coretree[NextProgenitor].append(-1)
coretree[NextProgenitorOffset].append(-1)
# add supplied properties; locations in other trees not known yet
coretree[FirstHaloInFOFGroup].append(first_sibling)
coretree[NextHaloInFOFGroup].append(next_sibling)
if fmt == lgal:
coretree[FirstHaloInFOFGroupOffset].append(first_sibling)
coretree[NextHaloInFOFGroupOffset].append(next_sibling)
# other properties
if SnapNum in properties['derived']:
coretree[SnapNum].append(last_row - snap_index)
if timestep in properties['derived']:
coretree[timestep].append(current_snap)
if ParentHaloTag in properties['derived']:
coretree[ParentHaloTag].append(parent_fof_tag)
if Len in properties['derived']:
coretree[Len].append(int(max(np.round(corecat[coremass][location]/particle_mass), 1.))) #set min mass to 1 particle
for p, v in properties['read'].items():
if Zero in v:
if p in properties['int']:
coretree[p].append(0)
else:
coretree[p].append(0.)
else:
coretree[p].append(corecat[v][location])
#fix normalizations
if 'M_Crit' in p:
if corecat['central'][location] == 0:
coretree[p][-1] = 0. #overwrite last entry with zero for satellite
else:
coretree[p][-1] /= M_Crit_norm
if 'Spin' in p:
if 'sod' in v:
if corecat[infall_sod_mass] > 0:
coretree[p][-1] /= corecat[infall_sod_halo_mass][location] # divide by mass
else:
coretree[p][-1] = no_mass
else:
coretree[p][-1] /= corecat[infall_fof_halo_mass][location]
if fmt == lgal and p in list(a_scaling[fmt].keys()):
if 'sod' in v:
if corecat[infall_sod_mass] > 0:
coretree[p][-1] *= a**(a_scaling[fmt][p])
else:
coretree[p][-1] = no_mass
else:
coretree[p][-1] *= a**(a_scaling[fmt][p])
return coretree
def get_parent_boundary(foftags, loc, ncores, name='input', upper=True):
# assumes foftags are in fofm order
oldloc = loc
foftag_this = foftags[loc-1] # parent of preceding index
args = np.where(foftags == foftag_this)[0] #locations of this parent
if upper:
loc = min(np.max(args) + 1, ncores) # maximum argument +1
else:
loc = min(np.min(args) - 1, 0)
if loc != oldloc:
print('Resetting {} to {} to line up with parent boundary'.format(name, loc))
return loc
def overwrite_fragment_quantities(coretrees, Nsnaps, vector=True, replace=[],
MMF_check=False):
if replace:
print('\nFragment overwrite: replacing values for {}\n'.format(', '.join(replace)))
else:
print('\nFragment replace: No properties supplied for replacement')
return coretrees
if vector:
for s in np.arange(0, Nsnaps)[::-1]: #start with earliest snapshot
stime = time()
valid = (coretrees[MostBoundID_Coretag][s] != no_int) #remove placeholder values
maskf = (coretrees[fof_halo_tag][s] < 0) & valid #find -ve halo tags
if np.count_nonzero(maskf) == 0:
print('No fragments in {} halos in snapnum {}'.format(np.count_nonzero(valid), s))
continue
print('Processing {} fragments in {} halos in snapnum {}'.format(np.count_nonzero(maskf), np.count_nonzero(valid), s))
if s == Nsnaps:
print(' Fragments in earliest snapshot cannot be updated with earlier values: skipping')
continue
# loop over -ve halo tags, decode and find original halos and associated cores
original_fof_tags = byte_mask(coretrees[fof_halo_tag][s][maskf])
frag_tags = shift_tag(coretrees[fof_halo_tag][s][maskf])
fragment_masses = coretrees[Len][s][maskf]
fragment_columns = np.where(maskf==True)[0]
# identify small fragments
small_frag_mask = (frag_tags > 0)
small_frag_columns = fragment_columns[(np.where(small_frag_mask==True)[0])]
small_frag_masses = fragment_masses[small_frag_mask]
assert np.array_equal(coretrees[Len][s][small_frag_columns], small_frag_masses), 'Small-fragment masses do not match'
small_frag_halo_tags = original_fof_tags[small_frag_mask]
#coretags = coretrees[MostBoundID_Coretag][s][maskf][small_frag_mask]
# replace values
print(' Processing {} LMFs'.format(np.count_nonzero(small_frag_mask)))
if MMF_check:
missing_mmf = 0
for halo_tag, frag_mass in zip(small_frag_halo_tags, small_frag_masses):
#check that it is a less massive fragment (less massive than fragment 0)
mmf_mask = (original_fof_tags == halo_tag) & (frag_tags == 0)
if np.count_nonzero(mmf_mask) > 0:
mmf_mass = fragment_masses[mmf_mask][0] #only element in array
mmf_coretag = coretrees[MostBoundID_Coretag][s][maskf][mmf_mask][0]
if mmf_mass < frag_mass:
print(' Warning: MMF with halotag {} and coretag {} has mass {} < fragment with coretag {} and mass {}'.format(halo_tag,
mmf_coretag,
mmf_mass,
coretag,
frag_mass))
else:
missing_mmf +=1
if missing_mmf > 0:
n_small_frag = np.count_nonzero(small_frag_mask)
missing_frac = missing_mmf/np.count_nonzero(maskf)
print(' Warning: Found {}/{} LMFs with no MMF counterpart in snap {}\n Fraction of all fragments = {:.3g}'.format(missing_mmf,
np.count_nonzero(small_frag_mask),
s, missing_frac))
rows = np.asarray([no_int]*len(small_frag_columns))
previous = 1
while any(rows == no_int) and s+previous < Nsnaps: #search earlier rows for positive halo tags
halo_tags_prev = coretrees[fof_halo_tag][:,small_frag_columns][s+previous]
non_frag_mask = (halo_tags_prev >0) & (rows < 0)
non_frags = np.where(non_frag_mask==True)[0]
rows[non_frags] = s + previous
#overwrite selected quantities with earlier non-fragment value
print(' Replacing {} values from snap {}'.format(np.count_nonzero(non_frag_mask), s+previous))
for r in replace:
coretrees[r][s][small_frag_columns][non_frag_mask] = coretrees[r][s+previous][small_frag_columns][non_frag_mask]
previous += 1
if any(rows == no_int):
print(' Warning: {}/{} LMFs not updated'.format(np.count_nonzero((rows == no_int)), np.count_nonzero(small_frag_mask)))
print('\nTime to run snapshot {} fragment processing= {:.3g} minutes\n'.format(s, (time() - stime)/60.))
else:
print('Fragment overwite not implemented yet for serial processing\n')
return coretrees
def byte_mask(tag_val, bit_mask=0xffffffffffff, warn=False):
if (tag_val<0).all() == False and warn:
print("Warning: fof tag passed to byte masking routine, this assumes fragment tags only")
return (-tag_val)&bit_mask
def shift_tag(tag_val, shift=48, warn=False):
if (tag_val<0).all() == False and warn:
print("Warning: fof tag passed to byte masking routine, this assumes fragment tags only")
return np.right_shift(-tag_val, 48)
def get_missed_LMFs(coretrees, s, original_fof_tags, frag_tags, small_frag_columns, small_frag_mask):
small_frag_halo_tags = original_fof_tags[small_frag_mask]
coretags = coretrees[MostBoundID_Coretag][s][small_frag_columns]
small_frag_fofs = coretrees[fof_halo_tag][s][small_frag_columns]
small_frag_tnis = coretrees[ParentHaloTag][s][small_frag_columns]
lmf_tni = []
lmf_fof = []
lmf_core = []
lmf_halo = []
print('coretag tree_node_index fof_halo_tag original_fof_tag')
for halo_tag, ct, tni, fof in zip(small_frag_halo_tags, coretags, small_frag_tnis, small_frag_fofs):
mmf_mask = (original_fof_tags == halo_tag) & (frag_tags == 0)
if np.count_nonzero(mmf_mask) == 0:
print('{} {} {} {}'.format(ct, tni, fof, halo_tag))
lmf_tni.append(tni)
lmf_fof.append(fof)
lmf_halo.append(halo_tag)
lmf_core.append(ct)
return lmf_core, lmf_tni, lmf_fof, lmf_halo
def write_outfile(outfile, coretrees, cores_to_write, vector=False, start=None, end=None,
column_counts=None):
"""
coretrees: trees to output
cores_to_write: list of sorted cores
vector: True if using vectorized code (requires start and end arguments)
start: starting column of coretree matrix
end: ending column of coretree matrix (= parent_boundary+1)
"""
wtime = time()
if os.path.exists(outfile):
os.remove(outfile)
print("Removed old file {}".format(outfile))
if len(cores_to_write) == 0:
return
hdfFile = h5py.File(outfile, 'w')
hdfFile.create_group('treeData')
hdfFile['treeData']['Ntrees'] = len(cores_to_write)
# use Descendent to get lengths, masks etc.
if vector:
if column_counts is None:
print('Need column counts')
return
hdfFile['treeData']['TreeNHalos'] = column_counts
else:
hdfFile['treeData']['TreeNHalos'] = np.asarray([len(coretrees[k][Descendent]) for k in cores_to_write])
hdfFile['treeData']['coretags'] = cores_to_write
hdfFile['treeData']['totNHalos'] = np.sum(hdfFile['treeData']['TreeNHalos'])
print('Number of core trees = {}, Total halos = {}'.format(hdfFile['treeData']['Ntrees'][()],
hdfFile['treeData']['totNHalos'][()]))
# concatenate trees
tgroup = hdfFile.create_group('trees')
if vector:
mtime = time()
properties_list = list(coretrees.keys())
mask = (coretrees[Descendent][:, start:end] != -999) # mask for non-existent elements
flat_mask = mask.flatten(order='F')
print('Time to build flat mask = {:.2e} minutes'.format((time() - mtime)/60.))
else:
properties_list = list(coretrees[cores_to_write[0]].keys())
ptime = time()
for p in properties_list:
if vector:
prop_array = coretrees[p][:, start:end].flatten(order='F')
tgroup[p] = prop_array[flat_mask]
else:
tgroup[p] = concatenate_trees(coretrees, cores_to_write, p)
assert len(tgroup[p][()]) == hdfFile['treeData']['totNHalos'][()], \
'Length mismatch for {}'.format(p, len(tgroup[p][()]), hdfFile['treeData']['totNHalos'][()])
print('Assembled group {} in {:.2e} minutes'.format(p, (time() - ptime)/60.))
print('Time to write trees to {} = {:.2e} minutes'.format(outfile, (time() - wtime)/60.))
hdfFile.close()
def get_column_counts(coretree_matrix_transpose):
#vectorize
counts = np.zeros(len(coretree_matrix_transpose)).astype(int)
for n, c in enumerate(coretree_matrix_transpose):
mask = (c != -999)
counts[n] = np.count_nonzero(mask)
return counts
def concatenate_trees(coretrees, keys, p):
if p in integer_properties:
prop_array = np.asarray([]).astype(int)
else:
prop_array = np.asarray([])
for k in keys:
v = np.asarray(coretrees[k][p])
prop_array = np.concatenate((prop_array, v))
return prop_array
def read_outfile(outfile, vector=True):
with h5py.File(outfile, 'r') as fh:
Ntrees = fh['treeData']['Ntrees'][()]
totNHalos = fh['treeData']['totNHalos'][()]
TreeNHalos = fh['treeData']['TreeNHalos'][()]
coretags = fh['treeData']['coretags'][()]
assert len(TreeNHalos) == Ntrees, 'Mismatch in number of trees, {} != {}'.format(len(TreeNHalos), Ntrees)
coretrees = {}