-
Notifications
You must be signed in to change notification settings - Fork 3
/
depth-map.py
4245 lines (3552 loc) · 149 KB
/
depth-map.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')
from astrometry.blind.plotstuff import *
from astrometry.util.util import *
from astrometry.util.fits import *
import pylab as plt
from collections import Counter
from scipy.ndimage.filters import minimum_filter, median_filter
from glob import glob
from astrometry.libkd.spherematch import match_radec
from astrometry.util.starutil_numpy import radectolb
# Last date included in the CCDs files
recent_date = '2018-02-11'
target_depths = dict(g=24.0, r=23.4, z=22.5)
compress = '[compress R; qz -1e-4]'
def mosaic_wcs(ra, dec, pixbin=1.):
# This is pretty close to the outline of the four Mosaic chips.
W = H = (4096 * 2 + 100) / pixbin
cd = pixbin * 0.262 / 3600.
tan = Tan(ra, dec, W/2., H/2., cd, 0., 0., cd,
float(W), float(H))
return tan
def draw_grid(wcs, ra_gridlines=None, dec_gridlines=None,
ra_labels=None, dec_labels=None,
ra_gridlines_decs=None, dec_gridlines_ras=None,
ra_labels_dec=None, dec_labels_ra=None):
if ra_gridlines_decs is None:
ra_gridlines_decs = dec_gridlines
if dec_gridlines_ras is None:
ra_gridlines_decs = ra_gridlines
ax = plt.axis()
for d in dec_gridlines:
rr = dec_gridlines_ras
dd = np.zeros_like(rr) + d
ok,xx,yy = wcs.radec2pixelxy(rr, dd)
plt.plot(xx, yy, 'k-', alpha=0.1)
for r in ra_gridlines:
dd = ra_gridlines_decs
rr = np.zeros_like(dd) + r
ok,xx,yy = wcs.radec2pixelxy(rr, dd)
plt.plot(xx, yy, 'k-', alpha=0.1)
if ra_labels_dec is None:
ra_labels_dec = dec_gridlines[0]
if dec_labels_ra is None:
dec_labels_ra = ra_gridlines[0]
ok,xx,yy = wcs.radec2pixelxy(ra_labels, ra_labels_dec)
plt.xticks(xx-0.5, ra_labels)
ok,xx,yy = wcs.radec2pixelxy(dec_labels_ra, dec_labels)
plt.yticks((yy-0.5), dec_labels)
plt.axis(ax)
def get_grid_kwargs(mosaic, ngc):
drawkwargs = {}
if mosaic:
dec_gridlines = list(range(30, 90, 10))
dec_gridlines_ras = np.arange(0, 360, 1)
ra_gridlines = range(0, 360, 30)
ra_gridlines_decs = np.arange(20, 90, 1.)
else:
if ngc:
dec_gridlines = list(range(-10, 31, 10))
dec_gridlines_ras = np.arange(100, 280, 1)
ra_gridlines = range(120, 271, 30)
ra_gridlines_decs = np.arange(-10, 36, 1.)
ra_labels = ra_gridlines
dec_labels = dec_gridlines
else:
dec_gridlines = list(range(-20, 40, 10))
dec_gridlines_ras = np.arange(0, 360, 1)
#dec_gridlines_ras = np.arange(-80, 280, 1)
ra_gridlines = range(0, 360, 30)
ra_gridlines_decs = np.arange(-20, 41, 1.)
ra_labels = ra_gridlines
dec_labels = dec_gridlines
drawkwargs.update(
ra_gridlines_decs=ra_gridlines_decs,
dec_gridlines_ras=dec_gridlines_ras,
)
drawkwargs.update(ra_gridlines=ra_gridlines, dec_gridlines=dec_gridlines,
ra_labels=ra_labels, dec_labels=dec_labels)
return drawkwargs
def from_ccds(mp, mosaic=False, ngc=True,
prefix_pat=None):
from legacypipe.survey import LegacySurveyData
drawkwargs = get_grid_kwargs(mosaic, ngc)
if mosaic:
obsfn = 'obstatus/mosaic-tiles_obstatus.fits'
else:
obsfn = 'obstatus/decam-tiles_obstatus.fits'
survey = LegacySurveyData()
T = survey.get_annotated_ccds()
print('Read', len(T), 'CCDs from annotated table')
T.cut(T.ccd_cuts == 0)
print('Cut to', len(T), 'with ccd_cuts == 0')
if ngc:
T.l, T.b = radectolb(T.ra, T.dec)
T.cut(T.b > 0)
print('Cut to', len(T), 'in NGC')
print('Tile passes from CCDs table:')
print(Counter(T.tilepass).most_common())
if mosaic:
from camera_mosaic import ephem_observer
from obsbot import mjd_to_ephem_date, get_airmass
from jnox import ra2hms, dec2dms
import ephem
print('Recomputing airmasses assuming MOSAIC camera...')
T.airmass = np.zeros(len(T), np.float32)
obs = ephem_observer()
for i,(mjd,ra,dec) in enumerate(zip(T.mjd_obs, T.ra, T.dec)):
obs.date = mjd_to_ephem_date(mjd)
rastr = ra2hms(ra)
decstr = dec2dms(dec)
ephemstr = str('%s,f,%s,%s,20' % ('name', rastr, decstr))
etile = ephem.readdb(ephemstr)
etile.compute(obs)
T.airmass[i] = get_airmass(float(etile.alt))
print('done computing airmasses')
from camera import nominal_cal
bands = ['g','r','z']
print('Computing depth & transparency')
nom = nominal_cal
T.band = np.array([f.strip() for f in T.filter])
# ugrizY
band_index = dict(g=1, r=2, z=4)
iband = np.array([band_index[b] for b in T.band])
T.depth = T.galdepth - T.decam_extinction[np.arange(len(T)), iband]
T.seeing = T.fwhm * T.pixscale_mean
if False:
#kx = 0.10
#zp0 = 26.4
#T.transparency = 10.**(-0.4 * (zp0 - T.ccdzpt - kx*(T.airmass-1.)))
kx = dict([(b, nom.fiducial_exptime(b).k_co) for b in bands])
zp0 = dict([(b, nom.zeropoint(b)) for b in bands])
T.transparency = np.array([10.**(-0.4 * (zp0[b] - zpt - kx[b]*(airmass-1.)))
for b,zpt,airmass in zip(T.band, T.ccdzpt, T.airmass)])
# plt.clf()
# plt.scatter(T.ra, T.dec, c=T.transparency, s=3)
# plt.colorbar()
# plt.savefig('transp.png')
#
# for band in bands:
# for passnum in [1,2,3]:
# plt.clf()
# I = np.flatnonzero((T.tilepass == passnum) * (T.band == band))
# plt.scatter(T.ra[I], T.dec[I], c=T.transparency[I], s=3)
# plt.colorbar()
# plt.savefig('transp-%s-p%i.png' % (band, passnum))
#
# plt.clf()
# plt.scatter(T.ra[I], T.dec[I], c=T.airmass[I], s=3)
# plt.colorbar()
# plt.savefig('airmass-%s-p%i.png' % (band, passnum))
print('Producing depth maps...')
if prefix_pat is None:
if ngc:
prefix_pat = 'depth-ngc-%s-p%i'
else:
prefix_pat = 'maps/depth-%s-p%i'
args = []
for band in bands:
target = target_depths[band]
for passnum in [0,1,2,3]:
prefix = prefix_pat % (band, passnum)
fn = '%s.fits.fz' % prefix
if os.path.exists(fn):
print('Depth map already exists:', fn)
else:
I = np.flatnonzero((T.tilepass == passnum) *
(T.depth > 10) *
(T.band == band))
print(len(I), 'CCDs for', band, 'pass', passnum)
args.append((fn, survey, T[I], mosaic, ngc, target))
print('mp.map depths for', len(args), 'maps...')
mp.map(write_depth_map, args)
print('Created maps. Making plots...')
assert((not mosaic) and (not ngc))
#wcsfn = 'cea.wcs'
wcsfn = 'cea-flip.wcs'
wcs = anwcs(wcsfn)
for band in bands:
totaldepth = 0.
seeings = []
transps = []
target = target_depths[band]
for passnum in [1,2,3, 0, 9]:
prefix = prefix_pat % (band, passnum)
fn = '%s.fits.fz' % prefix
if passnum != 9:
tt = '%s band, Pass %i' % (band, passnum)
print('Reading', fn)
depthmap = fitsio.read(fn)
iv = 1./(10.**((depthmap - 22.5) / -2.5))**2
totaldepth = totaldepth + iv
d = -2.5 * (np.log10(1./np.sqrt(totaldepth)) - 9.)
plt.clf()
plt.subplot(1,2,1)
plt.hist(depthmap.ravel(), 50, log=True)
plt.hist(d.ravel(), 50, log=True, range=(0,26), histtype='step', color='r')
plt.subplot(1,2,2)
plt.hist(iv.ravel(), 50, log=True, histtype='step', color='r')
plt.hist(totaldepth.ravel(), 50, log=True, histtype='step', color='k')
plt.savefig('depth-hist-%s-%i.png' % (band, passnum))
else:
depthmap = -2.5 * (np.log10(1./np.sqrt(totaldepth)) - 9.)
tt = '%s band, All Passes' % band
if os.path.exists(fn):
print('Already exists:', fn)
else:
hdr = fitsio.read_header(wcsfn)
fitsio.write(fn + compress, depthmap, clobber=True, header=hdr)
print('Wrote', fn)
fn = prefix + '-1.png'
depth_map_plot(depthmap, wcs, fn, obsfn, target, drawkwargs,
tt='Depth: %s' % tt, redblue=False)
print('Wrote', fn)
fn = prefix + '-2.png'
depth_map_plot(depthmap, wcs, fn, obsfn, target, drawkwargs,
tt='Depth: %s' % tt, redblue=True)
print('Wrote', fn)
# if passnum != 9:
# seeing,transp,wcs = best_seeing_map_for_ccds(survey, T[I])
# seeings.append(seeing)
# transps.append(transp)
# else:
# seeing = seeings[0]
# transp = transps[0]
# for s,t in zip(seeings, transps):
# # Handle zeros...
# sI = (seeing == 0)
# seeing[sI] = s[sI]
# sI = (s != 0)
# seeing[sI] = np.minimum(seeing[sI], s[sI])
# transp = np.maximum(transp, t)
#
# lo,hi = 0.5, 2.0
# if passnum == 9:
# plt.clf()
# plt.imshow(median_filter(seeing, size=3),
# interpolation='nearest', origin='lower',
# vmin=lo, vmax=hi, cmap=cm)
# plt.xticks([]); plt.yticks([])
# plt.title('Best seeing (unfiltered): %s' % tt)
# plt.colorbar()
# plt.savefig('depth-%s-p%i-17.png' % (band, passnum))
#
# plt.clf()
# plt.imshow(median_filter(seeing, size=3),
# interpolation='nearest', origin='lower',
# vmin=lo, vmax=hi, cmap=cm)
# plt.xticks([]); plt.yticks([])
# plt.title('Best seeing: %s' % tt)
# plt.colorbar()
# plt.savefig('depth-%s-p%i-15.png' % (band, passnum))
#
# plt.clf()
# lo,hi = 0.5, 1.1
# plt.imshow(transp, interpolation='nearest', origin='lower',
# vmin=lo, vmax=hi, cmap=cm)
# plt.xticks([]); plt.yticks([])
# plt.title('Best transparency: %s' % tt)
# plt.colorbar()
# plt.savefig('depth-%s-p%i-16.png' % (band, passnum))
#fitsio.write('seeing-%s-p%i.fits' % (band, passnum), seeing, clobber=True)
#fitsio.write('transp-%s-p%i.fits' % (band, passnum), transp, clobber=True)
# plt.clf()
# lo,hi = target-1, target+1
# hh = depthmap.ravel()
# hh = hh[hh != 0]
# plt.hist(np.clip(hh, lo, hi), 50, range=(lo,hi))
# plt.xlim(lo, hi)
# plt.title('Depths: %s' % tt)
# plt.yticks([])
# plt.ylabel('sky area')
# plt.savefig('depth-%s-p%i-10.png' % (band, passnum))
#
# if len(I):
# plt.clf()
# plt.hist(np.clip(T.depth[I], lo+0.001, hi-0.001), 50,
# range=(lo,hi))
# plt.xlim(lo, hi)
# plt.title('Depths: %s' % tt)
# plt.ylabel('Number of CCDs')
# plt.savefig('depth-%s-p%i-11.png' % (band, passnum))
def depth_map_plot(depthmap, wcs, outfn, tilefn, target, drawkwargs,
tt=None, redblue=False):
if redblue:
cm = matplotlib.cm.RdBu
else:
cm = matplotlib.cm.viridis
cm = cmap_discretize(cm, 10)
cm.set_bad('0.9')
tiles = fits_table(tilefn)
tiles.cut(tiles.get('pass') == 1)
tiles.cut(tiles.in_desi == 1)
ok,tiles.x,tiles.y = wcs.radec2pixelxy(tiles.ra, tiles.dec)
tiles.x -= 1
tiles.y -= 1
tiles.cut(ok)
depthmap[depthmap < 1] = np.nan
depthmap[np.logical_not(np.isfinite(depthmap))] = np.nan
H,W = wcs.shape
imkwa = dict(interpolation='nearest', origin='lower',
extent=[0,W,0,H])
lo,hi = target-1, target+1
plt.figure(1)
plt.clf()
plt.plot(tiles.x, tiles.y, 'k.', alpha=0.1)
plt.imshow(depthmap[::4,::4],
vmin=lo, vmax=hi, cmap=cm, **imkwa)
plt.xticks([]); plt.yticks([])
draw_grid(wcs, **drawkwargs)
cb = plt.colorbar(orientation='horizontal')
cb.set_label('Depth')
if tt is not None:
plt.title(tt)
plt.savefig(outfn)
def main():
W,H = 1300,800
plot = Plotstuff(size=(W,H), outformat='png')
zoom = 2.5
plot.wcs = anwcs_create_hammer_aitoff(195., 60., zoom, W, H, True)
#plot.wcs = anwcs_create_mollweide(195., 60., zoom, W, H, True)
#print('WCS:', anwcs_print_stdout(plot.wcs))
# generated by update-obstatus.py
T = fits_table('mosaic-obstatus-depth.fits')
plt.figure(2)
plt.figure(1, figsize=(13,8))
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.95)
for passnum in [1,2,3, 0]:
if passnum == 0:
I = np.flatnonzero((T.get('pass') >= 1) *
(T.get('pass') <= 3) *
(T.z_done == 1) *
(T.z_depth > 1) * (T.z_depth < 30))
tt = 'MzLS z-band depth (AB, 5-sigma galaxy profile)' #'All Passes'
else:
I = np.flatnonzero((T.get('pass') == passnum) *
(T.z_done == 1) *
(T.z_depth > 1) * (T.z_depth < 30))
tt = 'Pass %i' % passnum
plot.color = 'black'
plot.plot('fill')
plot.color = 'white'
plot.outline.fill = True
plot.outline.stepsize = 2000
targetdepth = 22.5
#maxfrac = 0.4
# This sets the maximum (saturation) value of the image map;
# it's in invvar fluxes, so 0.16 means 1 mag deeper than "targetdepth"
maxfrac = 0.16
targetsig = 10.**((targetdepth - 22.5) / -2.5)
targetiv = 1./targetsig**2
print(len(I), 'tiles for pass', passnum)
plot.op = CAIRO_OPERATOR_ADD
for j,i in enumerate(I):
if j % 1000 == 0:
print('Tile', j)
depth = T.z_depth[i]
detsig = 10.**((depth - 22.5) / -2.5)
depthfrac = 1./detsig**2 / targetiv
#print('depth', depth, 'frac', depthfrac)
mwcs = mosaic_wcs(T.ra[i], T.dec[i])
plot.outline.wcs = anwcs_new_tan(mwcs)
plot.alpha = np.clip(maxfrac * depthfrac, 0., 1.)
plot.apply_settings()
plot.plot('outline')
img = plot.get_image_as_numpy(flip=True)
print('Image', img.dtype, img.shape)
img = img[:,:,0]
# It's a uint8
img = img * 1./255.
print('Image', img.dtype, img.shape)
#
img /= maxfrac
# plt.clf()
# plt.hist(img.ravel(), 120, range=(0.1,2))
# plt.savefig('depth-p%i-4.png' % passnum)
# Now it's in factor of detiv of target depth.
# back to sig -> depth
img = -2.5 * (np.log10(1./np.sqrt(img * targetiv)) - 9.)
img[np.logical_not(np.isfinite(img))] = 0.
cm = matplotlib.cm.viridis
#cm = matplotlib.cm.jet
cm = cmap_discretize(cm, 10)
plt.figure(2)
plt.clf()
lo,hi = 21.5,23.5
#lo,hi = 22,23
hh = img.ravel()
hh = hh[hh != 0]
plt.hist(np.clip(hh, lo, hi), 50, range=(lo,hi))
plt.xlim(lo, hi)
plt.title('Depths: %s' % tt)
plt.yticks([])
plt.ylabel('Sky Area')
plt.savefig('depth-p%i-4.png' % passnum)
plt.clf()
plt.hist(np.clip(T.z_depth[I], lo, hi), 50, range=(lo,hi))
plt.xlim(lo, hi)
plt.title('Depths: %s' % tt)
plt.savefig('depth-p%i-5.png' % passnum)
plt.figure(1)
plt.clf()
img[img == 0] = np.nan
plt.imshow(img, interpolation='nearest', origin='lower',
vmin=lo, vmax=hi, cmap=cm)
plt.xticks([]); plt.yticks([])
ax = plt.axis()
H,W = img.shape
for d in range(30, 90, 10):
rr = np.arange(0, 360, 1)
dd = np.zeros_like(rr) + d
ok,xx,yy = plot.wcs.radec2pixelxy(rr, dd)
plt.plot(xx, H-yy, 'k-', alpha=0.1)
ok,xx,yy = plot.wcs.radec2pixelxy(85, d)
plt.text(xx, H-yy, '%+i' % d,
bbox=dict(edgecolor='none', facecolor='white'),
ha='center', va='center')
for r in range(0, 360, 30):
dd = np.arange(20, 90, 1.)
rr = np.zeros_like(dd) + r
ok,xx,yy = plot.wcs.radec2pixelxy(rr, dd)
plt.plot(xx, H-yy, 'k-', alpha=0.1)
ok,xx,yy = plot.wcs.radec2pixelxy(r, 28)
plt.text(xx, H-yy, '%i' % r,
bbox=dict(edgecolor='none', facecolor='white'),
ha='center', va='center')
plt.axis(ax)
plt.colorbar()
plt.title(tt)
plt.savefig('depth-p%i-3.png' % passnum)
goal = 22.5
drange = 1.
plt.clf()
img[img == 0] = np.nan
plt.imshow(img, interpolation='nearest', origin='lower',
vmin=goal-drange, vmax=goal+drange, cmap='RdBu')
plt.xticks([]); plt.yticks([])
ax = plt.axis()
H,W = img.shape
for d in range(30, 90, 10):
rr = np.arange(0, 360, 1)
dd = np.zeros_like(rr) + d
ok,xx,yy = plot.wcs.radec2pixelxy(rr, dd)
plt.plot(xx, H-yy, 'k-', alpha=0.1)
for r in range(0, 360, 30):
dd = np.arange(20, 90, 1.)
rr = np.zeros_like(dd) + r
ok,xx,yy = plot.wcs.radec2pixelxy(rr, dd)
plt.plot(xx, H-yy, 'k-', alpha=0.1)
plt.axis(ax)
cb = plt.colorbar()
cb.set_label('Depth')
plt.title(tt)
plt.savefig('depth-p%i-2.png' % passnum)
# #if passnum == 3:
# if True:
# R = fits_table('retirable-p3.fits')
# tileids = set(R.tileid)
# I = np.array([i for i,tid in enumerate(T.tileid) if tid in tileids])
# imH,imW = img.shape
# for i in I:
# mwcs = mosaic_wcs(T.ra[i], T.dec[i])
# H,W = mwcs.shape
# rr,dd = mwcs.pixelxy2radec(np.array([1,1,W,W,1]),
# np.array([1,H,H,1,1]))
# ok,xx,yy = plot.wcs.radec2pixelxy(rr, dd)
# plt.plot(xx, imH - yy, 'r-')
#
# plt.axis(ax)
# plt.title('Retirable: %s' % tt)
# plt.savefig('depth-p%i-6.png' % passnum)
plot.op = CAIRO_OPERATOR_OVER
# plot.write('depth-p%i-1.png' % passnum)
#
# plot.color = 'gray'
# plot.plot_grid(30, 10, 30, 10)
# plot.write('depth-p%i-2.png' % passnum)
#
# rgb = cm(np.clip((img - lo) / (hi - lo), 0., 1.), bytes=True)
# #rgb = (rgb * 255.0).astype(np.uint8)
# I,J = np.nonzero(np.logical_not(np.isfinite(img)))
# print(len(I), 'inf pixels')
# #for i in range(3):
# # rgb[I,J,i] = 0
# rgb[I,J,:3] = 255
# rgb = np.flipud(rgb)
#
# print('RGB:', rgb.dtype, rgb.shape, rgb.min(), rgb.max())
# plot.set_image_from_numpy(rgb)
# plot.color = 'black'
# plot.bg_rgba = (0,0,0,0)
# plot.plot_grid(30, 10, 30, 10)
# plot.write('depth-p%i-6.png' % passnum)
# From http://scipy-cookbook.readthedocs.io/items/Matplotlib_ColormapTransformations.html
def cmap_discretize(cmap, N):
from matplotlib.cm import get_cmap
from numpy import concatenate, linspace
"""Return a discrete colormap from the continuous colormap cmap.
cmap: colormap instance, eg. cm.jet.
N: number of colors.
Example
x = resize(arange(100), (5,100))
djet = cmap_discretize(cm.jet, 5)
imshow(x, cmap=djet)
"""
if type(cmap) == str:
cmap = get_cmap(cmap)
colors_i = concatenate((linspace(0, 1., N), (0.,0.,0.,0.)))
colors_rgba = cmap(colors_i)
indices = linspace(0, 1., N+1)
cdict = {}
for ki,key in enumerate(('red','green','blue')):
cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1) ]
# Return colormap object.
return matplotlib.colors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
def tiles_todo():
'''
Makes maps like depth-p?.fits, but for tiles that are still marked to-do
in the obstatus file. We give them a nominal depth (22.2 is ~ the median)
'''
depth = 22.2
plt.figure(1, figsize=(13,8))
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.95)
tiles = fits_table('obstatus/mosaic-tiles_obstatus.fits')
tiles.cut(tiles.get('pass') <= 3)
tiles.cut(tiles.in_desi == 1)
tiles.cut(tiles.dec > 30)
print(len(tiles), 'above Dec=30 in passes', np.unique(tiles.get('pass')))
#print('Z_DATEs:', np.unique(tiles.z_date))
#for d in np.unique(tiles.z_date):
# print('date', d, 'after 2017-12-08?', d > '2017-12-08')
tiles.recent = np.array([d > recent_date for d in tiles.z_date])
print('To-do:', np.sum(tiles.z_done == 0))
print('Done recently:', np.sum(tiles.recent))
tiles.cut(np.logical_or(tiles.z_done == 0, tiles.recent))
print(len(tiles), 'not done (or done recently)')
print('Per pass:', Counter(tiles.get('pass')))
## Copied from from_ccds
W,H = 4800,3200
plot = Plotstuff(size=(W,H), outformat='png')
zoom = 2.7
plot.wcs = anwcs_create_hammer_aitoff(195., 65., zoom, W, H, True)
imgs = []
for passnum in [1,2,3, 9]:
plot.color = 'black'
plot.plot('fill')
plot.color = 'white'
plot.outline.fill = True
plot.outline.stepsize = 2000
plot.op = CAIRO_OPERATOR_ADD
targetdepth = 22.5
# This gives a 1-mag margin on the target depth
maxfrac = 0.16
targetsig = 10.**((targetdepth - 22.5) / -2.5)
targetiv = 1./targetsig**2
I = np.flatnonzero(tiles.get('pass') == passnum)
for j,i in enumerate(I):
detsig = 10.**((depth - 22.5) / -2.5)
depthfrac = 1./detsig**2 / targetiv
mwcs = mosaic_wcs(tiles.ra[i], tiles.dec[i])
plot.outline.wcs = anwcs_new_tan(mwcs)
plot.alpha = np.clip(maxfrac * depthfrac, 0., 1.)
plot.apply_settings()
plot.plot('outline')
img = plot.get_image_as_numpy(flip=True)
img = img[:,:,0]
# It's a uint8; scale and convert to float
img = img * 1./255.
img /= maxfrac
# Now it's in factor of detiv of target depth.
imgs.append(img)
if passnum == 9:
img = imgs[0]
for im in imgs[1:]:
img += im
# back to sig -> depth
img = -2.5 * (np.log10(1./np.sqrt(img * targetiv)) - 9.)
img[np.logical_not(np.isfinite(img))] = 0.
fitsio.write('depth-todo-p%i.fits' % passnum, img, clobber=True)
lo,hi = 21.5,23.5
cm = matplotlib.cm.viridis
cm = cmap_discretize(cm, 10)
plt.clf()
img[img == 0] = np.nan
#plt.plot(tiles.x, H-tiles.y, 'k.', alpha=0.1)
plt.imshow(img, interpolation='nearest', origin='lower',
vmin=lo, vmax=hi, cmap=cm)
plt.xticks([]); plt.yticks([])
ax = plt.axis()
H,W = img.shape
for d in range(30, 90, 10):
rr = np.arange(0, 360, 1)
dd = np.zeros_like(rr) + d
ok,xx,yy = plot.wcs.radec2pixelxy(rr, dd)
plt.plot(xx, H-yy, 'k-', alpha=0.1)
for r in range(0, 360, 30):
dd = np.arange(20, 90, 1.)
rr = np.zeros_like(dd) + r
ok,xx,yy = plot.wcs.radec2pixelxy(rr, dd)
plt.plot(xx, H-yy, 'k-', alpha=0.1)
plt.axis(ax)
plt.colorbar()
plt.title('To-do: pass %i' % passnum)
plt.savefig('depth-p%i-14.png' % passnum)
plot.op = CAIRO_OPERATOR_OVER
def needed_tiles():
from astrometry.util.miscutils import point_in_poly
targetdepth = 22.5
fn = 'depth-p9.fits'
#wcs = anwcs(fn)
wcs = anwcs('plot.wcs')
depth = fitsio.read(fn)
print('Depth:', depth.shape, depth.dtype)
ima = dict(interpolation='nearest', origin='lower',
vmin=22.0, vmax=23.0, cmap='RdBu')
plt.clf()
plt.imshow(depth, **ima)
plt.savefig('depth-0.png')
todo = fitsio.read('depth-todo-p9.fits')
iv1 = 1./(10.**((depth - 22.5) / -2.5))**2
iv2 = 1./(10.**((todo - 22.5) / -2.5))**2
depth = -2.5 * (np.log10(1./np.sqrt(iv1 + iv2)) - 9.)
print('inf:', np.sum(np.logical_not(np.isfinite(depth))))
plt.clf()
plt.imshow(depth, **ima)
plt.savefig('depth-1.png')
tiles = fits_table('obstatus/mosaic-tiles_obstatus.fits')
tiles.cut(tiles.get('pass') == 1)
tiles.cut(tiles.in_desi == 1)
### Drop ones that are already on the to-do list.
tiles.cut(tiles.z_done == 1)
tiles.cut(np.lexsort((tiles.ra, tiles.dec)))
#ok,tiles.x,tiles.y = plot.wcs.radec2pixelxy(tiles.ra, tiles.dec)
#tiles.x -= 1
#tiles.y -= 1
#tiles.cut(ok)
print(len(tiles), 'tiles in pass 1')
tiles.cut(tiles.dec > 30)
print(len(tiles), 'with Dec > 30')
print('Min Dec:', min(tiles.dec))
#tiles.cut(tiles.dec < 70)
#print(len(tiles), 'with Dec < 70')
# from mosaic_wcs
tilesize = (4096 * 2 + 100) * 0.262 / 3600.
dlo = tiles.dec - tilesize/2.
dhi = tiles.dec + tilesize/2.
cosdec = np.cos(np.deg2rad(tiles.dec))
rlo = tiles.ra - tilesize/2./cosdec
rhi = tiles.ra + tilesize/2./cosdec
ok1,tiles.x1,tiles.y1 = wcs.radec2pixelxy(rlo,dlo)
ok2,tiles.x2,tiles.y2 = wcs.radec2pixelxy(rlo,dhi)
ok3,tiles.x3,tiles.y3 = wcs.radec2pixelxy(rhi,dhi)
ok4,tiles.x4,tiles.y4 = wcs.radec2pixelxy(rhi,dlo)
ishallow = []
shallowpcts = []
t1,t2,t3 = targetdepth, targetdepth - 0.3, targetdepth - 0.6
for itile,t in enumerate(tiles):
# -1: FITS to numpy coords
x0 = int(np.floor(min(t.x1, t.x2, t.x3, t.x4))) - 1
y0 = int(np.floor(min(t.y1, t.y2, t.y3, t.y4))) - 1
x1 = int(np.ceil( max(t.x1, t.x2, t.x3, t.x4))) - 1
y1 = int(np.ceil( max(t.y1, t.y2, t.y3, t.y4))) - 1
print('tile', t.ra, t.dec)
#print('x0,x1, y0,y1', x0,x1,y0,y1)
print(' x0,y0', x0,y0)
print(' w,h', 1+x1-x0, 1+y1-y0)
tiledepth = depth[y0:y1+1, x0:x1+1].copy()
print(' tiledepth', tiledepth.min(), tiledepth.max())
if tiledepth.min() > targetdepth:
print(' Rectangular region is already to depth')
continue
# polygon
xx,yy = np.meshgrid(np.arange(x0, x1+1), np.arange(y0, y1+1))
poly = np.array([[t.x1,t.y1],[t.x2,t.y2],[t.x3,t.y3],[t.x4,t.y4]])
inpoly = point_in_poly(xx, yy, poly-1)
print(' ', np.sum(inpoly), 'pixels')
tmin = tiledepth[inpoly].min()
print(' Minimum depth:', tmin)
if tmin > targetdepth:
print(' Tile shaped region is already to depth')
continue
[d1,d2,d3] = np.percentile(tiledepth[inpoly], [10, 5, 2])
print(' Depth at completeness 90/95/98:', d1, d2, d3)
print(' Hitting target?',
'yes' if d1 > t1 else 'no',
'yes' if d2 > t2 else 'no',
'yes' if d3 > t3 else 'no')
if (d1 > t1) and (d2 > t2) and (d3 > t3):
print(' Reached target!')
continue
ishallow.append(itile)
shallowpcts.append((d1,d2,d3))
# tiledepth[inpoly == False] = np.nan
# plt.clf()
# #plt.imshow(depth, interpolation='nearest', origin='lower')
# plt.imshow(tiledepth, interpolation='nearest', origin='lower')#, cmap='RdBu')
# #plt.axis([x0,x1+1,y0,y1+1])
# plt.savefig('depth-tile%i.png' % itile)
ishallow = np.array(ishallow)
shallow = tiles[ishallow]
shallow.depth_90 = np.array([d[0] for d in shallowpcts])
shallow.depth_95 = np.array([d[1] for d in shallowpcts])
shallow.depth_98 = np.array([d[2] for d in shallowpcts])
for c in 'x1 y1 x2 y2 x3 y3 x4 y4'.split():
shallow.delete_column(c)
shallow.writeto('shallow.fits')
print(len(ishallow), 'tiles deemed shallow')
#print('shallow z_done:', Counter(shallow.z_done))
plt.clf()
plt.imshow(depth, **ima)
sh = tiles[ishallow]
plt.plot(np.vstack((sh.x1, sh.x2, sh.x3, sh.x4, sh.x1)),
np.vstack((sh.y1, sh.y2, sh.y3, sh.y4, sh.y1)),
'r-')
plt.savefig('depth-2.png')
plt.clf()
for d1,d2,d3 in shallowpcts:
plt.plot([d1,d2,d3], 'b-', alpha=0.02)
for i,target in enumerate([t1,t2,t3]):
plt.plot([i-0.25,i+0.25], [target,target], 'r-')
plt.xticks([0,1,2], ['90%', '95%', '98%'])
plt.xlabel('Coverage fraction')
plt.ylabel('Depth of shallow tiles')
plt.ylim(20, 23)
plt.savefig('depth-3.png')
plt.clf()
plt.imshow(depth, **ima)
sh = tiles[ishallow]
sh.xm = (sh.x1 + sh.x2 + sh.x3 + sh.x4) / 4
sh.ym = (sh.y1 + sh.y2 + sh.y3 + sh.y4) / 4
plt.plot(np.vstack((sh.x1, sh.x2, sh.x3, sh.x4, sh.x1)),
np.vstack((sh.y1, sh.y2, sh.y3, sh.y4, sh.y1)),
'r-')
plt.colorbar()
for j,i in enumerate(np.random.permutation(len(sh))[:20]):
plt.axis([sh.xm[i] - 50, sh.xm[i] + 50,
sh.ym[i] - 50, sh.ym[i] + 50])
plt.savefig('depth-3-%02i.png' % j)
def write_depth_map(X):
fn = X[0]
args = X[1:]
depthmap,wcs = depth_map_for_ccds(*args)
print('Writing', fn)
fitsio.write(fn + compress, depthmap, clobber=True)
print('Wrote', fn)
def depth_map_for_ccds(survey, ccds, mosaic, ngc, targetdepth):
if mosaic:
W,H = 4800,3200
plot = Plotstuff(size=(W,H), outformat='png')
zoom = 2.7
args = (195., 65., zoom, W, H, True)
wcs = anwcs_create_hammer_aitoff(*args)
plot.wcs = anwcs_create_hammer_aitoff(*args)
else:
if ngc:
W,H = 8000,2000
plot = Plotstuff(size=(W,H), outformat='png')
# refra,refdec = 190., 12.
# cd = 180. / W
# wcs = anwcs_new_tan(Tan(refra, refdec, W/2.+0.5, H/2.+0.5,
# zoom = 2.5
# args = (190., 12., zoom, W, H, True)
# wcs = anwcs_create_hammer_aitoff(*args)
# plot.wcs = anwcs_create_hammer_aitoff(*args)
pixscale = 180. / W
ra,dec = 190., 12.
refx = W/2. + 0.5
refy = (H/2. + 0.5 - dec / -pixscale)
args = (ra, 0., refx, refy, pixscale, W, H, True)
wcs = anwcs_create_cea_wcs(*args)
plot.wcs = anwcs_create_cea_wcs(*args)
anwcs_write(wcs, 'ngc-cea.wcs')
else:
# W,H = 15000,2500
# plot = Plotstuff(size=(W,H), outformat='png')
# zoom = 1.2
# args = (100., 5., zoom, W, H, True)
# wcs = anwcs_create_hammer_aitoff(*args)
# plot.wcs = anwcs_create_hammer_aitoff(*args)
# W,H = 8000,2000
# plot = Plotstuff(size=(W,H), outformat='png')
# refra,refdec = 190., 12.
# cd = 180. / W
# wcs = anwcs_new_tan(Tan(refra, refdec, W/2.+0.5, H/2.+0.5,
# zoom = 2.5
# args = (190., 12., zoom, W, H, True)
# wcs = anwcs_create_hammer_aitoff(*args)
# plot.wcs = anwcs_create_hammer_aitoff(*args)
#W,H = 16000,2500
W,H = 32000,5000
#W,H = 64000,10000
plot = Plotstuff(size=(W,H), outformat='png')
pixscale = 340. / W
ra,dec = 110., 8.
refx = W/2. + 0.5
refy = (H/2. + 0.5 - dec / -pixscale)
args = (ra, 0., refx, refy, pixscale, W, H, True)
wcs = anwcs_create_cea_wcs(*args)
plot.wcs = anwcs_create_cea_wcs(*args)
wcsfn = 'cea.wcs'
if os.path.exists(wcsfn):
print('WCS file exists:', wcsfn)
else:
anwcs_write(wcs, wcsfn)
# ?
refy2 = (H/2. + 0.5 - dec / pixscale)
args2 = (ra, 0., refx, refy2, pixscale, W, H, False)
wcs2 = anwcs_create_cea_wcs(*args2)
wcsfn = 'cea-flip.wcs'
if os.path.exists(wcsfn):
print('WCS file exists:', wcsfn)
else:
anwcs_write(wcs2, wcsfn)
plot.color = 'black'
plot.plot('fill')
plot.color = 'white'
plot.outline.fill = True
plot.outline.stepsize = 2000
plot.op = CAIRO_OPERATOR_ADD
# This gives a 1-mag margin on the target depth
maxfrac = 0.16
targetsig = 10.**((targetdepth - 22.5) / -2.5)
targetiv = 1./targetsig**2
for j,ccd in enumerate(ccds):
if j and j % 1000 == 0:
print('CCD', j, '/', len(ccds))
depth = ccd.depth
mwcs = survey.get_approx_wcs(ccd)
detsig = 10.**((depth - 22.5) / -2.5)
depthfrac = 1./detsig**2 / targetiv
plot.outline.wcs = anwcs_new_tan(mwcs)
plot.alpha = np.clip(maxfrac * depthfrac, 0., 1.)
plot.apply_settings()
plot.plot('outline')
# print('Creating numpy image...')
# img1 = plot.get_image_as_numpy(flip=True)
# img1 = img1[:,:,0]
# print('img1 range', img1.min(), img1.max())
print('Getting numpy view...')
img = plot.get_image_as_numpy_view()
print('Img:', img.shape, 'dtype', img.dtype)
print('Img range:', img.min(), img.max())
print('Converting to depth...')
fimg = np.empty((H,W), np.float32)
with np.errstate(invalid='ignore', divide='ignore'):
fimg[:,:] = -2.5 * (np.log10(1./np.sqrt(
img[::-1,:,0] * (1./255. * targetiv/maxfrac))) - 9.)
# note the "::-1" vertical flip here