-
Notifications
You must be signed in to change notification settings - Fork 4
/
image_subtraction.py
294 lines (229 loc) · 10.6 KB
/
image_subtraction.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
from astropy.io import fits
import numpy as np
import matplotlib.pyplot as plt
from reproject import reproject_interp
import os
from astropy.wcs import WCS, _wcs
from astropy.visualization import PercentileInterval, ImageNormalize
import requests
from astropy.table import Table
from astropy.nddata import CCDData, NDData
from photutils import psf, EPSFBuilder
from io import BytesIO
from PyZOGY.subtract import calculate_difference_image, calculate_difference_image_zero_point, \
normalize_difference_image, save_difference_image_to_file
from PyZOGY.image_class import ImageClass
import scipy
import warnings
def read_with_datasec(filename, hdu=0):
ccddata = CCDData.read(filename, format='fits', unit='adu', hdu=hdu)
if 'datasec' in ccddata.meta:
jmin, jmax, imin, imax = eval(ccddata.meta['datasec'].replace(':', ','))
ccddata = ccddata[imin-1:imax, jmin-1:jmax]
return ccddata
def get_ccd_bbox(ccddata):
corners = [[0.], [0.5], [1.]] * np.array(ccddata.shape)[::-1]
(ra_min, dec_min), (ra_ctr, dec_ctr), (ra_max, dec_max) = ccddata.wcs.all_pix2world(corners, 0.)
if ra_min > ra_max:
ra_min, ra_max = ra_max, ra_min
if dec_min > dec_max:
dec_min, dec_max = dec_max, dec_min
max_size_dec = 0.199
if dec_max - dec_min > max_size_dec:
dec_min = dec_ctr - max_size_dec / 2.
dec_max = dec_ctr + max_size_dec / 2.
return ra_min, dec_min, ra_max, dec_max
def get_ps1_catalog(ra_min, dec_min, ra_max, dec_max, mag_max=21., mag_min=16., mag_filter='r'):
res = requests.get('http://gsss.stsci.edu/webservices/vo/CatalogSearch.aspx',
params={'cat': 'PS1V3OBJECTS', 'format': 'csv', 'mindet': 25,
'bbox': '{},{},{},{}'.format(ra_min, dec_min, ra_max, dec_max)})
t = Table.read(res.text, format='csv', header_start=1, data_start=2)
psfmag_key = mag_filter + 'MeanPSFMag'
is_point_source = t[psfmag_key] - t[mag_filter + 'MeanKronMag'] < 0.05
mag_cut = (t[psfmag_key] < mag_max) & (t[psfmag_key] > mag_min)
t_stars = t[is_point_source & mag_cut]
return t_stars
def make_psf(data, catalog, show=False, boxsize=25.):
catalog = catalog.copy()
catalog['x'], catalog['y'] = data.wcs.all_world2pix(catalog['raMean'], catalog['decMean'], 0)
bkg = np.nanmedian(data)
nddata = NDData(data - bkg)
stars = psf.extract_stars(nddata, catalog, size=boxsize)
epsf_builder = EPSFBuilder(oversampling=1.)
epsf, fitted_stars = epsf_builder(stars)
if show:
plt.figure()
plt.imshow(epsf.data)
plot_stars(fitted_stars)
return epsf, fitted_stars
def plot_stars(stars):
nrows = int(np.ceil(len(stars) ** 0.5))
fig, axarr = plt.subplots(nrows, nrows, figsize=(20, 20), squeeze=True)
for ax, star in zip(axarr.ravel(), stars):
ax.imshow(star)
ax.plot(star.cutout_center[0], star.cutout_center[1], 'r+')
def update_wcs(wcs, p):
wcs.wcs.crval += p[:2]
c, s = np.cos(p[2]), np.sin(p[2])
if wcs.wcs.has_cd():
wcs.wcs.cd = wcs.wcs.cd @ np.array([[c, -s], [s, c]]) * p[3]
if wcs.wcs.has_pc():
wcs.wcs.pc = wcs.wcs.pc @ np.array([[c, -s], [s, c]]) * p[3]
def wcs_offset(p, radec, xy, origwcs):
wcs = origwcs.deepcopy()
update_wcs(wcs, p)
test_xy = wcs.all_world2pix(radec, 0)
rms = (np.sum((test_xy - xy)**2) / len(radec))**0.5
return rms
def refine_wcs(wcs, stars, catalog, use_sep=False):
if use_sep:
xy = np.array([[star['x'], star['y']] for star in stars])
t_match = catalog[stars['i']]
else:
xy = np.array([star.center for star in stars.all_good_stars])
t_match = catalog[[star.id_label - 1 for star in stars.all_good_stars]]
radec = np.array([t_match['raMean'], t_match['decMean']]).T
res = scipy.optimize.minimize(wcs_offset, [0., 0., 0., 1.], args=(radec, xy, wcs),
bounds=[(-0.01, 0.01), (-0.01, 0.01), (-0.1, 0.1), (0.9, 1.1)])
orig_rms = wcs_offset([0., 0., 0., 1.], radec, xy, wcs)
print(' orig_fun: {}'.format(orig_rms))
print(res)
update_wcs(wcs, res.x)
def get_ps1_filename(ra, dec, filt):
"""
Download Image from PS1 and correct luptitudes back to a linear scale.
Parameters
---------------
ra, dec : Coordinates in degrees
filt : Filter color 'g', 'r', 'i', 'z', or 'y'
Output
---------------
filename : PS1 image filename
"""
# Query a center RA and DEC from PS1 in a specified color
res = requests.get('http://ps1images.stsci.edu/cgi-bin/ps1filenames.py',
params={'ra': ra, 'dec': dec, 'filters': filt})
t = Table.read(res.text, format='ascii')
return t['filename'][0]
def download_ps1_image(filename, saveas=None):
"""
Download image from PS1 and correct luptitudes back to a linear scale.
Parameters
---------------
filename : PS1 image filename (from `get_ps1_filename`)
saveas : Path to save template file (default: do not save)
Output
---------------
ccddata : CCDData format of data with WCS
"""
res = requests.get('http://ps1images.stsci.edu' + filename)
hdulist = fits.open(BytesIO(res.content))
# Linearize from luptitudes
boffset = hdulist[1].header['boffset']
bsoften = hdulist[1].header['bsoften']
data_linear = boffset + bsoften * 2 * np.sinh(hdulist[1].data * np.log(10.) / 2.5)
warnings.simplefilter('ignore') # ignore warnings from nonstandard PS1 header keywords
ccddata = CCDData(data_linear, wcs=WCS(hdulist[1].header), unit='adu')
# Save the template to file
if saveas is not None:
ccddata.write(saveas, overwrite=True)
return ccddata
def download_references(ra_min, dec_min, ra_max, dec_max, mag_filter, template_basename=None, catalog=None):
"""
Download 1 to 4 references from PS1 as necessary to cover full RA & dec range
Parameters
---------------
ra_min, ra_max : Minimum and Maximum RA and DEC
dec_min, dec_max in units of degrees
mag_filter : Filter color 'g', 'r', 'i', 'z', or 'y'
template_basename: Filename of the output(s), to be suffixed by 0.fits, 1.fits, ...
catalog : Catalog to which to align the reference image WCS (default: do not align)
Output
---------------
refdatas : List of CCDData objects containing the reference images
"""
filename0 = get_ps1_filename(ra_min, dec_min, mag_filter)
filename1 = get_ps1_filename(ra_max, dec_max, mag_filter)
filename2 = get_ps1_filename(ra_min, dec_max, mag_filter)
filename3 = get_ps1_filename(ra_max, dec_min, mag_filter)
filenames = {filename0, filename1, filename2, filename3}
refdatas = []
for i, fn in enumerate(filenames):
if template_basename is not None:
saveas = template_basename + '{:d}.fits'.format(i)
print('downloading', saveas)
else:
saveas = None
print('downloading', fn)
refdata = download_ps1_image(fn, saveas)
if catalog is not None:
_, stars = make_psf(refdata, catalog)
try:
refine_wcs(refdata.wcs, stars, catalog)
except _wcs.InvalidTransformError:
print('WARNING: unable to refine wcs')
except ValueError:
print('WARNING: no stars found, unable to refine wcs')
refdatas.append(refdata)
return refdatas
def assemble_reference(refdatas, wcs, shape):
"""Reproject and stack the reference images to match the science image"""
refdatas_reprojected = []
refdata_foot = np.zeros(shape, float)
for data in refdatas:
reprojected, foot = reproject_interp((data.data, data.wcs), wcs, shape)
refdatas_reprojected.append(reprojected)
refdata_foot += foot
refdata_reproj = np.nanmean(refdatas_reprojected, axis=0)
refdata_reproj[np.isnan(refdata_reproj)] = 0.
refdata = CCDData(refdata_reproj, wcs=wcs, mask=refdata_foot == 0., unit='adu')
return refdata
if __name__ == '__main__':
# # Read the science image
show = False
workdir = '/Users/griffin/imgsub/'
filename = os.path.join(workdir, 'PS17dbf.Science.5615_proc.fits')
scidata0 = read_with_datasec(filename)
# # Download the PS1 catalog
ccd_bbox = get_ccd_bbox(scidata0)
catalog = get_ps1_catalog(*ccd_bbox)
# # Pretend to make the PSF for the science image
# This is just to find the centroids of the stars so we can update the WCS in the next step
_, sci_stars = make_psf(scidata0, catalog, show=show)
# # Update the WCS for the science image
scidata = scidata0.copy()
refine_wcs(scidata.wcs, sci_stars, catalog)
science_filename = os.path.join(workdir, 'science.fits')
scidata.write(science_filename, overwrite=True)
# # Actually make the PSF for the science image
sci_psf, _ = make_psf(scidata, catalog, show=show)
# # Download the reference image
refdatas = download_references(*ccd_bbox, scidata.meta['filter'][0], catalog=catalog)
refdata = assemble_reference(refdatas, scidata.wcs, scidata.shape)
template_filename = os.path.join(workdir, 'template.fits')
refdata.write(template_filename, overwrite=True)
if show:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 15))
x, y = scidata.wcs.all_world2pix(catalog['raMean'], catalog['decMean'], 0.)
vmin, vmax = np.percentile(scidata.data, (15., 99.5))
ax1.imshow(scidata.data, vmin=vmin, vmax=vmax)
ax1.plot(x, y, marker='o', mec='r', mfc='none', ls='none')
norm = ImageNormalize(refdata.data, PercentileInterval(99.))
ax2.imshow(refdata.data, norm=norm)
ax2.plot(x, y, marker='o', mec='r', mfc='none', ls='none')
# # Make the PSF for the reference image
refdata_unmasked = refdata.copy()
refdata_unmasked.mask = np.zeros_like(refdata, bool)
ref_psf, _ = make_psf(refdata_unmasked, catalog, show=show)
# # Subtract the images and view the result
output_filename = os.path.join(workdir, 'diff.fits')
science = ImageClass(scidata, sci_psf.data, saturation=65565)
reference = ImageClass(refdata, ref_psf.data, refdata.mask)
difference = calculate_difference_image(science, reference, show=show)
difference_zero_point = calculate_difference_image_zero_point(science, reference)
normalized_difference = normalize_difference_image(difference, difference_zero_point, science, reference, 'i')
save_difference_image_to_file(normalized_difference, science, 'i', output_filename)
if show:
vmin, vmax = np.percentile(difference, (15., 99.5))
plt.figure(figsize=(7., 15.))
plt.imshow(difference, vmin=vmin, vmax=vmax)