-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy paththumbstack.py
More file actions
2195 lines (1827 loc) · 90.7 KB
/
thumbstack.py
File metadata and controls
2195 lines (1827 loc) · 90.7 KB
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
from headers import *
##################################################################################
##################################################################################
class ThumbStack(object):
# def __init__(self, U, Catalog, pathMap="", pathMask="", pathHit="", name="test", nameLong=None, save=False, nProc=1):
def __init__(self, U, Catalog, cmbMap, cmbMask, cmbHit=None, name="test", nameLong=None, save=False, nProc=1, filterTypes='diskring', doStackedMap=False, doMBins=False, doVShuffle=False, doBootstrap=False, cmbNu=150.e9, cmbUnitLatex=r'$\mu$K'):
self.nProc = nProc
self.U = U
self.Catalog = Catalog
self.name = name
if nameLong is None:
self.nameLong = self.name
else:
self.nameLong = nameLong
self.cmbMap = cmbMap
self.cmbMask = cmbMask
self.cmbHit = cmbHit
self.doMBins = doMBins
self.doVShuffle = doVShuffle
self.doBootstrap = doBootstrap
self.cmbNu = cmbNu
self.cmbUnitLatex = cmbUnitLatex
# aperture photometry filters to implement
if filterTypes=='diskring':
self.filterTypes = np.array(['diskring'])
elif filterTypes=='disk':
self.filterTypes = np.array(['disk'])
elif filterTypes=='ring':
self.filterTypes = np.array(['ring'])
elif filterTypes=='all':
self.filterTypes = np.array(['diskring', 'disk', 'ring'])
# estimators (ksz, tsz) and weightings (uniform, hit, var, ...)
# for stacked profiles, bootstrap cov and v-shuffle cov
if self.cmbHit is not None:
self.Est = ['tsz_uniformweight', 'tsz_varweight'] #['tsz_uniformweight', 'tsz_hitweight', 'tsz_varweight', 'ksz_uniformweight', 'ksz_hitweight', 'ksz_varweight', 'ksz_massvarweight']
self.EstBootstrap = ['tsz_uniformweight', 'tsz_varweight'] #['tsz_varweight', 'ksz_varweight']
self.EstVShuffle = [] #['ksz_varweight']
self.EstMBins = ['tsz_uniformweight', 'tsz_varweight']# ['tsz_varweight', 'ksz_varweight']
else:
self.Est = ['tsz_uniformweight'] #['tsz_uniformweight', 'ksz_uniformweight', 'ksz_massvarweight']
self.EstBootstrap = ['tsz_uniformweight'] #['tsz_uniformweight', 'ksz_uniformweight']
self.EstVShuffle = [] #['ksz_uniformweight']
self.EstMBins = ['tsz_uniformweight'] #['ksz_uniformweight'] #['tsz_uniformweight', 'ksz_uniformweight']
# resolution of the cutout maps to be extracted
self.resCutoutArcmin = 0.25 # [arcmin]
# projection of the cutout maps
self.projCutout = 'cea'
# number of samples for bootstraps, shuffles
self.nSamples = 10000
# number of mMax cuts to test,
# for tSZ contamination to kSZ
self.nMMax = 20
# fiducial mass cuts, to avoid eg tSZ contamination
# from massive clusters
self.mMin = 0. #1.e6
self.mMax = np.inf #1.e14 # 1.e17
# Output path
self.pathOut = "./output/thumbstack/"+self.name
if not os.path.exists(self.pathOut):
os.makedirs(self.pathOut)
# Figures path
self.pathFig = "./figures/thumbstack/"+self.name
if not os.path.exists(self.pathFig):
os.makedirs(self.pathFig)
# test figures path
self.pathTestFig = self.pathFig+"/tests"
if not os.path.exists(self.pathTestFig):
os.makedirs(self.pathTestFig)
print "- Thumbstack: "+str(self.name)
self.loadAPRadii()
self.loadMMaxBins()
if save:
self.saveOverlapFlag(nProc=self.nProc)
self.loadOverlapFlag()
if save:
self.saveFiltering(nProc=self.nProc)
self.loadFiltering()
self.measureAllVarFromHitCount(plot=save)
# self.measureAllMeanTZBins(plot=save, test=False)
if save:
self.saveAllStackedProfiles()
self.loadAllStackedProfiles()
if save:
self.plotAllStackedProfiles()
self.plotAllCov()
self.computeAllSnr()
#if save:
if True:
if doStackedMap:
# save all stacked maps
#self.saveAllStackedMaps()
# save only the stacked maps for
# the best tsz and ksz estimators,
# and for the diskring weighting
#self.saveAllStackedMaps(filterTypes=['diskring'], Est=['tsz_varweight', 'ksz_varweight'])
self.saveAllStackedMaps(filterTypes=None, Est=None)
##################################################################################
##################################################################################
def loadAPRadii(self):
# radii to use for AP filter: comoving Mpc/h
self.nRAp = 9 #30 #9 #4
# Aperture radii in Mpc/h
#self.rApMinMpch = 1.
#self.rApMaxMpch = 5
#self.RApMpch = np.linspace(self.rApMinMpch, self.rApMaxMpch, self.nRAp)
# Aperture radii in arcmin
self.rApMinArcmin = 1. #0.1 #1. # 1.
self.rApMaxArcmin = 6. #6. #6. # 4.
self.RApArcmin = np.linspace(self.rApMinArcmin, self.rApMaxArcmin, self.nRAp)
def cutoutGeometry(self, test=False):
'''Create enmap for the cutouts to be extracted.
Returns a null enmap object with the right shape and wcs.
'''
# choose postage stamp size to fit the largest ring
dArcmin = np.ceil(2. * self.rApMaxArcmin * np.sqrt(2.))
#
nx = np.floor((dArcmin / self.resCutoutArcmin - 1.) / 2.) + 1.
dxDeg = (2. * nx + 1.) * self.resCutoutArcmin / 60.
ny = np.floor((dArcmin / self.resCutoutArcmin - 1.) / 2.) + 1.
dyDeg = (2. * ny + 1.) * self.resCutoutArcmin / 60.
# define geometry of small square maps to be extracted
shape, wcs = enmap.geometry(np.array([[-0.5*dxDeg,-0.5*dyDeg],[0.5*dxDeg,0.5*dyDeg]])*utils.degree, res=self.resCutoutArcmin*utils.arcmin, proj=self.projCutout)
cutoutMap = enmap.zeros(shape, wcs)
if test:
print "cutout sides are dx, dy =", dxDeg*60., ",", dyDeg*60. , "arcmin"
print "cutout pixel dimensions are", shape
print "hence a cutout resolution of", dxDeg*60./shape[0], ",", dyDeg*60./shape[1], "arcmin per pixel"
print "(requested", self.resCutoutArcmin, "arcmin per pixel)"
return cutoutMap
def loadMMaxBins(self, test=False):
'''Choose the mMax values to have the same number of galaxies
added in the sample for each mMax increment.
'''
# self.MMax = np.interp(np.linspace(0, self.Catalog.nObj, self.nMMax+1),
# np.arange(self.Catalog.nObj),
# np.sort(self.Catalog.Mvir))[1:]
self.MMax = np.logspace(np.log10(self.Catalog.Mvir.min()*1.1), np.log10(self.Catalog.Mvir.max()), self.nMMax)
if test:
print "Checking the mMax bins:"
print "number of bins:", self.nMMax, len(self.MMax)
print "values of mMax:", self.MMax
##################################################################################
def sky2map(self, ra, dec, map):
'''Gives the map value at coordinates (ra, dec).
ra, dec in degrees.
Uses nearest neighbor, no interpolation.
Will return 0 if the coordinates requested are outside the map
'''
# interpolate the map to the given sky coordinates
sourcecoord = np.array([dec, ra]) * utils.degree # convert from degrees to radians
# use nearest neighbor interpolation
return map.at(sourcecoord, prefilter=False, mask_nan=False, order=0)
#def saveOverlapFlag(self, thresh=1.e-5, nProc=1):
def saveOverlapFlag(self, thresh=0.95, nProc=1):
'''1 for objects that overlap with the hit map,
0 for objects that don't.
'''
print "Create overlap flag"
# find if a given object overlaps with the CMB hit map
def foverlap(iObj):
'''Returns 1. if the object overlaps with the hit map and 0. otherwise.
'''
if iObj%100000==0:
print "-", iObj
ra = self.Catalog.RA[iObj]
dec = self.Catalog.DEC[iObj]
#hit = self.sky2map(ra, dec, self.cmbHit)
hit = self.sky2map(ra, dec, self.cmbMask)
return np.float(hit>thresh)
# overlapFlag = np.array(map(foverlap, range(self.Catalog.nObj)))
tStart = time()
with sharedmem.MapReduce(np=nProc) as pool:
overlapFlag = np.array(pool.map(foverlap, range(self.Catalog.nObj)))
tStop = time()
print "took", (tStop-tStart)/60., "min"
print "Out of", self.Catalog.nObj, "objects,", np.sum(overlapFlag), "overlap, ie a fraction", np.sum(overlapFlag)/self.Catalog.nObj
np.savetxt(self.pathOut+"/overlap_flag.txt", overlapFlag)
def loadOverlapFlag(self):
self.overlapFlag = np.genfromtxt(self.pathOut+"/overlap_flag.txt")
##################################################################################
def examineCmbMaps(self):
# mask, before re-thresholding
x = self.cmbMask.copy()
path = self.pathFig+"/hist_cmbmask_prerethresh.pdf"
myHistogram(x, nBins=71, lim=(np.min(x), np.max(x)), path=path, nameLatex=r'CMB mask value', semilogy=True)
# rethreshold the mask
mask = (self.cmbMask>0.5)[0]
# mask, after re-thresholding
x = 1. * mask.copy()
path = self.pathFig+"/hist_cmbmask_postrethresh.pdf"
myHistogram(x, nBins=71, lim=(np.min(x), np.max(x)), path=path, nameLatex=r'CMB mask value', semilogy=True)
# masked map histogram
x = self.cmbMap[mask]
path = self.pathFig+"/hist_cmbmap.pdf"
myHistogram(x, nBins=71, lim=(-10.*np.std(x), 10.*np.std(x)), path=path, nameLatex=r'CMB map value', semilogy=True, doGauss=True, S2Theory=[110.**2])
# masked hit count histogram
x = self.cmbHit[mask]
path = self.pathFig+"/hist_cmbhit.pdf"
myHistogram(x, nBins=71, lim=(np.min(x), np.max(x)), path=path, nameLatex=r'CMB hit count', semilogy=True)
##################################################################################
def extractStamp(self, ra, dec, test=False):
"""Extracts a small CEA or CAR map around the given position, with the given angular size and resolution.
ra, dec in degrees.
Does it for the map, the mask and the hit count.
"""
stampMap = self.cutoutGeometry()
stampMask = stampMap.copy()
stampHit = stampMap.copy()
# coordinates of the square map (between -1 and 1 deg)
# output map position [{dec,ra},ny,nx]
opos = stampMap.posmap()
# coordinate of the center of the square map we want to extract
# ra, dec in this order
sourcecoord = np.array([ra, dec])*utils.degree # convert from degrees to radians
# corresponding true coordinates on the big healpy map
ipos = rotfuncs.recenter(opos[::-1], [0,0,sourcecoord[0],sourcecoord[1]])[::-1]
# extract the small square map by interpolating the big map
# these are now numpy arrays: the wcs info is gone
# # Here, I use nearest neighbor interpolation (order=0)
# stampMap[:,:] = self.cmbMap.at(ipos, prefilter=False, mask_nan=False, order=0)
# stampMask[:,:] = self.cmbMask.at(ipos, prefilter=False, mask_nan=False, order=0)
# stampHit[:,:] = self.cmbHit.at(ipos, prefilter=False, mask_nan=False, order=0)
# Here, I use bilinear interpolation
stampMap[:,:] = self.cmbMap.at(ipos, prefilter=True, mask_nan=False, order=1)
stampMask[:,:] = self.cmbMask.at(ipos, prefilter=True, mask_nan=False, order=1)
if self.cmbHit is not None:
stampHit[:,:] = self.cmbHit.at(ipos, prefilter=True, mask_nan=False, order=1)
# # Here, I use bicubic spline interpolation
# stampMap[:,:] = self.cmbMap.at(ipos, prefilter=True, mask_nan=False, order=3)
# stampMask[:,:] = self.cmbMask.at(ipos, prefilter=True, mask_nan=False, order=3)
# stampHit[:,:] = self.cmbHit.at(ipos, prefilter=True, mask_nan=False, order=3)
# re-threshold the mask map, to keep 0 and 1 only
stampMask[:,:] = 1.*(stampMask[:,:]>0.5)
if test:
print "Extracted cutouts around ra=", ra, "dec=", dec
print "Map:"
print "- min, mean, max =", np.min(stampMap), np.mean(stampMap), np.max(stampMap)
print "- plot"
plots=enplot.plot(stampMap, grid=True)
enplot.write(self.pathTestFig+"/stampmap_ra"+np.str(np.round(ra, 2))+"_dec"+np.str(np.round(dec, 2)), plots)
print "Mask:"
print "- min, mean, max =", np.min(stampMask), np.mean(stampMask), np.max(stampMask)
print "- plot"
plots=enplot.plot(stampMask, grid=True)
enplot.write(self.pathTestFig+"/stampmask_ra"+np.str(np.round(ra, 2))+"_dec"+np.str(np.round(dec, 2)), plots)
print "Hit count:"
print "- min, mean, max =", np.min(stampHit), np.mean(stampHit), np.max(stampHit)
print "- plot the hit"
plots=enplot.plot(stampHit, grid=True)
enplot.write(self.pathTestFig+"/stamphit_ra"+np.str(np.round(ra, 2))+"_dec"+np.str(np.round(dec, 2)), plots)
return opos, stampMap, stampMask, stampHit
##################################################################################
def aperturePhotometryFilter(self, opos, stampMap, stampMask, stampHit, r0, r1, filterType='diskring', test=False):
"""Apply an AP filter (disk minus ring) to a stamp map:
AP = int d^2theta * Filter * map.
Unit is [map unit * sr]
The filter function is dimensionless:
Filter = 1 in the disk, - (disk area)/(ring area) in the ring, 0 outside.
Hence:
int d^2theta * Filter = 0.
r0 and r1 are the radius of the disk and ring in radians.
stampMask should have values 0 and 1 only.
Output:
filtMap: [map unit * sr]
filtMask: [mask unit * sr]
filtHitNoiseStdDev: [1/sqrt(hit unit) * sr], ie [std dev * sr] if [hit map] = inverse var
diskArea: [sr]
"""
# coordinates of the square map in radians
# zero is at the center of the map
# output map position [{dec,ra},ny,nx]
dec = opos[0,:,:]
ra = opos[1,:,:]
radius = np.sqrt(ra**2 + dec**2)
# exact angular area of a pixel [sr] (same for all pixels in CEA, not CAR)
pixArea = ra.area() / len(ra.flatten())
# detect point sources within the filter:
# gives 0 in the absence of point sources/edges; gives >=1 in the presence of point sources/edges
filtMask = np.sum((radius<=r1) * (1-stampMask)) # [dimensionless]
# disk filter [dimensionless]
inDisk = 1.*(radius<=r0)
# exact angular area of disk [sr]
diskArea = np.sum(inDisk) * pixArea
# ring filter [dimensionless]
inRing = 1.*(radius>r0)*(radius<=r1)
if filterType=='diskring':
# normalize the ring so that the disk-ring filter integrates exactly to zero
inRing *= np.sum(inDisk) / np.sum(inRing)
# disk minus ring filter [dimensionless]
filterW = inDisk - inRing
if np.isnan(np.sum(filterW)):
print "filterW sums to nan", r0, r1, np.sum(radius), np.sum(1.*(radius>r0)), np.sum(1.*(radius>r0)*(radius<=r1))
elif filterType=='disk':
# disk filter [dimensionless]
inDisk = 1.*(radius<=r0)
filterW = inDisk
elif filterType=='ring':
filterW = inRing
elif filterType=='meanring':
filterW = inRing / np.sum(pixArea * inRing)
# apply the filter: int_disk d^2theta map - disk_area / ring_area * int_ring d^2theta map
filtMap = np.sum(pixArea * filterW * stampMap) # [map unit * sr]
# quantify noise std dev in the filter
if self.cmbHit is not None:
filtHitNoiseStdDev = np.sqrt(np.sum((pixArea * filterW)**2 / (1.e-16 + stampHit))) # to get the std devs [sr / sqrt(hit unit)]
else:
filtHitNoiseStdDev = 0.
#print "filtHitNoiseStdDev = ", filtHitNoiseStdDev
if np.isnan(filtHitNoiseStdDev):
print "filtHitNoiseStdDev is nan"
if test:
print "AP filter with disk radius =", r0 * (180.*60./np.pi), "arcmin"
# count nb of pixels where filter is strictly positive
nbPix = len(np.where(filterW>0.)[0])
print "- nb of pixels in the cutout: "+str(filterW.shape[0] * filterW.shape[1])
print "= nb of pixels where filter=0: "+str(len(np.where(filterW==0.)[0]))
print "+ nb of pixels where filter>0: "+str(len(np.where(filterW>0.)[0]))
print "+ nb of pixels where filter<0: "+str(len(np.where(filterW<0.)[0]))
print "- disk area: "+str(diskArea)+" sr, ie "+str(diskArea * (180.*60./np.pi)**2)+"arcmin^2"
print " (from r0, expect "+str(np.pi*r0**2)+" sr, ie "+str(np.pi*r0**2 * (180.*60./np.pi)**2)+"arcmin^2)"
print "- disk-ring filter sums over pixels to "+str(np.sum(filterW))
print " (should be 0; compared to "+str(len(filterW.flatten()))+")"
print "- filter on unit disk: "+str(np.sum(pixArea * filterW * inDisk))
print " (should be disk area in sr: "+str(diskArea)+")"
print "- filter on map: "+str(filtMap)
print "- filter on mask: "+str(filtMask)
print "- filter on inverse hit: "+str(filtHitNoiseStdDev)
print "- plot the filter"
filterMap = stampMap.copy()
filterMap[:,:] = filterW.copy()
vmax = np.max(np.abs(filterW))
plots=enplot.plot(filterMap,grid=True, min=-vmax, max=vmax)#, color='hotcold')
enplot.write(self.pathTestFig+"/stampfilter_r0"+floatExpForm(r0)+"_r1"+floatExpForm(r1), plots)
return filtMap, filtMask, filtHitNoiseStdDev, diskArea
##################################################################################
def analyzeObject(self, iObj, test=False):
'''Analysis to be done for each object: extract cutout map once,
then apply all aperture photometry filters requested on it.
Returns:
filtMap: [map unit * sr]
filtMask: [mask unit * sr]
filtHitNoiseStdDev: [1/sqrt(hit unit) * sr], ie [std dev * sr] if [hit map] = inverse var
diskArea: [sr]
'''
if iObj%10000==0:
print "- analyze object", iObj
# create arrays of filter values for the given object
filtMap = {}
filtMask = {}
filtHitNoiseStdDev = {}
filtArea = {}
for iFilterType in range(len(self.filterTypes)):
filterType = self.filterTypes[iFilterType]
# create arrays of filter values for the given object
filtMap[filterType] = np.zeros(self.nRAp)
filtMask[filterType] = np.zeros(self.nRAp)
filtHitNoiseStdDev[filterType] = np.zeros(self.nRAp)
filtArea[filterType] = np.zeros(self.nRAp)
# only do the analysis if the object overlaps with the CMB map
if self.overlapFlag[iObj]:
# Object coordinates
ra = self.Catalog.RA[iObj] # in deg
dec = self.Catalog.DEC[iObj] # in deg
z = self.Catalog.Z[iObj]
# choose postage stamp size to fit the largest ring
dArcmin = np.ceil(2. * self.rApMaxArcmin * np.sqrt(2.))
dDeg = dArcmin / 60.
# extract postage stamp around it
opos, stampMap, stampMask, stampHit = self.extractStamp(ra, dec, test=test)
for iFilterType in range(len(self.filterTypes)):
filterType = self.filterTypes[iFilterType]
# loop over the radii for the AP filter
for iRAp in range(self.nRAp):
## disk radius in comoving Mpc/h
#rApMpch = self.RApMpch[iRAp]
## convert to radians at the given redshift
#r0 = rApMpch / self.U.bg.comoving_transverse_distance(z) # rad
# Disk radius in rad
r0 = self.RApArcmin[iRAp] / 60. * np.pi/180.
# choose an equal area AP filter
r1 = r0 * np.sqrt(2.)
# perform the filtering
filtMap[filterType][iRAp], filtMask[filterType][iRAp], filtHitNoiseStdDev[filterType][iRAp], filtArea[filterType][iRAp] = self.aperturePhotometryFilter(opos, stampMap, stampMask, stampHit, r0, r1, filterType=filterType, test=test)
if test:
print " plot the measured profile"
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
for iFilterType in range(len(self.filterTypes)):
filterType = self.filterTypes[iFilterType]
ax.plot(self.RApArcmin, filtMap[filterType])
#
plt.show()
return filtMap, filtMask, filtHitNoiseStdDev, filtArea
def saveFiltering(self, nProc=1):
print("Evaluate all filters on all objects")
# loop over all objects in catalog
# result = np.array(map(self.analyzeObject, range(self.Catalog.nObj)))
tStart = time()
with sharedmem.MapReduce(np=nProc) as pool:
f = lambda iObj: self.analyzeObject(iObj, test=False)
result = np.array(pool.map(f, range(self.Catalog.nObj)))
tStop = time()
print "took", (tStop-tStart)/60., "min"
# unpack and save to file
for iFilterType in range(len(self.filterTypes)):
filterType = self.filterTypes[iFilterType]
filtMap = np.array([result[iObj,0][filterType][:] for iObj in range(self.Catalog.nObj)])
filtMask = np.array([result[iObj,1][filterType][:] for iObj in range(self.Catalog.nObj)])
filtHitNoiseStdDev = np.array([result[iObj,2][filterType][:] for iObj in range(self.Catalog.nObj)])
filtArea = np.array([result[iObj,3][filterType][:] for iObj in range(self.Catalog.nObj)])
np.savetxt(self.pathOut+"/"+filterType+"_filtmap.txt", filtMap)
np.savetxt(self.pathOut+"/"+filterType+"_filtmask.txt", filtMask)
np.savetxt(self.pathOut+"/"+filterType+"_filtnoisestddev.txt", filtHitNoiseStdDev)
np.savetxt(self.pathOut+"/"+filterType+"_filtarea.txt", filtArea)
def loadFiltering(self):
self.filtMap = {}
self.filtMask = {}
self.filtHitNoiseStdDev = {}
self.filtArea = {}
for iFilterType in range(len(self.filterTypes)):
filterType = self.filterTypes[iFilterType]
self.filtMap[filterType] = np.genfromtxt(self.pathOut+"/"+filterType+"_filtmap.txt")
self.filtMask[filterType] = np.genfromtxt(self.pathOut+"/"+filterType+"_filtmask.txt")
self.filtHitNoiseStdDev[filterType] = np.genfromtxt(self.pathOut+"/"+filterType+"_filtnoisestddev.txt")
self.filtArea[filterType] = np.genfromtxt(self.pathOut+"/"+filterType+"_filtarea.txt")
##################################################################################
def catalogMask(self, overlap=True, psMask=True, mVir=None, z=[0., 100.], extraSelection=1., filterType=None, outlierReject=True):
'''Returns catalog mask: 1 for objects to keep, 0 for objects to discard.
Use as:
maskedQuantity = Quantity[mask]
'''
if mVir is None:
mVir = [self.mMin, self.mMax]
# Here mask is 1 for objects we want to keep
mask = np.ones_like(self.Catalog.RA)
print "start with fraction", np.sum(mask)/len(mask), "of objects"
if mVir is not None:
mask *= (self.Catalog.Mvir>=mVir[0]) * (self.Catalog.Mvir<=mVir[1])
print "keeping fraction", np.sum(mask)/len(mask), "of objects after mass cut"
if z is not None:
mask *= (self.Catalog.Z>=z[0]) * (self.Catalog.Z<=z[1])
print "keeping fraction", np.sum(mask)/len(mask), "of objects after further z cut"
if overlap:
mask *= self.overlapFlag.copy()
print "keeping fraction", np.sum(mask)/len(mask), "of objects after further overlap cut"
# PS mask: look at largest aperture, and remove if any point within the disk or ring is masked
if psMask:
# The point source mask may vary from one filterType to another
if filterType is None:
filterType = self.filtMask.keys()[0]
mask *= 1.*(np.abs(self.filtMask[filterType][:,-1])<1.)
print "keeping fraction", np.sum(mask)/len(mask), "of objects after PS mask"
mask *= extraSelection
#print "keeping fraction", np.sum(mask)/len(mask), " of objects"
if outlierReject:
mask = mask.astype(bool)
# we reject objects whose filter values are such
# that the probability to have >=1 object with such a high absolute value
# in a sample of this size
# is equivalent to a 5sigma PTE = 5.73e-7.
# Sample of 1: proba that the value is found outside of [-n*sigma, +n*sigma]
# called PTE
# is p = erf( n / sqrt(2))
# Sample of N independent objects: the proba that at least one of them is outside [-n*sigma, +n*sigma]
# is 1 - (1-p)^N
# ie N * p if p<<1
# Our threshold: n*p should correspond to a 5 sigma PTE, ie
# N * p = erf(5/sqrt(2)) = 5.733e-7
nObj = np.sum(mask)
if nObj<>0:
f = lambda nSigmas: nObj * special.erfc(nSigmas / np.sqrt(2.)) - special.erfc(5. / np.sqrt(2.))
nSigmasCut = optimize.brentq(f , 0., 1.e2)
# ts has shape (nObj, nRAp)
# sigmas has shape nRAp
sigmas = np.std(self.filtMap[filterType][mask,:], axis=0)
# shape is (nObj, nRAp)
newMask = (np.abs(self.filtMap[filterType][:,:]) <= nSigmasCut * sigmas[np.newaxis,:])
# take the intersection of the masks
mask *= np.prod(newMask, axis=1).astype(bool)
print "keeping fraction", np.sum(1.*mask)/len(mask), "of objects after further outlier cut"
# make sure the mask is boolean
mask = mask.astype(bool)
print "keeping fraction", np.sum(1.*mask)/len(mask), "in the end"
return mask
##################################################################################
def measureVarFromHitCount(self, filterType, plot=False):
"""Returns a list of functions, one for each AP filter radius,
where the function takes filtHitNoiseStdDev**2 \propto [(map var) * sr^2] as input and returns the
actual measured filter variance [(map unit)^2 * sr^2].
The functions are expected to be linear if the detector noise is the main source of noise,
and if the hit counts indeed reflect the detector noise.
To be used for noise weighting in the stacking.
"""
# keep only objects that overlap, and mask point sources
mask = self.catalogMask(overlap=True, psMask=True, filterType=filterType, mVir=(self.Catalog.Mvir.min(), self.Catalog.Mvir.max()), outlierReject=False)
# This array contains the true variances for each object and aperture
filtVarTrue = np.zeros((self.Catalog.nObj, self.nRAp))
if self.cmbHit is not None:
print("Interpolate variance=f(hit count) for each aperture")
fVarFromHitCount = np.empty(self.nRAp, dtype='object')
for iRAp in range(self.nRAp):
#print("Aperture number "+str(iRAp))
x = self.filtHitNoiseStdDev[filterType][mask, iRAp]**2
y = self.filtMap[filterType][mask, iRAp].copy()
y = (y - np.mean(y))**2
# define bins of hit count values
nBins = 10 #21
binEdges = np.logspace(np.log10(np.min(x)), np.log10(np.max(x)), nBins, 10.)
# # define bins of hit count values,
# # with an equal number of objects in each bin
# nBins = 10
# binEdges = splitBins(x, nBins)
# print "bin edges"
# print binEdges
# print np.min(x), np.max(x)
# compute histograms
binCenters, binEdges, binIndices = stats.binned_statistic(x, x, statistic='mean', bins=binEdges)
binCounts, binEdges, binIndices = stats.binned_statistic(x, x, statistic='count', bins=binEdges)
binnedVar, binEdges, binIndices = stats.binned_statistic(x, y, statistic=np.mean, bins=binEdges)
sBinnedVar, binEdges, binIndices = stats.binned_statistic(x, y, statistic=np.std, bins=binEdges)
sBinnedVar /= np.sqrt(binCounts)
# exclude the empty bins, which did not contain data
I = np.where(np.isfinite(binCenters * binCounts * binnedVar * sBinnedVar))[0]
binCenters = binCenters[I]
binCounts = binCounts[I]
binnedVar = binnedVar[I]
sBinnedVar = sBinnedVar[I]
# interpolate, to use as noise weighting
fVarFromHitCount[iRAp] = interp1d(binCenters, binnedVar, kind='linear', bounds_error=False, fill_value=(binnedVar[0],binnedVar[-1]))
# evaluate the variance for each object
filtVarTrue[mask,iRAp] = fVarFromHitCount[iRAp](x)
# # evaluate the variance for each object
# # for the objects masked, still give them a weight just in case,
# # to avoid null weights
# xFull = self.filtHitNoiseStdDev[filterType][:, iRAp]**2
# filtVarTrue[:,iRAp] = fVarFromHitCount[iRAp](xFull)
if plot:
# plot
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
# measured
ax.errorbar(binCenters, binnedVar*(180.*60./np.pi)**2, yerr=sBinnedVar*(180.*60./np.pi)**2, fmt='.', label=r'measured')
# interpolated
newX = np.logspace(np.log10(np.min(x)/2.), np.log10(np.max(x)*2.), 10.*nBins, 10.)
newY = np.array(map(fVarFromHitCount[iRAp], newX))
ax.plot(newX, newY*(180.*60./np.pi)**2, label=r'interpolated')
#
ax.set_xscale('log', nonposx='clip')
ax.set_yscale('log', nonposy='clip')
ax.set_xlabel(r'Det. noise var. from combined hit [arbitrary]')
ax.set_ylabel(r'Measured var. [$\mu$K.arcmin$^2$]')
#
path = self.pathFig+"/binned_noise_vs_hit_"+filterType+"_"+str(iRAp)+".pdf"
fig.savefig(path, bbox_inches='tight')
fig.clf()
else:
print("Measure var for each aperture (no hit count)")
meanVarAperture = np.var(self.filtMap[filterType][mask, :], axis=0)
for iRAp in range(self.nRAp):
filtVarTrue[mask,iRAp] = meanVarAperture[iRAp] * np.ones(np.sum(mask))
return filtVarTrue
def measureAllVarFromHitCount(self, plot=False):
self.filtVarTrue = {}
for iFilterType in range(len(self.filterTypes)):
filterType = self.filterTypes[iFilterType]
self.filtVarTrue[filterType] = self.measureVarFromHitCount(filterType, plot=plot)
##################################################################################
def measureMeanTZBins(self, filterType, plot=False, test=False):
'''Measure the mean filter temperatures in redshift bins,
in order to subtract it to make the kSZ estimator robust to dust evolution * mean velocities.
'''
print("Measure mean T in z-bins (to subtract for kSZ)")
# keep only objects that overlap, and mask point sources
mask = self.catalogMask(overlap=True, psMask=True, filterType=filterType, mVir=(self.Catalog.Mvir.min(), self.Catalog.Mvir.max()))
# redshift bins
nZBins = 10
zBinEdges = np.linspace(self.Catalog.Z.min(), self.Catalog.Z.max(), nZBins)
# array of mean t to fill
meanT = np.zeros((self.Catalog.nObj, self.nRAp))
fMeanT = np.empty(self.nRAp, dtype='object')
for iRAp in range(self.nRAp):
# quantities to be binned
z = self.Catalog.Z[mask].copy()
t = self.filtMap[filterType][mask, iRAp].copy()
# s2 = self.filtVarTrue[filterType][mask, iRAp].copy()
# # inverse-variance weight the temperatures
# t = t/s2 / np.mean(1./s2)
# compute histograms
zBinCenters, zBinEdges, zBinIndices = stats.binned_statistic(z, z, statistic='mean', bins=zBinEdges)
zBinCounts, zBinEdges, zBinIndices = stats.binned_statistic(z, z, statistic='count', bins=zBinEdges)
tMean, zBinEdges, zBinIndices = stats.binned_statistic(z, t, statistic=np.mean, bins=zBinEdges)
sTMean, zBinEdges, zBinIndices = stats.binned_statistic(z, t, statistic=np.std, bins=zBinEdges)
sTMean /= np.sqrt(zBinCounts)
# piecewise-constant interpolation
fMeanT[iRAp] = interp1d(zBinEdges[:-1], tMean, kind='previous', bounds_error=False, fill_value=(tMean[0], tMean[-1]))
# evaluate the interpolation at each object
meanT[mask,iRAp] = fMeanT[iRAp](z)
if plot:
fig=plt.figure(0)
ax=fig.add_subplot(111)
factor = (180.*60./np.pi)**2
#
ax.axhline(0., color='k')
# Measured
ax.errorbar(zBinCenters, factor*tMean, yerr=factor*sTMean, label=r'Measured')
# Check interpolation
z = np.linspace(self.Catalog.Z.min(), self.Catalog.Z.max(), 101)
ax.plot(z, factor*fMeanT[iRAp](z), '--', label=r'Interpolated')
#
ax.legend(loc=1, fontsize='x-small', labelspacing=0.1)
ax.set_xlabel(r'$z$ bins')
ax.set_ylabel(r'Mean T per $z$-bin [$\mu$K$\cdot$arcmin$^2$]')
#
path = self.pathFig+"/binned_mean_t_"+filterType+"_"+str(iRAp)+".pdf"
fig.savefig(path, bbox_inches='tight')
if test:
plt.show()
fig.clf()
return meanT
def measureAllMeanTZBins(self, plot=False, test=False):
self.meanT = {}
for iFilterType in range(len(self.filterTypes)):
filterType = self.filterTypes[iFilterType]
print("For "+filterType+" filter:")
self.meanT[filterType] = self.measureMeanTZBins(filterType, plot=plot, test=test)
##################################################################################
def computeStackedProfile(self, filterType, est, iBootstrap=None, iVShuffle=None, tTh='', stackedMap=False, mVir=None, z=[0., 100.], ts=None, mask=None):
"""Returns the estimated profile and its uncertainty for each aperture.
est: string to select the estimator
iBootstrap: index for bootstrap resampling
iVShuffle: index for shuffling velocities
tTh: to replace measured temperatures by a theory expectation
ts: option to specify another thumbstack object
"""
#tStart = time()
print("- Compute stacked profile: "+filterType+", "+est+", "+tTh)
# compute stacked profile from another thumbstack object
if ts is None:
ts = self
if mVir is None:
mVir = [ts.mMin, ts.mMax]
# select objects that overlap, and reject point sources
if mask is None:
mask = ts.catalogMask(overlap=True, psMask=True, filterType=filterType, mVir=mVir, z=z)
# tMean = ts.meanT[filterType].copy()
# temperatures [muK * sr]
if tTh=='':
t = ts.filtMap[filterType].copy() # [muK * sr]
elif tTh=='tsz':
# expected tSZ signal
# AP profile shape, between 0 and 1
sigma_cluster = 3. #1.5 # arcmin
shape = ts.ftheoryGaussianProfile(sigma_cluster) # between 0 and 1 [dimless]
# multiply by integrated y to get y profile [sr]
t = np.column_stack([ts.Catalog.integratedY[:] * shape[iAp] for iAp in range(ts.nRAp)])
# convert from y profile to dT profile if needed
if self.cmbUnitLatex==r'$\mu$K':
nu = self.cmbNu # Hz
Tcmb = 2.726 # K
h = 6.63e-34 # SI
kB = 1.38e-23 # SI
def f(nu):
"""frequency dependence for tSZ temperature
"""
x = h*nu/(kB*Tcmb)
return x*(np.exp(x)+1.)/(np.exp(x)-1.) -4.
#t *= 2. * f(nu) * Tcmb * 1.e6 # [muK * sr]
t *= f(nu) * Tcmb * 1.e6 # [muK * sr]
elif tTh=='ksz':
# expected kSZ signal
# AP profile shape, between 0 and 1
sigma_cluster = 1.5 # arcmin
shape = ts.ftheoryGaussianProfile(sigma_cluster) # between 0 and 1 [dimless]
# multiply by integrated kSZ to get kSZ profile [muK * sr]
t = np.column_stack([ts.Catalog.integratedKSZ[:] * shape[iAp] for iAp in range(ts.nRAp)]) # [muK * sr]
if self.cmbUnitLatex=='':
t /= 2.726e6 # convert from [muK*sr] to [sr]
t = t[mask, :]
# tMean = tMean[mask,:]
# -v/c [dimless]
v = -ts.Catalog.vR[mask] / 3.e5
v -= np.mean(v)
# # expected sigma_{v_{true}}, for the normalization
# #print "computing v1d norm"
# #tStartV = time()
# z = ts.Catalog.Z[mask]
# #f = lambda zGal: ts.U.v1dRms(0., zGal, W3d_sth)**2
# #sVTrue = np.sqrt(np.mean(np.array(map(f, z))))
# sVTrue = ts.U.v1dRms(0., np.mean(z), W3d_sth) / 3.e5 # (v^true_rms/c) [dimless]
# #print "sigma_v_true =", sVTrue
# #print "at z=0.57, expect", np.sqrt(f(0.57))
# #tStopV = time()
# #print "v1d norm took", tStopV - tStartV, "sec"
#true filter variance for each object and aperture,
# valid whether or not a hit count map is available
s2Full = ts.filtVarTrue[filterType][mask, :]
# Variance from hit count (if available)
s2Hit = ts.filtHitNoiseStdDev[filterType][mask, :]**2
#print "Shape of s2Hit = ", s2Hit.shape
# halo masses
m = ts.Catalog.Mvir[mask]
if iBootstrap is not None:
# make sure each resample is independent,
# and make the resampling reproducible
np.random.seed(iBootstrap)
# list of overlapping objects
nObj = np.sum(mask)
#print "sample "iBootstrap, ";", nObj, "objects overlap with", ts.name
I = np.arange(nObj)
# choose with replacement from this list
J = np.random.choice(I, size=nObj, replace=True)
#
t = t[J,:]
#tMean = tMean[J,:]
v = v[J]
s2Hit = s2Hit[J,:]
s2Full = s2Full[J,:]
m = m[J]
if iVShuffle is not None:
# make sure each shuffling is independent,
# and make the shuffling reproducible
np.random.seed(iVShuffle)
# list of overlapping objects
nObj = np.sum(mask)
I = np.arange(nObj)
# shuffle the velocities
J = np.random.permutation(I)
#
v = v[J]
# tSZ: uniform weighting
if est=='tsz_uniformweight':
weights = np.ones_like(s2Hit)
norm = 1./np.sum(weights, axis=0)
# tSZ: detector-noise weighted (hit count)
elif est=='tsz_hitweight':
weights = 1./s2Hit
norm = 1./np.sum(weights, axis=0)
# tSZ: full noise weighted (detector noise + CMB)
elif est=='tsz_varweight':
weights = 1./s2Full
norm = 1./np.sum(weights, axis=0)
# kSZ: uniform weighting
elif est=='ksz_uniformweight':
# remove mean temperature
#t -= np.mean(t, axis=0)
# t -= tMean
weights = v[:,np.newaxis] * np.ones_like(s2Hit)
#norm = sVTrue / np.sum(v[:,np.newaxis]*weights, axis=0)
norm = np.std(v) / ts.Catalog.rV / np.sum(v[:,np.newaxis]*weights, axis=0)
# kSZ: detector-noise weighted (hit count)
elif est=='ksz_hitweight':
# remove mean temperature
#t -= np.mean(t, axis=0)
# t -= tMean
weights = v[:,np.newaxis] / s2Hit
#norm = sVTrue / np.sum(v[:,np.newaxis]*weights, axis=0)
norm = np.std(v) / ts.Catalog.rV / np.sum(v[:,np.newaxis]*weights, axis=0)
# kSZ: full noise weighted (detector noise + CMB)
elif est=='ksz_varweight':
# remove mean temperature
#t -= np.mean(t, axis=0)
# t -= tMean
weights = v[:,np.newaxis] / s2Full
#norm = sVTrue / np.sum(v[:,np.newaxis]*weights, axis=0)
norm = np.std(v) / ts.Catalog.rV / np.sum(v[:,np.newaxis]*weights, axis=0)
# kSZ: full noise weighted (detector noise + CMB)
elif est=='ksz_massvarweight':
# remove mean temperature
#t -= np.mean(t, axis=0)
# t -= tMean
weights = m[:,np.newaxis] * v[:,np.newaxis] / s2Full
#norm = np.mean(m) * sVTrue / np.sum(m[:,np.newaxis]**2 * v[:,np.newaxis]**2 / s2Full, axis=0)
norm = np.mean(m) * np.std(v) / ts.Catalog.rV / np.sum(m[:,np.newaxis]**2 * v[:,np.newaxis]**2 / s2Full, axis=0)
#tStop = time()
#print "stacked profile took", tStop-tStart, "sec"
# return the stacked profiles
if not stackedMap:
stack = norm * np.sum(t * weights, axis=0)
sStack = norm * np.sqrt(np.sum(s2Full * weights**2, axis=0))
return stack, sStack
# or, if requested, compute and return the stacked cutout map
else:
# define chunks
nChunk = ts.nProc
chunkSize = ts.Catalog.nObj / nChunk
# list of indices for each of the nChunk chunks
chunkIndices = [range(iChunk*chunkSize, (iChunk+1)*chunkSize) for iChunk in range(nChunk)]
# make sure not to miss the last few objects:
# add them to the last chunk
chunkIndices[-1] = range((nChunk-1)*chunkSize, ts.Catalog.nObj)
# select weights for a typical aperture size (not the smallest, not the largest)
#iRAp0 = ts.nRAp / 2
iRAp0 = ts.nRAp / 4
norm = norm[iRAp0]
# need to link object number with weight,
# despite the mask
weightsLong = np.zeros(ts.Catalog.nObj)
weightsLong[mask] = weights[:,iRAp0]
def stackChunk(iChunk):
# object indices to be processed
chunk = chunkIndices[iChunk]
# start with a null map for stacking
resMap = ts.cutoutGeometry()
for iObj in chunk:
if iObj%10000==0:
print "- analyze object", iObj
if ts.overlapFlag[iObj]:
# Object coordinates
ra = ts.Catalog.RA[iObj] # in deg
dec = ts.Catalog.DEC[iObj] # in deg
z = ts.Catalog.Z[iObj]
# extract postage stamp around it
opos, stampMap, stampMask, stampHit = ts.extractStamp(ra, dec, test=False)
resMap += stampMap * weightsLong[iObj]
return resMap
# dispatch each chunk of objects to a different processor
with sharedmem.MapReduce(np=ts.nProc) as pool:
resMap = np.array(pool.map(stackChunk, range(nChunk)))