-
Notifications
You must be signed in to change notification settings - Fork 1
/
unwise_coadd.py
3055 lines (2654 loc) · 107 KB
/
unwise_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
#! /usr/bin/env python
import matplotlib
if __name__ == '__main__':
matplotlib.use('Agg')
import numpy as np
import pylab as plt
import os
import sys
import tempfile
import datetime
import gc
from functools import reduce
from scipy.ndimage.morphology import binary_dilation
from scipy.ndimage.measurements import label, center_of_mass
import fitsio
from astrometry.util.file import trymakedirs
from astrometry.util.fits import fits_table, merge_tables
from astrometry.util.miscutils import estimate_mode, polygons_intersect, clip_polygon, patch_image
from astrometry.util.util import Tan, Sip, flat_median_f
from astrometry.util.resample import resample_with_wcs, OverlapError
from astrometry.util.run_command import run_command
from astrometry.util.starutil_numpy import degrees_between
from astrometry.util.ttime import Time, MemMeas
from astrometry.libkd.spherematch import match_radec
import logging
logger = None
def info(*args):
msg = ' '.join(map(str, args))
logger.info(msg)
def debug(*args):
import logging
if logger.isEnabledFor(logging.DEBUG):
msg = ' '.join(map(str, args))
logger.debug(msg)
#median_f = np.median
median_f = flat_median_f
# GLOBALS:
# Location of WISE Level 1b inputs
wisedir = 'wise-frames'
'''
at NERSC:
mkdir wise-frames-neo7
for x in /global/cfs/cdirs/cosmo/work/wise/etc/etc_neo7/W*; do ln -s $x wise-frames-neo7/; done
ln -s $COSMO/data/wise/merge/merge_p1bm_frm/wise_allsky_4band_p3as_cdd.fits wise-frames-neo7/
ln -s wise-frames-neo7 wise-frames
ln -s $COSMO/staging/wise/neowiser7/neowiser/p1bm_frm neowiser7-frames
ln -s $COSMO/staging/wise/neowiser6/neowiser/p1bm_frm neowiser6-frames
ln -s $COSMO/staging/wise/neowiser5/neowiser/p1bm_frm neowiser5-frames
ln -s $COSMO/staging/wise/neowiser4/neowiser/p1bm_frm/ neowiser4-frames
ln -s $COSMO/staging/wise/neowiser3/neowiser/p1bm_frm/ neowiser3-frames
ln -s $COSMO/staging/wise/neowiser2/neowiser/p1bm_frm/ neowiser2-frames
ln -s $COSMO/data/wise/neowiser/p1bm_frm/ neowiser-frames
ln -s $COSMO/data/wise/merge/merge_p1bm_frm/ .
'''
wisedirs = [wisedir,
'merge_p1bm_frm',
'neowiser-frames',
'neowiser2-frames',
'neowiser3-frames',
'neowiser4-frames',
'neowiser5-frames',
'neowiser6-frames',
'neowiser7-frames',
]
# when adding a year, also see below in "The metadata files to read:"...
mask_gz = True
unc_gz = True
def tile_to_radec(tileid):
assert(len(tileid) == 8)
ra = int(tileid[:4], 10) / 10.
sign = -1 if tileid[4] == 'm' else 1
dec = sign * int(tileid[5:], 10) / 10.
return ra,dec
def get_l1b_file(basedir, scanid, frame, band):
scangrp = scanid[-2:]
return os.path.join(basedir, scangrp, scanid, '%03i' % frame,
'%s%03i-w%i-int-1b.fits' % (scanid, frame, band))
# from tractor.basics.NanoMaggies
def zeropointToScale(zp):
'''
Converts a traditional magnitude zeropoint to a scale factor
by which nanomaggies should be multiplied to produce image
counts.
'''
return 10.**((zp - 22.5)/2.5)
class Duck():
pass
def get_coadd_tile_wcs(ra, dec, W=2048, H=2048, pixscale=2.75):
'''
Returns a Tan WCS object at the given RA,Dec center, axis aligned, with the
given pixel W,H and pixel scale in arcsec/pixel.
'''
cowcs = Tan(ra, dec, (W+1)/2., (H+1)/2.,
-pixscale/3600., 0., 0., pixscale/3600., W, H)
return cowcs
def walk_wcs_boundary(wcs, step=1024, margin=0):
'''
Walk the image boundary counter-clockwise.
Returns rr,dd -- RA,Dec numpy arrays.
'''
W = wcs.get_width()
H = wcs.get_height()
xlo = 1
xhi = W
ylo = 1
yhi = H
if margin:
xlo -= margin
ylo -= margin
xhi += margin
yhi += margin
xx,yy = [],[]
xwalk = np.linspace(xlo, xhi, int(np.ceil((1+xhi-xlo)/float(step)))+1)
ywalk = np.linspace(ylo, yhi, int(np.ceil((1+yhi-ylo)/float(step)))+1)
# bottom edge
x = xwalk[:-1]
y = ylo
xx.append(x)
yy.append(np.zeros_like(x) + y)
# right edge
x = xhi
y = ywalk[:-1]
xx.append(np.zeros_like(y) + x)
yy.append(y)
# top edge
x = list(reversed(xwalk))[:-1]
y = yhi
xx.append(x)
yy.append(np.zeros_like(x) + y)
# left edge
x = xlo
y = list(reversed(ywalk))[:-1]
# (note, NOT closed)
xx.append(np.zeros_like(y) + x)
yy.append(y)
#
rr,dd = wcs.pixelxy2radec(np.hstack(xx), np.hstack(yy))
return rr,dd
def get_wcs_radec_bounds(wcs):
rr,dd = walk_wcs_boundary(wcs)
r0,r1 = rr.min(), rr.max()
d0,d1 = dd.min(), dd.max()
return r0,r1,d0,d1
def in_radec_box(ra,dec, r0,r1,d0,d1, margin):
assert(r0 <= r1)
assert(d0 <= d1)
assert(margin >= 0.)
if r0 == 0. and r1 == 360.:
# Just cut on Dec.
return ((dec + margin >= d0) * (dec - margin <= d1))
cosdec = np.cos(np.deg2rad(max(abs(d0),abs(d1))))
debug('cosdec:', cosdec)
# wrap-around... time to switch to unit-sphere instead?
# Still issues near the Dec poles (if margin/cosdec -> 360)
## HACK: 89 degrees -> cosdec 0.017
if cosdec < 0.02:
return ((dec + margin >= d0) * (dec - margin <= d1))
elif (r0 - margin/cosdec < 0) or (r1 + margin/cosdec > 360):
# python mod: result has same sign as second arg
rlowrap = (r0 - margin/cosdec) % 360.0
rhiwrap = (r1 + margin/cosdec) % 360.0
if (r0 - margin/cosdec < 0):
raA = rlowrap
raB = 360.
raC = 0.
raD = rhiwrap
else:
raA = rhiwrap
raB = 360.0
raC = 0.
raD = rlowrap
debug('RA wrap-around:', r0,r1, '+ margin', margin, '->', rlowrap, rhiwrap)
debug('Looking at ranges (%.2f, %.2f) and (%.2f, %.2f)' % (raA,raB,raC,raD))
assert(raA <= raB)
assert(raC <= raD)
return (np.logical_or((ra >= raA) * (ra <= raB),
(ra >= raC) * (ra <= raD)) *
(dec + margin >= d0) *
(dec - margin <= d1))
else:
return ((ra + margin/cosdec >= r0) *
(ra - margin/cosdec <= r1) *
(dec + margin >= d0) *
(dec - margin <= d1))
def get_wise_frames(r0,r1,d0,d1, margin=2., bands=[1,2,3,4]):
'''
Returns WISE frames touching the given RA,Dec box plus margin.
'''
# Read WISE frame metadata
#WISE = fits_table(os.path.join(wisedir, 'WISE-index-L1b.fits'))
#print('Read', len(WISE), 'WISE L1b frames')
WISE = []
for band in bands:
fn = os.path.join(wisedir, 'WISE-index-L1b_w%i.fits' % band)
print('Reading', fn)
W = fits_table(fn)
WISE.append(W)
WISE = merge_tables(WISE)
print('Total of', len(WISE), 'frames')
WISE.row = np.arange(len(WISE))
# Coarse cut on RA,Dec box.
WISE.cut(in_radec_box(WISE.ra, WISE.dec, r0,r1,d0,d1, margin))
debug('Cut to', len(WISE), 'WISE frames near RA,Dec box')
# Join to WISE Single-Frame Metadata Tables
WISE.qual_frame = np.zeros(len(WISE), np.int16) - 1
WISE.moon_masked = np.zeros(len(WISE), bool)
WISE.dtanneal = np.zeros(len(WISE), np.float32)
# pixel distribution stats (used for moon masking)
WISE.intmedian = np.zeros(len(WISE), np.float32)
WISE.intstddev = np.zeros(len(WISE), np.float32)
WISE.intmed16p = np.zeros(len(WISE), np.float32)
WISE.matched = np.zeros(len(WISE), bool)
# 4-band, 3-band, or 2-band phase
WISE.phase = np.zeros(len(WISE), np.uint8)
# The metadata files to read:
for nbands,name in [(4,'4band'),
(3,'3band'),
(2,'2band'),
(2,'neowiser'),
(2, 'neowiser2'),
(2, 'neowiser3'),
(2, 'neowiser4'),
(2, 'neowiser5'),
(2, 'neowiser6'),
(2, 'neowiser7'),
]:
# the bands in this dataset
bb = [1,2,3,4][:nbands]
if not any([b in bands for b in bb]):
# no bands of interest in this observation phase - skip
continue
fn = os.path.join(wisedir, 'WISE-l1b-metadata-%s.fits' % name)
if not os.path.exists(fn):
print('WARNING: ignoring missing', fn)
continue
print('Reading', fn)
cols = (['ra', 'dec', 'scan_id', 'frame_num',
'qual_frame', 'moon_masked', ] +
['w%iintmed16ptile' % b for b in bb] +
['w%iintmedian' % b for b in bb] +
['w%iintstddev' % b for b in bb])
if nbands > 2:
cols.append('dtanneal')
T = fits_table(fn, columns=cols)
debug('Read', len(T), 'from', fn)
# Cut with extra large margins
T.cut(in_radec_box(T.ra, T.dec, r0,r1,d0,d1, 2.*margin))
debug('Cut to', len(T), 'near RA,Dec box')
if len(T) == 0:
continue
if not 'dtanneal' in T.get_columns():
T.dtanneal = np.zeros(len(T), np.float64) + 1000000.
I,J,d = match_radec(WISE.ra, WISE.dec, T.ra, T.dec, 60./3600.)
debug('Matched', len(I))
debug('WISE-index-L1b scan_id:', WISE.scan_id.dtype, 'frame_num:', WISE.frame_num.dtype)
debug('WISE-metadata scan_id:', T.scan_id.dtype, 'frame_num:', T.frame_num.dtype)
K = np.flatnonzero((WISE.scan_id [I] == T.scan_id [J]) *
(WISE.frame_num[I] == T.frame_num[J]))
I = I[K]
J = J[K]
debug('Cut to', len(I), 'matching scan/frame')
for band in bb:
K = (WISE.band[I] == band)
debug('Band', band, ':', sum(K))
if sum(K) == 0:
continue
II = I[K]
JJ = J[K]
WISE.qual_frame [II] = T.qual_frame [JJ].astype(WISE.qual_frame.dtype)
moon = T.moon_masked[JJ]
WISE.moon_masked[II] = np.array([m[band-1] == '1' for m in moon]
).astype(WISE.moon_masked.dtype)
WISE.dtanneal [II] = T.dtanneal[JJ].astype(WISE.dtanneal.dtype)
WISE.intmedian[II] = T.get('w%iintmedian' % band)[JJ].astype(np.float32)
WISE.intstddev[II] = T.get('w%iintstddev' % band)[JJ].astype(np.float32)
WISE.intmed16p[II] = T.get('w%iintmed16ptile' % band)[JJ].astype(np.float32)
WISE.matched[II] = True
WISE.phase[II] = nbands
debug(np.sum(WISE.matched), 'of', len(WISE), 'matched to metadata tables')
assert(np.sum(WISE.matched) == len(WISE))
WISE.delete_column('matched')
# Reorder by scan, frame, band
WISE.cut(np.lexsort((WISE.band, WISE.frame_num, WISE.scan_id)))
return WISE
def get_dir_for_coadd(outdir, coadd_id):
# base/RRR/RRRRsDDD/unwise-*
return os.path.join(outdir, coadd_id[:3], coadd_id)
def get_epoch_breaks(mjds):
mjds = np.sort(mjds)
# define an epoch either as a gap of more than 3 months
# between frames, or as > 6 months since start of epoch.
start = mjds[0]
ebreaks = []
for lastmjd,mjd in zip(mjds, mjds[1:]):
if (mjd - lastmjd >= 90.) or (mjd - start >= 180.):
ebreaks.append((mjd + lastmjd) / 2.)
start = mjd
print('Defined epoch breaks', ebreaks)
print('Found', len(ebreaks), 'epoch breaks')
return ebreaks
def one_coadd(ti, band, W, H, frames,
pixscale=2.75,
zoom=None,
outdir='unwise-coadds',
medfilt=None,
do_dsky=False,
bgmatch=False, center=False,
minmax=False, rchi_fraction=0.01, epoch=None,
before=None, after=None,
ascendingOnly=False,
descendingOnly=False,
ps=None,
wishlist=False,
mp1=None, mp2=None,
do_cube=False, do_cube1=False,
plots2=False,
frame0=0, nframes=0, nframes_random=0,
force=False, maxmem=0,
allow_download=False,
force_outdir=False, just_image=False, version=None,
write_masks=True):
'''
Create coadd for one tile & band.
'''
debug('Coadd tile', ti.coadd_id)
debug('RA,Dec', ti.ra, ti.dec)
debug('Band', band)
from astrometry.util.multiproc import multiproc
if mp1 is None:
mp1 = multiproc()
if mp2 is None:
mp2 = multiproc()
wisepixscale = 2.75
if version is None:
from astrometry.util.run_command import run_command
rtn,version,err = run_command('git describe')
if rtn:
raise RuntimeError('Failed to get version string (git describe):' + ver + err)
version = version.strip()
debug('"git describe" version info:', version)
if not force_outdir:
outdir = get_dir_for_coadd(outdir, ti.coadd_id)
trymakedirs(outdir)
tag = 'unwise-%s-w%i' % (ti.coadd_id, band)
prefix = os.path.join(outdir, tag)
ofn = prefix + '-img-m.fits'
if os.path.exists(ofn):
print('Output file exists:', ofn)
if not force:
return 0
cowcs = get_coadd_tile_wcs(ti.ra, ti.dec, W, H, pixscale)
if zoom is not None:
(x0,x1,y0,y1) = zoom
W = x1-x0
H = y1-y0
zoomwcs = cowcs.get_subimage(x0, y0, W, H)
print('Zooming WCS from', cowcs, 'to', zoomwcs)
cowcs = zoomwcs
# Intermediate world coordinates (IWC) polygon
r,d = walk_wcs_boundary(cowcs, step=W, margin=10)
ok,u,v = cowcs.radec2iwc(r,d)
copoly = np.array(list(reversed(list(zip(u,v)))))
#print('Coadd IWC polygon:', copoly)
margin = (1.1 # safety margin
* (np.sqrt(2.) / 2.) # diagonal
* (max(W,H) * pixscale/3600.
+ 1016 * wisepixscale/3600) # WISE FOV + coadd FOV side length
) # in deg
t0 = Time()
ra_center,dec_center = cowcs.radec_center()
# cut
frames = frames[frames.band == band]
frames.cut(degrees_between(ra_center, dec_center, frames.ra, frames.dec) < margin)
debug('Found', len(frames), 'WISE frames in range and in band W%i' % band)
if before is not None:
frames.cut(frames.mjd < before)
debug('Cut to', len(frames), 'frames before MJD', before)
if after is not None:
frames.cut(frames.mjd > after)
debug('Cut to', len(frames), 'frames after MJD', after)
# Cut on IWC box
ok,u,v = cowcs.radec2iwc(frames.ra, frames.dec)
u0,v0 = copoly.min(axis=0)
u1,v1 = copoly.max(axis=0)
#print 'Coadd IWC range:', u0,u1, v0,v1
margin = np.sqrt(2.) * (1016./2.) * (wisepixscale/3600.) * 1.01 # safety
frames.cut((u + margin >= u0) * (u - margin <= u1) *
(v + margin >= v0) * (v - margin <= v1))
debug('cut to', len(frames), 'in RA,Dec box')
# Use a subset of frames?
if epoch is not None:
ebreaks = get_epoch_breaks(frames.mjd)
assert(epoch <= len(ebreaks))
if epoch > 0:
frames = frames[frames.mjd >= ebreaks[epoch - 1]]
if epoch < len(ebreaks):
frames = frames[frames.mjd < ebreaks[epoch]]
debug('Cut to', len(frames), 'within epoch')
if bgmatch or center:
# reorder by dist from center
frames.cut(np.argsort(degrees_between(ra_center, dec_center, frames.ra, frames.dec)))
if ps and False:
plt.clf()
plt.plot(copoly[:,0], copoly[:,1], 'r-')
plt.plot(copoly[0,0], copoly[0,1], 'ro')
plt.plot(u, v, 'b.')
plt.axvline(u0 - margin, color='k')
plt.axvline(u1 + margin, color='k')
plt.axhline(v0 - margin, color='k')
plt.axhline(v1 + margin, color='k')
ok,u2,v2 = cowcs.radec2iwc(frames.ra, frames.dec)
plt.plot(u2, v2, 'go')
ps.savefig()
# We keep all of the input frames in the list, marking ones we're not
# going to use, for later diagnostics.
frames.use = np.ones(len(frames), bool)
frames.use *= (frames.qual_frame > 0)
debug('Cut out qual_frame = 0;', sum(frames.use), 'remaining')
if band in [3,4]:
frames.use *= (frames.dtanneal > 2000.)
debug('Cut out dtanneal <= 2000 seconds:', sum(frames.use), 'remaining')
if band == 4:
ok = np.array([np.logical_or(s < '03752a', s > '03761b')
for s in frames.scan_id])
frames.use *= ok
debug('Cut out bad scans in W4:', sum(frames.use), 'remaining')
# Cut ones where the w?intmedian is NaN
frames.use *= np.isfinite(frames.intmedian)
debug('Cut out intmedian non-finite:', sum(frames.use), 'remaining')
if band in [3,4]:
# Cut on moon, based on (robust) measure of standard deviation
if sum(frames.moon_masked[frames.use]):
moon = frames.moon_masked[frames.use]
nomoon = np.logical_not(moon)
Imoon = np.flatnonzero(frames.use)[moon]
assert(sum(moon) == len(Imoon))
debug(sum(nomoon), 'of', sum(frames.use), 'frames are not moon_masked')
nomoonstdevs = frames.intmed16p[frames.use][nomoon]
med = np.median(nomoonstdevs)
mad = 1.4826 * np.median(np.abs(nomoonstdevs - med))
debug('Median', med, 'MAD', mad)
moonstdevs = frames.intmed16p[frames.use][moon]
okmoon = (moonstdevs - med)/mad < 5.
debug(sum(np.logical_not(okmoon)), 'of', len(okmoon), 'moon-masked frames have large pixel variance')
frames.use[Imoon] *= okmoon
debug('Cut to', sum(frames.use), 'on moon')
del Imoon
del moon
del nomoon
del nomoonstdevs
del med
del mad
del moonstdevs
del okmoon
if frame0 or nframes or nframes_random:
i0 = frame0
if nframes:
frames = frames[frame0:frame0 + nframes]
elif nframes_random:
frames = frames[frame0 + np.random.permutation(len(frames)-frame0)[:nframes_random]]
else:
frames = frames[frame0:]
debug('Cut to', len(frames), 'frames starting from index', frame0)
debug('Frames to coadd:')
for i,w in enumerate(frames):
debug(' ', i, w.scan_id, '%4i' % w.frame_num, 'MJD', w.mjd)
if len(frames) == 0:
info('No frames overlap position x time')
return -1
if wishlist:
for wise in frames:
intfn = get_l1b_file(wisedir, wise.scan_id, wise.frame_num, band)
if not os.path.exists(intfn):
print('Need:', intfn)
#cmd = 'rsync -LRvz carver:unwise/./%s .' % intfn
#print cmd
#os.system(cmd)
return 0
# Estimate memory usage and bail out if too high.
if maxmem:
mem = 1. + (len(frames) * 1e6/2. * 5. / 1e9)
print('Estimated mem usage:', mem)
if mem > maxmem:
print('Estimated memory usage:', mem, 'GB > max', maxmem)
return -1
# *inclusive* coordinates of the bounding-box in the coadd of this
# image (x0,x1,y0,y1)
frames.coextent = np.zeros((len(frames), 4), np.int32)
# *inclusive* coordinates of the bounding-box in the image
# overlapping coadd
frames.imextent = np.zeros((len(frames), 4), np.int32)
frames.imagew = np.zeros(len(frames), np.int32)
frames.imageh = np.zeros(len(frames), np.int32)
frames.intfn = np.zeros(len(frames), object)
frames.wcs = np.zeros(len(frames), object)
# count total number of coadd-space pixels -- this determines memory use
pixinrange = 0.
frames.ascending = np.zeros(len(frames), bool)
frames.descending = np.zeros(len(frames), bool)
nu = 0
NU = sum(frames.use)
failedfiles = []
for wi,wise in enumerate(frames):
if not wise.use:
continue
nu += 1
debug(nu, 'of', NU, 'scan', wise.scan_id, 'frame', wise.frame_num, 'band', band)
found = False
for wdir in wisedirs + [None]:
download = False
if wdir is None:
download = allow_download
wdir = 'merge_p1bm_frm'
intfn = get_l1b_file(wdir, wise.scan_id, wise.frame_num, band)
debug('intfn', intfn)
intfnx = intfn.replace(wdir+'/', '')
if download:
# Try to download the file from IRSA.
cmd = (('(wget -r -N -nH -np -nv --cut-dirs=4 -A "*w%i*" ' +
'"http://irsa.ipac.caltech.edu/ibe/data/wise/merge/merge_p1bm_frm/%s/")') %
(band, os.path.dirname(intfnx)))
print()
print('Trying to download file:')
print(cmd)
print()
os.system(cmd)
print()
if os.path.exists(intfn):
hdr = fitsio.read_header(intfn)
events = hdr['INEVENTS']
events = events.split()
#print('Frame', wise.scan_id, wise.frame_num, band, 'events:', events)
if 'ASCE' in events:
frames.ascending[wi] = True
if 'DESC' in events:
frames.descending[wi] = True
try:
wcs = Sip(intfn)
except RuntimeError:
import traceback
traceback.print_exc()
continue
else:
debug('does not exist:', intfn)
continue
if (os.path.exists(intfn.replace('-int-', '-unc-') + '.gz') and
os.path.exists(intfn.replace('-int-', '-msk-') + '.gz')):
found = True
break
else:
print('missing unc or msk file')
continue
if not found:
print('WARNING: Not found: scan', wise.scan_id, 'frame', wise.frame_num, 'band', band)
failedfiles.append(intfnx)
continue
if ascendingOnly and not frames.ascending[wi]:
frames.use[wi] = False
print('Skipping non-ascending frame', wise.scan_id, wise.frame_num, band)
continue
if descendingOnly and not frames.descending[wi]:
frames.use[wi] = False
print('Skipping non-descending frame', wise.scan_id, wise.frame_num, band)
continue
h,w = int(wcs.get_height()), int(wcs.get_width())
r,d = walk_wcs_boundary(wcs, step=2.*w, margin=10)
ok,u,v = cowcs.radec2iwc(r, d)
poly = np.array(list(reversed(list(zip(u,v)))))
#print 'Image IWC polygon:', poly
intersects = polygons_intersect(copoly, poly)
if ps and False:
plt.clf()
plt.plot(copoly[:,0], copoly[:,1], 'r-')
plt.plot(copoly[0,0], copoly[0,1], 'ro')
plt.plot(poly[:,0], poly[:,1], 'b-')
plt.plot(poly[0,0], poly[0,1], 'bo')
cpoly = np.array(clip_polygon(copoly, poly))
if len(cpoly) == 0:
pass
else:
print('cpoly:', cpoly)
plt.plot(cpoly[:,0], cpoly[:,1], 'm-')
plt.plot(cpoly[0,0], cpoly[0,1], 'mo')
ps.savefig()
if not intersects:
debug('Image does not intersect target')
frames.use[wi] = False
continue
cpoly = np.array(clip_polygon(copoly, poly))
if len(cpoly) == 0:
debug('No overlap between coadd and image polygons')
debug('copoly:', copoly)
debug('poly:', poly)
debug('cpoly:', cpoly)
frames.use[wi] = False
continue
# Convert the intersected polygon in IWC space into image
# pixel bounds.
# Coadd extent:
xy = np.array([cowcs.iwc2pixelxy(u,v) for u,v in cpoly])
xy -= 1
x0,y0 = np.floor(xy.min(axis=0)).astype(int)
x1,y1 = np.ceil (xy.max(axis=0)).astype(int)
frames.coextent[wi,:] = [np.clip(x0, 0, W-1),
np.clip(x1, 0, W-1),
np.clip(y0, 0, H-1),
np.clip(y1, 0, H-1)]
# Input image extent:
# There was a bug in the as-run coadds; all imextents are
# [0,1015,0,1015] as a result.
#rd = np.array([cowcs.iwc2radec(u,v) for u,v in poly])
# Should be: ('cpoly' rather than 'poly' here)
rd = np.array([cowcs.iwc2radec(u,v) for u,v in cpoly])
ok,x,y = np.array(wcs.radec2pixelxy(rd[:,0], rd[:,1]))
x -= 1
y -= 1
x0,y0 = [np.floor(v.min(axis=0)).astype(int) for v in [x,y]]
x1,y1 = [np.ceil (v.max(axis=0)).astype(int) for v in [x,y]]
frames.imextent[wi,:] = [np.clip(x0, 0, w-1),
np.clip(x1, 0, w-1),
np.clip(y0, 0, h-1),
np.clip(y1, 0, h-1)]
frames.intfn[wi] = intfn
frames.imagew[wi] = w
frames.imageh[wi] = h
frames.wcs[wi] = wcs
debug('Image extent:', frames.imextent[wi,:])
debug('Coadd extent:', frames.coextent[wi,:])
# Count total coadd-space bounding-box size -- this x 5 bytes
# is the memory toll of our round-1 coadds, which is basically
# the peak memory use.
e = frames.coextent[wi,:]
pixinrange += (1+e[1]-e[0]) * (1+e[3]-e[2])
debug('Total pixels in coadd space:', pixinrange)
if len(failedfiles):
print(len(failedfiles), 'failed:')
for f in failedfiles:
print(' ', f)
print()
# Now we can make a more informed estimate of memory use.
if maxmem:
mem = 1. + (pixinrange * 5. / 1e9)
print('Estimated mem usage:', mem)
if mem > maxmem:
print('Estimated memory usage:', mem, 'GB > max', maxmem)
return -1
# convert from object array to string array; '' rather than '0'
frames.intfn = np.array([{0:''}.get(s,s) for s in frames.intfn])
debug('Cut to', sum(frames.use), 'frames intersecting target')
t1 = Time()
debug('Up to coadd_wise:', t1 - t0)
debug('Frames to coadd after cuts:')
ii = np.argsort(frames.mjd)
for i in ii:
w = frames[i]
if not w.use:
continue
debug(' ', w.scan_id, '%4i' % w.frame_num, 'MJD', w.mjd,
'ASC', w.ascending, 'DESC', w.descending, 'RA,Dec %.4f, %.4f' % (w.ra, w.dec))
# Now that we've got some information about the input frames, call
# the real coadding code. Maybe we should move this first loop into
# the round 1 coadd...
try:
(coim,coiv,copp,con, coimb,coivb,coppb,conb,masks, cube, cosky,
comin,comax,cominb,comaxb
)= coadd_wise(ti.coadd_id, cowcs, frames[frames.use], ps, band, mp1, mp2, do_cube,
medfilt, plots2=plots2, do_dsky=do_dsky,
bgmatch=bgmatch, minmax=minmax,
rchi_fraction=rchi_fraction, do_cube1=do_cube1)
except:
print('coadd_wise failed:')
import traceback
traceback.print_exc()
print('time up to failure:')
t2 = Time()
print(t2 - t1)
return -1
t2 = Time()
debug('coadd_wise:', t2-t1)
# For any "masked" pixels that have invvar = 0 (ie, NO pixels
# contributed), fill in the image from the "unmasked" image.
# Leave the invvar image untouched.
coimb[coivb == 0] = coim[coivb == 0]
# Plug the WCS header cards into the output coadd files.
hdr = fitsio.FITSHDR()
cowcs.add_to_header(hdr)
hdr.add_record(dict(name='MAGZP', value=22.5,
comment='Magnitude zeropoint (in Vega mag)'))
hdr.add_record(dict(name='UNW_SKY', value=cosky,
comment='Background value subtracted from coadd img'))
hdr.add_record(dict(name='UNW_VER', value=version,
comment='unWISE code git revision'))
hdr.add_record(dict(name='UNW_URL', value='https://github.com/dstndstn/unwise-coadds',
comment='git URL'))
hdr.add_record(dict(name='UNW_DVER', value=1,
comment='unWISE data model version'))
hdr.add_record(dict(name='UNW_DATE', value=datetime.datetime.now().isoformat(),
comment='unWISE run time'))
hdr.add_record(dict(name='UNW_FR0', value=frame0, comment='unWISE frame start'))
hdr.add_record(dict(name='UNW_FRN', value=nframes, comment='unWISE N frames'))
hdr.add_record(dict(name='UNW_FRNR', value=nframes_random, comment='unWISE N random frames'))
hdr.add_record(dict(name='UNW_MEDF', value=medfilt, comment='unWISE median filter sz'))
hdr.add_record(dict(name='UNW_BGMA', value=bgmatch, comment='unWISE background matching?'))
# "Unmasked" versions
ofn = prefix + '-img-u.fits'
fitsio.write(ofn, coim.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
if just_image:
return 0
ofn = prefix + '-invvar-u.fits'
fitsio.write(ofn, coiv.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-std-u.fits'
fitsio.write(ofn, copp.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-n-u.fits'
fitsio.write(ofn, con.astype(np.int32), header=hdr, clobber=True)
debug('Wrote', ofn)
# "Masked" versions
ofn = prefix + '-img-m.fits'
fitsio.write(ofn, coimb.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-invvar-m.fits'
fitsio.write(ofn, coivb.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-std-m.fits'
fitsio.write(ofn, coppb.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-n-m.fits'
fitsio.write(ofn, conb.astype(np.int32), header=hdr, clobber=True)
debug('Wrote', ofn)
if do_cube:
ofn = prefix + '-cube.fits'
fitsio.write(ofn, cube.astype(np.float32), header=hdr, clobber=True)
if minmax:
ofn = prefix + '-min-m.fits'
fitsio.write(ofn, cominb.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-max-m.fits'
fitsio.write(ofn, comaxb.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-min-u.fits'
fitsio.write(ofn, comin.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
ofn = prefix + '-max-u.fits'
fitsio.write(ofn, comax.astype(np.float32), header=hdr, clobber=True)
debug('Wrote', ofn)
frames.included = np.zeros(len(frames), bool)
frames.sky1 = np.zeros(len(frames), np.float32)
frames.sky2 = np.zeros(len(frames), np.float32)
frames.zeropoint = np.zeros(len(frames), np.float32)
frames.npixoverlap = np.zeros(len(frames), np.int32)
frames.npixpatched = np.zeros(len(frames), np.int32)
frames.npixrchi = np.zeros(len(frames), np.int32)
frames.weight = np.zeros(len(frames), np.float32)
Iused = np.flatnonzero(frames.use)
assert(len(Iused) == len(masks))
maskdir = os.path.join(outdir, tag + '-mask')
if not os.path.exists(maskdir):
os.mkdir(maskdir)
for i,mm in enumerate(masks):
if mm is None:
continue
ii = Iused[i]
frames.sky1 [ii] = mm.sky
frames.sky2 [ii] = mm.dsky
frames.zeropoint [ii] = mm.zp
frames.npixoverlap[ii] = mm.ncopix
frames.npixpatched[ii] = mm.npatched
frames.npixrchi [ii] = mm.nrchipix
frames.weight [ii] = mm.w
if not mm.included:
continue
frames.included [ii] = True
# Write outlier masks
if write_masks:
ofn = frames.intfn[ii].replace('-int', '')
ofn = os.path.join(maskdir, 'unwise-mask-' + ti.coadd_id + '-'
+ os.path.basename(ofn) + '.gz')
w,h = frames.imagew[ii],frames.imageh[ii]
fullmask = np.zeros((h,w), mm.omask.dtype)
x0,x1,y0,y1 = frames.imextent[ii,:]
fullmask[y0:y1+1, x0:x1+1] = mm.omask
fitsio.write(ofn, fullmask, clobber=True)
debug('Wrote mask', (i+1), 'of', len(masks), ':', ofn)
frames.delete_column('wcs')
# downcast datatypes, and work around fitsio's issues with
# "bool" columns
for c,t in [('included', np.uint8),
('use', np.uint8),
('moon_masked', np.uint8),
('imagew', np.int16),
('imageh', np.int16),
('coextent', np.int16),
('imextent', np.int16),
]:
frames.set(c, frames.get(c).astype(t))
ofn = prefix + '-frames.fits'
frames.writeto(ofn)
debug('Wrote', ofn)
if write_masks:
md = tag + '-mask'
cmd = ('cd %s && tar czf %s %s && rm -R %s' %
(outdir, md + '.tgz', md, md))
debug('tgz:', cmd)
rtn,out,err = run_command(cmd)
debug(out, err)
if rtn:
print('ERROR: return code', rtn, file=sys.stderr)
print('Command:', cmd, file=sys.stderr)
print(out, file=sys.stderr)
print(err, file=sys.stderr)
ok = False
return rtn
def plot_region(r0,r1,d0,d1, ps, T, WISE, wcsfns, W, H, pixscale, margin=1.05,
allsky=False, grid_ra_range=None, grid_dec_range=None,
grid_spacing=[5, 5, 20, 10], label_tiles=True, draw_outline=True,
tiles=[], ra=0., dec=0.):
from astrometry.blind.plotstuff import Plotstuff
maxcosdec = np.cos(np.deg2rad(min(abs(d0),abs(d1))))
if allsky:
W,H = 1000,500
plot = Plotstuff(outformat='png', size=(W,H))
plot.wcs = anwcs_create_allsky_hammer_aitoff(ra, dec, W, H)
else:
plot = Plotstuff(outformat='png', size=(800,800),
rdw=((r0+r1)/2., (d0+d1)/2., margin*max(d1-d0, (r1-r0)*maxcosdec)))
plot.fontsize = 10
plot.halign = 'C'
plot.valign = 'C'
for i in range(3):
if i in [0,2]:
plot.color = 'verydarkblue'
else:
plot.color = 'black'
plot.plot('fill')
plot.color = 'white'
out = plot.outline
if i == 0:
if T is None:
continue
print('plot 0')
for i,ti in enumerate(T):
cowcs = get_coadd_tile_wcs(ti.ra, ti.dec, W, H, pixscale)
plot.alpha = 0.5
out.wcs = anwcs_new_tan(cowcs)
out.fill = 1
plot.plot('outline')
out.fill = 0
plot.plot('outline')
if label_tiles:
plot.alpha = 1.
rc,dc = cowcs.radec_center()
plot.text_radec(rc, dc, '%i' % i)
elif i == 1:
if WISE is None:
continue
print('plot 1')
# cut
#WISE = WISE[WISE.band == band]
plot.alpha = (3./256.)
out.fill = 1
print('Plotting', len(WISE), 'exposures')
wcsparams = []
fns = []
for wi,wise in enumerate(WISE):
if wi % 10 == 0:
print('.', end=' ')
if wi % 1000 == 0:
print(wi, 'of', len(WISE))
if wi and wi % 10000 == 0:
fn = ps.getnext()
plot.write(fn)
print('Wrote', fn)
wp = np.array(wcsparams)
WW = fits_table()
WW.crpix = wp[:, 0:2]
WW.crval = wp[:, 2:4]
WW.cd = wp[:, 4:8]
WW.imagew = wp[:, 8]
WW.imageh = wp[:, 9]
WW.intfn = np.array(fns)
WW.writeto('sequels-wcs.fits')