-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcorr.py
executable file
·6922 lines (6169 loc) · 246 KB
/
corr.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
# Routines for clustering analysis
from __future__ import division
from __future__ import print_function
import copy
import glob
import math
import numpy as np
import os
import os.path
import pdb
import pickle
#from astLib import astCalc
import matplotlib as mpl
if not('DISPLAY' in os.environ):
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
#from mayavi import mlab
import scipy.integrate
import scipy.interpolate
import scipy.optimize
import scipy.spatial
import scipy.stats
import subprocess
#import triangle
import warnings
from astropy.io import fits
import emcee
import h5py
import jswml
import lum
import util
# Catch invalid values in numpy calls
np.seterr(divide='warn')
np.seterr(invalid='warn')
#np.seterr(invalid='raise')
#warnings.simplefilter('error')
# Global parameters
gama_data = os.environ['GAMA_DATA']
H0 = 100
omega_l = 0.7
ln10 = math.log(10)
root2 = math.sqrt(2)
root2pi = math.sqrt(2*math.pi)
# Default evolution parameters
Qdef, Pdef = 1.0, 1.0
def_mass_limits = (8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5)
def_mag_limits = (-23, -22, -21, -20, -19, -18, -17, -16, -15)
def_binning = (-2, 2, 20, 0, 100, 100)
def_theta_max = 12
def_J3_pars = (1.84, 5.59, 30)
qsub_xi_cmd = 'qsub /research/astro/gama/loveday/Documents/Research/python/apollo_job.sh $BIN/xi {} {} {}'
qsub_xia_cmd = 'qsub /research/astro/gama/loveday/Documents/Research/python/apollo_job.sh $BIN/xi {} {}'
qsub_xix_cmd = 'qsub /research/astro/gama/loveday/Documents/Research/python/apollo_job.sh $BIN/xi {} {} {}'
# Default jackknife regions
njack = 9
ra_limits = [[129.0, 133.0], [133.0, 137.0], [137.0, 141.0],
[174.0, 178.0], [178.0, 182.0], [182.0, 186.0],
[211.5, 215.5], [215.5, 219.5], [219.5, 223.5]]
# Standard symbol and colour order for plots
#symb_list = 'os^<v>p*os^<v>p*os^<v>p*'
def_plot_size = (5, 3.5)
clr_list = 'bgrmyckbgrmyckbgrmyck'
symb_list = ('ko', 'bs', 'g^', 'r<', 'mv', 'y>', 'cp')
line_list = ('k-', 'b--', 'g:', 'r-.', 'm-', 'y--', 'c:')
sl_list = ('ko-', 'bs--', 'g^:', 'r<-.', 'mv-', 'y>--', 'cp:')
mpl.rcParams['image.cmap'] = 'viridis'
xlabel = {'xis': r'$s\ [h^{-1}{\rm Mpc}]$',
'xi2': '',
'w_p': r'$r_p\ [h^{-1}{\rm Mpc}]$',
'xir': r'$r\ [h^{-1}{\rm Mpc}]$', 'bias': r'$M_r$'}
ylabel = {'xis': r'$\xi(s)$', 'xi2': '',
'w_p': r'$w_p(r_p)$', 'xir': r'$\xi(r)$',
'bias': r'$b(M) / b(M^*)$'}
# Directory to save plots
plot_dir = os.environ['HOME'] + '/Documents/tex/papers/gama/pvd/'
# -----
# Tests
# -----
def test(infile=gama_data+'/jswml/auto/kcorrz01.fits', ran_dist='vol',
Q=Qdef, P=Pdef, key='w_p', xlimits=(0.01, 100)):
"""Test basic functionality of sample selection, correlation function
calculation and plotting on a small data sample."""
Mlimits = (-22, -21)
zlimits = util.vol_limits(infile, Q=Q, Mlims=Mlimits)
z_range = [0.002, zlimits[1]]
galout = 'gal_test.dat'
ranout = 'ran_test.dat'
xiout = 'xi_test.dat'
xi_select(infile, galout, ranout, xiout,
z_range=z_range, nz=20, app_range=(14, 19.8),
abs_range=Mlimits,
Q=Q, P=P, ran_dist=ran_dist, ran_fac=1)
# Run the clustering code executable in $BIN/xi, compiled from xi.c
# cmd = '$BIN/xi {} {} {}'.format(galout, ranout, xiout)
# subprocess.call(cmd, shell=True)
cmd = '$BIN/xi {} {}'.format(galout, 'gg_test.dat')
subprocess.call(cmd, shell=True)
cmd = '$BIN/xi {} {} {}'.format(galout, ranout, 'gr_test.dat')
subprocess.call(cmd, shell=True)
cmd = '$BIN/xi {} {}'.format(ranout, 'rr_test.dat')
subprocess.call(cmd, shell=True)
# Plot the results
panels = []
comps = []
label = 'Test'
panels.append({'files': (xiout, ), 'comps': comps, 'label': label})
xi_plot(key, panels, xlimits=xlimits)
plt.show()
xi2d_plot(xiout, binning=0, mirror=0)
plt.show()
xi2d_plot(xiout, binning=1, mirror=0)
plt.show()
xi2d_plot(xiout, binning=2, mirror=0)
plt.show()
# xi_plot('xi2', panels, binning=0, xlimits=xlimits)
# xi_plot('xi2', panels, binning=1, xlimits=xlimits)
# xi_plot('xi2', panels, binning=2, xlimits=xlimits)
def xtest(infile=gama_data+'/jswml/auto/kcorrz01.fits', ran_dist='vol',
Q=Qdef, P=Pdef, key='w_p', xlimits=(0.01, 100), run=1,
pi_lim=100, rp_lim=100, onevol=0):
"""Test cross-correlation using two luminsoity-selected samples
within a volume-limited sample if onevol is True."""
if run > 0:
Mlimits = (-21, -20, -19)
if onevol:
zlimits = util.vol_limits(infile, Q=Q, Mlims=(Mlimits[-1],))
else:
zlimits = util.vol_limits(infile, Q=Q, Mlims=Mlimits[1:3])
for ilim in xrange(2):
if onevol:
z_range = [0.002, zlimits[0]]
else:
z_range = [0.002, zlimits[ilim]]
Mrange = Mlimits[ilim:ilim+2]
galout = 'gal_test_{}.dat'.format(ilim)
ranout = 'ran_test_{}.dat'.format(ilim)
xiout = 'xi_test_{}.dat'.format(ilim)
xi_select(infile, galout, ranout, xiout,
z_range=z_range, nz=20, app_range=(14, 19.8),
abs_range=Mrange,
Q=Q, P=P, ran_dist=ran_dist, ran_fac=5, run=run)
# Cross counts
if run == 1:
cmd = '$BIN/xi {} {} {}'.format('gal_test_0.dat', 'gal_test_1.dat',
'gg_test_x.dat')
subprocess.call(cmd, shell=True)
cmd = '$BIN/xi {} {} {}'.format('gal_test_0.dat', 'ran_test_1.dat',
'gr_test_x.dat')
subprocess.call(cmd, shell=True)
if run == 2:
cmd = qsub_xix_cmd.format('gal_test_0.dat', 'gal_test_1.dat',
'gg_test_x.dat')
subprocess.call(cmd, shell=True)
cmd = qsub_xix_cmd.format('gal_test_0.dat', 'ran_test_1.dat',
'gr_test_x.dat')
subprocess.call(cmd, shell=True)
# Plot the results
panels = []
comps = []
label = 'Test'
panels.append({'files': ('xi_test_0.dat', 'xi_test_1.dat'),
'comps': comps, 'label': label})
xi_plot(key, panels, xlimits=xlimits)
plt.show()
# xi2d_plot(xiout, binning=0, mirror=0)
# plt.show()
# xi2d_plot(xiout, binning=1, mirror=0)
# plt.show()
# xi2d_plot(xiout, binning=2, mirror=0)
# plt.show()
Gg = PairCounts('gg_test_x.dat')
Gr = PairCounts('gr_test_x.dat')
gr = PairCounts('gr_test_1.dat')
rr = PairCounts('rr_test_1.dat')
counts = {'Gg': Gg, 'Gr': Gr, 'gr': gr, 'rr': rr}
xi = Xi()
w_p_dpx = xi.est(counts, dpx, key=key, pi_lim=pi_lim, rp_lim=rp_lim)
w_p_lsx = xi.est(counts, lsx, key=key, pi_lim=pi_lim, rp_lim=rp_lim)
plt.clf()
ax = plt.subplot(111)
w_p_dpx.plot(ax, label='DPX')
w_p_lsx.plot(ax, label='LSX')
ax.loglog(basex=10, basey=10, nonposy='clip')
ax.set_xlabel(r'$r_p\ [h^{-1}{\rm Mpc}]$')
ax.set_ylabel(r'$w_p(r_p)$')
ax.legend()
plt.show()
# -------
# Classes
# -------
class Cat(object):
"""Galaxy or random catalogue."""
def __init__(self, ra, dec, r, weight=None, den=None, Vmax=None, info=""):
# Trim tail of high-redshift objects
idx = r < info['rcut']
ra, dec, r = ra[idx], dec[idx], r[idx]
try:
weight, den, Vmax = weight[idx], den[idx], Vmax[idx]
except:
pass
self.nobj = len(ra)
self.ra = ra
self.dec = dec
self.x = r*np.cos(np.deg2rad(ra))*np.cos(np.deg2rad(dec))
self.y = r*np.sin(np.deg2rad(ra))*np.cos(np.deg2rad(dec))
self.z = r*np.sin(np.deg2rad(dec))
if weight is None: weight = np.ones(self.nobj)
self.weight = weight
if den is None: den = np.ones(self.nobj)
self.den = den
if Vmax is None: Vmax = np.ones(self.nobj)
self.Vmax = Vmax
self.info = info
def output(self, outfile, binning=def_binning, theta_max=def_theta_max,
J3_pars=def_J3_pars):
"""Output the galaxy or random data for xi.c v 2.1."""
# 3 jackknife regions per GAMA field (each 4x4 deg). Single cell.
ncell = 1
ix = 0
iy = 0
iz = 0
cellsize = 100.0
njack = self.info['njack']
print('Writing out ', outfile)
fout = open(outfile, 'w')
print(self.info, file=fout)
print(self.nobj, ncell, ncell, njack, cellsize,
binning[0], binning[1], binning[2],
binning[3], binning[4], binning[5],
theta_max, J3_pars[0], J3_pars[1], J3_pars[2], file=fout)
print(ix, iy, iz, self.nobj, file=fout)
for i in xrange(self.nobj):
if njack > 1:
for ireg in range(njack):
if (ra_limits[ireg][0] <= self.ra[i] <= ra_limits[ireg][1]):
ijack = ireg
else:
ijack = 0
print(self.x[i], self.y[i], self.z[i], self.weight[i],
self.den[i], self.Vmax[i], ijack, file=fout)
fout.close()
class PairCounts(object):
"""Class to hold pair counts."""
def __init__(self, infile=None, pi_rebin=1, rp_rebin=1):
"""Read pair counts from file if specified with optional rebinning."""
if infile is None:
return
f = open(infile, 'r')
f.readline()
self.info = eval(f.readline())
args = f.readline().split()
self.na = float(args[0])
self.nb = float(args[1])
self.njack = int(args[2])
self.n2d = int(args[3])
# Read direction-averaged counts
args = f.readline().split()
self.ns = int(args[0])
self.smin = float(args[1])
self.smax = float(args[2])
self.sep = np.zeros(self.ns)
self.pc = np.zeros((self.ns, self.njack+1))
for i in range(self.ns):
data = f.readline().split()
self.sep[i] = float(data[0])
self.pc[i, :] = map(float, data[1:])
if self.nb > 0:
self.pcn = self.pc/self.na/self.nb
else:
self.pcn = 2*self.pc/self.na/(self.na - 1)
# Read counts for 2d binnings
self.pc2_list = []
for i2d in range(self.n2d):
args = f.readline().split()
nrp = int(args[0])
rpmin = float(args[1])
rpmax = float(args[2])
npi = int(args[3])
pimin = float(args[4])
pimax = float(args[5])
pi = np.zeros((npi, nrp))
rp = np.zeros((npi, nrp))
pc = np.zeros((npi, nrp, self.njack+1))
for i in range(nrp):
for j in range(npi):
data = f.readline().split()
pi[j, i] = float(data[0])
rp[j, i] = float(data[1])
pc[j, i, :] = map(float, data[2:])
# Rebin counts
if rp_rebin * pi_rebin > 1:
npibin = npi//pi_rebin
nrpbin = nrp//rp_rebin
pibin = np.zeros((npibin, nrpbin))
rpbin = np.zeros((npibin, nrpbin))
pcbin = np.zeros((npibin, nrpbin, self.njack+1))
for i in range(0, nrp, rp_rebin):
ib = i//rp_rebin
for j in range(0, npi, pi_rebin):
jb = j//pi_rebin
for ii in range(i, min(nrp, i + rp_rebin)):
for jj in range(j, min(npi, j + pi_rebin)):
pibin[jb, ib] += pc[jj, ii, 0] * pi[jj, ii]
rpbin[jb, ib] += pc[jj, ii, 0] * rp[jj, ii]
pcbin[jb, ib, :] += pc[jj, ii, :]
if pcbin[jb, ib, 0] > 0:
pibin[jb, ib] /= pcbin[jb, ib, 0]
rpbin[jb, ib] /= pcbin[jb, ib, 0]
npi = npibin
nrp = nrpbin
pi = pibin
rp = rpbin
pc = pcbin
if self.nb > 0:
pcn = pc/self.na/self.nb
else:
pcn = 2*pc/self.na/(self.na - 1)
self.pc2_list.append(
{'npi': npi, 'pimin': pimin, 'pimax': pimax, 'pi': pi,
'nrp': nrp, 'rpmin': rpmin, 'rpmax': rpmax, 'rp': rp,
'pc': pc, 'pcn': pcn})
f.close()
def sum(self, pcs):
"""Sum over GAMA regions."""
nest = len(pcs)
ests = xrange(nest)
self.na = np.sum([pcs[i].na for i in ests])
self.nb = np.sum([pcs[i].nb for i in ests])
self.njack = pcs[0].njack
self.n2d = pcs[0].n2d
self.info = pcs[0].info
# Direction-averaged counts
self.ns = pcs[0].ns
self.smin = pcs[0].smin
self.smax = pcs[0].smax
self.sep = np.ma.average(
[pcs[i].sep for i in ests], axis=0,
weights=[pcs[i].pc[:, 0] for i in ests]).filled(0)
self.pc = np.zeros((self.ns, self.njack+1))
self.pc[:, 0] = np.sum([pcs[i].pc[:, 0] for i in ests], axis=0)
# Counts for 2d binnings
self.pc2_list = []
for i2d in range(self.n2d):
nrp = pcs[0].pc2_list[i2d]['nrp']
rpmin = pcs[0].pc2_list[i2d]['rpmin']
rpmax = pcs[0].pc2_list[i2d]['rpmax']
npi = pcs[0].pc2_list[i2d]['npi']
pimin = pcs[0].pc2_list[i2d]['pimin']
pimax = pcs[0].pc2_list[i2d]['pimax']
pi = np.ma.average(
[pcs[i].pc2_list[i2d]['pi'] for i in ests], axis=0,
weights=[pcs[i].pc2_list[i2d]['pc'][:, :, 0]
for i in ests]).filled(0)
rp = np.ma.average(
[pcs[i].pc2_list[i2d]['rp'] for i in ests], axis=0,
weights=[pcs[i].pc2_list[i2d]['pc'][:, :, 0]
for i in ests]).filled(0)
pc = np.zeros((npi, nrp, self.njack+1))
pc[:, :, 0] = np.sum([pcs[i].pc2_list[i2d]['pc'][:, :, 0]
for i in ests], axis=0)
self.pc2_list.append(
{'npi': npi, 'pimin': pimin, 'pimax': pimax, 'pi': pi,
'nrp': nrp, 'rpmin': rpmin, 'rpmax': rpmax, 'rp': rp,
'pc': pc})
def average(self, pcs):
"""Average over different estimates."""
nest = len(pcs)
ests = xrange(nest)
self.na = np.mean([pcs[i].na for i in ests])
self.nb = np.mean([pcs[i].nb for i in ests])
self.njack = nest
self.n2d = pcs[0].n2d
self.info = pcs[0].info
# Direction-averaged counts
self.ns = pcs[0].ns
self.smin = pcs[0].smin
self.smax = pcs[0].smax
self.sep = np.ma.average(
[pcs[i].sep for i in ests], axis=0,
weights=[pcs[i].pc[:, 0] for i in ests]).filled(0)
self.pc = np.zeros((self.ns, self.njack+1))
self.pc[:, 0] = np.mean([pcs[i].pc[:, 0] for i in ests], axis=0)
self.pc[:, 1:] = np.array([pcs[i].pc[:, 0] for i in ests]).T
# pdb.set_trace()
# Counts for 2d binnings
self.pc2_list = []
for i2d in range(self.n2d):
nrp = pcs[0].pc2_list[i2d]['nrp']
rpmin = pcs[0].pc2_list[i2d]['rpmin']
rpmax = pcs[0].pc2_list[i2d]['rpmax']
npi = pcs[0].pc2_list[i2d]['npi']
pimin = pcs[0].pc2_list[i2d]['pimin']
pimax = pcs[0].pc2_list[i2d]['pimax']
pi = np.ma.average(
[pcs[i].pc2_list[i2d]['pi'] for i in ests], axis=0,
weights=[pcs[i].pc2_list[i2d]['pc'][:, :, 0]
for i in ests]).filled(0)
rp = np.ma.average(
[pcs[i].pc2_list[i2d]['rp'] for i in ests], axis=0,
weights=[pcs[i].pc2_list[i2d]['pc'][:, :, 0]
for i in ests]).filled(0)
pc = np.zeros((npi, nrp, self.njack+1))
pc[:, :, 0] = np.mean([pcs[i].pc2_list[i2d]['pc'][:, :, 0]
for i in ests], axis=0)
pc[:, :, 1:] = np.transpose(np.array(
[pcs[i].pc2_list[i2d]['pc'][:, :, 0] for i in ests]),
(1, 2, 0))
self.pc2_list.append(
{'npi': npi, 'pimin': pimin, 'pimax': pimax, 'pi': pi,
'nrp': nrp, 'rpmin': rpmin, 'rpmax': rpmax, 'rp': rp,
'pc': pc})
def write(self, outfile):
"""Write pair counts to file."""
f = open(outfile, 'w')
print('PairCounts.write() output', file=f)
print(self.info, file=f)
print(self.na, self.nb, self.njack, self.n2d, file=f)
print(self.ns, self.smin, self.smax, file=f)
for i in range(self.ns):
print(self.sep[i], ' '.join(map(str, self.pc[i, :])), file=f)
for i2d in range(self.n2d):
pc2 = self.pc2_list[i2d]
print(pc2['nrp'], pc2['rpmin'], pc2['rpmax'],
pc2['npi'], pc2['pimin'], pc2['pimax'], file=f)
for i in range(pc2['nrp']):
for j in range(pc2['npi']):
print(pc2['pi'][j, i], pc2['rp'][j, i],
' '.join(map(str, pc2['pc'][j, i, :])), file=f)
f.close()
class Xi(object):
"""Class to hold clustering estimates."""
def __init__(self):
"""Placeholder initialiser."""
def est(self, counts, estimator, key='w_p', binning=1,
pi_lim=100, rp_lim=100):
"""Calculate xi(s) and xi(rp,pi) from pair counts
using specified estimator."""
if 'Gg' in counts:
galpairs = counts['Gg']
else:
galpairs = counts['gg']
if 'rr' in counts:
ranpairs = counts['rr']
else:
ranpairs = counts['Gr']
self.info = galpairs.info
self.njack = galpairs.njack
self.n2d = galpairs.n2d
self.err_type = self.info['err_type']
# Direction-averaged xi(s)
ns = galpairs.ns
smin = galpairs.smin
smax = galpairs.smax
xis = Xi1d(ns, self.njack, smin, smax, 'xis', self.err_type)
xis.sep = galpairs.sep
xis.galpairs = galpairs.pc[:, 0]
xis.ranpairs = ranpairs.pc[:, 0]
xis.est = estimator(counts, -1)
# xi(r_p, pi) and w_p(r_p) for 2d binnings
xi2_list = []
for i2d in range(self.n2d):
gal2 = galpairs.pc2_list[i2d]
ran2 = ranpairs.pc2_list[i2d]
nrp = gal2['nrp']
rpmin = gal2['rpmin']
rpmax = gal2['rpmax']
npi = gal2['npi']
pimin = gal2['pimin']
pimax = gal2['pimax']
rpstep = (rpmax - rpmin)/nrp
pistep = (pimax - pimin)/npi
if pimin < 0:
pilim = min(pimax, math.log10(pi_lim))
else:
pilim = min(pimax, pi_lim)
npi_use = int((pilim - pimin)/pistep)
pilim = pimin + npi_use*pistep
if rpmin < 0:
rplim = min(rpmax, math.log10(rp_lim))
else:
rplim = min(rpmax, rp_lim)
nrp_use = int((rplim - rpmin)/rpstep)
rplim = rpmin + nrp_use*rpstep
xi2 = Xi2d(nrp_use, rpmin, rplim, npi_use, pimin, pilim,
self.njack, self.err_type)
xi2.pi = gal2['pi'][:npi_use, :nrp_use]
xi2.rp = gal2['rp'][:npi_use, :nrp_use]
xi2.galpairs = gal2['pc'][:npi_use, :nrp_use]
xi2.ranpairs = ran2['pc'][:npi_use, :nrp_use]
xi2.est = estimator(counts, i2d)[:npi_use, :nrp_use, :]
xi2_list.append(xi2)
self.xis = xis
self.xi2_list = xi2_list
if key == 'xis':
xis = self.xis
xis.clear_empties()
xis.cov = Cov(xis.est[:, 1:], self.err_type)
return xis
xi2 = self.xi2_list[binning]
if key == 'xi2':
# xi2.cov = Cov(xi2.est[:, :, 1:], self.err_type)
return xi2
w_p = xi2.w_p(rp_lim, pi_lim)
if key == 'w_p':
w_p.cov = Cov(w_p.est[:, 1:], self.err_type)
return w_p
xir = w_p.xir()
xir.cov = Cov(xir.est[:, 1:], self.err_type)
return xir
class Xi1d(object):
"""1d clustering estimate, including jackknife sub-estimates."""
def __init__(self, nbin, njack, rmin, rmax, xi_type, err_type):
self.nbin = nbin
self.njack = njack
self.rmin = rmin
self.rmax = rmax
self.rstep = (rmax - rmin)/nbin
self.sep = np.zeros(nbin)
self.galpairs = np.zeros(nbin)
self.ranpairs = np.zeros(nbin)
self.est = np.zeros((nbin, njack+1))
self.ic = 0.0
self.xi_type = xi_type
self.err_type = err_type
def clear_empties(self):
"""Remove any empty bins with zero galaxy-galaxy pairs."""
keep = self.galpairs > 0
self.sep, self.galpairs, self.ranpairs, self.est = \
self.sep[keep], self.galpairs[keep], self.ranpairs[keep],\
self.est[keep]
self.nbin = len(self.sep)
return self.nbin
def xir(self):
"""Inversion of w_p(r_p) to xi(r) - Saunders et al 1992, eq 26.
Assumes log binning."""
def invert(rp, wp, njack):
nbin = len(rp)
xi = np.zeros((nbin-1, njack+1))
for i in range(nbin-1):
sum = 0.0
for j in range(i, nbin-1):
try:
sum += ((wp[j+1, :] - wp[j, :])/(rp[j+1] - rp[j]) *
math.log((rp[j+1] +
math.sqrt(rp[j+1]**2 - rp[i]**2)) /
(rp[j] + math.sqrt(rp[j]**2 - rp[i]**2))))
except:
pass
xi[i, :] = -sum/math.pi
return xi
xir = Xi1d(self.nbin-1, self.njack, self.rmin, self.rmax,
'xir', self.err_type)
xir.sep = self.sep[:-1]
xir.galpairs = self.galpairs[:-1]
xir.ranpairs = self.ranpairs[:-1]
xir.est = invert(self.sep, self.est, self.njack)
# for ijack in range(self.njack):
# xir.jack[:, ijack] = invert(self.sep, self.jack[:, ijack])
xir.cov = Cov(xir.est[:, 1:], xir.err_type)
return xir
def ic_calc(self, gamma, r0, ic_rmax):
"""Returns estimated integral constraint for power law xi(r)
truncated at ic_rmax."""
xi_mod = np.zeros(len(self.sep))
pos = (self.sep > 0) * (self.sep < ic_rmax)
xi_mod[pos] = (self.sep[pos]/r0)**-gamma
self.ic = (self.ranpairs * xi_mod).sum() / (self.ranpairs).sum()
def plot(self, ax, jack=0, color=None, fout=None, label=None, pl_div=None):
if pl_div:
pl_fit = (self.sep/pl_div[0])**(- pl_div[1])
else:
pl_fit = 1
# if color:
ax.errorbar(self.sep, self.est[:, jack]/pl_fit + self.ic,
self.cov.sig/pl_fit,
fmt='o', color=color, label=label, capthick=1)
# else:
# ax.errorbar(self.sep, self.est[:, jack] + self.ic, self.cov.sig,
# fmt='o', label=label, capthick=1)
if fout:
print(label, file=fout)
for i in range(self.nbin):
print(self.sep[i], self.est[i, jack] + self.ic,
self.cov.sig[i], file=fout)
def fit(self, fit_range, jack=0, logfit=0, ic_rmax=0, neig=0,
verbose=1, ax=None, cov_ax=None, covn_ax=None, color=None):
"""Fit a power law to main and jackknife estimates."""
def dofit(x, y, cov, neig=neig):
"""Do the fit."""
def fit_chi2(p, x, y, cov, neig):
# returns chi^2 for given power-law parameters p
if logfit:
fit = x*p[1] + p[0]
else:
fit = (x/p[0])**-p[1]
return cov.chi2(y, fit, neig)
pinit = [5.0, 1.8]
out = scipy.optimize.fmin(fit_chi2, pinit, args=(x, y, cov, neig),
full_output=1, disp=0)
p = out[0]
chisq = out[1]
if neig in(0, 'all', 'full'):
nu = len(x) - 2
else:
nu = neig - 2
if logfit:
gamma = -p[1]
r0 = math.exp(-p[0]/p[1])
else:
gamma = p[1]
r0 = p[0]
if self.xi_type == 'w_p':
gamma += 1
r0 = (r0**(gamma-1)/scipy.special.gamma(0.5) /
scipy.special.gamma(0.5*(gamma-1)) *
scipy.special.gamma(0.5*gamma))**(1.0/gamma)
return gamma, r0, p, chisq, nu
idx = ((fit_range[0] < self.sep) * (self.sep < fit_range[1]) *
(self.galpairs > 0) * np.all(self.est > 0, axis=1))
if len(self.sep[idx]) < 2:
print('Insufficient valid bins for fit')
# pdb.set_trace()
return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
if logfit:
sep = np.log(self.sep[idx])
est = np.log(self.est[idx, :])
else:
sep = self.sep[idx]
est = self.est[idx, :]
cov = Cov(est[:, 1:], self.err_type)
if cov_ax:
cov.plot(ax=cov_ax)
if covn_ax:
cov.plot(norm=1, ax=covn_ax)
# Main estimate
if ic_rmax:
dic = 1
niter = 0
while dic > 0.01 and niter < 10:
ic_old = self.ic
y = est[:, jack] + self.ic
gamma, r0, p, chisq, nu = dofit(sep, y, cov, neig)
self.ic_calc(p[1], p[0], ic_rmax)
dic = math.fabs(self.ic - ic_old)
niter += 1
if dic > 0.01:
print('IC failed to converge', self.ic, ic_old)
else:
y = est[:, jack]
gamma, r0, p, chisq, nu = dofit(sep, y, cov, neig)
fra = np.array(fit_range)
if logfit:
yfit = np.exp(p[1]*np.log(fra) + p[0])
else:
yfit = (fra/p[0])**-p[1]
if ax:
if color:
ax.plot(fra, yfit, color=color)
else:
ax.plot(fra, yfit)
# Jackknife estimates
r0_jack = []
gamma_jack = []
for ijack in xrange(self.njack):
y = est[:, ijack+1] + self.ic
gamma_j, r0_j, p, chisq_j, nu_j = dofit(sep, y, cov, neig)
if not(math.isnan(gamma_j)) and not(math.isnan(r0_j)):
gamma_jack.append(gamma_j)
r0_jack.append(r0_j)
gamma_err = jack_err(gamma_jack, self.err_type)
r0_err = jack_err(r0_jack, self.err_type)
if verbose:
print('gamma {:4.2f}+/-{:4.2f} r_0 {:4.2f}+/-{:4.2f} chi^2/nu {:4.2f}/{:2d} IC {:4.2f}'.format(
gamma, gamma_err, r0, r0_err, chisq, nu, self.ic))
return gamma, gamma_err, r0, r0_err, self.ic, gamma_jack, r0_jack
def interp(self, r, jack=0, log=False):
"""Returns interpolated value and error (zero for r > r_max).
Interpolates in log-log space if log=True."""
if log:
return np.expm1(np.interp(np.log(r), np.log(self.sep),
np.log1p(self.est[:, jack]), right=0)), \
np.expm1(np.interp(np.log(r), np.log(self.sep),
np.log1p(self.cov.sig)))
else:
return np.interp(r, self.sep, self.est[:, jack], right=0), \
np.interp(r, self.sep, self.cov.sig)
class Xi2d(object):
"""2d clustering estimate."""
def __init__(self, nrp, rpmin, rpmax, npi, pimin, pimax, njack, err_type):
self.nrp = nrp
self.rpmin = rpmin
self.rpmax = rpmax
self.rpstep = (rpmax - rpmin)/nrp
self.rpc = rpmin + (np.arange(nrp) + 0.5) * self.rpstep
if rpmin < 0:
self.rpc = 10**self.rpc
self.npi = npi
self.pimin = pimin
self.pimax = pimax
self.pistep = (pimax - pimin)/npi
self.pic = pimin + (np.arange(npi) + 0.5) * self.pistep
if pimin < 0:
self.pic = 10**self.pic
self.rp, self.pi = np.meshgrid(self.rpc, self.pic)
self.njack = njack
self.est = np.zeros((npi, nrp, njack+1))
self.err_type = err_type
self.galpairs = np.zeros((npi, nrp, njack+1))
self.ranpairs = np.zeros((npi, nrp, njack+1))
def reflect(self, axes=(0, 1)):
"""Reflect 2d correlation function about specified axes."""
# Ensure that axes is a tuple
try:
n = len(axes)
except:
axes = (axes,)
npi = self.npi
pi0 = 0
nrp = self.nrp
rp0 = 0
pimin = self.pimin
pimax = self.pimax
rpmin = self.rpmin
rpmax = self.rpmax
if 0 in axes:
pi0 = npi
npi *= 2
pimin = -pimax
if 1 in axes:
rp0 = nrp
nrp *= 2
rpmin = -rpmax
xir = Xi2d(nrp, rpmin, rpmax, npi, pimin, pimax,
self.njack, self.err_type)
xir.est[pi0:, rp0:, :] = self.est
xir.pi[pi0:, rp0:] = self.pi
xir.rp[pi0:, rp0:] = self.rp
xir.pic[pi0:] = self.pic
xir.rpc[rp0:] = self.rpc
if 1 in axes:
xir.est[pi0:, :rp0, :] = np.fliplr(self.est)
xir.pi[pi0:, :rp0] = np.fliplr(self.pi)
xir.rp[pi0:, :rp0] = np.fliplr(self.rp)
xir.rpc[:rp0] = -self.rpc[::-1]
if 0 in axes:
xir.est[:pi0, rp0:, :] = np.flipud(self.est)
xir.pi[:pi0, rp0:] = np.flipud(self.pi)
xir.rp[:pi0, rp0:] = np.flipud(self.rp)
xir.pic[:pi0] = -self.pic[::-1]
if 0 in axes and 1 in axes:
xir.est[:pi0, :rp0, :] = np.flipud(np.fliplr(self.est))
xir.pi[:pi0, :rp0] = np.flipud(np.fliplr(self.pi))
xir.rp[:pi0, :rp0] = np.flipud(np.fliplr(self.rp))
# xir.cov = Cov(xir.est[:, :, 1:], self.err_type)
return xir
def beta_model(self, beta, xir=None, r0=None, gamma=None, meansep=0,
interplog=0, epsabs=1e-5, epsrel=1e-5):
"""Kaiser/Hamilton model of 2d correlation function."""
fac0 = 1 + 2*beta/3 + beta**2/5
fac2 = 4*beta/3 + 4*beta**2/7
fac4 = 8*beta**2/35
if meansep:
# Use mean separation rather than bin centres
rpgrid = self.rp
pigrid = self.pi
else:
rpgrid, pigrid = np.meshgrid(self.rpc, self.pic)
s = (rpgrid**2 + pigrid**2)**0.5
mu = pigrid / s
P2 = 0.5*(3*mu**2 - 1)
P4 = 0.125*(35*mu**4 - 30*mu**2 + 3)
if xir:
xi0 = np.interp(s, xir.r, xir.xi0, right=0)
xi2 = np.interp(s, xir.r, xir.xi2, right=0)
xi4 = np.interp(s, xir.r, xir.xi4, right=0)
self.est[:, :, 0] = xi0*fac0 + xi2*fac2*P2 + xi4*fac4*P4
# pdb.set_trace()
else:
xi = (s/r0)**-gamma
self.est[:, :, 0] = xi*(fac0 + fac2*(gamma/(gamma-3))*P2 +
fac4*gamma*(2+gamma)/(3-gamma)/(5-gamma)*P4)
def plot(self, ax, what='logxi', jack=0, prange=(-2, 2), mirror=True,
cbar=True, cmap=None, aspect='auto'):
nrp = self.nrp
npi = self.npi
if what == 'logxi':
label = r'$\log\ \xi$'
dat = self.est[:npi, :nrp, jack]
if what == 'log1xi':
label = r'$\log\ (1 + \xi)$'
dat = self.est[:npi, :nrp, jack] + 1
if what == 'logxierr':
label = r'$\log\ \epsilon_\xi$'
dat = self.cov.sig[:npi, :nrp]
if what == 'sn':
label = r'$\log\ (s/n)$'
dat = self.est[:npi, :nrp, jack] / self.cov.sig[:npi, :nrp]
logdat = np.zeros((npi, nrp)) + prange[0]
pos = dat > 0
logdat[pos] = np.log10(dat[pos])
if mirror:
# Reflect about axes
ximap = np.zeros((2*npi, 2*nrp))
ximap[npi:, nrp:] = logdat
ximap[npi:, :nrp] = np.fliplr(logdat)
ximap[:npi, nrp:] = np.flipud(logdat)
ximap[:npi, :nrp] = np.flipud(np.fliplr(logdat))
extent = (-self.rpmax, self.rpmax, -self.pimax, self.pimax)
else:
ximap = np.flipud(logdat)
extent = (self.rpmin, self.rpmax, self.pimin, self.pimax)
# aspect = self.pimax/self.rpmax
# print aspect, extent
# aspect = 1
# if self.rpmin * self.pimin > 0:
im = ax.imshow(ximap, cmap, aspect=aspect, interpolation='none',
vmin=prange[0], vmax=prange[1],
extent=extent)
ax.set_xlabel(r'$r_\perp\ [h^{-1} {{\rm Mpc}}]$')
ax.set_ylabel(r'$r_\parallel\ [h^{-1} {{\rm Mpc}}]$')
# divider = make_axes_locatable(ax)
# cax = divider.append_axes("top", size="5%", pad=0.5)
if what == 'logxi':
Li_cont = [0.1875]
while Li_cont[-1] < 48:
Li_cont.append(2*Li_cont[-1])
Li_cont = np.log10(Li_cont)
cont = ax.contour(np.flipud(ximap), Li_cont, aspect=aspect,
extent=extent)
# cb = plt.colorbar(im, cax=cax, orientation='horizontal')
# cb = plt.colorbar(im, cax=ax)
if cbar:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cb = plt.colorbar(im, cax=cax)
cb.set_label(label)
def vdist(self, lgximin=-2, hsmooth=0, neig=0, plots=1):
"""Velocity distribution function via Fourier transform of
2d correlation function."""
def vdist_samp(ximap, plots):
"""Velocity distribution for single xi."""
pk = np.fft.fftshift(np.fft.fft2(ximap))
freq = np.fft.fftshift(np.fft.fftfreq(nrp, 2*self.rpmax/nrp))
kextent = (freq[0], freq[-1], freq[0], freq[-1])
ratio = np.zeros(npi)
pklim = 0.001*np.max(pk)
use = np.abs(pk[nrp//2, :]) > pklim
ratio[use] = pk[use, npi//2] / pk[nrp//2, use]
# ratio = np.ma.masked_invalid(pk[:, npi//2] / pk[nrp//2, :])
fv = np.abs(np.fft.fftshift(np.fft.ifft(ratio)))
v = np.fft.fftshift(np.fft.fftfreq(nrp, (freq[-1]-freq[0])/(nrp)))
# pdb.set_trace()
if plots > 0:
plt.clf()
im = plt.imshow(np.abs(pk), aspect=aspect,
interpolation='none', extent=kextent)
plt.xlabel(r'$k_\bot\ [h\ {\rm Mpc}^{-1}]$')
plt.ylabel(r'$k_\parallel\ [h\ {\rm Mpc}^{-1}]$')
plt.title('FT(Xi)')
plt.colorbar()
plt.show()
plt.clf()
fig, axes = plt.subplots(3, 1, sharex=True, num=1)
fig.set_size_inches(3, 6)
fig.subplots_adjust(hspace=0, wspace=0)
ax = axes[0]
ax.plot(freq, np.abs(pk[nrp//2, :]))
ax.set_ylabel(r'$\hat\xi(k_\bot)$')
ax = axes[1]
ax.plot(freq, np.abs(pk[:, npi//2]))
ax.set_ylabel(r'$\hat\xi(k_\parallel)$')
ax = axes[2]
ax.plot(freq, np.abs(ratio))
ax.set_ylabel(r'$F(k)$')
ax.set_xlabel(r'$k\ [h\ {\rm Mpc}^{-1}]$')
plt.show()
plt.clf()
plt.plot(v, fv)
plt.xlabel(r'$v\ [100\ \mathrm{km\ s}^{-1}]$')
plt.ylabel(r'$f(v)$')
return freq[nrp//2:], ratio[nrp//2:], v[nrp//2:], fv[nrp//2:]
nrp = self.nrp
npi = self.npi
aspect = self.pimax/self.rpmax
if hsmooth:
rpgrid, pigrid = np.meshgrid(np.arange(nrp), np.arange(npi))
hann = (np.sin(math.pi * rpgrid / (nrp-1)) *
np.sin(math.pi * pigrid / (npi-1)))**2
else:
hann = 1
freq, ratio, v, fv = vdist_samp(hann*self.est[:, :, 0], plots)
if self.njack > 0:
ratio_jack = np.zeros((len(fv), self.njack))
fv_jack = np.zeros((len(fv), self.njack))
for ijack in xrange(self.njack):
freq, ratio_jack[:, ijack], v, fv_jack[:, ijack] = vdist_samp(