forked from EmmanuelSchaan/LensQuEst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflat_map.py
4162 lines (3535 loc) · 157 KB
/
flat_map.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
from headers import *
###################################################################
class FlatMap(object):
def __init__(self, nX=256, nY=256, sizeX=5.*np.pi/180., sizeY=5.*np.pi/180., name="test"):
"""n is number of pixels on one side
size is the angular size of the side, in radians
"""
self.name = name
self.nX = nX
self.sizeX = sizeX
self.dX = float(sizeX)/(nX-1)
x = self.dX * np.arange(nX) # the x value corresponds to the center of the cell
#
self.nY = nY
self.sizeY = sizeY
self.dY = float(sizeY)/(nY-1)
y = self.dY * np.arange(nY) # the y value corresponds to the center of the cell
#
self.x, self.y = np.meshgrid(x, y, indexing='ij')
#
self.fSky = self.sizeX*self.sizeY / (4.*np.pi)
self.data = np.zeros((nX,nY))
lx = np.zeros(nX)
lx[:nX/2+1] = 2.*np.pi/sizeX * np.arange(nX//2+1)
lx[nX/2+1:] = 2.*np.pi/sizeX * np.arange(-nX//2+1, 0, 1)
ly = 2.*np.pi/sizeY * np.arange(nY//2+1)
self.lx, self.ly = np.meshgrid(lx, ly, indexing='ij')
self.l = np.sqrt(self.lx**2 + self.ly**2)
self.dataFourier = np.zeros((nX,nY//2+1))
def copy(self):
newMap = FlatMap(nX=self.nX, nY=self.nY, sizeX=self.sizeX, sizeY=self.sizeY, name=self.name)
newMap.data = self.data.copy()
newMap.dataFourier = self.dataFourier.copy()
return newMap
def write(self, path=None):
# primary hdu: size of map
prihdr = fits.Header()
prihdr['name'] = self.name
prihdr['nX'] = self.nX
prihdr['sizeX'] = self.sizeX
prihdr['nY'] = self.nY
prihdr['sizeY'] = self.sizeY
hdu0 = fits.PrimaryHDU(header=prihdr)
# secondary hdu: real-space and Fourier maps
c1 = fits.Column(name='data', format='D', array=self.data.flatten())
c2 = fits.Column(name='dataFourier', format='M', array=self.dataFourier.flatten())
hdu1 = fits.BinTableHDU.from_columns([c1, c2])
#
hdulist = fits.HDUList([hdu0, hdu1])
if path is None:
path = "./output/lens_simulator/"+self.name+".fits"
print "writing to "+path
hdulist.writeto(path, overwrite=True)
def read(self, path=None):
if path is None:
path = "./output/lens_simulator/"+self.name+".fits"
print "reading from "+path
hdulist = fits.open(path)
#
#self.name = hdulist[0].header['name']
self.nX = hdulist[0].header['nX']
self.sizeX = hdulist[0].header['sizeX']
self.nY = hdulist[0].header['nY']
self.sizeY = hdulist[0].header['sizeY']
#
self.__init__(nX=self.nX, nY=self.nY, sizeX=self.sizeX, sizeY=self.sizeY, name=self.name)
#
self.data = hdulist[1].data['data'].reshape((self.nX, self.nY))
self.dataFourier = hdulist[1].data['dataFourier'][:self.nX*(self.nY//2+1)].reshape((self.nX, self.nY//2+1))
#
hdulist.close()
def saveDataFourier(self, dataFourier, path):
print "saving Fourier map to", path
# primary hdu: size of map
prihdr = fits.Header()
prihdr['nX'] = self.nX
prihdr['sizeX'] = self.sizeX
prihdr['nY'] = self.nY
prihdr['sizeY'] = self.sizeY
hdu0 = fits.PrimaryHDU(header=prihdr)
# secondary hdu: maps
c1 = fits.Column(name='dataFourier', format='M', array=dataFourier.flatten())
hdu1 = fits.BinTableHDU.from_columns([c1])
#
hdulist = fits.HDUList([hdu0, hdu1])
#
hdulist.writeto(path, overwrite=True)
def loadDataFourier(self, path):
print "reading fourier map from", path
hdulist = fits.open(path)
dataFourier = hdulist[1].data['dataFourier'][:self.nX*(self.nY//2+1)].reshape((self.nX, self.nY//2+1))
hdulist.close()
return dataFourier
###############################################################################
# change resolution of map
def downResolution(self, nXNew, nYNew, data=None, test=False):
"""Expects nXNew < self.nX and nYNew < self.nY
"""
if data is None:
data = self.data.copy()
# Fourier transform the map
dataFourier = self.fourier(data)
# truncate the fourier map
newMap = FlatMap(nXNew, nYNew, sizeX=self.sizeX, sizeY=self.sizeY)
IX = range(nXNew//2+1) + range(-nXNew//2+1, 0)
IY = range(nYNew//2+1)
IX, IY = np.meshgrid(IX, IY, indexing='ij')
newMap.dataFourier = dataFourier[IX, IY]
# update real space map
newMap.data = newMap.inverseFourier()
if test:
self.plot(data)
newMap.plot(newMap.data)
return newMap.data
def upResolution(self, nXNew, nYNew, data=None, test=False):
"""Expects nXNew > self.nX and nYNew > self.nY
"""
if data is None:
data = self.data.copy()
# Fourier transform the map
dataFourier = self.fourier(data)
# zero-pad the fourier map
newMap = FlatMap(nXNew, nYNew, sizeX=self.sizeX, sizeY=self.sizeY)
IX = range(self.nX//2+1) + range(-self.nX//2+1, 0)
IY = range(self.nY//2+1)
newMap.dataFourier[IX, IY] = dataFourier
# update real space map
newMap.data = newMap.inverseFourier()
if test:
self.plot(data)
newMap.plot(newMap.data)
return newMap.data
###############################################################################
# plots
def plot(self, data=None, save=False, path=None, cmap='viridis'):
if data is None:
data = self.data.copy()
sigma = np.std(data.flatten())
vmin = np.min(data.flatten())
vmax = np.max(data.flatten())
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
# pcolor wants x and y to be edges of cell,
# ie one more element, and offset by half a cell
x = self.dX * (np.arange(self.nX+1) - 0.5)
y = self.dY * (np.arange(self.nY+1) - 0.5)
x,y = np.meshgrid(x, y, indexing='ij')
#
cp=ax.pcolormesh(x*180./np.pi, y*180./np.pi, data, linewidth=0, rasterized=True)
#
# choose color map: jet, summer, winter, Reds, gist_gray, YlOrRd, bwr, seismic
cp.set_cmap(cmap)
#cp.set_clim(0.,255.)
#cp.set_clim(-3.*sigma, 3.*sigma)
cp.set_clim(vmin, vmax)
fig.colorbar(cp)
#
plt.axis('scaled')
ax.set_xlim(np.min(x)*180./np.pi, np.max(x)*180./np.pi)
ax.set_ylim(np.min(y)*180./np.pi, np.max(y)*180./np.pi)
ax.set_xlabel('$x$ [deg]')
ax.set_ylabel('$y$ [deg]')
#
if save==True:
if path is None:
path = "./figures/lens_simulator/"+self.name+".pdf"
print "saving plot to "+path
fig.savefig(path, bbox_inches='tight')
fig.clf()
else:
plt.show()
def plotFourier(self, dataFourier=None, save=False, name=None, cmap='viridis'):
if dataFourier is None:
dataFourier = self.dataFourier.copy()
dataFourier = np.real(dataFourier)
sigma = np.std(dataFourier.flatten())
vmin = np.min(dataFourier.flatten())
vmax = np.max(dataFourier.flatten())
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
# pcolor wants x and y to be edges of cell,
# ie one more element, and offset by half a cell
#
# left part of plot
lxLeft = 2.*np.pi/self.sizeX * (np.arange(-self.nX/2+1, 1, 1) - 0.5)
ly = 2.*np.pi/self.sizeY * (np.arange(self.nY//2+1+1) - 0.5)
lx, ly = np.meshgrid(lxLeft, ly, indexing='ij')
cp1=ax.pcolormesh(lx, ly, dataFourier[self.nX/2+1:,:], linewidth=0, rasterized=True)
#
# right part of plot
lxRight = 2.*np.pi/self.sizeX * (np.arange(self.nX/2+1+1) - 0.5)
ly = 2.*np.pi/self.sizeY * (np.arange(self.nY//2+1+1) - 0.5)
lx, ly = np.meshgrid(lxRight, ly, indexing='ij')
cp2=ax.pcolormesh(lx, ly, dataFourier[:self.nX/2+1,:], linewidth=0, rasterized=True)
#
# choose color map: jet, summer, winter, Reds, gist_gray, YlOrRd, bwr, seismic
cp1.set_cmap(cmap); cp2.set_cmap(cmap)
#cp1.set_clim(0.,255.); cp2.set_clim(0.,255.)
#cp1.set_clim(-3.*sigma, 3.*sigma); cp2.set_clim(-3.*sigma, 3.*sigma)
cp1.set_clim(vmin, vmax); cp2.set_clim(vmin, vmax)
#
fig.colorbar(cp1)
#
plt.axis('scaled')
ax.set_xlim(np.min(lxLeft), np.max(lxRight))
ax.set_ylim(np.min(ly), np.max(ly))
ax.set_xlabel('$\ell_x$')
ax.set_ylabel('$\ell_y$')
#
if save==True:
if name is None:
name = self.name
print "saving plot to "+"./figures/lens_simulator/"+name+".pdf"
fig.savefig("./figures/lens_simulator/"+name+".pdf", bbox_inches='tight')
fig.clf()
else:
plt.show()
def plotHistogram(self, data=None, save=False, name=None, nBins=100):
"""plot a pixel histogram
"""
if data is None:
data = self.data.copy()
# data mean, var, skewness, kurtosis
mean = np.mean(data)
sigma = np.std(data)
skewness = np.mean((data-mean)**3) / sigma**3
kurtosis = np.mean((data-mean)**4) / sigma**4
print "mean =", mean
print "std. dev =", sigma
print "skewness =", skewness
print "kurtosis =", kurtosis
# data histogram, and error bars on it
pdf, binEdges = np.histogram(data, density=False, bins=nBins)
binWidth = (np.max(data)-np.min(data))/nBins
spdf = np.sqrt(pdf) / (np.sum(pdf)*binWidth) # absolute 1-sigma error on pdf
pdf = pdf / (np.sum(pdf)*binWidth)
# Gaussian histogram with same mean and var
samples = np.random.normal(loc=mean, scale=sigma, size=self.nX*self.nY)
pdfGauss, binEdgesGauss = np.histogram(samples, density=True, bins=nBins, range=(binEdges[0], binEdges[-1]))
# Poisson histogram with same mean
if mean>0.:
samples = np.random.poisson(lam=mean, size=self.nX*self.nY)
pdfPoiss, binEdgesPoiss = np.histogram(samples, density=True, bins=nBins, range=(binEdges[0], binEdges[-1]))
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
# data histogram
ax.step(binEdges[:-1], pdf, where='post', color='b', lw=2, label=r'map')
# error band on data histogram
ax.fill_between(np.linspace(binEdges[0], binEdges[-1], 100*len(pdf)),
np.repeat(pdf-spdf, 100),
np.repeat(pdf+spdf, 100),
color='b')
#
# Gaussian histogram
ax.step(binEdgesGauss[:-1], pdfGauss, where='post', color='r', lw=2, label=r'Gaussian')
ax.axvline(mean, color='k')
ax.axvline(mean + 1.*sigma, color='gray')
ax.axvline(mean + 2.*sigma, color='gray')
ax.axvline(mean + 3.*sigma, color='gray')
ax.axvline(mean + 4.*sigma, color='gray')
ax.axvline(mean + 5.*sigma, color='gray')
ax.axvline(mean + -1.*sigma, color='gray')
ax.axvline(mean + -2.*sigma, color='gray')
ax.axvline(mean + -3.*sigma, color='gray')
ax.axvline(mean + -4.*sigma, color='gray')
ax.axvline(mean + -5.*sigma, color='gray')
#
# Poisson histogram
if mean>0.:
ax.step(binEdgesPoiss[:-1], pdfPoiss, where='post', color='g', lw=2, label=r'Poisson')
#
ax.legend(loc=1)
#ax.set_xlim((-4.*sigma, 4.*sigma))
ax.set_yscale('log')
#
if save==True:
if name is None:
name = self.name
print "saving plot to "+"./figures/lens_simulator/histogram_"+name+".pdf"
fig.savefig("./figures/lens_simulator/histogram_"+name+".pdf", bbox_inches='tight')
fig.clf()
else:
plt.show()
# !!! the x and y axes might be reversed!
def plotDeflectionFieldLines(self, dx, dy):
d = np.sqrt(dx**2+dy**2)
d /= np.max(d.flatten())
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
strm = ax.streamplot(self.y*180./np.pi, self.x*180./np.pi, dy, dx, color=d, linewidth=3.*d, cmap=plt.cm.autumn, density=3.)
fig.colorbar(strm.lines)
#
plt.axis('scaled')
ax.set_xlim(np.min(self.x.flatten())*180./np.pi, np.max(self.x.flatten())*180./np.pi)
ax.set_ylim(np.min(self.y.flatten())*180./np.pi, np.max(self.y.flatten())*180./np.pi)
ax.set_xlabel('$x$ [deg]')
ax.set_ylabel('$y$ [deg]')
plt.show()
def plotDeflectionArrows(self, dx, dy, save=False, name=None):
d = np.sqrt(dx**2+dy**2)
# Keep only some of the points
skip = (slice(None, None, self.nX/25), slice(None, None, self.nX/25))
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
#
# pcolor wants x and y to be edges of cell,
# ie one more element, and offset by half a cell
x = self.dX * (np.arange(self.nX+1) - 0.5)
y = self.dY * (np.arange(self.nY+1) - 0.5)
x,y = np.meshgrid(x, y, indexing='ij')
#
sigma = self.data.std()
cp=ax.pcolormesh(x*180./np.pi, y*180./np.pi, self.data, linewidth=0, rasterized=True, alpha=1, cmap=plt.cm.jet)
# cp=ax.pcolormesh(x*180./np.pi, y*180./np.pi, self.data, linewidth=0, rasterized=True, alpha=1, vmin=-2.5*sigma, vmax=2.5*sigma, cmap=cmaps.viridis)
fig.colorbar(cp)
#
#
# ax.quiver(self.x[skip]*180./np.pi, self.y[skip]*180./np.pi, dx[skip]*180./np.pi, dy[skip]*180./np.pi, d[skip]*180./np.pi, units='xy', edgecolor='', width=0.007*self.sizeX*180./np.pi)
ax.quiver(self.x[skip]*180./np.pi, self.y[skip]*180./np.pi, dx[skip]*180./np.pi, dy[skip]*180./np.pi, facecolor='k', units='xy', angles='xy', scale_units='xy', scale=1, width=0.003*self.sizeX*180./np.pi)
#
#
plt.axis('scaled')
ax.set_xlim(np.min(self.x.flatten())*180./np.pi, np.max(self.x.flatten())*180./np.pi)
ax.set_ylim(np.min(self.y.flatten())*180./np.pi, np.max(self.y.flatten())*180./np.pi)
ax.set_xlabel('$x$ [deg]')
ax.set_ylabel('$y$ [deg]')
#
if save==True:
if name is None:
name = self.name
print "saving plot to "+"./figures/lens_simulator/"+name+".pdf"
fig.savefig("./figures/lens_simulator/"+name+"_arrows.pdf", bbox_inches='tight')
fig.clf()
else:
plt.show()
###############################################################################
# Fourier transforms, notmalized such that
# f(k) = int dx e-ikx f(x)
# f(x) = int dk/2pi eikx f(k)
def fourier(self, data=None):
"""Fourier transforms, notmalized such that
f(k) = int dx e-ikx f(x)
f(x) = int dk/2pi eikx f(k)
"""
if data is None:
data = self.data.copy()
# use numpy's fft
result = np.fft.rfftn(data)
# # use pyfftw's fft. Make sure the real-space data has type np.float128
# result = pyfftw.interfaces.numpy_fft.rfftn((np.float128)(data))
result *= self.dX * self.dY
return result
def inverseFourier(self, dataFourier=None):
"""Fourier transforms, notmalized such that
f(k) = int dx e-ikx f(x)
f(x) = int dk/2pi eikx f(k)
"""
if dataFourier is None:
dataFourier = self.dataFourier.copy()
# use numpy's fft
result = np.fft.irfftn(dataFourier)
# # use pyfftw's fft. Make sure the Fourier data has type np.complex128
# result = pyfftw.interfaces.numpy_fft.irfftn((np.complex128)(dataFourier))
result /= self.dX * self.dY
return result
###############################################################################
# Measure power spectrum
def crossPowerSpectrum(self, dataFourier1, dataFourier2, theory=[], fsCl=None, nBins=51, lRange=None, plot=False, name="test", save=False):
# define ell bins
ell = self.l.flatten()
if lRange is None:
lEdges = np.logspace(np.log10(1.), np.log10(np.max(ell)), nBins, 10.)
else:
lEdges = np.logspace(np.log10(lRange[0]), np.log10(lRange[-1]), nBins, 10.)
# bin centers
lCen, lEdges, binIndices = stats.binned_statistic(ell, ell, statistic='mean', bins=lEdges)
# when bin is empty, replace lCen by a naive expectation
lCenNaive = 0.5*(lEdges[:-1]+lEdges[1:])
lCen[np.where(np.isnan(lCen))] = lCenNaive[np.where(np.isnan(lCen))]
# number of modes
Nmodes, lEdges, binIndices = stats.binned_statistic(ell, np.zeros_like(ell), statistic='count', bins=lEdges)
Nmodes = np.nan_to_num(Nmodes)
# power spectrum
power = (dataFourier1 * np.conj(dataFourier2)).flatten()
power = np.real(power) # unnecessary in principle, but avoids binned_statistics to complain
Cl, lEdges, binIndices = stats.binned_statistic(ell, power, statistic='mean', bins=lEdges)
Cl = np.nan_to_num(Cl)
# finite volume correction
Cl /= self.sizeX*self.sizeY
# 1sigma uncertainty on Cl
if fsCl is None:
sCl = Cl*np.sqrt(2)
else:
sCl = np.array(map(fsCl, lCen))
# In case of a cross-correlation, Cl may be negative.
# the absolute value is then still some estimate of the error bar
sCl = np.abs(sCl)
sCl /= np.sqrt(Nmodes)
sCl[np.where(np.isfinite(sCl)==False)] = 0.
if plot:
factor = 1. # lCen**2
fig=plt.figure(0)
ax=fig.add_subplot(111)
#
Ipos = np.where(Cl>=0.)
Ineg = np.where(Cl<0.)
ax.errorbar(lCen[Ipos], factor*Cl[Ipos], yerr=factor*sCl[Ipos], c='b', fmt='.')
ax.errorbar(lCen[Ineg], -factor*Cl[Ineg], yerr=factor*sCl[Ineg], c='r', fmt='.')
#
for f in theory:
L = np.logspace(np.log10(1.), np.log10(np.max(ell)), 201, 10.)
ClExpected = np.array(map(f, L))
ax.plot(L, factor*ClExpected, 'k')
#
# ax.axhline(0.)
ax.set_xscale('log', nonposx='clip')
ax.set_yscale('log', nonposy='clip')
#ax.set_xlim(1.e1, 4.e4)
#ax.set_ylim(1.e-5, 2.e5)
ax.set_xlabel(r'$\ell$')
#ax.set_ylabel(r'$\ell^2 C_\ell$')
ax.set_ylabel(r'$C_\ell$')
#
if save==True:
if name is None:
name = self.name
print "saving plot to "+"./figures/lens_simulator/"+name+"_power.pdf"
fig.savefig("./figures/lens_simulator/"+name+"_power.pdf", bbox_inches='tight')
fig.clf()
else:
plt.show()
return lCen, Cl, sCl
def powerSpectrum(self, dataFourier=None, theory=[], fsCl=None, nBins=51, lRange=None, plot=False, name="test", save=False):
if dataFourier is None:
dataFourier = self.dataFourier.copy()
return self.crossPowerSpectrum(dataFourier1=dataFourier, dataFourier2=dataFourier, theory=theory, fsCl=fsCl, nBins=nBins, lRange=lRange, plot=plot, name=name, save=save)
def binTheoryPowerSpectrum(self, fCl, nBins=17, lRange=None):
"""Bin a theory power spectrum to allow to compare it with the measured power spectrum of a map.
"""
# define ell bins
ell = self.l.flatten()
if lRange is None:
lEdges = np.logspace(np.log10(1.), np.log10(np.max(ell)), nBins, 10.)
else:
lEdges = np.logspace(np.log10(lRange[0]), np.log10(lRange[-1]), nBins, 10.)
# bin centers
lCen, lEdges, binIndices = stats.binned_statistic(ell, ell, statistic='mean', bins=lEdges)
# when bin is empty, replace lCen by a naive expectation
lCenNaive = 0.5*(lEdges[:-1]+lEdges[1:])
lCen[np.where(np.isnan(lCen))] = lCenNaive[np.where(np.isnan(lCen))]
# generate map with theory power spectrum
clmapFourier = self.filterFourierIsotropic(fCl, dataFourier=np.ones_like(self.l), test=False)
clmapFourier = np.real(clmapFourier.flatten())
Cl, lEdges, binIndices = stats.binned_statistic(ell, clmapFourier, statistic='mean', bins=lEdges)
Cl = np.nan_to_num(Cl)
return lCen, Cl
###############################################################################
# Gaussians and tests for Fourier transform conventions
def genGaussian(self, meanX=0., meanY=0., sigma1d=1.):
result = np.exp(-0.5*((self.x-meanX)**2 + (self.y-meanY)**2)/sigma1d**2)
result /= 2.*np.pi*sigma1d**2
return result
def genGaussianFourier(self, meanLX=0., meanLY=0., sigma1d=1.):
result = np.exp(-0.5*((self.lx-meanLX)**2 + (self.ly-meanLY)**2)/sigma1d**2)
result /= 2.*np.pi*sigma1d**2
return result
def testFourierGaussian(self):
"""tests that the FT of a Gaussian is a Gaussian,
with correct normalization and variance
"""
# generate a quarter of a Gaussian
sigma1d = self.sizeX / 10.
self.data = self.genGaussian(sigma1d=sigma1d)
# show it
self.plot()
# fourier transform it
self.dataFourier = self.fourier()
self.plotFourier()
# computed expected Gaussian
expectedFourier = self.genGaussianFourier(sigma1d=1./sigma1d)
expectedFourier *= 2.*np.pi*(1./sigma1d)**2
expectedFourier /= 4. # because only one quadrant in real space
#self.plotFourier(data=self.dataFourier/expectedFourier-1.)
# compare along one axis
plt.plot(self.dataFourier[0,:], 'k')
plt.plot(expectedFourier[0,:], 'r')
plt.show()
# compare along other axis
plt.plot(self.dataFourier[:,0], 'k')
plt.plot(expectedFourier[:,0], 'r')
plt.show()
def testFourierCos(self):
"""tests that the FT of cos(k*x)
peaks at the right k
"""
# generate a quarter of a Gaussian
ell = 100.
self.data = np.cos(ell*self.x) + np.cos(ell*self.y)
# show it
self.plot()
# fourier transform it
self.dataFourier = self.fourier()
#self.plotFourier()
self.plotFourier()
def testInverseFourier(self):
"""test that the inverse FT of the forward FT is the initial function
"""
# generate a quarter of a Gaussian
sigma1d = 2.
self.data = self.genGaussian(sigma1d=sigma1d)
# show it
self.plot()
# Fourier transform it
self.dataFourier = self.fourier()
# inverse Fourier transform it
expectedData = self.inverseFourier()
# compare along each axis
plt.plot(self.y[0,:], self.data[0,:]/expectedData[0,:]-1., 'g')
plt.plot(self.x[:,0], self.data[:,0]/expectedData[:,0]-1., 'b--')
plt.show()
###############################################################################
# generate Gaussian random field with any power spectrum
'''
#!!!!!!! Wrong on the axis ly=0: does not satisfy f(-l)=f(l)* there,
# which means that the real-space map will be complex.
#!!!!!!! Also, the modulus should not be Gaussian, but Rayleigh, and with mean non-zero!!!
def genGRF(self, fCl, test=False):
# flatten the Fourier data,
# and put in it the value of Cl
dataFourier = np.array(map(fCl, self.l.flatten()))
dataFourier = np.nan_to_num(dataFourier)
# rescale by finite volume
dataFourier *= self.sizeX*self.sizeY
# reshape it
dataFourier = dataFourier.reshape(np.shape(self.l))
if test:
print dataFourier[0,0]
# plot Fourier power map
self.plotFourier(dataFourier=self.l**2 * np.abs(dataFourier))
# plot Fourier power
plt.plot(self.l.flatten(), self.l.flatten()**2 * np.abs(dataFourier.flatten()), 'k.')
plt.show()
# for each ell vector,
# generate a Gaussian random number with variance = cl
f = lambda var: np.random.normal(0., scale=np.sqrt(var)+1.e-16) * np.exp(1j*np.random.uniform(0., 2.*np.pi))
dataFourier = np.array(map(f, dataFourier.flatten()))
# reshape it
dataFourier = dataFourier.reshape(np.shape(self.l))
if test:
print dataFourier[0,0]
# plot Fourier map
self.plotFourier(dataFourier=dataFourier)
self.plotFourier(dataFourier=self.l**2 * np.abs(dataFourier)**2)
# plot Fourier power
plt.plot(self.l.flatten(), self.l.flatten()**2 * np.abs(dataFourier.flatten())**2, 'k.', alpha=0.1)
plt.show()
if test:
print dataFourier[0,0]
data = self.inverseFourier()
self.plot(data=data)
self.plotFourier(dataFourier=dataFourier)
return dataFourier
'''
def genGRF(self, fCl, test=False):
# generate Gaussian white noise in real space
data = np.zeros_like(self.data)
data = np.random.normal(loc=0., scale=1./np.sqrt(self.dX*self.dY), size=len(self.x.flatten()))
data = data.reshape(np.shape(self.x))
# Fourier transform
dataFourier = self.fourier(data)
if test:
# check that the power spectrum is Cl = 1
self.powerSpectrum(dataFourier, theory=[lambda l:1.], plot=True)
# multiply by desired power spectrum
f = lambda l: np.sqrt(fCl(l))
clFourier = np.array(map(f, self.l.flatten()))
clFourier = np.nan_to_num(clFourier)
clFourier = clFourier.reshape(np.shape(self.l))
dataFourier *= clFourier
if test:
# check 0 mode
print "l=0 mode is:", dataFourier[0,0]
# check that the power spectrum is the desired one
self.powerSpectrum(dataFourier, theory=[fCl], plot=True)
# show the fourier map
self.plotFourier(dataFourier)
# show the real space map
data = self.inverseFourier(dataFourier)
self.plot(data)
return dataFourier
def saveGRFMocks(self, fCl, nRand, directory=None, name=None):
"""create nRand GRF mock maps
"""
if directory is None:
directory = "./output/lens_simulator/mocks/"+self.name
if name is None:
name = "mock_"
# create folder if needed
if not os.path.exists(directory):
os.makedirs(directory)
for iRand in range(nRand):
path = directory+"/"+name+str(iRand)+".fits"
randomFourier = self.genGRF(fCl)
self.saveDataFourier(randomFourier, path)
def loadAllGRFMocks(self, nRand, directory=None, name=None):
"""DO NOT USE unless you have infinite RAM ;)
"""
if directory is None:
directory = "./output/lens_simulator/mocks/"+self.name
if name is None:
name = "mock_"
self.mockDataFourier = {}
for iRand in range(nRand):
path = directory+"/"+name+str(iRand)+".fits"
self.mockDataFourier[iRand] = self.loadDataFourier(path)
def genCorrGRF(self, fC11, fC22, fC12, test=False):
"""Generate two correlated GRFs, with the correct auto and cross spectra.
"""
# mao 1: generate GRF
data1Fourier = self.genGRF(fC11, test=False)
# map 2: start with part correlated with map 1
f = lambda l: fC12(l)/fC11(l)
data2Fourier = self.filterFourierIsotropic(f, dataFourier=data1Fourier, test=False)
# map 2: add uncorrelated part
f = lambda l: fC22(l) - (fC12(l)*fC12(l))/(fC11(l))
data2Fourier += self.genGRF(f, test=False)
# avoid nan and inf
data1Fourier[np.where(np.isfinite(data1Fourier)==False)] = 0.
data2Fourier[np.where(np.isfinite(data2Fourier)==False)] = 0.
if test:
self.powerSpectrum(data1Fourier, theory=[fC11], plot=True)
self.powerSpectrum(data2Fourier, theory=[fC22], plot=True)
self.crossPowerSpectrum(data1Fourier, data2Fourier, theory=[fC12], plot=True)
return data1Fourier, data2Fourier
###############################################################################
# generate map where T_ell has C_ell for modulus square,
# and a random phase.
# Useful to avoid sample variance
def genMockIsotropicNoSampleVar(self, fCl, test=False, path=None):
# generate map with correct modulus
f = lambda l: np.sqrt(fCl(l))
resultFourier = self.filterFourierIsotropic(f, dataFourier=np.ones_like(self.dataFourier), test=test)
resultFourier *= np.sqrt(self.sizeX * self.sizeY)
# generate random phases
f = lambda lx,ly: np.exp(1j*np.random.uniform(0., 2.*np.pi))
resultFourier = self.filterFourier(f, dataFourier=resultFourier)
# keep it real ;)
# if lx=ly=0, set to zero
resultFourier[0,0] = 0.
# if ly=0, make sure T[lx, 0] = T[-lx, 0]^*
for i in range(self.nX//2+1, self.nX):
resultFourier[i,0] = np.conj(resultFourier[self.nX-i, 0])
# save if needed
if path is not None:
self.saveDataFourier(resultFourier, path)
return resultFourier
###############################################################################
# Generate Poisson white noise map
def genPoissonWhiteNoise(self, nbar, norm=False, test=False):
"""Generate Poisson white noise.
Returns real space map.
nbar mean number density of objects, in 1/sr.
if norm=False, returns a map of N (number)
if norm=True, returns a map of delta = N/Nbar - 1
"""
# number of objects per pixel
Ngal = nbar * self.dX * self.dY
if test:
print "generate Poisson white noise"
print nbar+" objects per sr, i.e. "+Ngal+" objects per pixel"
data = np.random.poisson(lam=Ngal, size=len(self.x.flatten()))
if norm:
data = data / Ngal - 1.
data = data.reshape(np.shape(self.x))
return data
###############################################################################
# filter map
def filterFourierIsotropic(self, fW, dataFourier=None, test=False):
"""the filter fW is assumed to be function of |ell|
"""
if dataFourier is None:
dataFourier = self.dataFourier.copy()
W = np.array(map(fW, self.l.flatten()))
W = W.reshape(self.l.shape)
if test:
self.plotFourier(dataFourier=W)
#
plt.plot(self.l.flatten(), W.flatten(), 'b.')
plt.show()
result = dataFourier * W
result = np.nan_to_num(result)
return result
def filterFourier(self, fW, dataFourier=None, test=False):
"""the filter fW is assumed to be function of lx, ly
"""
if dataFourier is None:
dataFourier = self.dataFourier.copy()
f = np.vectorize(fW)
W = f(self.lx, self.ly)
if test:
self.plotFourier(dataFourier=W)
#
plt.plot(self.l.flatten(), W.flatten(), 'b.')
plt.show()
result = dataFourier * W
result = np.nan_to_num(result)
return result
###############################################################################
# Matched filter and point source mask
def matchedFilterIsotropic(self, fCl, fprof=None, dataFourier=None, test=False):
""" Match-filter a surface brightness map into a flux map
T_filt = (T_l * prof_l / C_l) / (\int d^2l/(2pi)^2 prof_l^2/C_l)
If T(x) in Jy/sr, T_l in Jy,
then T_filt(x) in Jy, T_filt_l in Jy*sr.
fW = C_l is the total debeamed noise power.
prof_l is the profile before beam convolution (i.e. 1 for point source).
"""
if dataFourier is None:
dataFourier = self.dataFourier.copy()
if fprof is None:
fprof = lambda l: 1.
# filter function
def fW(l):
result = fprof(l) / fCl(l)
if not np.isfinite(result):
result = 0.
return result
# filter the map
resultFourier = self.filterFourierIsotropic(fW, dataFourier=dataFourier, test=test)
# normalization function
def fNorm(l):
result = l/(2.*np.pi) * fprof(l)**2 / fCl(l)
if not np.isfinite(result):
result = 0.
return result
# compute normalization
normalization = integrate.quad(fNorm, self.l.min(), self.l.max(), epsabs=0., epsrel=1.e-3)[0]
# normalize the filtered map
resultFourier /= normalization
if test:
result = self.inverseFourier(resultFourier)
self.plot(result)
return resultFourier
def pointSourceMaskMatchedFilterIsotropic(self, fCl, fluxCut, fprof=None, dataFourier=None, maskPatchRadius=None, test=False):
"""Returns the mask for point sources with flux above fluxCut.
If T(x) in Jy/sr, T_l in Jy, Cl in Jy^2/sr, fluxCut in Jy.
If T(x) in muK, T_l in muK*sr, Cl in (muK)^2*sr, fluxCut in muK*sr.
prof_l is the profile before beam convolution (i.e. 1 for point source).
The mask is 1 almost everywhere, and 0 on point sources.
Patch is patch radius in rad, to mask around point sources
"""
# matched-filter the map
filteredFourier = self.matchedFilterIsotropic(fCl, fprof=fprof, dataFourier=dataFourier, test=test)
filtered = self.inverseFourier(filteredFourier)
# threshold the map
mask = 1. * (np.abs(filtered) < fluxCut)
if maskPatchRadius is not None:
# make a Gaussian such that the fwhm is twice the maskPatchRadius
fwhm = 2. * maskPatchRadius#5. * np.pi/(180.*60.)
s = fwhm / np.sqrt(8.*np.log(2.))
f = lambda l: np.exp(-0.5 * l**2 * s**2)
gaussFourier = self.filterFourierIsotropic(f, dataFourier=np.ones_like(self.dataFourier))
# normalize properly, accounting for Kronecker vs Dirac and finite pixel size
gaussFourier /= special.erf(self.dX/(np.sqrt(8.)*s)) * special.erf(self.dY/(np.sqrt(8.)*s))
# smooth the mask
# Fourier transform 1-mask, to have zero everywhere except on the point sources
maskFourier = self.fourier(1. - mask)
mask = self.inverseFourier(maskFourier * gaussFourier)
# threshold the smoothed mask at half-max
mask = 1. * (mask < 0.5) #*np.max(mask.flatten()))
return mask
###############################################################################
# pixel window function, Gaussian beam
def pixelWindow(self, lx, ly, dX=None, dY=None):
if dX is None:
dX = self.dX
if dY is None:
dY = self.dY
result = sinc(0.5 * lx * dX)
result *= sinc(0.5 * ly * dY)
return result
def inversePixelWindow(self, lx, ly):
result = 1./self.pixelWindow(lx, ly)
if not np.isfinite(result):
result = 0.
return result
def gaussianBeam(self, l, fwhm):
"""fwhm is in radians
"""
sigma_beam = fwhm / np.sqrt(8.*np.log(2.))
return np.exp(-0.5*l**2 * sigma_beam**2)
def inverseBeam(self, l, fwhm):
result = self.gaussianBeam(l, fwhm)
result = 1./result
if not np.isfinite(result):
result = 0.
return result
def inverseBeamPixelWindow(self, lx, ly, fwhm):
l = np.sqrt(lx**2+ly**2)
result = self.pixelWindow(lx, ly) * self.gaussianBeam(l, fwhm)
result = 1./result
if not np.isfinite(result):
result = 0.
return result
###############################################################################
def randomizePhases(self, dataFourier=None, test=False):
"""Generate new map with same Fourier amplitudes,
but replacing the original phases
with iid uniformly distributed Fourier phases.
"""
if dataFourier is None:
dataFourier = self.dataFourier.copy()
f = lambda z: np.abs(z) * np.exp(1j*np.random.uniform(0., 2.*np.pi))
resultFourier = np.array(map(f, dataFourier.flatten()))
resultFourier = resultFourier.reshape(dataFourier.shape)
return resultFourier
###############################################################################
# def trispectrum(self, lmean=1000., dataFourier=None, theory=None, name="test", save=False, nBins=51, lRange=None):
# """Collapsed 4pt function of map, from power spectrum of squared map.
# Returns 4ptfunc = T + 2CC,
# evaluated at (l, -l+L, l', -l'-L),
# for various L and with l,l' \simeq lmean fixed
# """
# if dataFourier is None:
# dataFourier = self.dataFourier.copy()
#
## # define filter function
## lMean = 1.e3
## sl = 2.e2
## # defined so that int d^2l W^2 = 1?
## # !!! normalization is wrong here, but doesn't matter for ratios
## fW2 = lambda l: np.exp(-0.5*(l-lMean)**2/sl**2) / (2.*np.pi*sl**2)
## fW = lambda l: np.sqrt(fW2(l))
#
# # Window function normalized such that \int d^2l/(2\pi)^2 W(l)^2 very very close to 1
# # to match Simone's
# def fW(l):
# lsigma = 50.
# result = np.exp(-(l-lmean)**2 / (4. * lsigma**2)) )
# result *= (2.*np.pi / lsigma**2)**0.25 / np.sqrt(lmean)
# return result
#