-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjswml.py.bak
executable file
·4789 lines (4177 loc) · 174 KB
/
jswml.py.bak
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
# Joint stepwise maximum likelihood luminosity function and radial density
# estimation using the method of Cole (2011) but allowing for
# individual k-corections
#
# Revision history
#
# 1.0 21-may-13 Based on mlum.py and Shaun's rancat_jswml.f90
# 1.1 08-aug-14 Much simplified by separating out evolution fitting and
# Vdc_max calculation from LF fitting
import contextlib
import os
import matplotlib
from matplotlib.ticker import MaxNLocator
if not(os.environ.has_key('DISPLAY')):
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid import AxesGrid
import itertools
import lum
import math
import mpmath
import multiprocessing
import numpy as np
import pmap
import pickle
import pdb
import astropy.io.fits as fits
#import pyqt_fit.kde
import scipy.integrate
import scipy.interpolate
import scipy.optimize
import scipy.stats
import time
import util
# Allow customisation of printed array format,
# see http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array
@contextlib.contextmanager
def printoptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
yield
np.set_printoptions(**original)
# Avoid excessive space around markers in legend
matplotlib.rcParams['legend.handlelength'] = 0
# Treatment of numpy errors
np.seterr(all='warn')
# Global parameters
par = {'progName': 'jswml.py', 'version': 1.1, 'ev_model': 'z',
'clean_photom': True, 'use_wt': True, 'kc_use_poly': True}
cosmo = None
sel_dict = {}
chol_par_name = ('alpha', ' M*', ' phi*', ' beta', ' mu*', 'sigma')
methods = ('lfchi', 'denchi', 'post', 'min_slope', 'zero_slope')
mass_limits = (8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12)
mass_zlimits = (0.15, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12)
mag_limits = (-23, -22, -21, -20, -19, -18, -17, -16, -15)
wmax = 5.0 # max incompleteness weighting
# Constants
lg2pi = math.log10(2 * math.pi)
ln10 = math.log(10)
J3 = 30000.0
# Jacknife regions are 4 deg segments starting at given RA
njack = 9
ra_jack = (129, 133, 137, 174, 178, 182, 211.5, 215.5, 219.5)
# Determined from GAMA-I. Early/late cut at n = 1.9
Q_all = 1.59
P_all = 0.14
Q_early = 1.31
P_early = 0.14
Q_late = 1.98
P_late = 0.13
# Determined from GAMA-II.
Q_clr = {'c': 0.78, 'b': 0.23, 'r': 0.83}
P_clr = {'c': 1.72, 'b': 3.55, 'r': 1.10}
Qdef, Pdef = 1.0, 1.0
# Factor by which to multiply apparent radius in arcsec to get
# absolute radius in kpc when distance measured in Mpc
radfac = math.pi/180.0/3.6
# Solar magnitudes from Blanton et al 2003 for ^{0.1}ugriz bands
Msun_ugriz = [6.80, 5.45, 4.76, 4.58, 4.51]
# FNugrizYJHK (z0=0) Solar magnitudes from Driver et al 2012
Msun_z0 = {'F': 16.02, 'N': 10.18, 'u': 6.38, 'g': 5.15, 'r': 4.71,
'i': 4.56, 'z': 4.54, 'Y': 4.52, 'J': 4.57, 'H': 4.71, 'K': 5.19}
# Imaging completeness from Blanton et al 2005, ApJ, 631, 208, Table 1
# Modified to remove decline at bright end and to prevent negative
# completeness values at faint end
sb_tab = (18, 19, 19.46, 19.79, 20.11, 20.44, 20.76, 21.09, 21.41,
21.74, 22.06, 22.39, 22.71, 23.04, 23.36, 23.69, 24.01,
24.34, 26.00)
comp_tab = (1.0, 1.0, 0.99, 0.97, 0.98, 0.98, 0.98, 0.97, 0.96, 0.96,
0.97, 0.94, 0.86, 0.84, 0.76, 0.63, 0.44, 0.33, 0.01)
# Polynomial fits to mass completeness limits from misc.mass_comp()
mass_comp_pfit = {'c': (50.96, -57.42, 23.57, 7.32),
'b': (44.40, -51.90, 22.22, 7.21),
'r': (25.88, -32.11, 15.62, 8.13)}
# Standard symbol and colour order for plots
sym_list = ('ko', 'bs', 'g^', 'r<', 'mv', 'y>', 'cp')
clr_list = 'bgrck'
# Plot labels
mag_petro_label = r'$^{0.1}M_{r_{\rm Petro}} -\ 5 \lg h$'
mag_sersic_label = r'$^{0.1}M_{r_{\rm Sersic}} -\ 5 \lg h$'
den_mag_label = r'$\phi(M)\ (h^3 {\rm Mpc}^{-3} {\rm mag}^{-1})$'
den_mass_label = r'$\phi(M)\ (h^3 {\rm Mpc}^{-3} {\rm dex}^{-1})$'
# Directory to save plots
plot_dir = os.environ['HOME'] + '/Documents/tex/papers/gama/jswml/'
#------------------------------------------------------------------------------
# Driver routines
#------------------------------------------------------------------------------
def apollo_jobs():
"""Submit several jobs on apollo."""
dir = '/research/astro/gama/loveday/gama/jswml/auto'
# for ireal in range(26):
python_commands = ['import jswml',
'''jswml.ev_fit_samples("kcorrz00.fits",
"ev_z00_{}_petro_fit_{}.dat")''']
util.apollo_job(dir, python_commands)
def ev_fit_samples(infile='kcorrz01.fits', outroot='ev_{}_petro_fit_{}.dat',
colour='c', param='r_petro', method='lfchi', ev_model='z'):
"Determine ev parameters and density-corrected Vmax for specified sample."
par['ev_model'] = ev_model
par['clean_photom'] = True
clr_limits = ('a', 'z')
if (colour == 'b'): clr_limits = ('b', 'c')
if (colour == 'r'): clr_limits = ('r', 's')
sel_dict['colour'] = clr_limits
outfile = outroot.format(method, colour)
ev_fit(infile, outfile, Pbins=(0.0, 2.5, 25), Qbins=(0.0, 1.5, 30),
param=param, method=method)
del sel_dict['colour']
def ev_fit_test(infile='kcorrz01.fits', outroot='ev_test_Mlt{}.dat',
colour='c', param='r_petro', method='lfchi', ev_model='z',
Mmax=-12):
"""Determine ev parameters and density-corrected Vmax for specified sample
using small number of P, Q bins and no optimization."""
par['ev_model'] = ev_model
par['clean_photom'] = True
clr_limits = ('a', 'z')
if (colour == 'b'): clr_limits = ('b', 'c')
if (colour == 'r'): clr_limits = ('r', 's')
sel_dict['colour'] = clr_limits
# outfile = outroot.format(method, colour)
outfile = outroot.format(Mmax)
ev_fit(infile, outfile, Pbins=(0.0, 2.5, 25), Qbins=(0.0, 2.0, 20), opt=0,
param=param, method=method, Mmax=Mmax)
def ev_fit_mock(infile='kcorrz01.fits', outroot='ev_{:02d}.dat', ireal=0,
param='SDSS_R_OBS_APP', method='lfchi', ev_model='z'):
"""Evolution fitting for mocks."""
par['ev_model'] = ev_model
par['clean_photom'] = False
par['ireal'] = ireal
outfile = outroot.format(ireal)
print(ireal)
ev_fit(infile, outfile, Pbins=(-1.0, 2.0, 15), Qbins=(-1.0, 1.0, 10),
param=param, method=method)
def ev_sim_par(inroot='sim_z01_{}.fits', outroot='lf_kde_z01_{}_{}.dat'):
"""Evolution fitting for several simulations run in parallel."""
i = int(os.environ['SGE_TASK_ID']) - 1
infile = inroot.format(i)
for method in ('lfchi', 'post'):
outfile = outroot.format(method, i)
print infile, method
lf_PQ(inFile=infile, outFile=outfile,
param_list=(('r_petro',
(10, 19.8), (10, 19.8, 29), (-23, -15, 32), 0),),
zmin=0.002, zmax=0.65, nz=65, lf_zbins=((0, 20), (20, 64)),
Pbins=(0, 3.5, 35), Qbins=(0, 1.5, 30),
P_prior=(2, 1), Q_prior=(1, 1), method=method, err_type='j3',
use_mp=True, lf_est='kde')
def Vmax(infile='kcorrz01.fits', evroot='ev_{}_{}_fit_{}.dat',
outroot='Vmax_{}_{}.fits'):
"""Vmax calculation."""
par['clean_photom'] = False
magtype = 'petro'
for method in ('lfchi', 'post'):
for colour in 'cbr':
evfile = evroot.format(method, magtype, colour)
outfile = outroot.format(method, colour)
# Output Vmax values for ALL objects
# sel_dict['colour'] = ('a', 'z')
Vmax_out(infile, evfile, outfile)
def Vmax_z00(infile='kcorrz00.fits', evfile='ev_z00_lfchi_petro_fit_c.dat',
outfile='Vmax_z00.fits'):
"""Vmax calculation with k-correction to z=0.0."""
par['clean_photom'] = True
Vmax_out(infile, evfile, outfile)
def Vmax_noclean(infile='kcorrz01.fits', evroot='ev_lfchi_{}_fit_c.dat',
outroot='Vmax_{}_noclean.fits'):
"""Vmax calculation."""
par['clean_photom'] = False
for magtype in ('petro', 'sersic'):
evfile = evroot.format(magtype)
outfile = outroot.format(magtype)
Vmax_out(infile, evfile, outfile)
def Vmax_z_slices(infile='kcorrz01.fits', evroot='ev_lfchi_petro_fit_{}.dat',
outroot='Vmax_{}_z_{}_{}.fits'):
"""Vmax in redshift slices."""
for colour in 'cbr':
evfile = evroot.format(colour)
for zrange in ((0.002, 0.1), (0.1, 0.2), (0.2, 0.3), (0.3, 0.4),
(0.4, 0.5), (0.5, 0.6)):
# for zrange in ((0.002, 0.06), (0.002, 0.1), (0.1, 0.2), (0.2, 0.3),
# (0.3, 0.65)):
nz = int(math.ceil(100 * (zrange[1] - zrange[0])))
outfile = outroot.format(colour, zrange[0], zrange[1])
Vmax_out(infile, evfile, outfile, zmin=zrange[0], zmax=zrange[1],
nz=nz)
def Vmax_sim(inroot='sim_z01_{}.fits', evroot='lf_kde_z01_{}_{}.dat',
outroot='Vmax_{}_{}.fits'):
"""Vmax for simulations."""
for method in ('post', 'lfchi'):
for i in xrange(10):
infile = inroot.format(i)
evfile = evroot.format(method, i)
outfile = outroot.format(method, i)
Vmax_out(infile, evfile, outfile)
def Vmax_mocks(infile='kcorrz01.fits', evroot='ev_{:02d}.dat',
outroot='Vmax_{:02d}.fits', param='SDSS_R_OBS_APP'):
"""Vmax for mocks."""
par['clean_photom'] = False
for ireal in (1, 2, 5, 6, 14, 20):
par['ireal'] = ireal
evfile = evroot.format(ireal)
outfile = outroot.format(ireal)
Vmax_out(infile, evfile, outfile, param=param)
def Vmax_pinch_test(infile='Vmax_lfchi_c.fits', nz=65, idebug=1,
param='r_petro',
plot_file='Vmax_pinch_test.png', plot_size=(5, 8)):
"""Vmax pinch test."""
global par
hdulist = fits.open(infile)
header = hdulist[1].header
par['H0'] = header['H0']
par['omega_l'] = header['OMEGA_L']
par['z0'] = header['Z0']
par['area'] = header['AREA'] * (math.pi/180.0)**2
par['ev_model'] = header['ev_model']
Q = header['Q']
P = header['P']
mlims = [0, 19.8]
mlims[0] = header['mlim_0']
mlims[1] = header['mlim_1']
zmin = header['zmin']
zmax = header['zmax']
ev_model = 'z'
hdulist.close()
print 'P, Q, nz, zmin, zmax =', P, Q, nz, zmin, zmax
par.update({'infile': infile, 'param': param, 'zmin': zmin, 'zmax': zmax,
'mlims': mlims, 'dmlim': 2, 'Mmin': -99, 'Mmax': 99, 'Mbin': 1,
'ev_model': ev_model, 'idebug': idebug})
# Volume out to galaxy redshifts
# First calculate volumes without evolution
samp = Sample(infile, par, sel_dict, 0, nqmin=2)
gala = samp.calc_limits(0)
zbin, zhist, V, V_int = z_binning(gala, nz, (zmin, zmax))
zstep = zbin[1] - zbin[0]
S_obs, S_vis = vis_calc(gala, nz, zmin, zstep, V, V_int)
converged, Npred, delta, den_var, Pz, Vmax_dc, niter = delta_solve(
0, 0, gala, nz, (zmin, zmax), zbin, zhist, V, V_int, S_vis)
V_raw = np.dot(V, S_obs)
V_dc = np.dot(delta * V, S_obs)
# Now volume with evolution
samp = Sample(infile, par, sel_dict, Q, nqmin=2)
gala = samp.calc_limits(Q)
zbin, zhist, V, V_int = z_binning(gala, nz, (zmin, zmax))
zstep = zbin[1] - zbin[0]
S_obs, S_vis = vis_calc(gala, nz, zmin, zstep, V, V_int)
converged, Npred, delta, den_var, Pz, Vmax_dec, niter = delta_solve(
P, Q, gala, nz, (zmin, zmax), zbin, zhist, V, V_int, S_vis)
V_dec = np.dot(delta * Pz * V, S_obs)
plt.clf()
fig, axes = plt.subplots(4, 1, sharex=True, sharey=True, num=1)
plt.subplots_adjust(hspace=0.0)
ax = axes[0]
ax.scatter(gala['appval_sel'], gala['zhi']/gala['z'], 0.1)
ax.semilogy(basey=10, nonposy='clip')
ax.set_ylabel('zmax/z')
ax = axes[1]
ax.scatter(gala['appval_sel'], samp.Vmax_raw/V_raw, 0.1)
ax.semilogy(basey=10, nonposy='clip')
ax.text(0.1, 0.1, 'Raw', transform=ax.transAxes)
ax = axes[2]
ax.scatter(gala['appval_sel'], samp.Vmax_dc/V_dc, 0.1)
ax.semilogy(basey=10, nonposy='clip')
ax.text(0.1, 0.1, 'DC', transform=ax.transAxes)
ax.set_ylabel('Vmax/V')
odd = samp.Vmax_dc/V_dc < 1
print (samp.Vmax_dc/V_dc)[odd]
# pdb.set_trace()
ax = axes[3]
ax.scatter(gala['appval_sel'], samp.Vmax_dec/V_dec, 0.1)
ax.semilogy(basey=10, nonposy='clip')
ax.text(0.1, 0.1, 'DEC', transform=ax.transAxes)
ax.set_xlim(19, 19.9)
ax.set_ylim(0.5, 5)
ax.set_xlabel('r_petro')
plt.draw()
if plot_file:
fig = plt.gcf()
fig.set_size_inches(plot_size)
plt.savefig(plot_dir + plot_file, bbox_inches='tight')
print 'plot saved to ', plot_dir + plot_file
def lf1(infile='Vmax_lfchi_c.fits', outroot='lf_{}_wt{}.dat',
param='z_sersic', Mmin=-25, Mmax=-12, nbin=26, clean_photom=1,
use_wt=1):
"""LF in specified band."""
par['clean_photom'] = clean_photom
par['use_wt'] = use_wt
outfile = outroot.format(param, use_wt)
lf_1d(infile, outfile, param, Mmin, Mmax, nbin)
def lfr(inroot='Vmax_{}_{}.fits', outroot='lf_{}_{}_{}.dat',
method='lfchi', param='r_petro', Mmin=-25, Mmax=-12, nbin=52,
clean_photom=True):
"""Petrosian r-band LF."""
par['clean_photom'] = clean_photom
for colour in 'cbr':
clr_limits = ('a', 'z')
if (colour == 'b'): clr_limits = ('b', 'c')
if (colour == 'r'): clr_limits = ('r', 's')
sel_dict['colour'] = clr_limits
infile = inroot.format(method, colour)
outfile = outroot.format(param, method, colour)
lf_1d(infile, outfile, param, Mmin, Mmax, nbin)
del sel_dict['colour']
def lfr_z00(infile='Vmax_z00.fits', outfile='lf_r_z00.dat',
param='r_petro', Mmin=-25, Mmax=-12, nbin=52,
clean_photom=True):
"""Petrosian r-band LF k-corrected to z=0.0."""
par['clean_photom'] = clean_photom
lf_1d(infile, outfile, param, Mmin, Mmax, nbin)
def lfr_mocks(inroot='Vmax_{:02d}.fits', outroot='lf_{:02d}.dat',
method='lfchi', param='SDSS_R_OBS_APP', Mmin=-25, Mmax=-12,
nbin=52):
"""Petrosian r-band LF for mocks."""
par['clean_photom'] = False
for ireal in (1, 2, 5, 6, 14, 20):
par['ireal'] = ireal
infile = inroot.format(ireal)
outfile = outroot.format(ireal)
lf_1d(infile, outfile, param, Mmin, Mmax, nbin)
def lfr_ev(inroot='Vmax_{}_z_{}_{}.fits', outroot='lf_{}_{}_z_{}_{}.dat',
param='r_petro', Mmin=-25, Mmax=-12, nbin=52):
"""Evolution of r-band LF."""
par['clean_photom'] = True
for colour in 'cbr':
clr_limits = ('a', 'z')
if (colour == 'b'): clr_limits = ('b', 'c')
if (colour == 'r'): clr_limits = ('r', 's')
sel_dict['colour'] = clr_limits
for zrange in ((0.002, 0.1), (0.1, 0.2), (0.2, 0.3), (0.3, 0.65)):
infile = inroot.format(colour, zrange[0], zrange[1])
outfile = outroot.format(param, colour, zrange[0], zrange[1])
lf_1d(infile, outfile, param, Mmin, Mmax, nbin)
del sel_dict['colour']
def lfr_zslices(inroot='Vmax_{}_z_{}_{}.fits', outroot='lfr_zslice_{}_{}.dat',
param='r_petro', Mmin=-25, Mmax=-12, nbin=52,
Vmax_type='Vmax_raw'):
"""r-band LF in redshift slices, without any evolution corrections."""
par['clean_photom'] = True
colour = 'c'
for zrange in ((0.002, 0.1), (0.1, 0.2), (0.2, 0.3), (0.3, 0.4),
(0.4, 0.5), (0.5, 0.6)):
infile = inroot.format(colour, zrange[0], zrange[1])
outfile = outroot.format(zrange[0], zrange[1])
lf_1d(infile, outfile, param, Mmin, Mmax, nbin, Vmax_type=Vmax_type,
Q=0)
def smf(inroot='Vmax_lfchi_{}.fits', outroot='smf_{}.dat',
param='logmstar_fluxscale', Mmin=6, Mmax=13, nbin=28,
schec_guess=(-1.0, 10.6, -2)):
"Stellar mass function."
global par
par['clean_photom'] = True
for colour in 'cbr':
par['colour'] = colour
clr_limits = ('a', 'z')
if (colour == 'b'): clr_limits = ('b', 'c')
if (colour == 'r'): clr_limits = ('r', 's')
sel_dict['colour'] = clr_limits
infile = inroot.format(colour)
outfile = outroot.format(colour)
lf_1d(infile, outfile, param, Mmin, Mmax, nbin,
schec_guess=schec_guess)
def smf_ev(inroot='Vmax_z_{}_{}.fits', outroot='smf_{}_{}_{}.dat',
param='logmstar_fluxscale', Mmin=6, Mmax=13, nbin=28,
schec_guess=(-1.0, 10.6, -2)):
"Evolution of stellar mass function."
global par
# par['use_wt'] = False
par['clean_photom'] = True
for colour in 'cbr':
par['colour'] = colour
clr_limits = ('a', 'z')
if (colour == 'b'): clr_limits = ('b', 'c')
if (colour == 'r'): clr_limits = ('r', 's')
sel_dict['colour'] = clr_limits
for zrange in ((0.002, 0.06), (0.002, 0.1), (0.1, 0.2), (0.2, 0.3),
(0.3, 0.65)):
infile = inroot.format(zrange[0], zrange[1])
outfile = outroot.format(colour, zrange[0], zrange[1])
lf_1d(infile, outfile, param, Mmin, Mmax, nbin,
schec_guess=schec_guess)
def lf_sim(inroot='Vmax_{}_{}.fits', outroot='lf_bin_{}_{}.fits',
param='r_petro', Mmin=-24, Mmax=-12, nbin=48):
"""Petrosian r-band LF for simulations."""
for method in ('post', 'lfchi'):
for i in xrange(10):
infile = inroot.format(method, i)
outfile = outroot.format(method, i)
lf_1d(infile, outfile, param, Mmin, Mmax, nbin)
def delta_lf_plots(infile='kcorrz01.fits',
param_list=(('r_petro', (14, 19.8), (14, 19.8, 27),
(-23, -18, 20), 0),),
zmin=0.002, zmax=0.65, nz=65, lf_zbins=((0, 20), (20, 64)),
idebug=1, Pbins=(0.0, 4.0, 20), Qbins=(0.0, 2.0, 20),
P_prior=(1,1), Q_prior=(1,1), method='lfchi', err_type='jack'):
"Delta and LF plots to demonstrate lfchi method."
global par
par = {'zmin': zmin, 'zmax': zmax, 'idebug': idebug}
samp = read_gama(infile, param_list)
qty = samp.qty_list[0]
lf_bins = np.linspace(qty.absMin, qty.absMax, qty.nabs+1)
costfn = Cost(samp, nz, (zmin, zmax), lf_bins, lf_zbins, method,
P_prior, Q_prior, Qbins[0], Qbins[1], err_type)
c = costfn((0.0, 0.0))
fig = plt.gcf()
fig.set_size_inches(3, 6)
plt.savefig(plot_dir + 'delta_lf_0_0.pdf', bbox_inches='tight')
c = costfn((1.7, 0.7))
fig = plt.gcf()
fig.set_size_inches(3, 6)
plt.savefig(plot_dir + 'delta_lf_1.7_0.7.pdf', bbox_inches='tight')
def ran_gen_sample(infile='kcorrz01.fits', Q=Qdef, P=Pdef,
outfile='ranz.dat', param='lum', limits=(-25, -10),
colour='c', zmin=0.002, zmax=0.65, nz=65, nfac=30):
"""Generate random distribution for single specified sample."""
clr_limits = ('a', 'z')
if (colour == 'b'):
clr_limits = ('b', 'c')
if (colour == 'r'):
clr_limits = ('r', 's')
sel_dict['colour'] = clr_limits
Mmin = -25
Mmax = -10
if param == 'lum':
Mmin = limits[0]
Mmax = limits[1]
if param == 'mass':
M_h_corr = 2*math.log10(1.0/0.7)
sel_dict['logmstar'] = (limits[0] + M_h_corr, limits[1] + M_h_corr)
par.update({'zmin': zmin, 'zmax': zmax, 'nz': nz,
'Mmin': Mmin, 'Mmax': Mmax, 'Mbin': 1,
'param': 'r_petro', 'dmlim': 2, 'mlims': (0, 19.8),
'idebug': 1})
ran_gen(infile, outfile, nfac=nfac, Q=Q, P=P, vol=0)
# -----------------------------------------------------------------------------
# Main procedures
# -----------------------------------------------------------------------------
def ev_fit(infile, outfile, mlims=(0, 19.8), param='r_petro',
Mmin=-24, Mmax=-12, Mbin=48, dmlim=2,
zmin=0.002, zmax=0.65, nz=65,
lf_zbins=((0, 20), (20, 65)),
Pbins=(-0.5, 4.0, 45), Qbins=(0.0, 1.5, 30),
P_prior=(2, 1), Q_prior=(1, 1),
idebug=1, method='lfchi', err_type='jack', use_mp=False, opt=True,
lf_est='kde'):
"""Fit evolution parameters and radial overdensities.
Searches over both Q and P values,
rather than trying to estimate P from Cole eqn (25).
Elements of P_prior and Q_prior are mean and variance."""
global par
par.update({'infile': infile, 'mlims': mlims,
'param': param, 'dmlim': dmlim,
'zmin': zmin, 'zmax': zmax,
'Mmin': Mmin, 'Mmax': Mmax, 'Mbin': Mbin,
'idebug': idebug, 'method': method, 'lf_est': lf_est})
print '\n************************\njswml.py version ', par['version']
print method
print sel_dict
assert method in methods
lf_bins = np.linspace(Mmin, Mmax, Mbin+1)
samp = Sample(infile, par, sel_dict)
costfn = Cost(samp, nz, (zmin, zmax), lf_bins, lf_zbins, method,
P_prior, Q_prior, Qbins[0], Qbins[1], err_type)
out = {'par': par}
if par['idebug'] > 0:
print 'Q, P chi^2 grid using', method
# Calculate chi^2 on (P,Q) grid to get likelihood contours and to find
# starting point for minimization
Qmin = Qbins[0]
Qmax = Qbins[1]
nQ = Qbins[2]
Qstep = float(Qmax - Qmin)/nQ
Pmin = Pbins[0]
Pmax = Pbins[1]
nP = Pbins[2]
Pstep = float(Pmax - Pmin)/nP
Qa = np.linspace(Qmin, Qmax, nQ, endpoint=False) + 0.5*Qstep
Pa = np.linspace(Pmin, Pmax, nP, endpoint=False) + 0.5*Pstep
plt.clf()
if use_mp:
chi2grid = np.array(pmap.parallel_map(lambda Q: [costfn((P, Q))
for P in Pa], Qa))
else:
chi2grid = np.array(map(lambda Q: [costfn((P, Q)) for P in Pa], Qa))
extent = (Pmin, Pmax, Qmin, Qmax)
cmap = matplotlib.cm.jet
ax = plt.subplot(313)
im = ax.imshow(chi2grid, cmap=cmap, aspect='auto', origin='lower',
extent=extent, interpolation='nearest')
cb = plt.colorbar(im, ax=ax)
(j, i) = np.unravel_index(np.argmin(chi2grid), chi2grid.shape)
P_maxl = Pmin + (i+0.5)*Pstep
Q_maxl = Qmin + (j+0.5)*Qstep
ax.plot(P_maxl, Q_maxl, '+')
ax.set_xlabel('P')
ax.set_ylabel('Q')
plt.draw()
if opt:
if par['idebug'] > 0:
print 'Simplex optimization ...'
# Use simplex method to optimize ev parameters (P,Q)
res = scipy.optimize.fmin(costfn, (P_maxl, Q_maxl), xtol=0.1, ftol=0.1,
full_output=True)
Popt = res[0][0]
Qopt = res[0][1]
else:
c = costfn((P_maxl, Q_maxl))
Popt = P_maxl
Qopt = Q_maxl
out['Pbins'] = Pbins
out['Qbins'] = Qbins
out['chi2grid'] = chi2grid
out['Pa'] = Pa
out['Qa'] = Qa
out['P'] = Popt
out['P_err'] = 0
out['Q'] = Qopt
out['Q_err'] = 0
out['zbin'] = costfn.zbin
out['delta'] = costfn.delta
out['delta_err'] = costfn.delta_err
out['den_var'] = costfn.den_var
out['lf_bins'] = lf_bins
out['phi'] = costfn.phi
out['phi_err'] = costfn.phi_err
out['Mbin'] = costfn.Mbin
out['Mhist'] = costfn.Mhist
out['whist'] = costfn.whist
out['ev_fit_chisq'] = costfn.chisq
out['ev_fit_nu'] = costfn.nu
fout = open(outfile, 'w')
pickle.dump(out, fout)
fout.close()
def Vmax_out(infile, evfile, outfile, param='r_petro',
zmin=0.002, zmax=0.65, nz=65, mlims=(0, 19.8), idebug=1):
"""Output file of density-corrected Vmax."""
global par
dat = pickle.load(open(evfile, 'r'))
P = dat['P']
Q = dat['Q']
try:
ev_model = dat['par']['ev_model']
except:
ev_model = 'z'
print 'P, Q, nz, zmin, zmax =', P, Q, nz, zmin, zmax
par.update({'infile': infile, 'param': param, 'zmin': zmin, 'zmax': zmax,
'mlims': mlims, 'dmlim': 2, 'Mmin': -99, 'Mmax': 99, 'Mbin': 1,
'ev_model': ev_model, 'idebug': idebug})
# First calculate Vmax values without evolution
samp = Sample(infile, par, sel_dict, 0, nqmin=2)
gala = samp.calc_limits(0)
zbin, zhist, V, V_int = z_binning(gala, nz, (zmin, zmax))
zstep = zbin[1] - zbin[0]
S_obs, S_vis = vis_calc(gala, nz, zmin, zstep, V, V_int)
Vmax_raw = np.dot(V, S_vis)
converged, Npred, delta, den_var, Pz, Vmax_dc, niter = delta_solve(
0, 0, gala, nz, (zmin, zmax), zbin, zhist, V, V_int, S_vis)
# Vmax_dc = np.dot(delta * V, S)
# Now include evolution
samp = Sample(infile, par, sel_dict, Q, nqmin=2)
gala = samp.calc_limits(Q)
S_obs, S_vis = vis_calc(gala, nz, zmin, zstep, V, V_int)
converged, Npred, delta, den_var, Pz, Vmax_dec, niter = delta_solve(
P, Q, gala, nz, (zmin, zmax), zbin, zhist, V, V_int, S_vis)
# Vmax_ec = np.dot(Pz * V, S)
# Output a new file of selected objects
header = samp.header
header['H0'] = (par['H0'], 'Hubble parameter (km/s/Mpc)')
header['mlim_0'] = (mlims[0], 'Petrosian r-band mag bright limit')
header['mlim_1'] = (mlims[1], 'Petrosian r-band mag faint limit')
header['ev_model'] = (ev_model, 'ev z-dependence, z1z = z/(1+z)')
header['Q'] = (Q, 'Luminosity evolution')
header['P'] = (P, 'Density evolution')
header['zmin'] = zmin
header['zmax'] = zmax
for ik in xrange(5):
header['kc_{}'.format(ik)] = (samp.kmean[ik],
'Mean kcorr coeff {}'.format(ik))
hdu = fits.BinTableHDU(data=samp.tbdata, header=header)
hdu.writeto(outfile, clobber=True)
# Add Vmax columns
hdulist = fits.open(outfile)
cols = hdulist[1].data.columns
c1 = fits.Column(name='Vmax_raw', format='E', unit='(Mpc/h)^3',
array=Vmax_raw)
c2 = fits.Column(name='Vmax_dc', format='E', unit='(Mpc/h)^3',
array=Vmax_dc)
# c3 = fits.Column(name='Vmax_ec', format='E', unit='(Mpc/h)^3',
# array=Vmax_ec)
c4 = fits.Column(name='Vmax_dec', format='E', unit='(Mpc/h)^3',
array=Vmax_dec)
# pdb.set_trace()
hdu = fits.BinTableHDU.from_columns(cols + c1 + c2 + c4, header=header)
hdu.writeto(outfile, clobber=True)
def lf_1d(infile, outfile, param, Mmin=-24, Mmax=-12, nbin=48, dmlim=2,
Vmax_type='Vmax_dec', Q='read', schec_guess=(-1.0, -20.0, -2),
saund_guess=(-1.0, -20.0, 0.4, -2), idebug=1, lf_est='bin'):
"""Univariate LF using density-corrected Vmax."""
global par
par.update({'infile': infile, 'param': param, 'dmlim': dmlim,
'idebug': idebug, 'lf_est': lf_est})
out = {'infile': infile, 'param': param, 'Mmin': Mmin, 'Mmax': Mmax,
'nbin': nbin, 'Vmax_type': Vmax_type, 'lf_est': lf_est}
print '\n************************\njswml.py version ', par['version']
print sel_dict
gala = read_vmax(infile, sel_dict, param, Vmax_type, Q=Q)
lf_bins = np.linspace(Mmin, Mmax, nbin+1)
# Find completeness limits in magnitude (Loveday+2012 sec 3.3)
Mbright = par['mlims'][0] - dmodk(par['zmax'], par['kc_mean'], par['Q'])
Mfaint = par['mlims'][1] - dmodk(par['zmin'], par['kc_mean'], par['Q'])
print 'Mag completeness limits:', Mbright, Mfaint
if param in ('logmstar', 'logmstar_fluxscale'):
# 95 percentile completeness in stellar mass
pfit = mass_comp_pfit[par['colour']]
Mmin = np.polyval(pfit, par['zmin'])
comp = (lf_bins[:-1] > Mmin)
print 'mass completeness limit:', Mmin
out['Mmin'] = Mmin
else:
comp = (lf_bins[1:] < Mfaint) * (lf_bins[:-1] > Mbright)
out['Mbright'] = Mbright
out['Mfaint'] = Mfaint
lf = lf1d(gala, gala['Vmax'], lf_bins)
schec = util.schec_fit(lf['Mbin'][comp], lf['phi'][comp],
lf['phi_err'][comp],
schec_guess, sigma=lf['kde_bandwidth'], loud=1)
saund = util.saund_fit(lf['Mbin'][comp], lf['phi'][comp],
lf['phi_err'][comp], saund_guess)
out['par'] = par
out['comp'] = comp
out['alpha'] = schec['alpha']
out['alpha_err'] = schec['alpha_err']
out['Mstar'] = schec['Mstar']
out['Mstar_err'] = schec['Mstar_err']
out['lpstar'] = schec['lpstar']
out['lpstar_err'] = schec['lpstar_err']
out['lf_chi2'] = schec['chi2']
out['lf_nu2'] = schec['nu']
out['kde_bandwidth'] = lf['kde_bandwidth']
plt.clf()
plt.semilogy(basey=10, nonposy='clip')
plt.errorbar(lf['Mbin'][comp], lf['phi'][comp], lf['phi_err'][comp],
fmt='o')
util.schec_plot(schec['alpha'], schec['Mstar'], 10**schec['lpstar'],
lf['Mbin'][0], lf['Mbin'][-1], lineStyle='--')
util.saund_plot(saund['alpha'], saund['Mstar'], saund['sigma'],
10**saund['lpstar'],
lf['Mbin'][0], lf['Mbin'][-1], lineStyle=':')
plt.xlabel(plot_label(param)[1])
plt.ylabel(r'$\Phi({})$'.format(plot_label(param)[1]))
plt.ylim(2e-7, 1)
plt.draw()
out['Mbin'] = lf['Mbin']
out['Mhist'] = lf['Mhist']
out['phi'] = lf['phi']
out['phi_err'] = lf['phi_err']
fout = open(outfile, 'w')
pickle.dump(out, fout)
fout.close()
def lfnd(inFile, outFile, param_list, zmin=0.002, zmax=0.65, nz=65,
idebug=1, lf_est='bin'):
"""Multivariate distribution function given evolution parameters."""
global par, plot
par = {'progName': 'jswml.py', 'version': '1.0', 'inFile': inFile,
'zmin': zmin, 'zmax': zmax, 'idebug': idebug, 'lf_est': lf_est}
# Default log radius and sb limits
# par['rad_min'] = -0.6
# par['rad_max'] = 1.6
# par['mu_min'] = 15
# par['mu_max'] = 26
par['rad_min'] = -99
par['rad_max'] = 99
par['mu_min'] = -99
par['mu_max'] = 99
print '\n************************\njswml.py version ', par['version']
print param_list, sel_dict
samp = read_gama(inFile, param_list)
qty = samp.qty_list[0]
lf_bins = np.linspace(qty.absMin, qty.absMax, qty.nabs+1)
Q = qty.Q
print 'Q =', Q
out = {'par': par, 'qty_list': samp.qty_list}
gala = samp.calc_limits()
zbin, zhist, V, V_int = z_binning(gala, nz, (zmin, zmax))
zstep = zbin[1] - zbin[0]
S_obs, S_vis = vis_calc(gala, nz, zmin, zstep, V, V_int)
converged, Npred, delta, den_var, Pz, Vdc_max, niter = delta_solve(
P, Q, gala, nz, (zmin, zmax), zbin, zhist, V, V_int, S_vis)
# Jacknife errors on delta
delta_jack = np.zeros((njack, nz))
for jack in range(njack):
idx = (gala['ra'] < ra_jack[jack]) + (gala['ra'] >= ra_jack[jack] + 4.0)
zhist, bin_edges = np.histogram(
gala['z'][idx], nz, (zmin, zmax), weights=gala['weight'][idx])
xx, xx, delta_jack[jack, :], xx, xx, xx, xx = delta_solve(
P, Q, gala[idx], nz, (zmin, zmax), zbin, zhist,
V, V_int, S[:, idx])
delta_err = np.sqrt((njack-1) * np.var(delta_jack, axis=0))
delta_poiss_err = delta/np.sqrt(zhist)
plt.clf()
ax = plt.subplot(211)
ax.step(zbin, delta, where='mid')
ax.errorbar(zbin, delta, delta_err, fmt='none')
ax.errorbar(zbin, delta, delta_poiss_err, fmt='none')
ax.errorbar(zbin, delta, np.sqrt(den_var), fmt='none')
ax.plot([zmin, zmax], [1.0, 1.0], ':')
ax.set_ylim(0.3, 1.7)
ax.set_xlabel('Redshift z')
ax.set_ylabel(r'$\Delta(z)$')
if samp.nq > 1:
lf_bins = []
lf_range = []
absStep = 1.0
for qty in samp.qty_list:
absStep *= qty.absStep
lf_bins.append(qty.nabs)
lf_range.append((qty.absMin, qty.absMax))
Mhist, whist, phi, phi_err, edges = lfnd(gala, Vdc_max, lf_bins,
lf_range, absStep)
Mbin = edges[0][:-1] + 0.5 * samp.qty_list[0].absStep
phi_proj = (np.sum(phi, axis=tuple(range(1, samp.nq))) *
absStep/samp.qty_list[0].absStep)
Mhist_proj = np.sum(Mhist, axis=tuple(range(1, samp.nq)))
else:
lf = LF1d(gala, Vdc_max, lf_bins)
(Mbin, Mhist, whist, phi, phi_err) = (
lf.Mbin, lf.Mhist, lf.whist, lf.phi, lf.phi_err)
phi_proj = phi
edges = lf_bins
# pdb.set_trace()
schec = util.schec_fit(lf.Mbin, lf.phi, lf.phi_err,
(-1.0, -20.0, -2), sigma=lf.kde_bandwidth)
out['alpha'] = schec['alpha']
out['alpha_err'] = schec['alpha_err']
out['Mstar'] = schec['Mstar']
out['Mstar_err'] = schec['Mstar_err']
out['lpstar'] = schec['lpstar']
out['lpstar_err'] = schec['lpstar_err']
out['lf_chi2'] = schec['chi2']
out['lf_nu2'] = schec['nu']
out['kde_bandwidth'] = lf.kde_bandwidth
ax = plt.subplot(2, 1, 2)
ax.semilogy(basey=10, nonposy='clip')
ax.plot(Mbin, phi_proj)
fit = Mhist > 0
ax.set_xlabel(samp.qty_list[0].name)
ax.set_ylabel(r'$\Phi({})$'.format(samp.qty_list[0].name))
ax.set_ylim(2e-7, 1)
plt.draw()
out['P'] = P
out['P_err'] = 0
out['Q'] = samp.qty_list[0].Q
out['Q_err'] = 0
out['zbin'] = zbin
out['delta'] = delta
out['delta_err'] = delta_err
out['den_var'] = den_var
out['phi'] = phi
out['phi_err'] = phi_err
out['edges'] = edges
out['Mbin'] = Mbin
out['Mhist'] = Mhist
out['whist'] = whist
out['ev_fit_chisq'] = 0
out['ev_fit_nu'] = 1
fout = open(outFile, 'w')
pickle.dump(out, fout)
fout.close()
def ran_gen(gala, outfile, nfac, Q=Qdef, P=Pdef, vol=0):
"""Generate random distribution nfac times larger than input catalogue."""
def vol_ev(z):
"""Volume element multiplied by density evolution."""
pz = cosmo.dV(z) * den_evol(z, P)
return pz
global par
nz = par['nz']
zmin = par['zmin']
zmax = par['zmax']
print par
print sel_dict
# f = open(evfile, 'r')
# dat = pickle.load(f)
# f.close()
# P = dat['P']
# Q = dat['Q']
# print 'P, Q =', P, Q
# samp = Sample(infile, par, sel_dict)
# gala = samp.calc_limits(Q)
zbin, zhist, V, V_int = z_binning(gala, nz, (zmin, zmax))
zstep = zbin[1] - zbin[0]
S_obs, S_vis = vis_calc(gala, nz, zmin, zstep, V, V_int)
converged, Npred, delta, den_var, Pz, Vdc_max, niter = delta_solve(
P, Q, gala, nz, (zmin, zmax), zbin, zhist, V, V_int, S_vis)
V_max = np.dot(Pz * V, S_vis)
ndupe = np.round(nfac * V_max / Vdc_max).astype(np.int32)
ngal = len(gala['z'])
nran = np.sum(ndupe)
galhist, zbins = np.histogram(gala['z'], nz, (zmin, zmax))
ranhist = np.zeros(nz)
zcen = zbins[:-1] + 0.5 * (zbins[1]-zbins[0])
zstep = (zmax - zmin)/nz
info = par.copy()
info.update({'P': P, 'Q': Q, 'nfac': nfac,
'ngal': ngal, 'nran': nran,'sel_dict': sel_dict,
'galhist': list(galhist), 'zbins': list(zbins), 'zcen': list(zcen)})
fout = open(outfile, 'w')
print >> fout, info
for i in xrange(ngal):
if vol:
z = util.ran_fun(vol_ev, zmin, zmax, ndupe[i])
else:
# Avoid tail of randoms beyond highest z galaxy
# zhi = min(zmaxg, gala['zhi'][i])
z = util.ran_fun(vol_ev, gala['zlo'][i], gala['zhi'][i], ndupe[i])
for j in xrange(len(z)):
print >> fout, z[j], V_max[i], gala['weight'][i]
jz = int((z[j] - zmin)/zstep)
ranhist[jz] += 1
fout.close()
print nran, ' redshifts output'
plt.clf()
plt.step(zcen, galhist, where='mid')
plt.plot(zcen, ranhist*float(ngal)/nran)
plt.xlabel('Redshift')
plt.ylabel('Frequency')
plt.draw()
def vol_limit(Mmin, Mmax, zmin, zmax, infile='kcorrz01.fits', Q=0):
"""Form volume-limited sample between specified absolute magnitiude
and redshift limits."""
global par
par['clean_photom'] = 0
par['nz'] = 1
par['param'] = 'r_petro'
par['Mbin'] = 1
par['Mmin'] = Mmin
par['Mmax'] = Mmax
par['zmin'] = zmin
par['zmax'] = zmax