-
Notifications
You must be signed in to change notification settings - Fork 12
/
jointmap.py
3847 lines (3720 loc) · 163 KB
/
jointmap.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 __future__ import division, print_function
import numpy as np, os, time, imp, copy, functools, sys
from scipy import ndimage, optimize, interpolate, integrate, stats, special
from . import enmap, retile, utils, bunch, cg, fft, powspec, array_ops, memory, wcsutils, bench
from astropy import table
from astropy.io import fits
#from matplotlib import pyplot
def read_config(fname):
config = imp.load_source("config", fname)
config.path = fname
return config
def read_geometry(fname):
if os.path.isdir(fname):
geo = retile.read_tileset_geometry(fname + "/tile%(y)03d_%(x)03d.fits")
return geo.shape, geo.wcs
else:
return enmap.read_map_geometry(fname)
def read_beam(params, nl=50000, workdir=".", regularization="ratio", cutoff=0.01):
l = np.arange(nl).astype(float)
if params[0] == "fwhm":
sigma = params[1]*utils.fwhm*utils.arcmin
res = -0.5*l**2*sigma**2
elif params[0] == "transfun":
fname = os.path.join(workdir, params[1])
bdata = np.zeros(nl)
tmp = np.loadtxt(fname)[:,1]
bdata[:len(tmp)] = tmp[:nl]
del tmp
# We want a normalized beam
if "nonorm" not in params[2:]:
bdata[~np.isfinite(bdata)] = 0
bdata /= np.max(bdata)
l = np.arange(len(bdata)).astype(float)
if regularization == "gauss":
# FIXME this assumes normalization and l=0 peak
low = np.where(bdata<cutoff)[0]
if len(low) > 0:
lcut = low[0]
bdata[:lcut+1] = np.log(bdata[:lcut+1])
bdata[lcut+1:] = l[lcut+1:]**2*bdata[lcut]/lcut**2
else:
bdata = np.log(bdata)
elif regularization == "ratio":
# The purpose of this approach is to keep the *ratio* between
# beams constant after they leave the reliable area. This is useful
# because the bema ratio is what matters for the coadded solution, and
# we don't want to invent very high ratios in the area where the beam isn't
# well-defined in the first place. To keep the ratio fixed we must use the
# same function for all the beam continuations, though we can multiply
# that function by a per-beam constant. If we assume that most beams are
# approximately gaussian, then there is a single function that has these
# properties while matching both the slope and value at the cutoff point:
# g(l) = cutoff*(l/lc)**(2*log(cutoff)), where lc is the cutoff point.
# Update: We support beams that don't peak at 1 and where the peak isn't
# at the beginning, by searching from the peak, and scaling the cutoff by it.
ipeak = np.argmax(bdata)
cuteff = bdata[ipeak]*cutoff
low = np.where(bdata[ipeak:]<cuteff)[0]+ipeak
if len(low) > 0:
lcut = low[0]
lv = np.log(cuteff)
bdata[:lcut+1] = np.log(np.maximum(bdata[:lcut+1], bdata[ipeak]*1e-6))
bdata[lcut+1:] = lv + (np.log(l[lcut+1:])-np.log(l[lcut]))*(2*lv)
else:
bdata = np.log(bdata)
else: raise ValueError("Unknown beam regularization '%s'" % regularization)
## we don't trust the beam after the point where it becomes negative
#negs = np.where(bdata<=0)[0]
#ndata = min(nl,len(bdata) if len(negs) == 0 else negs[0]*9//10)
#res[:ndata] = np.log(bdata[:ndata])
## Fit power law to extend the beam beyond its end. That way we will have
## a well-defined value everywhere.
#i1, i2 = ndata*18/20, ndata*19/20
#x1, x2 = np.log(l[i1]), np.log(l[i2])
#y1, y2 = res[i1], res[i2]
#alpha = (y2-y1)/(x2-x1)
#res[i2:] = res[i2] + alpha*np.log(l[i2:]/l[i2-1])
res = bdata
else: raise ValueError("beam type '%s' not implemented" % type)
res = np.maximum(res, -80)
return res
def beam_ratio(beam1, beam2): return beam1 - beam2
def beam_size(beam):
"""Returns the l where the beam has fallen by one sigma. The beam should
be given in the logarithmic form."""
return np.where(beam > -1)[0][-1]
def eval_beam(beam, l, raw=False):
res = enmap.samewcs(utils.interpol(beam, l[None], order=1, mask_nan=False),l)
if not raw: res = np.exp(res)
return res
def calc_profile_ptsrc(freq, nl=50000):
return np.full(nl, 1.0)
# Need to unify the different catalogue formats in use here
cat_format = [("ra","f"),("dec","f"),("sn","f"),("I","f"),("dI","f"),("Q","f"),("dQ","f"),("U","f"),("dU","f")]
def read_catalog(params, workdir="."):
format, fname = params
fname = os.path.join(workdir, fname)
if format == "dory":
data = np.loadtxt(fname)
cat = np.zeros(len(data),dtype=cat_format).view(np.recarray)
cat["ra"], cat["dec"] = data.T[:2]*utils.degree
cat["sn"] = data.T[2]
cat["I"], cat["dI"] = data.T[3:5]*1e3
else: raise NotImplementedError(format)
return cat
def read_spectrum(fname, workdir="."):
fname = os.path.join(workdir, fname)
return powspec.read_spectrum(fname)
# This approach does not work as it is - it suffers from aliasing.
# It could probably be made to work with a fiducial beam, a variable
# step size, and more interpolation, but for now I have bypassed it
# to work directly in fourier space
#def calc_profile_sz(freq, scale=1.0, nl=50000, dl=250):
# # This gives the y to signal response in fourier space
# amp = sz_freq_core(freq*1e9)
# # f(k) = fft(f(x)). Fourier interval is related to l
# # via dl = 2*pi/(dx*n), and lmax is pi/dx. So dx must be
# # pi/nl.
# dl = dl/float(scale)
# dr = np.pi/nl
# nr = utils.nint(2*np.pi/(dr*dl))
# r = np.arange(nr)*dr # radians
# # We want scale=1 to correspond to a FWHM of the sz profile at
# # 1 arcmin. In dimensionless units the FWHM is 0.34208
# y = sz_rad_projected(r/utils.arcmin, scale)
# fy = fft.rfft(y).real
# l = np.arange(len(fy),dtype=float)*dl
# # Expand to full array
# spline = interpolate.splrep(l, np.log(fy))
# profile = np.exp(interpolate.splev(np.arange(nl), spline))
# # This is a good approximation for avoiding aliasing. In the real world,
# # the beam smoothes away high-l modes before they can be aliased, but since
# # we don't have an easy way to compute the beam-convoluted real-space signal,
# # we must avoid the aliasing another way
# profile -= profile[-1]
# # Normalize to 1 response in center, so the mean is not changed
# profile /= profile[0]
# return amp*profile
h_P = 6.62607004e-34
k_B =1.38064852e-23
def sz_freq_core(f, T=2.725):
x = h_P*f/(k_B*T)
ex = np.exp(x)
return x*(ex+1)/(ex-1)-4
def sz_rad_core(x):
"""Dimensionless radial sz profile as a function of r/R500.
Normalized to 1 in center."""
c500 = 1.177
alpha = 1.0510
beta = 5.4905
gamma = 0.3081
cx = c500*x
p = 1/(cx**gamma * (1+cx**alpha)**((beta-gamma)/alpha))
return p
def sz_rad_projected_core(r_ort, zmax=1000):
"""Dimensionaless angular sz profile with FWHM of 1 and an integral of 1. Takes about
0.35 ms to evaluate on laptop."""
return integrate.quad(lambda z: sz_rad_core((z**2+r_ort**2)**0.5*0.34208), 0, zmax)[0]*(2/3.6616198499715846)
class SZInterpolator:
"""This class provides a fast spline-based interpolator for sz_rad_projected_core,
which importantly makes it parallelizable. Only a single instance should be needed, which
which is instantiated globally. When called it will set up its internal state the first
time. The fwhm argument scales it radially while keeping the central amplitude constant.
This means that the total integral will change. If this is not what you want, divide the
result by fwhm**2. It takes 7 us to evaluate for 1 number, 77 us for an array of length
1000 and 66 ms for an array of length 1e6.
"""
def __init__(self, rmax=1000, npoint=1001, sqrt=True, log=True):
self.rmax, self.npoint, self.sqrt, self.log = rmax, npoint, sqrt, log
self.spline = None
def setup(self):
if self.sqrt: self.r = np.linspace(0, self.rmax**0.5, self.npoint)**2
else: self.r = np.linspace(0, self.rmax, self.npoint)
self.v = np.array([sz_rad_projected_core(r) for r in self.r])
if self.log: self.spline = interpolate.splrep(self.r, np.log(self.v))
else: self.spline = interpolate.splrep(self.r, self.v)
def __call__(self, r, fwhm=1.0, fwhm_deriv=False):
"""If fwhm_deriv is True, then computes the derivative of the
spline profile with respect to fwhm."""
if self.spline is None: self.setup()
x = r/fwhm
if self.log:
res = np.exp(interpolate.splev(x, self.spline))
if fwhm_deriv:
res *= -r/fwhm**2*interpolate.splev(x, self.spline, der=1)
else:
res = interpolate.splev(x, self.spline, der=fwhm_deriv)
if fwhm_deriv:
res *= -r/fwhm**2
return res
sz_rad_projected_fast = SZInterpolator()
def sz_2d_profile(shape, pixshape, pos=[0,0], fwhm=1.0, oversample=5, core=10, pad=100,
periodic=False, nofft=False, pos_deriv=None, scale_deriv=False):
"""Return a 2d sz profile with shape [ny,nx] where each pixel has the physical
shape pixshape [wy,wx] in arcminutes. This means that any cos(dec) factors must
be included in pixshape. The profile will be offset by pos [oy,ox]
from the fiducial location shape//2 in the center of the map. The sz profile
will have the given fwhm in arcminutes. The profile will be evaluated at
high resolution given by oversample in order to handle the sz profile's bandlimitlessness.
This introduces a pixel window, which we deconvolve. Fractional offsets are supported
and are handled with fourier shifting, which preserves the overall signal amplitude.
With the default parameters, this function has an accuracy of 5e-6 relative to the peak
for fwhm=1, and takes 14 ms to evaluate for a (33,33) map, about half of which is the
fourier stuff.
"""
n = np.array(shape[-2:])
pos = np.array(pos)
ipos = utils.nint(pos)
fpos = pos-ipos
bpos = n//2
if periodic: pad = 0
def over_helper(shape, pixshape, fwhm, offset, oversample):
#print "over_hepler", shape, pixshape, fwhm, oversample
oversample = oversample//2*2+1
n = np.array(shape[-2:])
N = n*oversample
i = offset*oversample + oversample//2
big_pos = (np.mgrid[:N[0],:N[1]] - i[:,None,None])*(np.array(pixshape)/oversample)[:,None,None]
big_rad = np.sum(big_pos**2,0)**0.5
big_map = sz_rad_projected_fast(big_rad, fwhm, fwhm_deriv=scale_deriv)
# Then downgrade. This is done to get the pixel window. We can't just use
# fourier method to get the pixel window here, as the signal is not band-limited
#map = enmap.downgrade(big_map, oversample)
map = utils.block_reduce(big_map, oversample, axis=-2)
map = utils.block_reduce(map, oversample, axis=-1)
return map
# First evaluate the locations at medium resolution
map = over_helper(shape, pixshape, fwhm, bpos+ipos, oversample)
if nofft: return map
# Then get the central region as high resolution
while core >= 1:
oversample *= 2
cw = core//2*2+1
ci = n//2-cw//2
map[ci[0]:ci[0]+cw,ci[1]:ci[1]+cw] = over_helper((cw,cw), pixshape, fwhm, bpos+ipos-ci, oversample)
core = core//2
# We will now fourier shift to the target offset from the center, and also
# deconvolve the band-limited part of the pixel window.
pad_map = np.pad(map, pad, "constant")+0j
fmap = fft.fft(pad_map, axes=[0,1])
wy, wx = enmap.calc_window(fmap.shape)
fmap *= wy[:,None]
fmap *= wx[None,:]
fmap = fft.shift(fmap, fpos, axes=[0,1], nofft=True, deriv=pos_deriv)
fft.ifft(fmap, pad_map, axes=[0,1], normalize=True)
map[:] = pad_map[(slice(pad,-pad),)*pad_map.ndim].real if pad > 0 else pad_map.real
return map
#def sz_rad_projected(r_ort, fwhm=1.0, xmax=5, dx=1e-3):
# """Compute the projected sz radial profile on the sky, as a function of
# the angular distance r_ort from the center, in arcminutes. The cluster profile full-width
# half-max is given by fwhm."""
# x_ort = np.asarray(r_ort)*0.34208/fwhm
# x_par = np.arange(0,xmax,dx)+dx/2
# res = np.array([np.sum(sz_rad_core((x_par**2 + xo**2)**0.5)) for xo in x_ort.reshape(-1)])
# norm = np.sum(sz_rad_core(x_par))
# return res.reshape(x_ort.shape)/norm
#
#def sz_rad_projected_map(shape, wcs, fwhm=1.0, xmax=5, dx=1e-3):
# pos = enmap.posmap(shape, wcs)
# iy,ix = np.array(shape[-2:])//2+1
# r = np.sum((pos-pos[:,iy,ix][:,None,None])**2,0)**0.5
# r = np.roll(np.roll(r,-ix,-1),-iy,-2)
# # Next build a 1d spline of the sz cluster profile covering all our radii
# r1d = np.arange(0, np.max(r)*1.1, min(r[0,1],r[1,0])*0.5)
# y1d = sz_rad_projected(r1d/utils.arcmin, fwhm, xmax, dx)
# spline = interpolate.splrep(r1d, np.log(y1d))
# y2d = enmap.ndmap(np.exp(interpolate.splev(r, spline)), wcs)
# return y2d
def sz_map_profile(shape, wcs, fwhm=1.0, corner=True):
"""Evaluate the 2d sz profile for the enmap with the given shape
and profile."""
pixshape = enmap.pixshape(shape, wcs)/utils.arcmin
pixshape[1] *= np.cos(enmap.pix2sky(shape, wcs, [shape[-2]//2,shape[-1]//2])[0])
res = sz_2d_profile(shape, pixshape, fwhm=fwhm, oversample=1, core=min(50,min(shape[-2:])//2), periodic=True)
# Shift center to top left corner
if corner: res = np.roll(np.roll(res, -(shape[-2]//2), -2), -(shape[-1]//2), -1)
return enmap.ndmap(res, wcs)
def butter(f, f0, alpha):
if f0 <= 0: return f*0+1
with utils.nowarn():
return 1/(1 + (np.abs(f)/f0)**alpha)
def smooth_pix(map, pixrad):
fmap = enmap.fft(map)
ky = np.fft.fftfreq(map.shape[-2])
kx = np.fft.fftfreq(map.shape[-1])
kr2 = ky[:,None]**2+kx[None,:]**2
fmap *= np.exp(-0.5*kr2*pixrad**2)
map = enmap.ifft(fmap).real
return map
def smooth_ps_pix_log(ps, pixrad):
"""Smooth ps with 2 dof per pixel by the given pixel radius
in lograthmic scale, while applying a correction factor to approximate
the effect of plain smoothing when the background is flat."""
return smooth_pix(ps, pixrad)*1.783
log_smooth_corrections = [ 1.0, # dummy for 0 dof
3.559160, 1.780533, 1.445805, 1.310360, 1.237424, 1.192256, 1.161176, 1.139016,
1.121901, 1.109064, 1.098257, 1.089441, 1.082163, 1.075951, 1.070413, 1.065836,
1.061805, 1.058152, 1.055077, 1.052162, 1.049591, 1.047138, 1.045077, 1.043166,
1.041382, 1.039643, 1.038231, 1.036866, 1.035605, 1.034236, 1.033090, 1.032054,
1.031080, 1.030153, 1.029221, 1.028458, 1.027655, 1.026869, 1.026136, 1.025518,
1.024864, 1.024259, 1.023663, 1.023195, 1.022640, 1.022130, 1.021648, 1.021144,
1.020772]
def smooth_ps_grid(ps, res, alpha=4, log=False, ndof=2):
"""Smooth a 2d power spectrum to the target resolution in l"""
# First get our pixel size in l
lx, ly = enmap.laxes(ps.shape, ps.wcs)
ires = np.array([lx[1],ly[1]])
smooth = np.abs(res/ires)
# We now know how many pixels to somoth by in each direction,
# so perform the actual smoothing
if log: ps = np.log(ps)
fmap = enmap.fft(ps)
ky = np.fft.fftfreq(ps.shape[-2])
kx = np.fft.fftfreq(ps.shape[-1])
fmap /= 1 + np.abs(2*ky[:,None]*smooth[0])**alpha
fmap /= 1 + np.abs(2*kx[None,:]*smooth[1])**alpha
ps = enmap.ifft(fmap).real
if log: ps = np.exp(ps)*log_smooth_corrections[ndof]
return ps
def smooth_radial(ps, res=2.0):
ly, lx = enmap.laxes(ps.shape, ps.wcs)
lr = (ly[:,None]**2+lx[None,:]**2)**0.5
dl = min(lr[0,1],lr[1,1])*res
bi = np.floor(lr/dl).astype(int).reshape(-1)
hits = np.bincount(bi)
ops = ps*0
for i in range(len(ps.preflat)):
profile = np.bincount(bi, ps.preflat[i].reshape(-1))/hits
ops.preflat[i] = profile[bi].reshape(ps.preflat[i].shape)
return ops
def smooth_ps_hybrid(ps, grid_res, rad_res=2.0):
"""Smooth spectrum by first building a radial profile, then
smoothing the residual after dividing that out. The residual
grid will have a resolution tuned to have 100 nper samples per
bin, where each fourier cell contributes ndof samples."""
ps_radial = np.maximum(smooth_radial(ps, res=rad_res),np.max(ps)*1e-14)
ps_resid = smooth_ps_grid(ps/ps_radial, res=grid_res)
ps_smooth = ps_resid*ps_radial
return ps_smooth
def read_map(fname, pbox=None, geometry=None, name=None, cache_dir=None, dtype=None, read_cache=False):
if read_cache:
map = enmap.read_map(cache_dir + "/" + name)
if dtype is not None: map = map.astype(dtype)
else:
if os.path.isdir(fname):
fname = fname + "/tile%(y)03d_%(x)03d.fits"
map = retile.read_area(fname, pbox)
if dtype is not None: map = map.astype(dtype)
else:
map = enmap.read_map(fname, pixbox=pbox, geometry=geometry)
if cache_dir is not None and name is not None:
enmap.write_map(cache_dir + "/" + name, map)
#if map.ndim == 3: map = map[:1]
return map
def map_fft(x): return enmap.fft(x)
def map_ifft(x): return enmap.ifft(x).real
def calc_pbox(shape, wcs, box, n=10):
nphi = utils.nint(np.abs(360/wcs.wcs.cdelt[0]))
dec = np.linspace(box[0,0],box[1,0],n)
ra = np.linspace(box[0,1],box[1,1],n)
y = enmap.sky2pix(shape, wcs, [dec,dec*0+box[0,1]])[0]
x = enmap.sky2pix(shape, wcs, [ra*0+box[0,0],ra])[1]
x = utils.unwind(x, nphi)
pbox = np.array([
[np.min(y),np.min(x)],
[np.max(y),np.max(x)]])
xm1 = np.mean(pbox[:,1])
xm2 = utils.rewind(xm1, shape[-1]//2, nphi)
pbox[:,1] += xm2-xm1
pbox = utils.nint(pbox)
return pbox
def make_dummy_tile(shape, wcs, box, pad=0, dtype=np.float64):
pbox = calc_pbox(shape, wcs, box)
if pad:
pbox[0] -= pad
pbox[1] += pad
shape2, wcs2 = enmap.slice_geometry(shape, wcs, (slice(pbox[0,0],pbox[1,0]),slice(pbox[0,1],pbox[1,1])), nowrap=True)
shape2 = shape[:-2]+tuple(pbox[1]-pbox[0])
map = enmap.zeros(shape2, wcs2, dtype)
div = enmap.zeros(shape2, wcs2, dtype)
return bunch.Bunch(map=map, div=div)
def robust_ref(div,tol=1e-5):
ref = np.median(div[div>0])
ref = np.median(div[div>ref*tol])
return ref
def add_missing_comps(map, ncomp, fill="random", rms_factor=1e3):
map = map.preflat
if len(map) >= ncomp: return map[:ncomp]
omap = enmap.zeros((ncomp,)+map.shape[-2:], map.wcs, map.dtype)
omap[:len(map)] = map[:ncomp]
if fill == "random":
r = np.random.standard_normal((ncomp-len(map),)+map.shape[-2:])
scale = np.std(map)*rms_factor
omap[len(map):] = r*scale
return omap
def make_div_3d(div, ncomp_map, ncomp_target, polfactor=0.5):
if div.ndim == 2:
res = enmap.zeros((ncomp_target,)+div.shape[-2:], div.wcs, div.dtype)
res[0] = div
res[1:ncomp_map] = div*polfactor
return res
elif div.ndim == 3: return div
elif div.ndim == 4: return enmap.samewcs(np.einsum("iiyx->iyx",div),div)
else: raise ValueError("Too many components in div")
def detrend_map(map, div, edge=60, tol=1e-3, nstep=30):
#print("Fixme detrend")
#enmap.write_map("detrend_before.fits", map)
hit = div.preflat[0]>0
bhit = hit.copy()
bhit[0,:] = 0; bhit[-1,:] = 0; bhit[:,0] = 0; bhit[:,-1] = 0
weight = bhit*(np.maximum(0,(1-ndimage.distance_transform_edt(hit)/edge))) + tol
del bhit
l = map.modlmap()
iN = (1 + ( (l+0.5)/1000 )**-3.5)**-1
def A(x):
imap = weight*0+x.reshape(map.shape)
omap = weight*imap + enmap.ifft(iN*enmap.fft(imap)).real
return omap.reshape(-1)
def M(x):
imap = weight*0+x.reshape(map.shape)
omap = enmap.ifft(1/iN*enmap.fft(imap)).real
return omap.reshape(-1)
rhs = map*weight
solver = cg.CG(A, rhs.reshape(-1).copy(), M=M)
for i in range(nstep):
solver.step()
omap = (div>0)*(map-solver.x.reshape(map.shape))
#enmap.write_map("detrend_model.fits", enmap.samewcs(solver.x.reshape(map.shape),map))
#enmap.write_map("detrend_after.fits", omap)
return omap
def common_geometry(geos, ncomp=None):
shapes = np.array([shape[-2:] for shape,wcs in geos])
assert np.all(shapes == shapes[0]), "Inconsistent map shapes"
if ncomp is None:
ncomps = np.array([shape[-3] for shape,wcs in geos if len(shape)>2])
assert np.all(ncomps == ncomps[0]), "Inconsistent map ncomp"
ncomp = ncomps[0]
return (ncomp,)+tuple(shapes[0]), geos[0][1]
def filter_div(div):
"""Downweight very thin stripes in the div - they tend to be problematic single detectors"""
res = div.copy()
for comp in res.preflat: comp[:] = ndimage.minimum_filter(comp, size=2)
return res
def select_datasets(datasets, sel):
all_tags = set()
for dataset in datasets:
all_tags |= dataset.tags
flags = {flag: np.array([flag in dataset.tags for dataset in datasets],bool) for flag in all_tags}
# Extract the relevant datasets
if sel is not None:
sel = "&".join(["(" + w + ")" for w in utils.split_outside(sel, ",")])
selinds = np.where(eval(sel, flags))[0]
datasets = [datasets[i] for i in selinds]
return datasets
class Mapset:
def __init__(self, config, sel=None):
self.config = config
self.select(sel)
def select(self, sel):
config = self.config
datasets = select_datasets(config.datasets, sel)
#all_tags = set()
#for dataset in config.datasets:
# all_tags |= dataset.tags
#flags = {flag: np.array([flag in dataset.tags for dataset in config.datasets],bool) for flag in all_tags}
## Extract the relevant datasets
#datasets = config.datasets
#if sel is not None:
# sel = "&".join(["(" + w + ")" for w in utils.split_outside(sel, ",")])
# selinds = np.where(eval(sel, flags))[0]
# datasets = [datasets[i] for i in selinds]
# Make all paths relative to us instead of the config file
cdir = os.path.dirname(config.path)
# In tiled input format, all input maps have the same geometry
for dataset in datasets:
for split in dataset.splits:
split.map = os.path.join(cdir, split.map)
split.div = os.path.join(cdir, split.div)
if "mask" in dataset:
dataset.mask = os.path.join(cdir, dataset.mask)
if "filter_mask" in dataset:
dataset.filter_mask = os.path.join(cdir, dataset.filter_mask)
# Read the geometry from all the datasets. Also make paths relative to us instead
# of the config file
self.nl = 30000
for dataset in datasets:
shape, wcs = read_geometry(dataset.splits[0].map)
dataset.shape = shape
dataset.wcs = wcs
dataset.beam = read_beam(dataset.beam_params, workdir=cdir, nl=self.nl)
if "polbeam_params" in dataset:
dataset.polbeam = read_beam(dataset.polbeam_params, workdir=cdir, nl=self.nl)
#np.savetxt("beam_1d_%s.txt" % dataset.name, dataset.beam)
dataset.box = enmap.box(shape, wcs, corner=False)
self.datasets = datasets
# Read the target beam, if any
if "target_beam" in config.__dict__.keys():
self.target_beam = read_beam(config.target_beam, workdir=cdir, nl=self.nl)
elif "get_target_beam" in config.__dict__.keys():
self.target_beam = read_beam(config.get_target_beam(datasets), workdir=cdir, nl=self.nl)
else: self.target_beam = None
# Read the source catalog, if any
if "ptsrc_catalog" in config.__dict__.keys():
self.ptsrc_catalog = read_catalog(config.ptsrc_catalog, workdir=cdir)
# Read the background spectrum if any
if "background_spectrum" in config.__dict__.keys():
self.background_spectrum = read_spectrum(config.background_spectrum, workdir=cdir)
def copy(self):
config = self.config
self.config = None
res = copy.deepcopy(self)
res.config = config
self.config = config
return res
def read(self, box, pad=0, prune=True, verbose=False, cache_dir=None, dtype=np.float64, div_unhit=1e-7, read_cache=False, ncomp=1, wcs=None):
"""Read the data for each of our datasets that falls within the given box, returning a new Mapset
with the mapset.datasets[:].split[:].data member filled with a map and div. If prune is False,
then the returned mapset will have the same maps as the original mapset. If prune is True (the default),
on the other hand, splits with no data are removed, as are datasets with too few splits. This can
result in all the data being removed, in which case None is returned."""
res = self.copy()
res.ffpad, res.shape, res.wcs = None, None, None
res.ncomp, res.dtype = ncomp, dtype
for dataset in res.datasets:
# Find the pixel coordinates of our tile
pbox = np.sort(utils.nint(enmap.skybox2pixbox(dataset.shape, dataset.wcs, box)),0)
pbox[0] -= pad
pbox[1] += pad
# Determine the optimal fourier padding
psize = pbox[1]-pbox[0]
ffpad = np.array([fft.fft_len(s, direction="above")-s for s in psize])
pbox[1] += ffpad
# The overall tile geometry (wcs in particular) can be found even if there isn't
# any data to read, but in this case we can't be sure that the wcs object we read
# has the reference pixel placed sensibly. That's why we cal fix_wcs here.
if res.shape is None:
res.shape, res.wcs = enmap.slice_geometry(dataset.shape, dataset.wcs, (slice(pbox[0,0],pbox[1,0]),slice(pbox[0,1],pbox[1,1])), nowrap=True)
res.wcs = wcsutils.fix_wcs(res.wcs)
res.shape = (ncomp,)+res.shape[-2:]
res.ffpad = ffpad
dataset.pbox = pbox
dataset.ngood = 0
# Reading lots of uncessessary maps is slow. Should otpimize read_map.
# But as long as we are allowed to completely skip datasets (prune=True),
# we can just skip datasets that we know are empty.
#print dataset.name, pbox.reshape(-1), dataset.shape, pbox_out_of_bounds(pbox, dataset.shape, dataset.wcs)
if pbox_out_of_bounds(pbox, dataset.shape, dataset.wcs) and prune:
continue
if "mask" in dataset:
mask = 1-read_map(dataset.mask, geometry=(res.shape, res.wcs), name=os.path.basename(dataset.mask), cache_dir=cache_dir,dtype=dtype, read_cache=read_cache)
else: mask = None
if "filter_mask" in dataset:
dataset.filter_mask = 1-read_map(dataset.filter_mask, geometry=(res.shape, res.wcs), name=os.path.basename(dataset.filter_mask), cache_dir=cache_dir,dtype=dtype, read_cache=read_cache)
else: dataset.filter_mask = None
dataset.filter = dataset.filter if "filter" in dataset else []
dataset.downweight = dataset.downweight if "downweight" in dataset else []
for si, split in enumerate(dataset.splits):
split.data = None
if verbose: print("Reading %s" % split.map)
try:
map = read_map(split.map, geometry=(res.shape, res.wcs), name=os.path.basename(split.map), cache_dir=cache_dir,dtype=dtype, read_cache=read_cache)
div = read_map(split.div, geometry=(res.shape, res.wcs), name=os.path.basename(split.div), cache_dir=cache_dir,dtype=dtype, read_cache=read_cache)
except (IOError, OSError) as e: continue
map *= dataset.gain
div *= dataset.gain**-2
div[~np.isfinite(div)] = 0
map[~np.isfinite(map)] = 0
div[div<div_unhit] = 0
if mask is not None:
map *= mask
div *= mask
if np.all(div==0): continue
split.data = bunch.Bunch(map=map, div=div)
dataset.ngood += 1
if prune:
res.datasets = [dataset for dataset in res.datasets if dataset.ngood >= 2]
for dataset in res.datasets:
dataset.splits = [split for split in dataset.splits if split.data is not None]
# Precompute our lmap
res.l = enmap.modlmap(res.shape, res.wcs)
# At this point we have read all the data, but it's possible that we didn't actually
# read anything useful. If so res.datasets can be empty, or invididual datasets' ngood may be 0
return res
def sanitize_maps(mapset, map_max=1e8, div_tol=20, apod_val=0.2, apod_alpha=5, apod_edge=60, apod_div_edge=60, crop_div_edge=0, detrend=True):
"""Get rid of extreme values in maps and divs, and further downweights the the edges and
faint regions of div."""
for dataset in mapset.datasets:
for i, split in enumerate(dataset.splits):
if split.data is None: continue
# Expand div to be the same shape as map. This lets us track T and P noise separately,
# but we don't bother with cross-component correlations, which are usually not that
# important, and slow things down
split.data.div = make_div_3d(split.data.div, len(split.data.map.preflat), mapset.ncomp)
# Avoid single, crazy pixels
split.ref_div = robust_ref(split.data.div)
split.data.div = np.minimum(split.data.div, split.ref_div*div_tol)
split.data.div = filter_div(split.data.div)
split.data.map = np.maximum(-map_max, np.minimum(map_max, split.data.map))
# FIXME: detrend commented out for now. It was very slow, and introduced more bias
# than expected. Its inclusion was mainly motivated by MBAC and deep patches. Will think
# about what to do with it. Probably best to make it a per-dataset choice.
#if dataset.highpass and detrend:
# # This uses an area 60 pixels wide around the edge of the div as a context to solve
# # for a smooth background behavior, and then subtracts it. This will bias the the edge
# # power low, but mostly towards the outer parts of the reference region, which is strongly
# # apodized anyway.
# split.data.map = detrend_map(split.data.map, split.data.div, edge=apod_div_edge)
if crop_div_edge:
# Avoid areas too close to the edge of div
split.data.div *= calc_dist(split.data.div > 0) > 60
#print("A", dataset.name, i, np.std(split.data.map))
# Expand map to ncomp components
split.data.map = add_missing_comps(split.data.map, mapset.ncomp, fill="random")
# Distrust very low hitcount regions
split.data.apod = np.minimum(split.data.div/(split.ref_div*apod_val), 1.0)**apod_alpha
# Distrust regions very close to the edge of the hit area
mask = split.data.div > split.ref_div*1e-2
mask = shrink_mask_holes(mask, 10)
split.data.apod *= apod_mask_edge(mask, apod_div_edge)
# Make things more fourier-friendly
split.data.apod *= split.data.apod.apod(apod_edge)
#enmap.write_map("apod_%s_%d.fits" % (dataset.name, i), apod_mask_edge(mask, apod_div_edge))
# And apply it
split.data.div *= split.data.apod
dataset.ref_div = np.sum([split.ref_div for split in dataset.splits if split.data is not None])
mapset.ref_div = np.sum([dataset.ref_div for dataset in mapset.datasets])
mapset.apod_edge = apod_edge
def build_noise_model(mapset, ps_res=400, filter_kxrad=20, filter_highpass=200, filter_kx_ymax_scale=1):
"""This assumes that the mapset has been pruned, and may further prune the result"""
for dataset in mapset.datasets:
nsplit = 0
dset_map, dset_div = None, None
dataset.iN = None
for split in dataset.splits:
if split.data is None: continue
if dset_map is None:
dset_map = split.data.map*0
dset_div = split.data.div*0
dset_map += split.data.map * split.data.div
dset_div += split.data.div
# Also form the pixel part of our noise model
split.data.H = split.data.div**0.5
# Form the mean map for this dataset
dset_map[dset_div>0] /= dset_div[dset_div>0]
#enmap.write_map("test_totmap.fits", dset_map)
# Then use it to build the diff maps and noise spectra
dset_ps = None
for i, split in enumerate(dataset.splits):
if split.data is None: continue
diff = split.data.map - dset_map
#enmap.write_map("test_diff_%s_%d.fits" % (dataset.name, i), diff)
# We can't whiten diff with just H.
# diff = m_i - sum(div)"sum(div_j m_j), and so has
# var = div_i" + sum(div)"**2 * sum(div) - 2*sum(div)"div_i/div_i
# = div_i" - sum(div)"
# ivar = (div_i" - sum(div)")"
with utils.nowarn():
diff_H = (1/split.data.div - 1/dset_div)**-0.5
#print("rms from div", split.data.div.preflat[0,::100,::100]**-0.5)
diff_H[~np.isfinite(diff_H)] = 0
wdiff = diff * diff_H
#print("wdiff", np.std(wdiff))
#enmap.write_map("test_wdiff_%s_%d.fits" % (dataset.name, i), wdiff)
# What is the healthy area of wdiff? Wdiff should have variance
# 1 or above. This tells us how to upweight the power spectrum
# to take into account missing regions of the diff map.
# This breaks for datasets with a large pixel window. The pixel window
# has not yet been determined at this point, so we can't compensate for it
# here. That leaves us with e.g. planck having much lower pixel rms than
# its sensitivity would indicate. Instead we will use typical non-low values
# as reference.
ndown = 10
wvar = enmap.downgrade(wdiff[0]**2,ndown)
ref = robust_ref(wvar, tol=0.01)
goodfrac_var = np.sum(wvar > ref*1e-2)/float(wvar.size)
goodfrac_apod = np.mean(split.data.apod)
goodfrac = min(goodfrac_var, goodfrac_apod)
if goodfrac < 0.1: continue
ps = np.abs(map_fft(wdiff))**2
#enmap.write_map("test_ps_raw_%s_%d.fits" % (dataset.name, i), ps)
# correct for unhit areas, which can't be whitend
with utils.nowarn(): ps /= goodfrac
if dset_ps is None:
dset_ps = enmap.zeros(ps.shape, ps.wcs, ps.dtype)
dset_ps += ps
nsplit += 1
if nsplit < 2: continue
dset_ps /= nsplit
if np.any(dset_ps < 0): continue
if np.all(dset_ps == 0): continue
#enmap.write_map("test_ps_raw_%s.fits" % dataset.name, dset_ps)
# Fill all-zero components with a big number to make others happy
for ps in dset_ps.preflat:
if np.allclose(ps,0): ps[:] = 1e3
# Smooth ps to reduce sample variance
dset_ps = smooth_ps_grid(dset_ps, ps_res, ndof=2*(nsplit-1), log=True)
#enmap.write_map("test_ps_smooth_%s.fits" % dataset.name, dset_ps)
# Apply noise window correction if necessary:
noisewin = dataset.noise_window_params[0] if "noise_window_params" in dataset else "none"
if noisewin == "none": pass
elif noisewin == "lmax":
# ps beyond lmax is not valid. Use values near lmax to extrapolate
lmax = dataset.noise_window_params[1]
lref = lmax*3/4
refval = np.mean(dset_ps[:,(mapset.l>=lref)&(mapset.l<lmax)],1)
dset_ps[:,mapset.l>=lmax] = refval[:,None]
elif noisewin == "separable":
# Read y and x windows from disk
fname = os.path.join(os.path.dirname(mapset.config.path), dataset.noise_window_params[1])
l, ywin, xwin = np.loadtxt(fname, usecols=(0,1,2)).T
ly, lx = enmap.laxes(mapset.shape, mapset.wcs)
ywin = np.maximum(np.interp(np.abs(ly), l, ywin), 1e-4)
xwin = np.maximum(np.interp(np.abs(lx), l, xwin), 1e-4)
mask = (ywin[:,None] > 0.9)&(xwin[None,:] > 0.9)
ref_val = np.median(dset_ps[0,mask])
dset_ps /= ywin[:,None]**2
dset_ps /= xwin[None,:]**2
# We don't trust our ability to properly deconvolve the noise in the areas where the
# pixel window is too small
dset_ps[:,(ywin[:,None]<0.25)|(xwin[None,:]<0.25)] = ref_val
# HACK: avoid devonvolving too much by putting very low values in the beam.
# To do this we force ywin and xwin to be 1 when they get small, but instead
# greatly reduce the weight of the dataset by also setting dset_ps to a high
# value here
ymask = ywin<0.7
xmask = xwin<0.7
ywin[ymask] = 1
xwin[xmask] = 1
dset_ps[:,ymask[:,None]|xmask[None,:]] = 100
# Fill the low parts with a representative value to avoid dividing by too small numbers
# dset_ps looks OK at this point. It never gets very small.
# The windows do get small, though, which means that the beam will
# get small at high l. With mbac-only we would end up over-deconvolving,
# but with another dataset present that should not happen. However, when I
# teste with mbac + s17 I still got over-ceconvolution. The edge of the s17
# region also looked weird. Those areas were all noisy and a bit blue even
# in s17+planck-only, though. It looks like mbac reduced the noise at lower l
# without reducing it at high l, making it bluer, which would make sense.
#
# The old version ended up estimating ywin and xwin = 1 everywhere, leading to
# no deconvolution, but the incorrect result.
#enmap.write_map("new_dset_ps.fits", dset_ps)
#np.savetxt("new_ywin.txt", ywin)
#np.savetxt("new_xwin.txt", xwin)
#1/0
# Store the separable window so it can be used for the beam too
dataset.ywin, dataset.xwin = ywin, xwin
elif noisewin == "separable_old":
# The map has been interpolated using something like bicubic interpolation,
# leading to an unknown but separable pixel window
ywin, xwin = estimate_separable_pixwin_from_normalized_ps(dset_ps[0])
#print "ywin", utils.minmax(ywin), "xwin", utils.minmax(xwin), dataset.name
ref_area = (ywin[:,None] > 0.9)&(xwin[None,:] > 0.9)&(dset_ps[0]<2)
#print "ref_ara", np.sum(ref_area), dataset.name
if np.sum(ref_area) == 0: ref_area[:] = 1
dset_ps /= ywin[:,None]**2
dset_ps /= xwin[None,:]**2
fill_area = (ywin[:,None]<0.25)|(xwin[None,:]<0.25)
dset_ps[:,(ywin[:,None]<0.25)|(xwin[None,:]<0.25)] = np.mean(dset_ps[:,ref_area],1)[:,None]
#enmap.write_map("old_dset_ps.fits", dset_ps)
#np.savetxt("old_ywin.txt", ywin)
#np.savetxt("old_xwin.txt", xwin)
#1/0
# Store the separable window so it can be used for the beam too
dataset.ywin, dataset.xwin = ywin, xwin
else: raise ValueError("Noise window type '%s' not supported" % noisewin)
#enmap.write_map("test_ps_smooth2_%s.fits" % dataset.name, dset_ps)
#print("mean_smooth_ps", np.median(dset_ps[0]))
# If we have invalid values, then this whole dataset should be skipped
if not np.all(np.isfinite(dset_ps)): continue
dataset.iN = 1/dset_ps
#print "dataset.iN", np.sum(dataset.iN,(1,2))
# Prune away bad datasets and splits
for dataset in mapset.datasets:
dataset.splits = [split for split in dataset.splits if split.data is not None]
mapset.datasets = [dataset for dataset in mapset.datasets if len(dataset.splits) >= 2 and dataset.iN is not None]
#def setup_filter(mapset, mode="weight", filter_kxrad=50, filter_highpass=200, filter_kx_ymax_scale=0.5):
# # Add any fourier-space masks to this
# ly, lx = enmap.laxes(mapset.shape, mapset.wcs)
# lr = enmap.ndmap((ly[:,None]**2 + lx[None,:]**2)**0.5, mapset.wcs)
# if len(mapset.datasets) > 0:
# bmin = np.min([beam_size(dataset.beam) for dataset in mapset.datasets])
# for dataset in mapset.datasets:
# dataset.filter = 1
# if dataset.highpass:
# print(filter_kxrad, filter_highpass, filter_kx_ymax_scale, bmin)
# kxmask = butter(lx, filter_kxrad, -5)
# kxmask = 1-(1-kxmask[None,:])*(np.abs(ly[:,None])<(bmin*filter_kx_ymax_scale))
# highpass = butter(lr, filter_highpass,-10)
# filter = highpass * kxmask
# #enmap.write_map("filter.fits", filter.lform())
# #1/0
# del kxmask, highpass
# else:
# filter = 1
# if mode == "weight": dataset.iN *= filter
# elif mode == "filter": dataset.filter = filter
# elif mode == "none": pass
# else: raise ValueError("Unrecognized filter mode '%s'" % mode)
# mapset.mode = mode
def setup_downweight(mapset):
ly, lx = enmap.laxes(mapset.shape, mapset.wcs, method="intermediate")
lr = enmap.ndmap((ly[:,None]**2 + lx[None,:]**2)**0.5, mapset.wcs)
for dataset in mapset.datasets:
filter = build_filter(dataset.downweight, lr, ly, lx)
if filter is not None:
dataset.iN *= filter
def setup_filter(mapset):
ly, lx = enmap.laxes(mapset.shape, mapset.wcs, method="intermediate")
lr = enmap.ndmap((ly[:,None]**2 + lx[None,:]**2)**0.5, mapset.wcs)
for dataset in mapset.datasets:
dataset.filter = build_filter(dataset.filter, lr, ly, lx)
# And apply it
apply_filter(mapset)
def build_filter(filter_desc, lr, ly, lx):
"""Build a 2d fourier filter that can be applied by multiplying the fourier
coefificients of the map (but see filter_mask). filter_desc is a list of the form
[(name, params..),(name, params..),...], where name specifies which functional
form should be used, where params are a dict"""
if len(filter_desc) == 0: return None
filter = np.zeros_like(lr)
filter[:] = 1
for name, params in filter_desc:
if name == "invert": filter = 1-filter
elif name == "axial": filter *= build_filter_axial (lr, ly, lx, **params)
elif name == "radial": filter *= build_filter_radial(lr, ly, lx, **params)
else: raise ValueError("Unrecognized filter '%s'" % (str(name)))
return filter
def build_filter_radial(lr, ly, lx, lknee=1000, alpha=-3):
with utils.nowarn():
return 1/(1+(lr/lknee)**alpha)
def build_filter_axial(lr, ly, lx, axis="x", lknee=1000, alpha=-3, lmax=None):
if axis == "x": l = lx[None,:]; l2 = ly[:,None]
else: l = ly[:,None]; l2 = lx[None,:]
with utils.nowarn():
filter = 1/(1+(l/lknee)**alpha)
if lmax is not None:
filter = 1-(1-filter)*(np.abs(l2)<lmax)
return filter
def apply_filter(mapset):
"""Apply the filter set up in setup_filter to the maps in the mapset, changing them.
Should be done after the noise model has been computed."""
for dataset in mapset.datasets:
if dataset.filter is None: continue
if dataset.filter_mask is None:
for split in dataset.splits:
split.data.map = enmap.ifft(dataset.filter*enmap.fft(split.data.map)).real
else:
ifilter = 1-dataset.filter
for split in dataset.splits:
ivar= split.data.div*dataset.filter_mask
bad = enmap.ifft(ifilter*enmap.fft(split.data.map*ivar)).real
div = enmap.ifft(ifilter*enmap.fft( ivar)).real
# Avoid division by very low values
div = np.maximum(div, max(1e-10,np.max(div[::10,::10])*1e-4))
bad /= div
split.data.map -= bad
#def downweight_lowl(mapset, lknee, alpha, lim=1e-10):
# """Inflate low-l noise below l=lknee uniformly for all datasets.
# This could be used to represent a generic low-l foreground component
# with unknown frequency dependence, for example."""
# with utils.nowarn():
# filter = 1/(1+(mapset.l/lknee)**-alpha)
# filter = np.maximum(filter, lim)
# for dataset in mapset.datasets:
# dataset.iN *= filter
def setup_profiles_ptsrc(mapset):
setup_profiles_helper(mapset, lambda freq: calc_profile_ptsrc(freq, nl=mapset.nl))
def setup_profiles_sz(mapset, scale):
# sz must be evaluated in real space to avoid aliasing. First get the
# distance from the corner, including wrapping. We do this by getting the
# distance from the center, and then moving the center to the corner afterwards
y2d = sz_map_profile(mapset.shape, mapset.wcs, fwhm=scale)
y2d_harm = np.abs(map_fft(y2d))
y2d_harm /= y2d_harm[0,0]
# We can now scale it as appropriately for each dataset
cache = {}
for d in mapset.datasets:
if d.freq not in cache:
cache[d.freq] = y2d_harm * sz_freq_core(d.freq*1e9)
d.signal_profile_2d = cache[d.freq]
def setup_profiles_helper(mapset, fun):
cache = {}
for d in mapset.datasets:
if d.freq not in cache:
profile_1d = fun(d.freq)
profile_2d = ndimage.map_coordinates(profile_1d, mapset.l[None], order=1)
cache[d.freq] = [profile_1d,profile_2d]
d.signal_profile, d.signal_profile_2d = cache[d.freq]
def calc_beam_area(beam_2d):
"""Compute the solid angle of an l-space 2d beam in steradians"""
# In real space this is sum(beam)/beam[0,0]*pix_area.
# beam[0,0] = mean(lbeam), and sum(beam) = lbeam[0,0]*npix.
# So the beam area should simply be lbeam[0,0]*npix/mean(lbeam)*pix_area,
# up to fourier normalization. In practice this works out to be
# area = lbeam[0,0]/mean(lbeam)*pix_area
return beam_2d[...,0,0]/np.mean(beam_2d)*beam_2d.pixsize()
def setup_beams(mapset):
"""Set up the full beams with pixel windows for each dataset in the mapset,
and the corresponding beam areas."""
cache = {}
any_pol = any(["polbeam" in d for d in mapset.datasets])
for d in mapset.datasets:
param = (d.beam_params, d.pixel_window_params)
if param not in cache:
beam_2d = eval_beam(d.beam, mapset.l)
if "polbeam" in d:
# If a separate polarization beam is defined, then
# beam_2d will be [T,Q,U] instead of just scalar.
polbeam_2d = eval_beam(d.polbeam, mapset.l)
beam_2d = enmap.enmap([beam_2d,polbeam_2d,polbeam_2d])
elif any_pol:
beam_2d = np.tile(beam_2d[None],(3,1,1))
#enmap.write_map("beam_2d_raw_%s.fits" % d.name, beam_2d)
# Apply pixel window
if d.pixel_window_params[0] == "native":
wy, wx = enmap.calc_window(beam_2d.shape)
beam_2d *= wy[:,None]
beam_2d *= wx[None,:]
elif d.pixel_window_params[0] == "none": pass
elif d.pixel_window_params[0] == "lmax":
beam_2d *= mapset.l<=d.pixel_window_params[1]
elif d.pixel_window_params[0] == "separable":
try:
beam_2d *= d.ywin[:,None]
beam_2d *= d.xwin[None,:]
except AttributeError:
print("Automatic separable pixel window can only be used together with")
print("the corresponding automatic spearable noise pixel window")
raise
else: raise ValueError("Unrecognized pixel window type '%s'" % (d.pixel_window_params[0]))
#beam_2d = enmap.ndmap(beam_2d, d.wcs)
area = calc_beam_area(beam_2d)
#enmap.write_map("beam_2d_win_%s.fits" % d.name, beam_2d)
cache[param] = (beam_2d, area)
d.beam_2d, d.beam_area = cache[param]
def setup_background_spectrum(mapset, spectrum=None):
# The background is shared between all datasets.
# We treat T,Q,U independently in this module for now
# (for speed reasons), so expand the spectrum to pixel
# coordinates and return its diagonal.
if spectrum is None: spectrum = mapset.background_spectrum
if spectrum is None: mapset.S = enmap.zeros(mapset.shape, mapset.wcs)
else:
S = enmap.spec2flat(mapset.shape, mapset.wcs, spectrum)