-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc_resample.py
executable file
·2465 lines (2289 loc) · 117 KB
/
lc_resample.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
#!/usr/bin/env python2.7
from __future__ import print_function, division
import sys
sys.path.insert(0, '/homes/dkorytov/.local/lib/python2.7/site-packages/halotools-0.7.dev4939-py2.7-linux-x86_64.egg')
import os
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib.colors as clr
import pdb
import dtk
import h5py
import time
import sys
import datetime
import subprocess
from astropy.table import Table
from scipy.spatial import cKDTree
from pecZ import pecZ
from astropy.cosmology import WMAP7 as cosmo
from scipy.integrate import cumtrapz
from scipy.interpolate import interp1d
from cosmodc2.black_hole_modeling import monte_carlo_bh_acc_rate, bh_mass_from_bulge_mass, monte_carlo_black_hole_mass
from cosmodc2.size_modeling import mc_size_vs_luminosity_late_type, mc_size_vs_luminosity_early_type
from cosmodc2.sdss_colors import assign_restframe_sdss_gri
from cosmodc2.mock_diagnostics import mean_des_red_sequence_gr_color_vs_redshift, mean_des_red_sequence_ri_color_vs_redshift, mean_des_red_sequence_iz_color_vs_redshift
from ellipticity_model import monte_carlo_ellipticity_bulge_disk
from halotools.utils import fuzzy_digitize
import galmatcher
def construct_gal_prop(fname, verbose=False, mask = None, mag_r_cut =
False):
t1 = time.time()
gal_prop = {}
hfile = h5py.File(fname,'r')
hgp = hfile['galaxyProperties']
m_star = np.log10(hgp['totalMassStellar'].value)
mag_g = hgp['SDSS_filters/magnitude:SDSS_g:rest:dustAtlas'].value
mag_r = hgp['SDSS_filters/magnitude:SDSS_r:rest:dustAtlas'].value
mag_i = hgp['SDSS_filters/magnitude:SDSS_i:rest:dustAtlas'].value
if mask is None:
mask = np.ones(mag_r.size,dtype=bool)
if mag_r_cut:
mask = (mag_r < -10) & mask
gal_prop['m_star'] = m_star[mask]
gal_prop['Mag_r'] = mag_r[mask]
gal_prop['clr_gr'] = mag_g[mask]-mag_r[mask]
gal_prop['clr_ri'] = mag_r[mask]-mag_i[mask]
if verbose:
print('done loading gal prop. {}'.format(time.time()-t1))
return gal_prop,mask
def cat_dics(dics, keys = None):
new_dic = {}
if keys is None:
keys = dics[0].keys()
for key in keys:
new_dic[key] = []
for dic in dics:
new_dic[key].append(dic[key])
new_dic[key] = np.concatenate(new_dic[key])
return new_dic
def select_dic(dic, slct):
new_dic = {}
for key in dic.keys():
new_dic[key]=dic[key][slct]
return new_dic
def clean_up_gal_prop(gal_prop):
"""For each galaxy, if any property is not finite, set all other
properties to some value (4) that will not be selected by the
kdtree query.
"""
print("Cleaning up gal prop: ",end="")
slct_nfnt = ~np.isfinite(gal_prop['m_star'])
for key in gal_prop.keys():
slct_nfnt = slct_nfnt | ~np.isfinite(gal_prop[key])
print("bad vals: ", np.sum(slct_nfnt))
for key in gal_prop.keys():
gal_prop[key][slct_nfnt] = -4
return gal_prop
def construct_gal_prop_redshift_dust_raw(fname, index, step1, step2,
step1_a, step2_a, target_a,
mask1, mask2,
dust_factor=1.0,
match_obs_color_red_seq = False,
cut_small_galaxies_mass = None,
snapshot = False):
"""Constructs gal_prop using the interpolation scheme from the galacticus
snapshots and index matching galaxies in step2 to galaxies in step1.
"""
h_in_gp1 = h5py.File(fname.replace("${step}", str(step1)), 'r')['galaxyProperties']
h_in_gp2 = h5py.File(fname.replace("${step}", str(step2)), 'r')['galaxyProperties']
##======DEBUG========
# stepz = dtk.StepZ(sim_name="AlphaQ")
# step1_ab = stepz.get_a(step1)
# step2_ab = stepz.get_a(step2)
# print("\t\t step1/2: {} - {}".format(step1, step2))
# print("\t\t step1/2_a: {:.4f} -> {:.4f}".format(step1_a, step2_a))
# print("\t\t step1/2_ab: {:.4f} -> {:.4f}".format(step1_ab, step2_ab))
# print("\t\t step1/2_z: {:.4f} -> {:.4f}".format(1.0/step1_a-1.0, 1.0/step2_a-1.0))
# print("\t\t step1/2_z2:{:.4f} -> {:.4f}".format(stepz.get_z(step1), stepz.get_z(step2)))
# print("\t\t target a: {:.4f}".format(target_a))
# print("\t\t target z: {:.3f}".format(1.0/target_a -1.0))
# step1_a = stepz.get_a(step1)
# step2_a = stepz.get_a(step2)
##=========DEBUG========
lum_g_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_g:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_r:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_i:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g_b = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_g:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_b = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_r:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_b = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_i:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g = lum_g_d + lum_g_b
lum_i = lum_i_d + lum_i_b
lum_r = lum_r_d + lum_r_b
##=======DEBUG======
# print("=============")
# print("lum_r non-finite: ", np.sum(~np.isfinite(lum_r)), np.sum(lum_r<0), lum_r.size)
# print("lum_r_d non-finite: ", np.sum(~np.isfinite(lum_r_d)), np.sum(lum_r_d<0), lum_r_d.size)
# print("lum_r_b non-finite: ", np.sum(~np.isfinite(lum_r_b)), np.sum(lum_r_b<0), lum_r_b.size)
# slct_neg = lum_r<0
# print(lum_r[slct_neg])
# print(lum_r_d[slct_neg])
# print(lum_r_b[slct_neg])
# print("=============")
##=======DEBUG======
m_star = get_column_interpolation_dust_raw(
'totalMassStellar',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
node_index = get_column_interpolation_dust_raw('infallIndex', h_in_gp1,
h_in_gp2, index, mask1, mask2, step1_a, step2_a, target_a,
dust_factor, snapshot=snapshot)
mag_g = -2.5*np.log10(lum_g)
mag_r = -2.5*np.log10(lum_r)
mag_i = -2.5*np.log10(lum_i)
size = m_star.size
gal_prop = {}
gal_prop['m_star'] = np.log10(m_star)
gal_prop['Mag_r'] = mag_r
gal_prop['clr_gr'] = mag_g - mag_r
gal_prop['clr_ri'] = mag_r - mag_i
gal_prop['dust_factor'] = np.ones(size, dtype='f4')*dust_factor
gal_prop['index'] = np.arange(size, dtype='i8')
gal_prop['node_index'] = node_index
if match_obs_color_red_seq:
lum_g_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_g:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_r:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_i:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_z_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_z:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_g:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_r:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_i:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_z_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_z:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g_obs = lum_g_obs_d + lum_g_obs_s
lum_r_obs = lum_r_obs_d + lum_r_obs_s
lum_i_obs = lum_i_obs_d + lum_i_obs_s
lum_z_obs = lum_z_obs_d + lum_z_obs_s
# Luminosity distance factors cancle when we compute galaxy color,
# so I'm not including them the magnitude calculation
mag_g_obs = -2.5*np.log10(lum_g_obs)
mag_r_obs = -2.5*np.log10(lum_r_obs)
mag_i_obs = -2.5*np.log10(lum_i_obs)
mag_z_obs = -2.5*np.log10(lum_z_obs)
gal_prop['clr_gr_obs'] = mag_g_obs - mag_r_obs
gal_prop['clr_ri_obs'] = mag_r_obs - mag_i_obs
gal_prop['clr_iz_obs'] = mag_i_obs - mag_z_obs
# Record LSST g-r color
lum_g_obs_d_lsst = get_column_interpolation_dust_raw(
'LSST_filters/diskLuminositiesStellar:LSST_g:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_obs_d_lsst = get_column_interpolation_dust_raw(
'LSST_filters/diskLuminositiesStellar:LSST_r:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
gal_prop['clr_gr_obs_lsst'] = -2.5*np.log10(lum_g_obs_d_lsst) + 2.5*np.log10( lum_r_obs_d_lsst)
if not (cut_small_galaxies_mass is None):
print("cutting out small galaxies in gltcs")
slct_gal = gal_prop['m_star']>cut_small_galaxies_mass
gal_prop = dic_select(gal_prop, slct_gal)
# print("nan test")
# print(np.sum(np.isnan(gal_prop['m_star'])))
# print("not finite test")
# print(np.sum(~np.isfinite(gal_prop['m_star'])))
# print(gal_prop['m_star'][np.isnan(gal_prop['m_star'])])
return gal_prop
def construct_lc_data(fname, match_obs_color_red_seq = False, verbose
= False, recolor=False, internal_step=None,
cut_small_galaxies_mass = None,
red_sequence_transition_mass_start=13.0,
red_sequence_transition_mass_end=13.5,
snapshot = False):
t1 = time.time()
lc_data = {}
if snapshot: # Snapshot baseDC2 format
hfile_snap = h5py.File(fname,'r')
hfile = hfile_snap['galaxyProperties']
snapshot_redshift = hfile_snap['metaData/redshift'].value
elif internal_step is None: # flat-file baseDC2 format
hfile = h5py.File(fname,'r')
else: # healpix basedDC2 format
hfile = h5py.File(fname,'r')[str(internal_step)]
non_empty_step = "obs_sm" in hfile
if non_empty_step:
lc_data['m_star'] = np.log10(hfile['obs_sm'].value)
lc_data['Mag_r'] = hfile['restframe_extincted_sdss_abs_magr'].value
lc_data['clr_gr'] = hfile['restframe_extincted_sdss_gr'].value
lc_data['clr_ri'] = hfile['restframe_extincted_sdss_ri'].value
if not snapshot:
lc_data['redshift'] = hfile['redshift'].value
else:
lc_data['redshift'] = np.ones(lc_data['m_star'].size)*snapshot_redshift
lc_data['sfr_percentile'] = hfile['sfr_percentile'].value
else:
lc_data['m_star'] = np.zeros(0, dtype=np.float)
lc_data['Mag_r'] = np.zeros(0, dtype=np.float)
lc_data['clr_gr'] = np.zeros(0, dtype=np.float)
lc_data['clr_ri'] = np.zeros(0, dtype=np.float)
if not snapshot:
lc_data['redshift'] = hfile['redshift'].value
else:
lc_data['redshift'] = np.ones(lc_data['m_star'].size)*snapshot_redshift
lc_data['sfr_percentile'] = np.zeros(0, dtype=np.float)
if recolor:
upid_mock = hfile['upid'].value
mstar_mock = hfile['obs_sm'].value
sfr_percentile_mock = hfile['sfr_percentile'].value
host_halo_mvir_mock = hfile['host_halo_mvir'].value
redshift_mock = lc_data['redshift']
a,b,c = assign_restframe_sdss_gri(upid_mock, mstar_mock, sfr_percentile_mock,
host_halo_mvir_mock, redshift_mock)
# plt.figure()
# h,xbins,ybins = np.histogram2d(lc_data['Mag_r'], a, bins=250)
# plt.pcolor(xbins,ybins, h.T, cmap='PuBu', norm =clr.LogNorm())
# plt.grid()
# plt.figure()
# h,xbins,ybins = np.histogram2d(lc_data['clr_gr'], b, bins=250)
# plt.pcolor(xbins,ybins, h.T, cmap='PuBu', norm =clr.LogNorm())
# plt.grid()
# plt.figure()
# h,xbins,ybins = np.histogram2d(lc_data['clr_ri'], c, bins=250)
# plt.pcolor(xbins,ybins, h.T, cmap='PuBu', norm =clr.LogNorm())
# plt.grid()
# plt.show()
lc_data['Mag_r'] = a
lc_data['clr_gr'] = b
lc_data['clr_ri'] = c
#lc_data['Mag_r'], lc_data['clr_gr'], lc_data['clr_ri'] = [a,b,c]
if match_obs_color_red_seq and non_empty_step:
# print("match obs color red seq")
host_halo_mvir_mock = hfile['host_halo_mvir'].value
is_on_red_seq_gr = hfile['is_on_red_sequence_gr'].value
is_on_red_seq_ri = hfile['is_on_red_sequence_ri'].value
mass_rs = soft_transition(np.log10(host_halo_mvir_mock), red_sequence_transition_mass_start, red_sequence_transition_mass_end)
lc_data['is_cluster_red_sequence'] = mass_rs & is_on_red_seq_gr & is_on_red_seq_ri
#lc_data['is_cluster_red_sequence'] = is_on_red_seq_gr & is_on_red_seq_ri
lc_data['clr_gr_obs'] = mean_des_red_sequence_gr_color_vs_redshift(lc_data['redshift'])
lc_data['clr_ri_obs'] = mean_des_red_sequence_ri_color_vs_redshift(lc_data['redshift'])
lc_data['clr_iz_obs'] = mean_des_red_sequence_iz_color_vs_redshift(lc_data['redshift'])
elif match_obs_color_red_seq:
lc_data['is_cluster_red_sequence'] = np.zeros(0,dtype=bool)
lc_data['clr_gr_obs'] = np.zeros(0,dtype=bool)
lc_data['clr_ri_obs'] = np.zeros(0,dtype=bool)
lc_data['clr_iz_obs'] = np.zeros(0,dtype=bool)
if not (cut_small_galaxies_mass is None):
print("cutting out small galaxies!")
# Cutting out low mass galaxies so it runs fasters
slct_gals = lc_data['m_star']>cut_small_galaxies_mass
lc_data = dic_select(lc_data, slct_gals)
#TODO remove once bug is fixed
lc_data['Mag_r'][~np.isfinite(lc_data['Mag_r'])] = -14.0
if verbose:
print('done loading lc data. {}'.format(time.time()-t1))
return lc_data
def construct_lc_data_healpix(fname, match_obs_color_red_seq = False,
verbose = False, recolor=False,
internal_step=None,
cut_small_galaxies_mass = None,
healpix_pixels=None,
red_sequence_transition_mass_start=13.0,
red_sequence_transition_mass_end=13.5,
snapshot=False):
print("Construicting light cone data.")
print("Input lightcone file pattern: ", fname)
print("Healpix files: ",healpix_pixels)
if healpix_pixels is None:
print("No healpix used")
lc_data = construct_lc_data(fname, match_obs_color_red_seq = match_obs_color_red_seq,
verbose = verbose, recolor=recolor, internal_step = internal_step,
cut_small_galaxies_mass = cut_small_galaxies_mass,
red_sequence_transition_mass_start = red_sequence_transition_mass_start,
red_sequence_transition_mass_end = red_sequence_transition_mass_end,
snapshot=snapshot)
else:
lc_data_hps = []
for healpix_pixel in healpix_pixels:
fname_healpix = fname.replace('${healpix}', str(healpix_pixel))
lc_data_hp = construct_lc_data(fname_healpix,
match_obs_color_red_seq = match_obs_color_red_seq,
recolor=recolor,
internal_step = internal_step,
cut_small_galaxies_mass = cut_small_galaxies_mass,
red_sequence_transition_mass_start = red_sequence_transition_mass_start,
red_sequence_transition_mass_end = red_sequence_transition_mass_end, verbose=False,
snapshot=snapshot)
lc_data_hp['healpix_pixel'] = np.ones(lc_data_hp['m_star'].size, dtype='i4')*healpix_pixel
lc_data_hps.append(lc_data_hp)
lc_data = cat_dics(lc_data_hps)
for key in lc_data.keys():
num = np.sum(~np.isfinite(lc_data[key]))
assert num == 0
return lc_data
def dic_select(dic, slct):
new_dic = {}
for key in dic.keys():
new_dic[key] = dic[key][slct]
return new_dic
def select_by_index(data,index):
new_data = {}
for key in data.keys():
new_data[key] = data[key][index]
return new_data
def squash_magnitudes(mag_dic, lim, a):
# I'm using a tanh function for the soft threshold. No magnitude will excessed
# 'lim'. Mags below lim-a aren't affect.
# plt.figure()
# plt.hist2d(mag_dic[:,0],mag_dic[:,1],bins=250,cmap='Blues',norm=clr.LogNorm())
# plt.axvline(x=lim+a,c='k',ls=':')
# plt.axvline(x=lim,c='k',ls='--')
# xlims = plt.xlim()
# plt.title("before magnitude squash")
# plt.xlabel('Mag_r')
# plt.ylabel('g-r rest')
if(a == 0.0):
slct = mag_dic[:,0]<lim
mag_dic[slct,0]= lim
else:
slct = mag_dic[:,0]<lim+a
mag_dic[slct,0]=a*np.tanh((mag_dic[slct,0]-lim-a)/a) + lim + a
# plt.figure()
# plt.hist2d(mag_dic[:,0],mag_dic[:,1],bins=250,cmap='Blues',norm=clr.LogNorm())
# plt.axvline(x=lim+a,c='k',ls=':')
# plt.axvline(x=lim,c='k',ls='--')
# plt.xlim(xlims)
# plt.title("after magntiude squash")
# plt.xlabel('Mag_r')
# plt.ylabel('g-r rest')
# plt.show()
return mag_dic
def resample_index(lc_data, gal_prop, ignore_mstar = False, nnk = 10,
verbose = False, ignore_bright_luminosity=False,
ignore_bright_luminosity_threshold=None,
ignore_bright_luminosity_softness=0.0, ):
if verbose:
t1 = time.time()
print("Starting kdtree resampling")
print("\nNum LC Galaxies: {:.2e} Num Gltcs Galaxies: {:.2e}".format(lc_data['m_star'].size, gal_prop['m_star'].size))
m_star = lc_data['m_star']
mag_r = lc_data['Mag_r']
clr_gr = lc_data['clr_gr']
clr_ri = lc_data['clr_ri']
if ignore_mstar:
print("\tIgnoring Mstar!")
lc_mat = np.stack((mag_r,clr_gr,clr_ri),axis=1)
gal_mat = np.stack((gal_prop['Mag_r'],
gal_prop['clr_gr'],
gal_prop['clr_ri']),axis=1)
else:
lc_mat = np.stack((mag_r,clr_gr,clr_ri,m_star),axis=1)
gal_mat = np.stack((gal_prop['Mag_r'],
gal_prop['clr_gr'],
gal_prop['clr_ri'],
gal_prop['m_star']),axis=1)
if ignore_bright_luminosity:
lc_mat = squash_magnitudes(lc_mat, ignore_bright_luminosity_threshold, ignore_bright_luminosity_softness)
gal_mat = squash_magnitudes(gal_mat, ignore_bright_luminosity_threshold, ignore_bright_luminosity_softness)
# slct_lc_mat = lc_mat[:,0]<ignore_bright_luminosity_threshold
# lc_mat[slct_lc_mat,0] = ignore_bright_luminosity_threshold
# slct_gal_mat = gal_mat[:,0]< ignore_bright_luminosity_threshold
# gal_mat[slct_gal_mat,0] = ignore_bright_luminosity_threshold
if verbose:
t2 = time.time()
print('\tdone formating data. {}'.format(t2-t1))
print("data size: {:.2e}".format(m_star.size))
# if the search size is large enough, it's saves total time to construct a
# faster to search tree. Otherwise build a quick tree.
if m_star.size > 3e7:
if verbose:
print("long balanced tree")
ckdtree = cKDTree(gal_mat, balanced_tree = True, compact_nodes = True)
elif m_star.size > 3e6:
if verbose:
print("long tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = True)
else:
if verbose:
print("quick tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = False)
if verbose:
t3 = time.time()
print('\tdone making tree. {}'.format(t3-t2))
dist_raw, index_raw = ckdtree.query(lc_mat, nnk, n_jobs=10)
if verbose:
t4= time.time()
print('\tdone querying. {}'.format(t4-t3))
if nnk > 1:
rand = np.random.randint(nnk,size=index_raw.shape[0])
aa = np.arange(index_raw.shape[0])
#dist = dist[aa,rand]
index = index_raw[aa,rand]
else:
index = index_raw
##======DEBUG===========
# print("lc_data size:")
# for k in lc_data:
# print(k,np.sum(~np.isfinite(lc_data[k])),'/',lc_data[k].size)
# print("\n\ngal_prop size:")
# for k in gal_prop:
# print(k,np.sum(~np.isfinite(gal_prop[k])),'/',gal_prop[k].size)
# print("index min/max: ", np.min(index), np.max(index))
# print("ckdtree size: ",gal_mat[:,0].size, gal_mat[0,:].size)
# plt.figure()
# h,xbins = np.histogram(index, bins=1000)
# plt.plot(dtk.bins_avg(xbins), h)
# plt.grid()
# plt.xlabel('index num')
# plt.ylabel('count')
##======DEBUG===========
return index
def resample_index_cluster_red_squence(lc_data, gal_prop, ignore_mstar
= False, nnk = 10, verbose =
False,
ignore_bright_luminosity=False,
ignore_bright_luminosity_threshold=False,
ignore_bright_luminosity_softness=0.0,
rs_scatter_dict = {}):
if verbose:
t1 = time.time()
print("Starting kdtree resampling with obs colors")
lc_data_list = []
gal_prop_list = []
# We modify the lightcone/baseDC2/query data with rs scatter, if listed
lc_data_list += (lc_data['Mag_r'],
lc_data['clr_gr'],
lc_data['clr_ri'],
modify_array_with_rs_scatter(lc_data, "query", "gr", rs_scatter_dict), #clr_gr_obs
modify_array_with_rs_scatter(lc_data, "query", "ri", rs_scatter_dict), #clr_ri_obs
modify_array_with_rs_scatter(lc_data, "query", "iz", rs_scatter_dict), #clr_iz_obs
)
# We modify the galaxy properties/galactics/tree data with rs scatter, if listed
gal_prop_list += (gal_prop['Mag_r'],
gal_prop['clr_gr'],
gal_prop['clr_ri'],
modify_array_with_rs_scatter(gal_prop, "tree", "gr", rs_scatter_dict), #clr_gr_obs
modify_array_with_rs_scatter(gal_prop, "tree", "ri", rs_scatter_dict), #clr_ri_obs
modify_array_with_rs_scatter(gal_prop, "tree", "iz", rs_scatter_dict), #clr_iz_obs
)
if ignore_mstar:
pass
else:
lc_data_list.append(lc_data['m_star'])
gal_prop_list.append(gal_prop['m_star'])
lc_mat = np.transpose(lc_data_list)
gal_mat = np.transpose(gal_prop_list)
if ignore_bright_luminosity:
if(ignore_bright_luminosity_softness == 0.0):
slct_lc_mat = lc_mat[:,0]<ignore_bright_luminosity_threshold
lc_mat[slct_lc_mat,0] = ignore_bright_luminosity_threshold
slct_gal_mat = gal_mat[:,0]< ignore_bright_luminosity_threshold
gal_mat[slct_gal_mat,0] = ignore_bright_luminosity_threshold
else:
lim = ignore_bright_luminosity_threshold
a = ignore_bright_luminosity_softness
slct_lc_mat = lc_mat[:,0]<lim+a
lc_mat[slct_lc_mat,0]=a*np.tanh((lc_mat[slct_lc_mat,0]-lim-a)/a) + lim +a
slct_gal_mat = gal_mat[:,0]<lim+a
gal_mat[slct_gal_mat,0]=a*np.tanh((gal_mat[slct_gal_mat,0]-lim-a)/a) + lim +a
if verbose:
t2 = time.time()
print("\tdone formatting data. {}".format(t2-t1))
if lc_data['m_star'].size > 3e6:
if verbose:
print("long tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = True)
else:
if verbose:
print("quick tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = False)
if verbose:
t3 = time.time()
print("\tdone making kdtree. {}".format(t3-t2))
dist, index = ckdtree.query(lc_mat, nnk, n_jobs=10)
if verbose:
t4 = time.time()
print("\tdone querying. {}".format(t4-t3))
if nnk > 1:
rand = np.random.randint(nnk,size=dist.shape[0])
aa = np.arange(dist.shape[0])
#dist = dist[aa,rand]
index = index[aa,rand]
# return orignal_index[slct_valid][index]
return index
def get_keys(hgroup):
keys = []
def _collect_keys(name, obj):
if isinstance(obj, h5py.Dataset):
keys.append(name)
hgroup.visititems(_collect_keys)
return keys
def soft_transition(vals, trans_start, trans_end):
if(vals.size ==0):
return np.ones(vals.size,dytpe='bool')
slct_between = (vals>trans_start) & (vals<trans_end)
if(trans_start == trans_end or np.sum(slct_between) == 0):
return vals>trans_start
elif(trans_start > trans_end):
raise ValueError('Trans_start value is greater than trans_end')
else:
# print(trans_start, trans_end)
# print(vals.size)
# print(np.sum(slct_between))
# print(vals[slct_between])
bins = fuzzy_digitize(vals[slct_between],[trans_start,trans_end], min_counts=0)
result = np.ones(vals.size, dtype='bool')
result[vals<=trans_start] = False
result[slct_between] = bins==1
return result
def get_rs_scatter_dict_from_param(param):
"""This function takes in a dtk.Param object and returns a dictionary
containing the scatter"""
print("seaching param file for red squence scatter information")
rs_scatter_dict = {}
colors = ['gr', 'ri', 'iz']
scatter_locations = ['query', 'tree']
for scatter_loc in scatter_locations:
for color in colors:
key = "red_sequence_scatter_{}_{}".format(scatter_loc, color)
if key in param:
val = param.get_float(key)
print("found {} = {:f} in param file".format(key, val))
rs_scatter_dict[key] = val
return rs_scatter_dict
def modify_data_with_rs_scatter(data_dict, data_type, rs_scatter_dict):
data_dict = data_dict.copydeep()
assert data_type == "query" or data_type == "tree", "Data type must be either \"query\" or \"tree\". Given data_type is {}".format(data_type)
colors = ['gr', 'ri', 'iz']
for color in colors:
rs_scatter_key = 'rs_scatter_{}_{}'.format(data_type, color)
if rs_scatter_key in rs_scatter_dict:
data = query_dict["clr_{}_obs".format(color)]
scatter = np.random.normal(scale=rs_scatter_dict[key],
size =data.size)
query_dict["clr_{}_obs".format(color)] = data + scatter
return data_dict
def modify_array_with_rs_scatter(data_dict, data_type, color,
rs_scatter_dict):
assert data_type == "query" or data_type == "tree", "Data type must be either \"query\" or \"tree\". Given data_type is {}".format(data_type)
data = data_dict['clr_{}_obs'.format(color)]
rs_scatter_key = "red_sequence_scatter_{}_{}".format(data_type, color)
if rs_scatter_key in rs_scatter_dict:
print("modifying {} data: color {} ".format(data_type, color))
scatter = np.random.normal(scale=rs_scatter_dict[rs_scatter_key],
size =data.size)
return data+scatter
else:
return data
copy_avoids = ('x','y','z','vx','vy','vz', 'peculiarVelocity','galaxyID','redshift',
'redshiftHubble','placementType','isCentral','hostIndex',
'blackHoleAccretionRate','blackHoleMass', 'step','infallHaloMass','infallHaloTag')
#TODO re-allow nitrogen contamination
copy_avoids_ptrn = ('hostHalo','magnitude','ageStatistics','Radius','Axis','Ellipticity','positionAngle','total', 'ContinuumLuminosity', 'contam_nitrogenII6584', 'Sersic', 'morphology', 'contam_nitrogen')
no_slope_var = ('x','y','z','vx','vy','vz', 'peculiarVelocity','galaxyID','redshift','redshiftHubble','inclination','positionAngle')
no_slope_ptrn =('morphology','hostHalo','infall')
def to_copy(key, short, supershort):
if short:
if "SED" in key or "other" in key or "Lines" in key:
print("\tnot copied: short var cut")
return False
if supershort:
if "SDSS" not in key and "total" not in key and ":rest" not in key and "MassStellar" not in key and "infallIndex" != key and "inclination" not in key:
print("\tnot copied: supershort var cut")
return False
if any([ ca == key for ca in copy_avoids]) or any([ cap in key for cap in copy_avoids_ptrn ]):
print("\tnot copied: by explicit listing")
return False
return True
# Keys that have their luminosity adjusted
luminosity_factors_keys = ['Luminosities', 'Luminosity']
_cached_column = {}
def get_column_interpolation_dust_raw(key, h_in_gp1, h_in_gp2, index,
mask1, mask2, step1_a, step2_a,
target_a, dust_factors,
kdtree_index=None,
luminosity_factors = None, cache
= False, snapshot = False):
"""This function returns the interpolated quantity between two
timesteps, from step1 to step2. Some galaxies are masked out: Any
galaxy that doesn't pass the mask in step1 (mask1), any galaxy
that doesn't a decendent in step2, or any galaxy that whose
descendent doesn't pass the step2 mask (mask2).
"""
print("\tLoading key: {}".format(key))
# if luminosity_factors is None:
# print("\t\tluminosity factors is none")
#print("dust_factors: ", dust_factors)
t1 = time.time()
step_del_a = step2_a - step1_a
target_del_a = target_a - step1_a
##=========DEBUG==========
# print("step del_a {:.3f} - {:.3f} = {:.3f}".format(step2_a, step1_a, step_del_a))
# print("target_del_a {:.3f} - {:.3f} = {:.3f}".format(target_a, step1_a, target_del_a))
##=========DEBUG==========
# The masking all galaxies that fail galmatcher's requirements at
# step1, galaxies that don't have a descndent, or if the
# descendent galaxy at step2 doesn't pass galmatcher requirements.
# If index is set None, we aren't doing interpolation at all. We
# are just using
if not snapshot:
mask_tot = mask1 & (index != -1) & mask2[index]
if (key in no_slope_var) or any(ptrn in key for ptrn in no_slope_ptrn):
#print('\t\tno interpolation')
data = h_in_gp1[key].value[mask_tot]
if kdtree_index is None:
val_out = data
else:
val_out = data[kdtree_index]
elif ":dustAtlas" in key:
#print('\t\tinterpolation with dust')
key_no_dust = key.replace(":dustAtlas","")
val1_no_dust = h_in_gp1[key_no_dust].value[mask_tot]
val1_dust = h_in_gp1[key].value[mask_tot]
if index is not None:
val2_no_dust = h_in_gp2[key].value[index][mask_tot]
else:
val2_no_dust = val1_no_dust
# val1_no_dust_lg = np.log(val1_no_dust)
# val1_dust_lg = np.log(val1_dust)
# val2_no_dust_lg = np.log(val2_no_dust)
dust_effect = val1_dust/val1_no_dust
dust_effect[val1_no_dust == 0] = 1
slope = (val2_no_dust - val1_no_dust)/step_del_a
slope[step_del_a ==0] =0
# slope_mag = (val2_no_dust_lg - val1_no_dust_lg)/step_del_a
# slope_mag[step_del_a == 0] = 0
##=======DEBUG=======
# def print_vals(label, data):
# print("\t\t{} below/zero/size: {}/{}/{}".format(label, np.sum(data<0), np.sum(data==0), data.size))
# print_vals("val1_no_dust", val1_no_dust)
# print_vals("val2_no_dust", val2_no_dust)
# print_vals("val1_dust", val1_dust)
##=======DEBUG=======
if kdtree_index is None:
tot_dust_effect = dust_effect**dust_factors
slct = dust_effect > 1.0
tot_dust_effect[slct] = dust_effect[slct]
val_out = (val1_no_dust + slope*target_del_a)*tot_dust_effect
#val_out = np.exp((val1_no_dust_lg + slope_mag*target_del_a)*tot_dust_effect)
else:
tot_dust_effect = (dust_effect[kdtree_index]**dust_factors)
slct = dust_effect[kdtree_index] > 1.0
tot_dust_effect[slct] = dust_effect[kdtree_index][slct]
val_out = (val1_no_dust[kdtree_index] + slope[kdtree_index]*target_del_a)*tot_dust_effect
#val_out = np.exp((val1_no_dust_lg[kdtree_index] + slope_mag[kdtree_index]*target_del_a)*tot_dust_effect)
else:
#print('\t\tinerpolation without dust')
val1_data = h_in_gp1[key].value[mask_tot]
val2_data = h_in_gp2[key].value[index][mask_tot]
# val1_data_lg = np.log(val1_data)
# val2_data_lg = np.log(val2_data)
slope = (val2_data - val1_data)/step_del_a
slope[step_del_a==0]=0
# slope_mag = (val1_data_lg-val2_data_lg)/step_del_a
# slope_mag[step_del_a==0]=0
if kdtree_index is None:
val_out = val1_data + slope*target_del_a
#val_out = np.log(val1_data_lg + slope_mag*target_del_a)
else:
val_out = val1_data[kdtree_index] + slope[kdtree_index]*target_del_a
#val_out = np.log(val1_data_lg[kdtree_index] + slope_mag[kdtree_index]*target_del_a)
#print('\t\t',val_out.dtype)
# If running on snapshot, we don't need to interpolate
else:
mask_tot = mask1
val1_data = h_in_gp1[key].value[mask_tot]
# reorder the data if it's a post-matchup index
if kdtree_index is None:
val_out = val1_data
else:
val_out = val1_data[kdtree_index]
if not(luminosity_factors is None):
if(any(l in key for l in luminosity_factors_keys)):
#print("\t\tluminosity adjusted")
val_out = val_out*luminosity_factors
elif('Luminosities' in key or 'Luminosity' in key):
#print("\t\tluminosity adjusted 2")
val_out = val_out*luminosity_factors
else:
pass
#print("\t\tluminosity untouched")
if np.sum(~np.isfinite(val_out))!=0:
print(key, "has a non-fininte value")
print("{:.2e} {:.2e}".format(np.sum(~np.isfinite(val_out)), val_out.size))
if ":dustAtlas" in key:
print(np.sum(~np.isfinite(val1_no_dust)))
print(np.sum(~np.isfinite(dust_effect)))
slct = ~np.isfinite(dust_effect)
print(val1_no_dust[slct])
print(val1_dust[slct])
print(np.sum(~np.isfinite(slope_mag)))
print(np.sum(~np.isfinite(target_del_a)))
if "emissionLines" in key:
print("overwriting non-finite values with 0")
val_out[~np.isfinite(val_out)]=0.0
else:
raise
#print("\t\toutput size: {:.2e}".format(val_out.size))
print("\t\t mask size:{:.1e}/{:.1e} data size:{:.1e} read + format time: {}".format(np.sum(mask_tot), mask_tot.size, val_out.size, time.time()-t1))
##=======DEBUG======
# print("\t\t non-finite: {}/{}/{}".format(np.sum(~np.isfinite(val_out)), np.sum(val_out<0), val_out.size))
# print("\t\t below/zero/size: {}/{}/{}".format(np.sum(val_out<0), np.sum(val_out==0), val_out.size))
##=======DEBUG======
return val_out
def copy_columns_interpolation_dust_raw(input_fname, output_fname,
kdtree_index, step1, step2,
step1_a, step2_a, mask1, mask2,
index_2to1, lc_a,
verbose = False,
short = False, supershort = False,
step = -1, dust_factors = 1.0,
luminosity_factors = None,
library_index = None,
node_index = None,
snapshot = False):
print("===================================")
print("copy columns interpolation dust raw")
# lc_a = 1.0/(1.0+lc_redshift)
# input_a = 1.0/(1.0 + input_redshift)
del_a = lc_a-step1_a
dtk.ensure_dir(output_fname)
h_out = h5py.File(output_fname,'w')
h_out_gp = h_out.create_group('galaxyProperties')
h_out_gp['matchUp/dustFactor'] = dust_factors
if luminosity_factors is not None:
h_out_gp['matchUp/luminosityFactor'] = luminosity_factors
if library_index is not None:
h_out_gp['matchUp/libraryIndex'] = library_index
if node_index is not None:
h_out_gp['matchUp/GalacticusNodeIndex'] = node_index
h_in_gp1 = h5py.File(input_fname.replace("${step}",str(step1)),'r')['galaxyProperties']
h_in_gp2 = h5py.File(input_fname.replace("${step}",str(step2)),'r')['galaxyProperties']
keys = get_keys(h_in_gp1)
max_float = np.finfo(np.float32).max #The max float size
for i in range(0,len(keys)):
t1 = time.time()
key = keys[i]
if verbose:
print('{}/{} [{}] {}'.format(i,len(keys),step, key))
if not to_copy(key, short, supershort):
continue
new_data = get_column_interpolation_dust_raw(
key, h_in_gp1, h_in_gp2, index_2to1, mask1, mask2, step1_a, step2_a, lc_a, dust_factors,
kdtree_index = kdtree_index, luminosity_factors = luminosity_factors, snapshot=snapshot)
slct_finite = np.isfinite(new_data)
#If the data is a double, record it as a float to save on disk space
if(new_data.dtype == np.float64 and np.sum(new_data[slct_finite]>max_float) == 0):
h_out_gp[key]= new_data.astype(np.float32)
else:
h_out_gp[key] = new_data
print("\t\tDone writing. read+format+write: {}".format(time.time()-t1))
return
def copy_columns_interpolation_dust_raw_healpix(input_fname, output_fname,
kdtree_index, step1, step2,
step1_a, step2_a, mask1, mask2,
index_2to1, lc_a,
healpix_pixels, lc_healpix,
verbose = False,
short = False, supershort = False,
step = -1, dust_factors = 1.0,
luminosity_factors = None,
library_index = None,
node_index = None,
snapshot= False):
print("===================================")
print("copy columns interpolation dust raw")
# lc_a = 1.0/(1.0+lc_redshift)
# input_a = 1.0/(1.0 + input_redshift)
del_a = lc_a-step1_a
#print("del_a: ", del_a)
h_out_gps = {}
h_out_gps_slct = {}
for healpix_pixel in healpix_pixels:
hp_fname = output_fname.replace("${healpix}", str(healpix_pixel))
dtk.ensure_dir(hp_fname)
h_out = h5py.File(hp_fname,'w')
h_out_gps[healpix_pixel] = h_out.create_group('galaxyProperties')
slct = lc_healpix == healpix_pixel
h_out_gps[healpix_pixel]['matchUp/dustFactor'] = dust_factors[slct]
h_out_gps[healpix_pixel]['matchUp/luminosityFactor'] = luminosity_factors[slct]
h_out_gps[healpix_pixel]['matchUp/libraryIndex'] = library_index[slct]
h_out_gps[healpix_pixel]['matchUp/GalacticusNodeIndex'] = node_index[slct]
h_out_gps_slct[healpix_pixel] = slct
h_in_gp1 = h5py.File(input_fname.replace("${step}",str(step1)),'r')['galaxyProperties']
h_in_gp2 = h5py.File(input_fname.replace("${step}",str(step2)),'r')['galaxyProperties']
keys = get_keys(h_in_gp1)
max_float = np.finfo(np.float32).max #The max float size
for i in range(0,len(keys)):
t1 = time.time()
key = keys[i]
if verbose:
print('{}/{} [{}] {}'.format(i,len(keys),step, key))
if not to_copy(key, short, supershort):
continue
new_data = get_column_interpolation_dust_raw(
key, h_in_gp1, h_in_gp2, index_2to1, mask1, mask2, step1_a, step2_a, lc_a, dust_factors,
kdtree_index = kdtree_index, luminosity_factors = luminosity_factors, snapshot = snapshot)
slct_finite = np.isfinite(new_data)
#If the data is a double, record it as a float to save on disk space
if(new_data.dtype == np.float64 and np.sum(new_data[slct_finite]>max_float) == 0):
new_data= new_data.astype(np.float32)
if 'LineLuminosity' in key:
key = key.replace(':rest', '')
for healpix_pixel in healpix_pixels:
h_out_gps[healpix_pixel][key] = new_data[h_out_gps_slct[healpix_pixel]]
print("\t\tDone writing. read+format+write: {}".format(time.time()-t1))
return
def overwrite_columns(input_fname, output_fname, ignore_mstar = False,
verbose=False, cut_small_galaxies_mass = None,
internal_step=None, fake_lensing=False,
healpix=False, step = None, healpix_shear_file =
None, no_shear_steps=None,
snapshot = False,
snapshot_redshift = None):
t1 = time.time()
if verbose:
print("Overwriting columns.")
#sdss = Table.read(input_fname,path='data')
if snapshot:
assert snapshot_redshift is not None, "Snapshot redshift must be specified in snapshot mode"
h_out = h5py.File(output_fname, 'a')
h_out_gp = h_out['galaxyProperties']
if snapshot:
h_in = h5py.File(input_fname,'r')['galaxyProperties']
elif internal_step is None:
h_in = h5py.File(input_fname,'r')
else:
h_in = h5py.File(input_fname,'r')[str(internal_step)]
# if the input file has no galaxies, it doesn't have any columns
step_has_data = "obs_sm" in h_in
if step_has_data:
sm = h_in['obs_sm'].value
else:
sm = np.zeros(0, dtype=float)
if cut_small_galaxies_mass is None:
mask = np.ones(sm.size, dtype=bool)
else:
mask = np.log10(sm) > cut_small_galaxies_mass
#redshift = np.ones(sdss['x'].quantity.size)*0.1
t2 = time.time()
if verbose:
print("\t done reading in data", t2-t1)
#xyz,v(xyz)
if step_has_data:
x = h_in['x'].value[mask]
y = h_in['y'].value[mask]
z = h_in['z'].value[mask]
vx = h_in['vx'].value[mask]
vy = h_in['vy'].value[mask]
vz = h_in['vz'].value[mask]
if snapshot:
redshift = np.ones(x.size)*snapshot_redshift
else:
redshift =h_in['redshift'].value[mask]
size = h_in['x'].size
if not snapshot:
h_out_gp['lightcone_rotation'] = h_in['lightcone_rotation'].value[mask]
h_out_gp['lightcone_replication'] = h_in['lightcone_replication'].value[mask]
else:
x = np.zeros(0, dtype=float)
y = np.zeros(0, dtype=float)
z = np.zeros(0, dtype=float)
vx = np.zeros(0, dtype=float)
vy = np.zeros(0, dtype=float)
vz = np.zeros(0, dtype=float)
size = 0
redshift =np.zeros(0, dtype=float)
if not snapshot:
h_out_gp['lightcone_rotation'] = np.zeros(0, dtype=int)
h_out_gp['lightcone_replication'] = np.zeros(0, dtype=int)
print('step: ', step)
assert step is not None, "Step is not specified"
if not snapshot:
h_out_gp['step']=np.ones(size,dtype='i4')*step
h_out_gp['x']=x
h_out_gp['y']=y