-
Notifications
You must be signed in to change notification settings - Fork 3
/
measure_raw.py
1762 lines (1495 loc) · 60.8 KB
/
measure_raw.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 os
import tempfile
import json
if __name__ == '__main__':
import matplotlib
matplotlib.use('Agg')
import numpy as np
import fitsio
from legacypipe.ps1cat import ps1cat, ps1_to_decam, ps1_to_90prime
from legacypipe.gaiacat import GaiaCatalog
# Color terms -- no MOSAIC specific ones yet:
ps1_to_mosaic = ps1_to_decam
class RawMeasurer(object):
def __init__(self, fn, ext, nom, aprad=3.5, skyrad_inner=7.,
skyrad_outer=10.,
minstar=5, pixscale=0.262, maxshift=240.):
'''
aprad: float
Aperture photometry radius in arcsec
skyrad_{inner,outer}: floats
Sky annulus radius in arcsec
nom: nominal calibration, eg NominalCalibration object
'''
self.fn = fn
self.ext = ext
self.nom = nom
self.aprad = aprad
self.skyrad = (skyrad_inner, skyrad_outer)
self.minstar = minstar
self.pixscale = pixscale
self.maxshift = maxshift
self.edge_trim = 100
self.nominal_fwhm = 5.0
# Detection threshold
self.det_thresh = 20
self.debug = True
self.camera = 'camera'
def remove_sky_gradients(self, img):
from scipy.ndimage.filters import median_filter
# Ugly removal of sky gradients by subtracting median in first x and then y
H,W = img.shape
meds = np.array([np.median(img[:,i]) for i in range(W)])
meds = median_filter(meds, size=5)
img -= meds[np.newaxis,:]
meds = np.array([np.median(img[i,:]) for i in range(H)])
meds = median_filter(meds, size=5)
img -= meds[:,np.newaxis]
def trim_edges(self, img):
# Trim off some extra pixels -- image edges are often bright...
# central part of the image
trim = self.edge_trim
if trim == 0:
return img,trim,trim
cimg = img[trim:-trim, trim:-trim]
return cimg, trim, trim
def read_raw(self, F, ext):
img = F[ext].read()
hdr = F[ext].read_header()
return img,hdr
def get_band(self, primhdr):
band = primhdr['FILTER']
band = band.split()[0]
# HACK PTF: R -> r
#band = band.lower()
return band
def match_ps1_stars(self, px, py, fullx, fully, radius, stars):
from astrometry.libkd.spherematch import match_xy
#print('Matching', len(px), 'PS1 and', len(fullx), 'detected stars with radius', radius)
I,J,d = match_xy(px, py, fullx, fully, radius)
#print(len(I), 'matches')
dx = px[I] - fullx[J]
dy = py[I] - fully[J]
return I,J,dx,dy
def detection_map(self, img, sig1, psfsig, ps):
from scipy.ndimage.filters import gaussian_filter
psfnorm = 1./(2. * np.sqrt(np.pi) * psfsig)
detsn = gaussian_filter(img / sig1, psfsig) / psfnorm
# zero out the edges -- larger margin here?
detsn[0 ,:] = 0
detsn[:, 0] = 0
detsn[-1,:] = 0
detsn[:,-1] = 0
return detsn
def detect_sources(self, detsn, thresh, ps):
from scipy.ndimage.measurements import label, find_objects
# HACK -- Just keep the brightest pixel in each blob!
peaks = (detsn > thresh)
blobs,nblobs = label(peaks)
slices = find_objects(blobs)
return slices
def zeropoint_for_exposure(self, band, ext=None, exptime=None, primhdr=None):
try:
zp0 = self.nom.zeropoint(band, ext=self.ext)
except KeyError:
print('Unknown band "%s"; no zeropoint available.' % band)
zp0 = None
return zp0
def get_reference_stars(self, wcs, band):
# Read in the PS1 catalog, and keep those within 0.25 deg of CCD center
# and those with main sequence colors
pscat = ps1cat(ccdwcs=wcs)
try:
stars = pscat.get_stars()
except:
print('Failed to find PS1 stars -- maybe this image is outside the PS1 footprint.')
import traceback
traceback.print_exc()
from astrometry.util.starutil_numpy import radectolb
rc,dc = wcs.radec_center()
print('RA,Dec center:', rc, dc)
lc,bc = radectolb(rc, dc)
print('Galactic l,b:', lc[0], bc[0])
return None
print('Got PS1 stars:', len(stars))
if len(stars) == 0:
print('Did not find any PS1 stars (maybe outside footprint?)')
return None
# we add the color term later
try:
ps1band = self.get_ps1_band(band)
stars.mag = stars.median[:, ps1band]
except KeyError:
print('Unknown band for PS1 mags:', band)
ps1band = None
stars.mag = np.zeros(len(stars), np.float32)
return stars
def cut_reference_catalog(self, stars):
# Now cut to just *stars* with good colors
stars.gicolor = stars.median[:,0] - stars.median[:,2]
keep = (stars.gicolor > 0.4) * (stars.gicolor < 2.7)
#keep = (stars.gicolor > -0.5) * (stars.gicolor < 2.7)
return keep
def get_color_term(self, stars, band):
#print('PS1 stars mags:', stars.median)
try:
colorterm = self.colorterm_ps1_to_observed(stars.median, band)
except KeyError:
print('Color term not found for band "%s"; assuming zero.' % band)
colorterm = 0.
return colorterm
def get_exptime(self, primhdr):
return primhdr['EXPTIME']
def run(self, ps=None, primext=0, focus=False, momentsize=5,
n_fwhm=100, verbose=True, get_image=False, flat=None):
if ps is not None:
import pylab as plt
from astrometry.util.plotutils import dimshow, plothist
import photutils
import tractor
if verbose:
printmsg = print
else:
def printmsg(*args, **kwargs):
pass
fn = self.fn
ext = self.ext
pixsc = self.pixscale
F = fitsio.FITS(fn)
primhdr = F[primext].read_header()
self.primhdr = primhdr
img,hdr = self.read_raw(F, ext)
self.hdr = hdr
# pre sky-sub
mn,mx = np.percentile(img.ravel(), [25,99])
self.imgkwa = dict(vmin=mn, vmax=mx, cmap='gray')
if self.debug and ps is not None:
plt.clf()
dimshow(img, **self.imgkwa)
plt.title('Raw image')
ps.savefig()
M = 200
plt.clf()
plt.subplot(2,2,1)
dimshow(img[-M:, :M], ticks=False, **self.imgkwa)
plt.subplot(2,2,2)
dimshow(img[-M:, -M:], ticks=False, **self.imgkwa)
plt.subplot(2,2,3)
dimshow(img[:M, :M], ticks=False, **self.imgkwa)
plt.subplot(2,2,4)
dimshow(img[:M, -M:], ticks=False, **self.imgkwa)
plt.suptitle('Raw image corners')
ps.savefig()
if flat is not None:
I = (flat != 0)
med = np.median(flat[I]).astype(float)
img[I] = img[I] / (flat[I] / med)
#img /= (flat / np.median(flat).astype(float))
img,trim_x0,trim_y0 = self.trim_edges(img)
fullH,fullW = img.shape
if self.debug and ps is not None:
plt.clf()
dimshow(img, **self.imgkwa)
plt.title('Trimmed image')
ps.savefig()
M = 200
plt.clf()
plt.subplot(2,2,1)
dimshow(img[-M:, :M], ticks=False, **self.imgkwa)
plt.subplot(2,2,2)
dimshow(img[-M:, -M:], ticks=False, **self.imgkwa)
plt.subplot(2,2,3)
dimshow(img[:M, :M], ticks=False, **self.imgkwa)
plt.subplot(2,2,4)
dimshow(img[:M, -M:], ticks=False, **self.imgkwa)
plt.suptitle('Trimmed corners')
ps.savefig()
band = self.get_band(primhdr)
exptime = self.get_exptime(primhdr)
airmass = primhdr['AIRMASS']
printmsg('Band', band, 'Exptime', exptime, 'Airmass', airmass)
# airmass can be 'NaN'
airmass = float(airmass)
if not np.isfinite(airmass):
printmsg('Bad airmass:', airmass, '-- setting to 1.0')
airmass = 1.0
zp0 = self.zeropoint_for_exposure(band, ext=self.ext, exptime=exptime, primhdr=primhdr)
printmsg('Nominal zeropoint:', zp0)
try:
sky0 = self.nom.sky(band)
printmsg('Nominal sky:', sky0)
except KeyError:
print('Unknown band "%s"; no nominal sky available.' % band)
sky0 = None
#print('Nominal calibration:', self.nom)
#print('Fid:', self.nom.fiducial_exptime(band))
try:
kx = self.nom.fiducial_exptime(band).k_co
except:
print('Unknown band "%s"; no k_co available.' % band)
kx = None
# Find the sky value and noise level
sky,sig1 = self.get_sky_and_sigma(img)
sky1 = np.median(sky)
if zp0 is not None:
skybr = -2.5 * np.log10(sky1/pixsc/pixsc/exptime) + zp0
printmsg('Sky brightness: %8.3f mag/arcsec^2' % skybr)
printmsg('Fiducial: %8.3f mag/arcsec^2' % sky0)
else:
skybr = None
# Read WCS header and compute boresight
wcs = self.get_wcs(hdr)
ra_ccd,dec_ccd = wcs.pixelxy2radec((fullW+1)/2., (fullH+1)/2.)
camera = primhdr.get('INSTRUME','').strip().lower()
# -> "decam" / "mosaic3"
meas = dict(band=band, airmass=airmass, exptime=exptime,
skybright=skybr, rawsky=sky1,
pixscale=pixsc, primhdr=primhdr,
hdr=hdr, wcs=wcs, ra_ccd=ra_ccd, dec_ccd=dec_ccd,
extension=ext, camera=camera)
if get_image:
meas.update(image=img, trim_x0=trim_x0, trim_y0=trim_y0)
if skybr is not None and not np.isfinite(skybr):
print('Measured negative sky brightness:', sky1, 'counts')
return meas
img -= sky
self.remove_sky_gradients(img)
# Post sky-sub
mn,mx = np.percentile(img.ravel(), [25,98])
self.imgkwa = dict(vmin=mn, vmax=mx, cmap='gray')
if ps is not None:
plt.clf()
dimshow(img, **self.imgkwa)
plt.title('Sky-sub image: %s-%s' % (os.path.basename(fn).replace('.fits','').replace('.fz',''), ext))
plt.colorbar()
ps.savefig()
# Detect stars
psfsig = self.nominal_fwhm / 2.35
detsn = self.detection_map(img, sig1, psfsig, ps)
slices = self.detect_sources(detsn, self.det_thresh, ps)
printmsg(len(slices), 'sources detected')
if len(slices) < 20:
slices = self.detect_sources(detsn, 10., ps)
printmsg(len(slices), 'sources detected')
ndetected = len(slices)
meas.update(ndetected=ndetected)
if ndetected == 0:
print('NO SOURCES DETECTED')
return meas
# Measure moments, etc around detected stars.
# These measurements don't seem to be very good!
xx,yy = [],[]
fx,fy = [],[]
mx2,my2,mxy = [],[],[]
wmx2,wmy2,wmxy = [],[],[]
# "Peak" region to centroid
P = momentsize
H,W = img.shape
for i,slc in enumerate(slices):
y0 = slc[0].start
x0 = slc[1].start
subimg = detsn[slc]
imax = np.argmax(subimg)
y,x = np.unravel_index(imax, subimg.shape)
if (x0+x) < P or (x0+x) > W-1-P or (y0+y) < P or (y0+y) > H-1-P:
#print('Skipping edge peak', x0+x, y0+y)
continue
xx.append(x0 + x)
yy.append(y0 + y)
pkarea = detsn[y0+y-P: y0+y+P+1, x0+x-P: x0+x+P+1]
from scipy.ndimage.measurements import center_of_mass
cy,cx = center_of_mass(pkarea)
#print('Center of mass', cx,cy)
fx.append(x0+x-P+cx)
fy.append(y0+y-P+cy)
#print('x,y', x0+x, y0+y, 'vs centroid', x0+x-P+cx, y0+y-P+cy)
### HACK -- measure source ellipticity
# go back to the image (not detection map)
#subimg = img[slc]
subimg = img[y0+y-P: y0+y+P+1, x0+x-P: x0+x+P+1].copy()
subimg /= subimg.sum()
ph,pw = subimg.shape
px,py = np.meshgrid(np.arange(pw), np.arange(ph))
mx2.append(np.sum(subimg * (px - cx)**2))
my2.append(np.sum(subimg * (py - cy)**2))
mxy.append(np.sum(subimg * (px - cx)*(py - cy)))
# Gaussian windowed version
s = 1.
wimg = subimg * np.exp(-0.5 * ((px - cx)**2 + (py - cy)**2) / s**2)
wimg /= np.sum(wimg)
wmx2.append(np.sum(wimg * (px - cx)**2))
wmy2.append(np.sum(wimg * (py - cy)**2))
wmxy.append(np.sum(wimg * (px - cx)*(py - cy)))
mx2 = np.array(mx2)
my2 = np.array(my2)
mxy = np.array(mxy)
wmx2 = np.array(wmx2)
wmy2 = np.array(wmy2)
wmxy = np.array(wmxy)
# semi-major/minor axes and position angle
theta = np.rad2deg(np.arctan2(2 * mxy, mx2 - my2) / 2.)
theta = np.abs(theta) * np.sign(mxy)
s = np.sqrt(((mx2 - my2)/2.)**2 + mxy**2)
a = np.sqrt((mx2 + my2) / 2. + s)
b = np.sqrt((mx2 + my2) / 2. - s)
ell = 1. - b/a
wtheta = np.rad2deg(np.arctan2(2 * wmxy, wmx2 - wmy2) / 2.)
wtheta = np.abs(wtheta) * np.sign(wmxy)
ws = np.sqrt(((wmx2 - wmy2)/2.)**2 + wmxy**2)
wa = np.sqrt((wmx2 + wmy2) / 2. + ws)
wb = np.sqrt((wmx2 + wmy2) / 2. - ws)
well = 1. - wb/wa
fx = np.array(fx)
fy = np.array(fy)
xx = np.array(xx)
yy = np.array(yy)
if ps is not None:
plt.clf()
dimshow(detsn, vmin=-3, vmax=50, cmap='gray')
ax = plt.axis()
plt.plot(fx, fy, 'go', mec='g', mfc='none', ms=10)
plt.colorbar()
plt.title('Detected sources')
plt.axis(ax)
ps.savefig()
# Aperture photometry
apxy = np.vstack((fx, fy)).T
ap = []
aprad_pix = self.aprad / pixsc
aper = photutils.CircularAperture(apxy, aprad_pix)
p = photutils.aperture_photometry(img, aper)
apflux = p.field('aperture_sum')
# Manual aperture photometry to get clipped means in sky annulus
sky_inner_r, sky_outer_r = [r / pixsc for r in self.skyrad]
sky = []
for xi,yi in zip(fx,fy):
ix = int(np.round(xi))
iy = int(np.round(yi))
skyR = int(np.ceil(sky_outer_r))
xlo = max(0, ix-skyR)
xhi = min(W, ix+skyR+1)
ylo = max(0, iy-skyR)
yhi = min(H, iy+skyR+1)
xx,yy = np.meshgrid(np.arange(xlo,xhi), np.arange(ylo,yhi))
r2 = (xx - xi)**2 + (yy - yi)**2
inannulus = ((r2 >= sky_inner_r**2) * (r2 < sky_outer_r**2))
skypix = img[ylo:yhi, xlo:xhi][inannulus]
#print('ylo,yhi, xlo,xhi', ylo,yhi, xlo,xhi, 'img subshape', img[ylo:yhi, xlo:xhi].shape, 'inann shape', inannulus.shape)
s,nil = sensible_sigmaclip(skypix)
sky.append(s)
sky = np.array(sky)
apflux2 = apflux - sky * (np.pi * aprad_pix**2)
good = (apflux2>0)*(apflux>0)
apflux = apflux[good]
apflux2 = apflux2[good]
fx = fx[good]
fy = fy[good]
stars = self.get_reference_stars(wcs, band)
if stars is None:
return meas
if len(fx) == 0:
print('No stars detected in image?')
return meas
wcs2,measargs = self.update_astrometry(stars, wcs, fx, fy, trim_x0, trim_y0,
pixsc, img, hdr, fullW, fullH, ps, printmsg)
meas.update(measargs)
keep = self.cut_reference_catalog(stars)
stars.cut(keep)
if len(stars) == 0:
print('No overlap or too few stars in PS1')
return meas
ok,px,py = wcs2.radec2pixelxy(stars.ra, stars.dec)
px -= 1
py -= 1
## DEBUG
if ps is not None:
radius2=200.
I,J,dx,dy = self.match_ps1_stars(px, py, fx, fy,
radius2, stars)
plt.clf()
plothist(dx, dy, range=((-radius2,radius2),(-radius2,radius2)))
plt.xlabel('dx (pixels)')
plt.ylabel('dy (pixels)')
plt.title('Offsets to PS1 stars (with new WCS)')
ax = plt.axis()
plt.axhline(0, color='b')
plt.axvline(0, color='b')
plt.axis(ax)
ps.savefig()
# Re-match with smaller search radius
radius2 = 3. / pixsc
I,J,dx,dy = self.match_ps1_stars(px, py, fx, fy,
radius2, stars)
printmsg('Keeping %i reference stars; matched %i with smaller search radius' %
(len(stars), len(I)))
nmatched = len(I)
meas.update(nmatched=nmatched)
if focus or zp0 is None:
meas.update(img=img, hdr=hdr, primhdr=primhdr,
fx=fx, fy=fy,
sig1=sig1, stars=stars,
moments=(mx2,my2,mxy,theta,a,b,ell),
wmoments=(wmx2,wmy2,wmxy,wtheta,wa,wb,well),
apflux=apflux, apflux2=apflux2)
return meas
#print('Mean astrometric shift (arcsec): delta-ra=', -np.mean(dy)*0.263, 'delta-dec=', np.mean(dx)*0.263)
# Compute photometric offset compared to PS1
# as the PS1 minus observed mags
colorterm = self.get_color_term(stars, band)
#print('Color term:', colorterm)
stars.mag += colorterm
ps1mag = stars.mag[I]
#print('PS1 mag:', ps1mag)
ps1_gi = stars.median[I, 0] - stars.median[I, 2]
if False and ps is not None:
plt.clf()
plt.semilogy(ps1mag, apflux2[J], 'b.')
plt.xlabel('PS1 mag')
plt.ylabel('DECam ap flux (with sky sub)')
ps.savefig()
plt.clf()
plt.semilogy(ps1mag, apflux[J], 'b.')
plt.xlabel('PS1 mag')
plt.ylabel('DECam ap flux (no sky sub)')
ps.savefig()
# "apmag2" is the annular sky-subtracted flux
apmag2 = -2.5 * np.log10(apflux2) + zp0 + 2.5 * np.log10(exptime)
apmag = -2.5 * np.log10(apflux ) + zp0 + 2.5 * np.log10(exptime)
meas.update(x=fx[J], y=fy[J], apflux=apflux2[J], apmag=apmag2[J],
colorterm=colorterm[I], refmag=ps1mag, refstars=stars[I])
if ps is not None:
plt.clf()
plt.plot(ps1mag, apmag[J], 'b.', label='No sky sub')
plt.plot(ps1mag, apmag2[J], 'r.', label='Sky sub')
# ax = plt.axis()
# mn = min(ax[0], ax[2])
# mx = max(ax[1], ax[3])
# plt.plot([mn,mx], [mn,mx], 'k-', alpha=0.1)
# plt.axis(ax)
plt.xlabel('PS1 mag')
plt.ylabel('DECam ap mag')
plt.legend(loc='upper left')
plt.title('Zeropoint')
ps.savefig()
dm = ps1mag - apmag[J]
dmag,dsig = sensible_sigmaclip(dm, nsigma=2.5)
printmsg('Mag offset: %8.3f' % dmag)
printmsg('Scatter: %8.3f' % dsig)
if not np.isfinite(dmag) or not np.isfinite(dsig):
print('FAILED TO GET ZEROPOINT!')
meas.update(zp=None)
return meas
from scipy.stats import sigmaclip
goodpix,lo,hi = sigmaclip(dm, low=3, high=3)
dmagmed = np.median(goodpix)
#print(len(goodpix), 'stars used for zeropoint median')
#print('Using median zeropoint:')
zp_med = zp0 + dmagmed
trans_med = 10.**(-0.4 * (zp0 - zp_med - kx * (airmass - 1.)))
#print('Zeropoint %6.3f' % zp_med)
#print('Transparency: %.3f' % trans_med)
dm = ps1mag - apmag2[J]
dmag2,dsig2 = sensible_sigmaclip(dm, nsigma=2.5)
#print('Sky-sub mag offset', dmag2)
#print('Scatter', dsig2)
# Median, sky-sub
goodpix,lo,hi = sigmaclip(dm, low=3, high=3)
dmagmedsky = np.median(goodpix)
if ps is not None:
plt.clf()
plt.plot(ps1mag, apmag[J] + dmag - ps1mag, 'b.', label='No sky sub')
plt.plot(ps1mag, apmag2[J]+ dmag2- ps1mag, 'r.', label='Sky sub')
plt.xlabel('PS1 mag')
plt.ylabel('DECam ap mag - PS1 mag')
plt.legend(loc='upper left')
plt.ylim(-0.25, 0.25)
plt.axhline(0, color='k', alpha=0.25)
plt.title('Zeropoint')
ps.savefig()
plt.clf()
plt.plot(ps1_gi, apmag2[J] + dmag2 - ps1mag, 'r.', label='Sky sub')
plt.xlabel('PS1 g-i color (mag)')
plt.ylabel('DECam ap mag - PS1 mag')
plt.legend(loc='upper left')
#plt.ylim(-0.25, 1.0)
plt.axhline(0, color='k', alpha=0.25)
plt.title('Zeropoint (color term)')
ps.savefig()
zp_mean = zp0 + dmag
zp_obs = zp0 + dmagmedsky
print('zp_obs', zp_obs, 'kx', kx, 'airmass', airmass)
print('zp0 for this exposure would be', zp_obs + kx * (airmass-1.))
transparency = 10.**(-0.4 * (zp0 - zp_obs - kx * (airmass - 1.)))
meas.update(zp=zp_obs, transparency=transparency)
printmsg('Zeropoint %6.3f' % zp_obs)
printmsg('Fiducial %6.3f' % zp0)
printmsg('Transparency: %.3f' % transparency)
# Also return the zeropoints using the sky-subtracted mags,
# and using median rather than clipped mean.
meas.update(zp_mean = zp_mean,
zp_skysub = zp0 + dmag2,
zp_med = zp_med,
zp_med_skysub = zp0 + dmagmedsky)
# print('Using sky-subtracted values:')
# zp_sky = zp0 + dmag2
# trans_sky = 10.**(-0.4 * (zp0 - zp_sky - kx * (airmass - 1.)))
# print('Zeropoint %6.3f' % zp_sky)
# print('Transparency: %.3f' % trans_sky)
fwhms = []
psf_r = 15
if n_fwhm not in [0, None]:
Jf = J[:n_fwhm]
for i,(xi,yi,fluxi) in enumerate(zip(fx[Jf],fy[Jf],apflux[Jf])):
#print('Fitting source', i, 'of', len(Jf))
ix = int(np.round(xi))
iy = int(np.round(yi))
xlo = max(0, ix-psf_r)
xhi = min(W, ix+psf_r+1)
ylo = max(0, iy-psf_r)
yhi = min(H, iy+psf_r+1)
xx,yy = np.meshgrid(np.arange(xlo,xhi), np.arange(ylo,yhi))
r2 = (xx - xi)**2 + (yy - yi)**2
keep = (r2 < psf_r**2)
pix = img[ylo:yhi, xlo:xhi].copy()
ie = np.zeros_like(pix)
ie[keep] = 1. / sig1
#print('fitting source at', ix,iy)
#print('number of active pixels:', np.sum(ie > 0), 'shape', ie.shape)
# plt.clf()
# plt.imshow(pix, interpolation='nearest', origin='lower',
# vmin=-2.*sig1, vmax=5.*sig1)
# plt.savefig('star-%03i.png' % i)
psf = tractor.NCircularGaussianPSF([4.], [1.])
psf.radius = psf_r
tim = tractor.Image(data=pix, inverr=ie, psf=psf)
src = tractor.PointSource(tractor.PixPos(xi-xlo, yi-ylo),
tractor.Flux(fluxi))
tr = tractor.Tractor([tim],[src])
#print('Posterior before prior:', tr.getLogProb())
src.pos.addGaussianPrior('x', 0., 1.)
#print('Posterior after prior:', tr.getLogProb())
doplot = (i < 5) * (ps is not None)
if doplot:
mod0 = tr.getModelImage(0)
tim.freezeAllBut('psf')
psf.freezeAllBut('sigmas')
# print('Optimizing params:')
# tr.printThawedParams()
#print('Parameter step sizes:', tr.getStepSizes())
optargs = dict(priors=False, shared_params=False)
for step in range(50):
dlnp,x,alpha = tr.optimize(**optargs)
#print('dlnp', dlnp)
#print('src', src)
#print('psf', psf)
if dlnp == 0:
break
# Now fit only the PSF size
tr.freezeParam('catalog')
# print('Optimizing params:')
# tr.printThawedParams()
for step in range(50):
dlnp,x,alpha = tr.optimize(**optargs)
# print('dlnp', dlnp)
# print('src', src)
# print('psf', psf)
if dlnp == 0:
break
fwhms.append(psf.sigmas[0] * 2.35 * pixsc)
if doplot:
mod1 = tr.getModelImage(0)
chi1 = tr.getChiImage(0)
plt.clf()
plt.subplot(2,2,1)
plt.title('Image')
dimshow(pix, **self.imgkwa)
plt.subplot(2,2,2)
plt.title('Initial model')
dimshow(mod0, **self.imgkwa)
plt.subplot(2,2,3)
plt.title('Final model')
dimshow(mod1, **self.imgkwa)
plt.subplot(2,2,4)
plt.title('Final chi')
dimshow(chi1, vmin=-10, vmax=10)
plt.suptitle('PSF fit')
ps.savefig()
fwhms = np.array(fwhms)
fwhm = np.median(fwhms)
printmsg('Median FWHM : %.3f arcsec' % np.median(fwhms))
meas.update(seeing=fwhm)
if False and ps is not None:
lo,hi = np.percentile(fwhms, [5,95])
lo -= 0.1
hi += 0.1
plt.clf()
plt.hist(fwhms, 25, range=(lo,hi), histtype='step', color='b')
plt.xlabel('FWHM (arcsec)')
ps.savefig()
if ps is not None:
plt.clf()
for i,(xi,yi) in enumerate(list(zip(fx[J],fy[J]))[:50]):
ix = int(np.round(xi))
iy = int(np.round(yi))
xlo = max(0, ix-psf_r)
xhi = min(W, ix+psf_r+1)
ylo = max(0, iy-psf_r)
yhi = min(H, iy+psf_r+1)
pix = img[ylo:yhi, xlo:xhi]
slc = pix[iy-ylo, :].copy()
slc /= np.sum(slc)
p1 = plt.plot(slc, 'b-', alpha=0.2)
slc = pix[:, ix-xlo].copy()
slc /= np.sum(slc)
p2 = plt.plot(slc, 'r-', alpha=0.2)
ph,pw = pix.shape
cx,cy = pw/2, ph/2
if i == 0:
xx = np.linspace(0, pw, 300)
dx = xx[1]-xx[0]
sig = fwhm / pixsc / 2.35
yy = np.exp(-0.5 * (xx-cx)**2 / sig**2) # * np.sum(pix)
yy /= (np.sum(yy) * dx)
p3 = plt.plot(xx, yy, 'k-', zorder=20)
#plt.ylim(-0.2, 1.0)
plt.legend([p1[0], p2[0], p3[0]],
['image slice (y)', 'image slice (x)', 'fit'])
plt.title('PSF fit')
ps.savefig()
return meas
def update_astrometry(self, *args):
return self.histogram_astrometric_shift(*args)
def histogram_astrometric_shift(self, stars, wcs, fx, fy, trim_x0, trim_y0, pixsc, img, hdr,
fullW, fullH, ps, printmsg):
'''
stars: reference stars
wcs: header WCS
fx,fy: detected stars
'''
import pylab as plt
from astrometry.util.plotutils import dimshow, plothist
ok,px,py = wcs.radec2pixelxy(stars.ra, stars.dec)
px -= 1
py -= 1
if ps is not None:
#kwa = dict(vmin=-3*sig1, vmax=50*sig1, cmap='gray')
# Add to the 'detected sources' plot
# mn,mx = np.percentile(img.ravel(), [50,99])
# kwa = dict(vmin=mn, vmax=mx, cmap='gray')
# plt.clf()
# dimshow(img, **kwa)
ax = plt.axis()
#plt.plot(fx, fy, 'go', mec='g', mfc='none', ms=10)
K = np.argsort(stars.mag)
plt.plot(px[K[:10]]-trim_x0, py[K[:10]]-trim_y0, 'o', mec='m', mfc='none',ms=12,mew=2)
plt.plot(px[K[10:]]-trim_x0, py[K[10:]]-trim_y0, 'o', mec='m', mfc='none', ms=8)
plt.axis(ax)
plt.title('PS1 stars')
#plt.colorbar()
ps.savefig()
# we trimmed the image before running detection; re-add that margin
fullx = fx + trim_x0
fully = fy + trim_y0
# Match PS1 to our detections, find offset
radius = self.maxshift / pixsc
print('Matching stars:', len(px), 'PS1 and', len(fullx), 'in image')
I,J,dx,dy = self.match_ps1_stars(px, py, fullx, fully, radius, stars)
#print(len(I), 'spatial matches with large radius', self.maxshift,
# 'arcsec,', radius, 'pix')
# Broad (5-pixel) bins are okay because we're going to refine them later... right?
bins = 2*int(np.ceil(radius / 5.))
print('Histogramming with', bins, 'bins')
histo,xe,ye = np.histogram2d(dx, dy, bins=bins,
range=((-radius,radius),(-radius,radius)))
# smooth histogram before finding peak -- fuzzy matching
from scipy.ndimage.filters import gaussian_filter
histo = gaussian_filter(histo, 1.)
histo = histo.T
mx = np.argmax(histo)
my,mx = np.unravel_index(mx, histo.shape)
shiftx = (xe[mx] + xe[mx+1])/2.
shifty = (ye[my] + ye[my+1])/2.
if ps is not None:
plt.clf()
#plothist(dx, dy, range=((-radius,radius),(-radius,radius)), nbins=bins)
plt.imshow(histo, interpolation='nearest', origin='lower', extent=[-radius, radius, -radius, radius],
cmap='hot')
plt.xlabel('dx (pixels)')
plt.ylabel('dy (pixels)')
plt.title('Offsets to PS1 stars')
ax = plt.axis()
plt.axhline(0, color='b')
plt.axvline(0, color='b')
plt.plot(shiftx, shifty, 'o', mec='m', mfc='none', ms=15, mew=3)
plt.axis(ax)
ps.savefig()
# Refine with smaller search radius
radius2 = 3. / pixsc
I,J,dx,dy = self.match_ps1_stars(px, py, fullx+shiftx, fully+shifty,
radius2, stars)
#print(len(J), 'matches to PS1 with small radius', 3, 'arcsec')
shiftx2 = np.median(dx)
shifty2 = np.median(dy)
#print('Stage-1 shift', shiftx, shifty)
#print('Stage-2 shift', shiftx2, shifty2)
sx = shiftx + shiftx2
sy = shifty + shifty2
printmsg('Astrometric shift (%.0f, %.0f) pixels' % (sx,sy))
# Find affine transformation
cx = fullW/2
cy = fullH/2
A = np.zeros((len(J), 3))
A[:,0] = 1.
A[:,1] = (fullx[J] + sx) - cx
A[:,2] = (fully[J] + sy) - cy
R = np.linalg.lstsq(A, px[I] - cx, rcond=None)
#R = np.linalg.lstsq(A, px[I] - cx)
resx = R[0]
#print('Affine transformation for X:', resx)
R = np.linalg.lstsq(A, py[I] - cy, rcond=None)
#R = np.linalg.lstsq(A, py[I] - cy)
resy = R[0]
#print('Affine transformation for Y:', resy)
measargs = dict(affine = [cx, cy] + list(resx) + list(resy),
px=px-trim_x0-sx, py=py-trim_y0-sy,
dx=sx, dy=sy)
subh,subw = img.shape
from astrometry.util.util import Sip
#print('WCS:', wcs)
#print('sx,sy,subw,subh', sx, sy, subw, subh)
wcs2 = Sip(wcs)
x,y = wcs2.get_crpix()
wcs2.set_crpix((x - trim_x0 - sx, y - trim_y0 - sy))
wcs2.set_width(subw)
wcs2.set_height(subh)
#print('WCS2:', wcs2)
#wcs2 = wcs.get_subimage(sx, sy, subw, subh)
#wcs2 = wcs.get_subimage(-trim_x0 - sx, -trim_y0 - sy, fullW, fullH)
#print('Trim', trim_x0, trim_y0)
if True:
r0,d0 = stars.ra[I[0]], stars.dec[I[0]]
#print('Pan-STARRS RA,Dec:', r0,d0)
ok,px0,py0 = wcs.radec2pixelxy(r0, d0)
#print('Header WCS -> x,y:', px0-1, py0-1)
mx0,my0 = fullx[J[0]], fully[J[0]]
#print('VS Matched star x,y:', mx0, my0)
if self.debug and ps is not None:
plt.clf()
plothist(dx, dy, range=((-radius2,radius2),(-radius2,radius2)))
plt.xlabel('dx (pixels)')
plt.ylabel('dy (pixels)')
plt.title('Offsets to PS1 stars')
ax = plt.axis()
plt.axhline(0, color='b')
plt.axvline(0, color='b')
plt.plot(shiftx2, shifty2, 'o', mec='m', mfc='none', ms=15, mew=3)
plt.axis(ax)
ps.savefig()
if ps is not None:
afx = (fullx[J] + sx) - cx
afy = (fully[J] + sy) - cy
affx = cx + (resx[0] + resx[1] * afx + resx[2] * afy)
affy = cy + (resy[0] + resy[1] * afx + resy[2] * afy)
affdx = px[I] - affx
affdy = py[I] - affy
plt.clf()
plothist(affdx, affdy, range=((-radius2,radius2),(-radius2,radius2)))
plt.xlabel('dx (pixels)')
plt.ylabel('dy (pixels)')
plt.title('Offsets to PS1 stars after Affine correction')
ax = plt.axis()
plt.axhline(0, color='b')
plt.axvline(0, color='b')
#plt.plot(shiftx, shifty, 'o', mec='m', mfc='none', ms=15, mew=3)
plt.axis(ax)
ps.savefig()
if ps is not None:
mn,mx = np.percentile(img.ravel(), [50,99])
kwa2 = dict(vmin=mn, vmax=mx, cmap='gray')
plt.clf()
dimshow(img, **kwa2)
ax = plt.axis()
plt.plot(fx[J], fy[J], 'go', mec='g', mfc='none', ms=10, mew=2)
plt.plot(px[I]-sx-trim_x0, py[I]-sy-trim_y0, 'm+', ms=10, mew=2)
plt.axis(ax)
plt.title('Matched PS1 stars')
plt.colorbar()
ps.savefig()
plt.clf()
dimshow(img, **kwa2)
ax = plt.axis()
plt.plot(fx[J], fy[J], 'go', mec='g', mfc='none', ms=10, mew=2)
K = np.argsort(stars.mag)
plt.plot(px[K[:10]]-sx-trim_x0, py[K[:10]]-sy-trim_y0, 'o', mec='m', mfc='none',ms=12,mew=2)
plt.plot(px[K[10:]]-sx-trim_x0, py[K[10:]]-sy-trim_y0, 'o', mec='m', mfc='none', ms=8,mew=2)
plt.axis(ax)
plt.title('All PS1 stars')
plt.colorbar()
ps.savefig()
plt.clf()
dimshow(img, **kwa2)
ax = plt.axis()
ok,px2,py2 = wcs2.radec2pixelxy(stars.ra, stars.dec)
px2 -= 1
py2 -= 1
#plt.plot(fx, fy, 'go', mec='g', mfc='none', ms=10, mew=2)
plt.plot(fx[J], fy[J], 'go', mec='g', mfc='none', ms=10, mew=2)
plt.plot(px2, py2, 'mo', mec='m', mfc='none', ms=8, mew=2)
plt.axis(ax)
plt.title('All PS1 stars (with New WCS')
plt.colorbar()
ps.savefig()
return wcs2, measargs
class DECamMeasurer(RawMeasurer):
def __init__(self, *args, **kwargs):
if not 'pixscale' in kwargs:
import decam
kwargs.update(pixscale = decam.decam_nominal_pixscale)
super(DECamMeasurer, self).__init__(*args, **kwargs)
self.camera = 'decam'
def read_raw(self, F, ext):
return read_raw_decam(F, ext)
def get_sky_and_sigma(self, img):
sky,sig1 = sensible_sigmaclip(img[1500:2500, 500:1000])
return sky,sig1
def get_wcs(self, hdr):
from astrometry.util.util import wcs_pv2sip_hdr
from astrometry.util.starutil_numpy import hmsstring2ra, dmsstring2dec
# In DECam images, the CRVAL values are set to TELRA and
# TELDEC, but for computing the RA,Dec offsets, we want to use