-
Notifications
You must be signed in to change notification settings - Fork 1
/
check-coadd.py
2475 lines (2025 loc) · 83.5 KB
/
check-coadd.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
import matplotlib
matplotlib.use('Agg')
matplotlib.rc('text', usetex=True)
matplotlib.rc('font', serif='computer modern roman')
matplotlib.rc('font', **{'sans-serif': 'computer modern sans serif'})
import matplotlib.cm
from matplotlib.ticker import FixedFormatter
import matplotlib.patches as patches
import numpy as np
import pylab as plt
import os
import sys
import fitsio
from astrometry.util.stages import *
from astrometry.util.plotutils import *
from astrometry.util.miscutils import *
from astrometry.util.fits import *
from astrometry.util.util import *
#wisel3 = 'wise-L3'
wisel3 = 'allwise-L3'
wise_tag = 'ac51'
coadds = 'wise-coadds'
from unwise_coadd import estimate_sky, estimate_sky_2, get_l1b_file
from tractor import GaussianMixturePSF, NanoMaggies
def read_wise_coadd(coadd_id, band, unc=False, cov=False, wget=True, get_imgfn=False,
basedir=None):
if basedir is None:
basedir = wisel3
dir1 = os.path.join(basedir, coadd_id[:2], coadd_id[:4],
coadd_id + '_' + wise_tag)
fn = '%s_%s-w%i-int-3.fits' % (coadd_id, wise_tag, band)
rtn = read(dir1, fn, header=True, wget=wget)
if get_imgfn:
rtn = rtn + (os.path.join(dir1, fn),)
if unc:
uncim = read(dir1, '%s_%s-w%i-unc-3.fits.gz' % (coadd_id, wise_tag, band), wget=wget)
rtn = rtn + (uncim,)
if cov:
covim = read(dir1, '%s_%s-w%i-cov-3.fits.gz' % (coadd_id, wise_tag, band), wget=wget)
rtn = rtn + (covim,)
return rtn
def read(dirnm, fn, header=False, wget=False):
pth = os.path.join(dirnm, fn)
print pth
if wget and not os.path.exists(pth):
coadd_id = os.path.basename(os.path.dirname(pth)).replace('_'+wise_tag,'')
print 'coadd_id', coadd_id
if '-3.fits' in pth:
if not os.path.exists(dirnm):
os.makedirs(dirnm)
cmd = 'wget -nv -O %s http://irsa.ipac.caltech.edu/ibe/data/wise/allwise/p3am_cdd/%s/%s/%s/%s' % (pth, coadd_id[:2], coadd_id[:4],
coadd_id + '_' + wise_tag, fn)
print cmd
os.system(cmd)
data = fitsio.read(pth, header=header)
return data
#def get_wise_dir(coadd_id, band):
# dir1 = os.path.join(wisel3, coadd_id[:2], coadd_id[:4], coadd_id + '_ac51')
# return dir1
def plot_exposures():
plt.subplots_adjust(bottom=0.01, top=0.9, left=0., right=1., wspace=0.05, hspace=0.2)
for coadd_id,band in [('1384p454', 3)]:
print coadd_id, band
plt.clf()
plt.subplot(1,2,1)
fn2 = os.path.join(coadds, 'unwise-%s-w%i-img-w.fits' % (coadd_id, band))
J = fitsio.read(fn2)
binJ = reduce(np.add, [J[i/4::4, i%4::4] for i in range(16)])
plo,phi = [np.percentile(binJ, p) for p in [25,99]]
plt.imshow(binJ, interpolation='nearest', origin='lower', cmap='gray',
vmin=plo, vmax=phi)
plt.xticks([]); plt.yticks([])
plt.subplot(1,2,2)
#fn3 = os.path.join(coadds, 'unwise-%s-w%i-invvar-w.fits' % (coadd_id, band))
fn3 = os.path.join(coadds, 'unwise-%s-w%i-ppstd.fits' % (coadd_id, band))
J = fitsio.read(fn3)
binJ = reduce(np.add, [J[i/4::4, i%4::4] for i in range(16)])
phi = np.percentile(binJ, 99)
plt.imshow(binJ, interpolation='nearest', origin='lower', cmap='gray',
vmin=0, vmax=phi)
plt.xticks([]); plt.yticks([])
ps.savefig()
fn = os.path.join(coadds, 'unwise-%s-w%i-frames.fits' % (coadd_id, band))
T = fits_table(fn)
print len(T), 'frames'
T.cut(np.lexsort((T.frame_num, T.scan_id)))
plt.clf()
n,b,p = plt.hist(np.log10(np.maximum(0.1, T.npixrchi)), bins=100, range=(-1,6),
log=True)
plt.xlabel('log10( N pix with bad rchi )')
plt.ylabel('Number of images')
plt.ylim(0.1, np.max(n) + 5)
ps.savefig()
J = np.argsort(-T.npixrchi)
print 'Largest npixrchi:'
for n,s,f in zip(T.npixrchi[J], T.scan_id[J], T.frame_num[J[:20]]):
print ' n', n, 'scan', s, 'frame', f
i0 = 0
while i0 <= len(T):
plt.clf()
R,C = 4,6
for i in range(i0, i0+(R*C)):
if i >= len(T):
break
t = T[i]
fn = get_l1b_file('wise-frames', t.scan_id, t.frame_num, band)
print fn
I = fitsio.read(fn)
bad = np.flatnonzero(np.logical_not(np.isfinite(I)))
I.flat[bad] = 0.
print I.shape
binI = reduce(np.add, [I[j/4::4, j%4::4] for j in range(16)])
print binI.shape
plt.subplot(R,C,i-i0+1)
plo,phi = [np.percentile(binI, p) for p in [25,99]]
print 'p', plo,phi
plt.imshow(binI, interpolation='nearest', origin='lower',
vmin=plo, vmax=phi, cmap='gray')
plt.xticks([]); plt.yticks([])
plt.title('%s %i' % (t.scan_id, t.frame_num))
plt.suptitle('%s W%i' % (coadd_id, band))
ps.savefig()
i0 += R*C
# T = fits_table('tab.fits')
# T.cut(T.band == 3)
# print len(T), 'in WISE coadd'
# F = fits_table('wise-coadds/unwise-1384p454-w3-frames.fits')
# print len(F), 'in unWISE coadd'
#
# for s,f in zip(T.scan_id, T.frame_num):
# I = np.flatnonzero((F.scan_id == s) * (F.frame_num == f))
# if len(I) == 1:
# continue
# print 'scan/frame', s,f, ': not found'
# #W = fits_table('sequels-frames.fits')
# sys.exit(0)
def pixel_area():
for wcs in [Sip('05127a136-w1-int-1b.fits'),
#wise-frames/2a/03242a/215/03242a215-w1-int-1b.fits'),
Tan('data/unwise/001/0015p000/unwise-0015p000-w1-img-m.fits'),
#wise-coadds/unwise-1384p454-w1-img.fits'),
]:
W,H = wcs.get_width(), wcs.get_height()
print 'W,H', W,H
#xx,yy = np.meshgrid(np.arange(0, W, 10), np.arange(0, H, 10))
xx,yy = np.meshgrid(np.arange(W), np.arange(H))
rr,dd = wcs.pixelxy2radec(xx, yy)
rr -= wcs.crval[0]
rr *= np.cos(np.deg2rad(dd))
dd -= wcs.crval[1]
# (zero,zero) r,d
zzr = rr[:-1, :-1]
zzd = dd[:-1, :-1]
ozr = rr[:-1, 1:]
ozd = dd[:-1, 1:]
zor = rr[1:, :-1]
zod = dd[1:, :-1]
oor = rr[1:, 1:]
ood = dd[1:, 1:]
a = np.hypot(zor - zzr, zod - zzd)
A = np.hypot(oor - ozr, ood - ozd)
b = np.hypot(ozr - zzr, ozd - zzd)
B = np.hypot(oor - zor, ood - zod)
C = np.hypot(ozr - zor, ozd - zod)
c = C
s = (a + b + c)/2.
S = (A + B + C)/2.
area = np.sqrt(s * (s-a) * (s-b) * (s-c)) + np.sqrt(S * (S-A) * (S-B) * (S-C))
print 'Pixel area:'
print ' min', area.min()
print ' max', area.max()
plt.clf()
plt.imshow(area, interpolation='nearest', origin='lower')
plt.title('Pixel area')
plt.colorbar()
ps.savefig()
# plt.clf()
# plt.plot(rr.ravel(), dd.ravel(), 'r.')
# plt.axis('scaled')
# ps.savefig()
def binimg(img, b):
hh,ww = img.shape
hh = int(hh / b) * b
ww = int(ww / b) * b
return (reduce(np.add, [img[i/b:hh:b, i%b:ww:b] for i in range(b*b)]) /
float(b*b))
def paper_plots(coadd_id, band, ps, dir2='e',
part1=True, part2=True, part3=True, part4=True,
cmap_nims='jet', bw=False):
figsize = (4,4)
spa = dict(left=0.01, right=0.99, bottom=0.02, top=0.99,
wspace=0.05, hspace=0.05)
medfigsize = (5,4)
medspa = dict(left=0.12, right=0.96, bottom=0.14, top=0.96)
bigfigsize = (8,6)
bigspa = dict(left=0.1, right=0.98, bottom=0.1, top=0.97)
plt.figure(figsize=figsize)
plt.subplots_adjust(**spa)
dir1 = os.path.join(wisel3, coadd_id[:2], coadd_id[:4],
coadd_id + '_' + wise_tag)
wiseim,wisehdr,unc,wisen = read_wise_coadd(coadd_id, band,
unc=True, cov=True)
imm = read(dir2, 'unwise-%s-w%i-img-m.fits' % (coadd_id, band))
imu = read(dir2, 'unwise-%s-w%i-img-u.fits' % (coadd_id, band))
ivm = read(dir2, 'unwise-%s-w%i-invvar-m.fits' % (coadd_id, band))
ivu = read(dir2, 'unwise-%s-w%i-invvar-u.fits' % (coadd_id, band))
ppstdm = read(dir2, 'unwise-%s-w%i-std-m.fits' % (coadd_id, band))
numm = read(dir2, 'unwise-%s-w%i-n-m.fits' % (coadd_id, band))
numu = read(dir2, 'unwise-%s-w%i-n-u.fits' % (coadd_id, band))
binwise = binimg(wiseim, 25)
binimm = binimg(imm, 16)
binimu = binimg(imu, 16)
sigm = 1./np.sqrt(np.maximum(ivm, 1e-16))
sigm1 = np.median(sigm)
print 'sigm1:', sigm1
wisemed = np.median(wiseim[::4,::4])
wisesig = np.median(unc[::4,::4])
#wisesky = estimate_sky(wiseim, wisemed-2.*wisesig, wisemed+1.*wisesig)
wisesky = estimate_sky_2(wiseim)
print 'WISE sky estimate:', wisesky
zp = wisehdr['MAGZP']
print 'WISE image zeropoint:', zp
zpscale = 1. / NanoMaggies.zeropointToScale(zp)
print 'zpscale', zpscale
P = fits_table('wise-psf-avg.fits', hdu=band)
psf = GaussianMixturePSF(P.amp, P.mean, P.var)
R = 100
psf.radius = R
pat = psf.getPointSourcePatch(0., 0.)
pat = pat.patch
pat /= pat.sum()
psfnorm = np.sqrt(np.sum(pat**2))
print 'PSF norm (native pixel scale):', psfnorm
wise_unc_fudge = 2.4
ima = dict(interpolation='nearest', origin='lower', cmap='gray')
def myimshow(img, pp=[25,95]):
plo,phi = [np.percentile(img, p) for p in [25,95]]
imai = ima.copy()
imai.update(vmin=plo, vmax=phi)
plt.clf()
plt.imshow(img, **imai)
plt.xticks([]); plt.yticks([])
if not part1:
ps.skip(9)
else:
for img in [binwise, binimm, binimu]:
myimshow(img)
ps.savefig()
hi,wi = wiseim.shape
hj,wj = imm.shape
#flo,fhi = 0.45, 0.55
flo,fhi = 0.45, 0.50
slcW = slice(int(hi*flo), int(hi*fhi)+1), slice(int(wi*flo), int(wi*fhi)+1)
slcU = slice(int(hj*flo), int(hj*fhi)+1), slice(int(wj*flo), int(wj*fhi)+1)
subwise = wiseim[slcW]
subimm = imm[slcU]
subimu = imu[slcU]
for img in [subwise, subimm, subimu]:
myimshow(img)
ps.savefig()
print 'Median coverage: WISE:', np.median(wisen)
print 'Median coverage: unWISE w:', np.median(numm)
print 'Median coverage: unWISE:', np.median(numu)
#mx = max(wisen.max(), un.max(), unw.max())
mx = 62.
na = ima.copy()
na.update(vmin=0, vmax=mx, cmap=cmap_nims)
plt.clf()
plt.imshow(wisen, **na)
plt.xticks([]); plt.yticks([])
ps.savefig()
plt.clf()
plt.imshow(numu, **na)
plt.xticks([]); plt.yticks([])
ps.savefig()
w,h = figsize
plt.figure(figsize=(w+1,h))
plt.subplots_adjust(**spa)
plt.clf()
plt.imshow(numm, **na)
plt.xticks([]); plt.yticks([])
parent = plt.gca()
pb = parent.get_position(original=True).frozen()
#print 'pb', pb
# new parent box, padding, child box
frac = 0.15
pad = 0.05
(pbnew, padbox, cbox) = pb.splitx(1.0-(frac+pad), 1.0-frac)
# print 'pbnew', pbnew
# print 'padbox', padbox
# print 'cbox', cbox
cbox = cbox.anchored('C', cbox)
parent.set_position(pbnew)
parent.set_anchor((1.0, 0.5))
cax = parent.get_figure().add_axes(cbox)
aspect = 20
cax.set_aspect(aspect, anchor=((0.0, 0.5)), adjustable='box')
parent.get_figure().sca(parent)
plt.colorbar(cax=cax, ticks=[0,15,30,45,60])
ps.savefig()
if not part2:
ps.skip(1)
else:
# Sky / Error properties
# plt.figure(figsize=figsize)
# plt.subplots_adjust(**spa)
#
# dskyim = fitsio.read('g/138/1384p454/unwise-1384p454-w1-img-m.fits')
# b = 15
# xbinwise = reduce(np.add, [wiseim[i/b::b, i%b::b] for i in range(b*b)]) / float(b*b)
# b = 8
# #xbinim = reduce(np.add, [im [i/b::b, i%b::b] for i in range(b*b)]) / float(b*b)
# xbinimw = reduce(np.add, [imw [i/b::b, i%b::b] for i in range(b*b)]) / float(b*b)
# xbindsky = reduce(np.add, [dskyim [i/b::b, i%b::b] for i in range(b*b)]) / float(b*b)
#
# #for img in [(binwise - wisesky) * zpscale / psfnorm, binim, binimw]:
# for img in [(xbinwise - wisesky) * zpscale / psfnorm, xbinimw, xbindsky]:
# plt.clf()
# plt.imshow(img, *sigw1, vmax=3.*sigw1, **ima)
# #plt.imshow(img, vmin=-2.*sigw1, vmax=2.*sigw1, **ima)
# plt.xticks([]); plt.yticks([])
# ps.savefig()
plt.figure(figsize=bigfigsize)
plt.subplots_adjust(**bigspa)
wisechi = ((wiseim-wisesky) / unc).ravel()
#wisechi2 = 2. * ((wiseim-wisesky) / (unc/psfnorm)).ravel()
#wisechi2 = (2.*psfnorm * (wiseim-wisesky) / unc).ravel()
#wisechi2 = 0.5 * ((wiseim-wisesky) / unc).ravel()
wisechi2 = ((wiseim-wisesky) / (wise_unc_fudge * unc)).ravel()
#galpha = 0.3
gsty = dict(linestyle='-', alpha=0.3)
chiw = (imm / sigm).ravel()
lo,hi = -6,12
ha = dict(range=(lo,hi), bins=100, log=True, histtype='step')
ha1 = dict(range=(lo,hi), bins=100)
plt.clf()
h1,e = np.histogram(wisechi, **ha1)
h3,e = np.histogram(chiw, **ha1)
nw = h3
nwise = h1
ee = e.repeat(2)[1:-1]
p1 = plt.plot(ee, (h1/1.).repeat(2), zorder=25, color='r', lw=3, alpha=0.5)
p3 = plt.plot(ee, h3.repeat(2), zorder=25, color='b', lw=2, alpha=0.75)
plt.yscale('log')
xx = np.linspace(lo, hi, 300)
plt.plot(xx, max(nwise)*np.exp(-0.5*(xx**2)/(2.**2)), color='r', **gsty)
plt.plot(xx, max(nwise)*np.exp(-0.5*(xx**2)/(2.5**2)), color='r', **gsty)
plt.plot(xx, max(nw)*np.exp(-0.5*(xx**2)), color='b', **gsty)
plt.xlabel('Pixel / Uncertainty ($\sigma$)')
plt.ylabel('Number of pixels')
wc = (wiseim-wisesky) / unc
print 'wc', wc.shape
pp = []
for ii,cc in [
(np.linspace(0, wc.shape[0], 6), 'm'),
#(np.linspace(0, wc.shape[0], 11), 'r'),
#(np.linspace(0, wc.shape[0], 21), 'g'),
]:
nmx = []
for ilo,ihi in zip(ii, ii[1:]):
for jlo,jhi in zip(ii, ii[1:]):
wsub = wiseim[ilo:ihi, jlo:jhi]
usub = unc[ilo:ihi, jlo:jhi]
ssky = wisesky
#ssky = estimate_sky(wsub, wisemed-2.*wisesig, wisemed+1.*wisesig)
h,e = np.histogram(((wsub - ssky)/usub).ravel(), **ha1)
imax = np.argmax(h)
ew = (e[1]-e[0])/2.
de = -(e[imax] + ew)
plt.plot(ee + de, h.repeat(2), color=cc, lw=1, alpha=0.25)
#plt.plot(e[:-1] + de + ew, h, color=cc, lw=1, alpha=0.5)
nmx.append(max(h))
# for legend only
p4 = plt.plot([0],[1e10], color=cc)
pp.append(p4[0])
for s in [np.sqrt(2.), 2.]:
plt.plot(xx, np.median(nmx)*np.exp(-0.5*(xx**2)/s**2),
zorder=20, color='k', **gsty)
plt.legend([p1[0],p3[0]]+pp, ('WISE', 'unWISE', '5x5 sub WISE'))
plt.ylim(3, 1e6)
plt.xlim(lo,hi)
plt.axvline(0, color='k', alpha=0.1)
ps.savefig()
if not part3:
ps.skip(2)
else:
plt.figure(figsize=medfigsize)
plt.subplots_adjust(**medspa)
wiseflux = (wiseim - wisesky) * zpscale
wiseerr = unc * zpscale
wiseflux /= psfnorm
wiseerr *= wise_unc_fudge / psfnorm
wiseerr1 = np.median(wiseerr)
print 'WISE err1:', wiseerr1
unflux = imm.ravel()
unerr = ppstdm.ravel()
print 'unWISE err1:', np.median(unerr)
logflo,logfhi = -2, 5.
logelo,logehi = 0., 3.
#logelo,logehi = -0.5, 3.
flo,fhi = 10.**logflo, 10.**logfhi
elo,ehi = 10.**logelo, 10.**logehi
# wf = wiseflux[::2, ::2].ravel()
# plt.clf()
# loghist(np.log10(wf), np.log10(unflux), range=[[np.log10(flo),np.log10(fhi)]]*2,
# nbins=200, hot=False, doclf=False,
# docolorbar=False, imshowargs=dict(cmap=antigray))
# plt.xlabel('log WISE flux')
# plt.ylabel('log unWISE flux')
# ps.savefig()
wiseflux = wiseflux.ravel()
wiseerr = wiseerr.ravel()
ha = dict(hot=False, doclf=False, nbins=200,
range=((np.log10(flo),np.log10(fhi)),
(np.log10(elo),np.log10(ehi))),
docolorbar=False, imshowargs=dict(cmap=antigray))
plt.clf()
loghist(np.log10(np.clip(wiseflux, flo,fhi)),
np.log10(np.clip(wiseerr, elo,ehi)), **ha)
plt.xlabel('WISE flux')
plt.ylabel('WISE flux uncertainty')
ax = plt.axis()
xx = np.linspace(np.log10(flo), np.log10(fhi), 500)
# yy = np.log10(np.hypot(wiseerr1, np.sqrt(0.01 * 10.**xx)))
# plt.plot(xx, yy, 'm-', lw=2)
yy = np.log10(np.hypot(wiseerr1, np.sqrt(0.02 * 10.**xx)))
c = 'r'
if bw:
c = 'k'
plt.plot(xx, yy, '-', lw=2, color=c)
plt.axis(ax)
logf = np.arange(logflo,logfhi+1)
plt.xticks(logf, ['$10^{%i}$' % x for x in logf])
loge = np.arange(int(np.ceil(logelo)),logehi+1)
plt.yticks(loge, ['$10^{%i}$' % x for x in loge])
ps.savefig()
plt.clf()
loghist(np.log10(np.clip(unflux, flo,fhi)),
np.log10(np.clip(unerr, elo,ehi)), **ha)
plt.xlabel('unWISE flux')
plt.ylabel('unWISE sample standard deviation')
yy = np.log10(np.hypot(np.hypot(wiseerr1, np.sqrt(0.02 * 10.**xx)),
3e-2*(10.**xx)))
ax = plt.axis()
plt.plot(xx, yy, '-', lw=2, color=c)
plt.axis(ax)
logf = np.arange(logflo,logfhi+1)
plt.xticks(logf, ['$10^{%i}$' % x for x in logf])
loge = np.arange(int(np.ceil(logelo)),logehi+1)
plt.yticks(loge, ['$10^{%i}$' % x for x in loge])
ps.savefig()
# plt.clf()
# plt.hist(wiseflux / wiseerr, range=(-6,10), log=True, bins=100,
# histtype='step', color='r')
# plt.hist(unflux / unerr, range=(-6,10), log=True, bins=100,
# histtype='step', color='b')
# yl,yh = plt.ylim()
# plt.ylim(0.1, yh)
# ps.savefig()
if part4:
plt.figure(figsize=figsize)
plt.subplots_adjust(**spa)
hi,wi = wiseim.shape
hj,wj = imm.shape
# franges = [ (0.0,0.05), (0.45,0.5), (0.94,0.99) ]
franges = [ (0.0,0.1), (0.45,0.55), (0.89,0.99) ]
imargs = ima.copy()
imargs.update(vmin=-2.*sigm1, vmax=2.*sigm1,
cmap='jet')
if bw:
imargs.update(cmap='gray')
plt.clf()
k = 1
for yflo,yfhi in reversed(franges):
for xflo,xfhi in franges:
plt.subplot(len(franges),len(franges), k)
k += 1
slcW = (slice(int(hi*yflo), int(hi*yfhi)+1),
slice(int(wi*xflo), int(wi*xfhi)+1))
subwise = wiseim[slcW]
# bin
# subwise = binimg(subwise, 2)
subwise = binimg(subwise, 4)
plt.imshow((subwise - wisesky) * zpscale / psfnorm, **imargs)
plt.xticks([]); plt.yticks([])
ps.savefig()
plt.clf()
k = 1
for yflo,yfhi in reversed(franges):
for xflo,xfhi in franges:
plt.subplot(len(franges),len(franges), k)
k += 1
slcU = (slice(int(hj*yflo), int(hj*yfhi)+1),
slice(int(wj*xflo), int(wj*xfhi)+1))
subimm = imm[slcU]
subimm = binimg(subimm, 2)
plt.imshow(subimm, **imargs)
plt.xticks([]); plt.yticks([])
ps.savefig()
class CompositeStage(object):
def __init__(self):
pass
def __call__(self, stage, **kwargs):
f = { 0:self.stage0, 1:self.stage1 }[stage]
return f(**kwargs)
def stage0(self, bands=None, coadd_id=None, medpct=None, dir2=None,
fxlo=None, fxhi=None, fylo=None, fyhi=None, official=None,
unmasked = True, fit_sky=False,
sky_plo=5, sky_phi=60, bin=None, sky_args={},
skyplots=True,
**kwargs):
wiseims = []
imws = []
ims = []
#hi,wi = wiseims[0].shape
#hj,wj = imws[0].shape
hi,wi = 4095,4095
slcI = (slice(int(hi*fylo), int(hi*fyhi)+1),
slice(int(wi*fxlo), int(wi*fxhi)+1))
# print 'slices:', slcI, slcJ
if official:
for band in bands:
wiseim,wisehdr,unc = read_wise_coadd(coadd_id, band, unc=True)
wisemed = np.percentile(wiseim[::4,::4], medpct)
wisesig = np.median(unc[::4,::4])
x,c,fc,wisesky = estimate_sky(wiseim, wisemed-2.*wisesig, wisemed+1.*wisesig,
return_fit=True)
print 'WISE sky', wisesky
wiseim = wiseim[slcI]
wiseim -= wisesky
# adjust zeropoints
zp = wisehdr['MAGZP']
zpscale = 1. / NanoMaggies.zeropointToScale(zp)
wiseim *= zpscale
wisesig *= zpscale
# plt.clf()
# plt.plot(x, c, 'ro', alpha=0.5)
# plt.plot(x, fc, 'b-', alpha=0.5)
# plt.title('WISE W%i' % band)
# ps.savefig()
sky = estimate_sky(wiseim, -2.*wisesig, 1.*wisesig)
print 'wise sky 2:', sky
wiseim -= sky
wiseims.append(wiseim)
for band in bands:
im = read(dir2, 'unwise-%s-w%i-img-m.fits' % (coadd_id, band))
hj,wj = im.shape #2048,2048
slcJ = (slice(int(hj*fylo), int(hj*fyhi)+1),
slice(int(wj*fxlo), int(wj*fxhi)+1))
imws.append(im[slcJ])
if unmasked:
im = read(dir2, 'unwise-%s-w%i-img-u.fits' % (coadd_id, band))
ims.append(im[slcJ])
# std = read(dir2, 'unwise-%s-w%i-std-m.fits' % (coadd_id, band))
# sig = np.median(std[::4,::4])
# print 'median std:', sig
if fit_sky:
imlist = [imws[-1]]
if unmasked:
imlist.append(ims[-1])
for im in imlist:
# med = np.percentile(im, medpct)
# # percentile ranges to include in sky fit
# plo,phi = sky_plo,sky_phi
# rlo,rhi = [np.percentile(im, p) for p in (plo,phi)]
# #rlo,rhi = (med-2.*sig, med+1.*sig)
x,c,fc,sky,warn,be1,c1 = estimate_sky_2(im, return_fit=True, **sky_args)
if skyplots:
plt.clf()
plt.hist(im.ravel(), range=(np.percentile(im, 5),
np.percentile(im, 90)),
bins=100, histtype='step', color='b', log=True)
#plt.axvline(rlo, color='g')
#plt.axvline(rhi, color='g')
plt.axvline(sky, color='r')
plt.title('Sky estimate: W%i' % band)
ps.savefig()
plt.clf()
plt.plot(x, c, 'b-', alpha=0.5)
plt.plot(x, fc, 'r-', alpha=0.5)
plt.xlabel('image')
plt.ylabel('sky hist vs fit')
plt.title('Sky estimate: W%i' % band)
ps.savefig()
# print 'med', med, 'sig', sig
print 'estimated sky', sky
im -= sky
# plt.clf()
# plt.plot(x, c, 'ro', alpha=0.5)
# plt.plot(x, fc, 'b-', alpha=0.5)
# plt.title('unWISE W%i' % band)
# ps.savefig()
if bin is not None:
wiseims = [binimg(im,bin) for im in wiseims]
imws = [binimg(im,bin) for im in imws]
ims = [binimg(im,bin) for im in ims]
return dict(wiseims=wiseims, imws=imws, ims=ims)
def stage1(self, wiseims=None, imws=None, ims=None, bands=None,
compoffset=None, inset=None, official=None,
QQ = [20],
SS = [100],
unmasked = True,
mix=None,
r0=0., b0=0., g0=0.,
w3scale=10.,
w4scale=50., subsample=False,
**kwargs):
# soften W2
# for im in [wiseims, imws, ims]:
# #im[1] /= 3.
# #im[1] /= 2
# #im[1] /= 1.5
# pass
# soften W3,W4
for imlist in [wiseims, imws, ims]:
for band,im in zip(bands, imlist):
if band == 3:
im /= w3scale
if band == 4:
im /= w4scale
# compensate for WISE psf norm
if official:
for im in wiseims:
im *= 4.
# histograms
if False:
medfigsize = (5,3.5)
medspa = dict(left=0.12, right=0.96, bottom=0.12, top=0.96)
plt.figure(figsize=medfigsize)
plt.subplots_adjust(**medspa)
for imlist in [wiseims, imws, ims]:
plt.clf()
for im,cc,scale in zip(imlist, 'bgr', [1.,1.,0.2]):
plt.hist((im*scale).ravel(), range=(-5,20), histtype='step',
bins=100)
ps.savefig()
# plt.figure(figsize=(8,8))
# #spa = dict(left=0.01, right=0.99, bottom=0.01, top=0.99)
# spa = dict(left=0.005, right=0.995, bottom=0.005, top=0.995)
# plt.subplots_adjust(**spa)
# for im in [wiseims, imws, ims]:
# plt.clf()
# for i,Q in enumerate([3, 10, 30, 100]):
# plt.subplot(2,2, i+1)
# L = _lupton_comp([i/100 for i in im], Q=Q)
# plt.imshow(L, interpolation='nearest', origin='lower')
# plt.xticks([]); plt.yticks([])
# ps.savefig()
# plt.figure(figsize=(4,4))
# #spa = dict(left=0.01, right=0.99, bottom=0.01, top=0.99)
# spa = dict(left=0.005, right=0.995, bottom=0.005, top=0.995)
# plt.subplots_adjust(**spa)
imslist,scales = [],[]
if official:
imslist.append(wiseims)
scales.append(2.)
if unmasked:
imslist.append(ims)
scales.append(1.)
imslist.append(imws)
scales.append(1.)
for im,sc in zip(imslist, scales):
plt.clf()
k = 1
# QQ = [10,20]
# SS = [100,200]
#QQ = [15,20,25]
#SS = [50,100,200]
for Q in QQ:
for S in SS:
kwa = dict(Q=Q, clip=False)
if len(im) != 3:
L = _lupton_comp([i/S for i in im], **kwa)
else:
b,g,r = im
# R = g * 0.4 + r * 0.6
# G = b * 0.2 + g * 0.8
# B = b
if mix is None:
R = g * 0.8 + r * 0.5
G = b * 0.4 + g * 0.6
B = b * 1.0
else:
RGB = []
r += r0
g += g0
b += b0
for ar,ag,ab in mix:
print 'Mix:', ar,ag,ab
RGB.append(ar * r + ag * g + ab * b)
R,G,B = RGB
L = _lupton_comp([i/S for i in [B,G,R]], **kwa)
plt.subplot(len(QQ), len(SS), k)
plt.title('Q=%.0f, S=%.0f' % (Q, S))
k += 1
H,W,nil = L.shape
mn = min(H,W)
L = L[:mn,:mn]
if sc == 1 and subsample:
# Lanczos sub-sample so it has the same pixel resolution
# as the WISE image.
sh,sw,planes = L.shape
xx,yy = np.meshgrid(np.linspace(-0.5, sw-0.5, 2*sw),
np.linspace(-0.5, sh-0.5, 2*sh))
xx = xx.ravel()
yy = yy.ravel()
ix = np.round(xx).astype(np.int32)
iy = np.round(yy).astype(np.int32)
dx = (xx - ix).astype(np.float32)
dy = (yy - iy).astype(np.float32)
RR = [np.zeros(sh*2*sw*2, np.float32) for i in range(planes)]
LL = [L[:,:,i] for i in range(planes)]
lanczos3_interpolate(ix, iy, dx, dy, RR, LL)
L = np.dstack([R.reshape((sh*2,sw*2)) for R in RR])
plt.imshow(np.clip(L, 0, 1),
interpolation='nearest', origin='lower')
plt.xticks([]); plt.yticks([])
print 'Inset:', inset
if inset is not None:
h,w,planes = L.shape
print 'w,h', w,h
xi = [int(np.round(i*w)) for i in inset[:2]]
yi = [int(np.round(i*h)) for i in inset[2:]]
dx = xi[1]-xi[0]
dy = yi[1]-yi[0]
dd = max(dx,dy)
Lsub = L[yi[0]:yi[0]+dd+1,xi[0]:xi[0]+dd+1]
ax = plt.axis()
xl,xh = xi[0], xi[0]+dd
yl,yh = yi[0], yi[0]+dd
plt.plot([xl,xl,xh,xh,xl], [yl,yh,yh,yl,yl], 'w-')
plt.axis(ax)
ax = plt.axes([0.69, 0.01, 0.3, 0.3])
plt.sca(ax)
plt.setp(ax.spines.values(), color='w')
if sc == 1:
# Lanczos sub-sample so it has the same pixel resolution
# as the WISE image.
sh,sw,planes = Lsub.shape
xx,yy = np.meshgrid(np.linspace(-0.5, sw-0.5, 2*sw),
np.linspace(-0.5, sh-0.5, 2*sh))
xx = xx.ravel()
yy = yy.ravel()
ix = np.round(xx).astype(np.int32)
iy = np.round(yy).astype(np.int32)
dx = (xx - ix).astype(np.float32)
dy = (yy - iy).astype(np.float32)
RR = [np.zeros(sh*2*sw*2, np.float32) for i in range(planes)]
LL = [L[:,:,i] for i in range(planes)]
lanczos3_interpolate(xi[0]+ix, yi[0]+iy, dx, dy, RR, LL)
Lsub = np.dstack([R.reshape((sh*2,sw*2)) for R in RR])
plt.imshow(np.clip(Lsub, 0, 1),
interpolation='nearest', origin='lower')
plt.xticks([]); plt.yticks([])
ps.savefig()
# for im in [wiseims, imws, ims]:
# comp = _comp(im)
# plt.clf()
#
# comp += compoffset
# #comp = (comp/200.)**0.3
# #comp = (comp/100.)**0.4
# comp = (comp/200.)**0.4
# #comp = (comp/300.)**0.5
# #comp = (comp/300.)
# #comp = np.sqrt(comp/25.)
#
# plt.imshow(np.clip(comp, 0., 1.),
# interpolation='nearest', origin='lower')
# plt.xticks([]); plt.yticks([])
# ps.savefig()
def _comp(imlist):
s = imlist[0]
HI,WI = s.shape
rgb = np.zeros((HI, WI, 3))
if len(imlist) == 2:
rgb[:,:,0] = imlist[1]
rgb[:,:,2] = imlist[0]
rgb[:,:,1] = (rgb[:,:,0] + rgb[:,:,2])/2.
elif len(imlist) == 3:
# rgb[:,:,0] = imlist[2]
# rgb[:,:,1] = imlist[1]
# rgb[:,:,2] = imlist[0]
r,g,b = imlist[2], imlist[1], imlist[0]
rgb[:,:,0] = g * 0.4 + r * 0.6
rgb[:,:,1] = b * 0.2 + g * 0.8
rgb[:,:,2] = b
return rgb
def _lupton_comp(imlist, alpha=1.5, Q=30, m=-2e-2, clip=True):
s = imlist[0]
HI,WI = s.shape
rgb = np.zeros((HI, WI, 3))
if len(imlist) == 2:
r = imlist[1]
b = imlist[0]
g = (r+b)/2.
elif len(imlist) == 3:
r,g,b = imlist[2], imlist[1], imlist[0]
else:
print len(imlist), 'images'
assert(False)
r = np.maximum(0, r - m)
g = np.maximum(0, g - m)
b = np.maximum(0, b - m)
I = (r+g+b)/3.
m2 = 0.
fI = np.arcsinh(alpha * Q * (I - m2)) / np.sqrt(Q)
I += (I == 0.) * 1e-6
R = fI * r / I
G = fI * g / I
B = fI * b / I
maxrgb = reduce(np.maximum, [R,G,B])
J = (maxrgb > 1.)
# R[J] = R[J]/maxrgb[J]
# G[J] = G[J]/maxrgb[J]
# B[J] = B[J]/maxrgb[J]
RGB = np.dstack([R,G,B])
if clip:
RGB = np.clip(RGB, 0., 1.)
return RGB
def composite(coadd_id, dir2='e', medpct=50, offset=0., bands=[1,2],
cname='comp',
df = 0.07,
fxlo = 0.43, fylo = 0.51,
fxhi = None, fyhi = None,
inset=None,
official=True,
**kwargs):
if fxhi is None:
fxhi = fxlo + df
if fyhi is None:
fyhi = fylo + df
print 'Composites for tile', coadd_id
iargs = dict(coadd_id=coadd_id, dir2=dir2, bands=bands, medpct=medpct,
compoffset=offset)
args = dict(fxlo=fxlo, fxhi=fxhi, fylo=fylo, fyhi=fyhi,
inset=inset, official=official)
args.update(kwargs)
runstage(1, 'comp-%s-stage%%02i.pickle' % cname, CompositeStage(),
force=[1], initial_args=iargs, **args)
return
# for imlist in [wiseims, imws, ims]:
# plt.clf()
# for im,cc in zip(imlist, ['b','r']):
# plt.hist(im.ravel(), bins=100, histtype='step', color=cc,
# range=(-5,30))
# plt.xlim(-5,30)
# ps.savefig()
def northpole_plots():
for dirpat in ['n%i', 'nr%i',]:
for n in range(0, 23):