-
Notifications
You must be signed in to change notification settings - Fork 26
/
pp_manident.py
executable file
·332 lines (272 loc) · 12.3 KB
/
pp_manident.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
#!/usr/bin/env python3
""" MANIDENT - manual target identification tool for the Photometry Pipeline
v1.0: 2016-08-08, [email protected]
this code is based in part on viewseries.py:
http://spider.wadsworth.org/spider_doc/spider/docs/python/spipylib/examples/viewseries.py
"""
from __future__ import print_function
from __future__ import division
from past.utils import old_div
import os
import sys
import numpy
import warnings
from tkinter import *
from PIL import Image
from PIL import ImageTk
from PIL import ImageDraw
import argparse
from astropy.io import fits
from scipy.ndimage import interpolation as interp
from scipy.interpolate import InterpolatedUnivariateSpline
# only import if Python3 is used
if sys.version_info > (3, 0):
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import object
# pipeline-specific modules
from catalog import *
# class structure for Tkinter control
class Clicker(object):
def __init__(self, master, zoom, filelist):
self.top = master
self.files = filelist
self.zoom = zoom
self.target_index = [None for i in range(len(self.files))]
self.interp_index = [None for i in range(len(self.files))]
self.index = 0
self.images = []
self.ldac = []
self.mjd = []
# load image data
print('please wait, loading images...', end=' ')
sys.stdout.flush()
self.read_all_fits(self.files)
print('done!')
# create title bar
self.title = Label(text='%s (%d/%d)' %
(self.images[0],
self.index+1, len(self.files)))
self.title.pack()
# select first image
self.tkimage = ImageTk.PhotoImage(self.images[0], palette=256)
self.canvas = Canvas(
master, height=self.tkimage.height(), width=self.tkimage.width())
self.image = self.canvas.create_image(0, 0, anchor='nw',
image=self.tkimage)
# create position indicators:
# green: sources, yellow: inter/extrapolated, red: manually
# selected
self.green_circles = []
self.redcircle_id = self.canvas.create_oval(-100, -100, -100,
-100, outline='red',
width=2)
self.yellowcircle_id = self.canvas.create_oval(-100, -100, -100,
-100, outline='orange',
width=1)
# frame counter variable
self.evar = IntVar()
self.evar.set(1)
self.canvas.pack(side='top', expand=1)
# display image
self.nextframe()
# events
self.canvas.focus_set()
self.canvas.bind("<Key>", self.key)
self.canvas.bind("<Button 1>", self.left_click)
self.canvas.bind("<Button 3>", self.right_click)
def left_click(self, event):
""" select source """
x, y = old_div(event.x, self.zoom), old_div(event.y, self.zoom)
# find source closest to click position in ldac, identify
# source index
residuals = numpy.sqrt((self.ldac[self.index]['XWIN_IMAGE']-x)**2 +
(self.ldac[self.index]['YWIN_IMAGE']-y)**2)
closest_idx = numpy.argmin(residuals)
self.target_index[self.index] = closest_idx
self.nextframe(0)
def right_click(self, event):
""" next frame """
self.nextframe(1)
def key(self, event):
""" keyboard events """
if event.char == 'a':
# previous frame
self.nextframe(-1)
elif event.char == 'd':
# next frame
self.nextframe(1)
elif event.char == 'q':
# quit
self.top.quit()
elif event.char == '+':
# zoom in
if self.zoom < 4.:
self.zoom *= 2
self.nextframe(0)
elif event.char == '-':
# zoom out
if self.zoom > 0.25:
self.zoom /= 2
self.nextframe(0)
def read_all_fits(self, filenames, zoom=0.5):
""" read in all image data, scale images """
for idx, filename in enumerate(filenames):
if idx > 0:
print('\b\b\b\b%3d' % (idx+1), end=' ')
else:
print('%3d' % (idx+1), end=' ')
sys.stdout.flush()
# read image data
hdulist = fits.open(filename, ignore_missing_end=True)
imgdat = hdulist[0].data
# median = numpy.median(imgdat)
# std = numpy.std(imgdat)
median = numpy.median(imgdat[int(imgdat.shape[1]*0.25):
int(imgdat.shape[1]*0.75),
int(imgdat.shape[0]*0.25):
int(imgdat.shape[0]*0.75)])
std = numpy.std(imgdat[int(imgdat.shape[1]*0.25):
int(imgdat.shape[1]*0.75),
int(imgdat.shape[0]*0.25):
int(imgdat.shape[0]*0.75)])
imgdat = old_div(numpy.clip(imgdat, median-0.5*std,
median+0.5*std), (old_div(std, 256)))
imgdat = imgdat - numpy.min(imgdat)
imgdat = interp.zoom(imgdat, self.zoom)
self.images.append(Image.fromarray(imgdat))
# read ldac data
cat = catalog(filename)
ldac_filename = filename[:filename.find('.fit')]+'.ldac'
cat.read_ldac(ldac_filename, filename, maxflag=4)
self.ldac.append(cat)
# read header data (MJD)
self.mjd.append(float(hdulist[0].header['MIDTIMJD']))
def nextframe(self, i=1, imgnum=-1):
""" display frame using iterator i"""
if imgnum == -1:
self.index += i
else:
self.index = imgnum - 1
if self.index >= len(self.files):
self.index = 0
elif self.index < 0:
self.index = len(self.files) - 1
filename = self.files[self.index]
if not os.path.exists(filename):
print("Unable to find %s" % filename)
self.top.quit()
self.evar.set(self.index+1)
self.title.configure(text='%s (%d/%d)' %
(os.path.basename(filename),
self.index+1, len(self.files)))
im = self.images[self.index]
# draw red circle, if target has been identified
# yellow circle if extrapolation
interp_idx = None
if self.target_index[self.index] is not None:
idx = self.target_index[self.index]
self.canvas.coords(self.redcircle_id,
(self.ldac[self.index][idx]['XWIN_IMAGE']*self.zoom-4,
self.ldac[self.index][idx]['YWIN_IMAGE'] *
self.zoom-4,
self.ldac[self.index][idx]['XWIN_IMAGE'] *
self.zoom+4,
self.ldac[self.index][idx]['YWIN_IMAGE']*self.zoom+4))
self.canvas.coords(self.yellowcircle_id, (-100, -100, -100, -100))
else:
# if no coordinates available, move red circle out of canvas
self.canvas.coords(self.redcircle_id, (-100, -100, -100, -100))
# use yellow circle if sufficient target positions known
interp_idx = self.extrapolate(self.mjd[self.index])
if interp_idx is not None:
self.canvas.coords(self.yellowcircle_id,
(self.ldac[self.index][interp_idx]['XWIN_IMAGE']*self.zoom-4,
self.ldac[self.index][interp_idx]['YWIN_IMAGE'] *
self.zoom-4,
self.ldac[self.index][interp_idx]['XWIN_IMAGE'] *
self.zoom+4,
self.ldac[self.index][interp_idx]['YWIN_IMAGE']*self.zoom+4))
else:
self.canvas.coords(self.yellowcircle_id,
(-100, -100, -100, -100))
self.interp_index[self.index] = interp_idx
# plot all sources
for circ in self.green_circles:
self.canvas.delete(circ)
x = self.ldac[self.index]['XWIN_IMAGE']
y = self.ldac[self.index]['YWIN_IMAGE']
indices = list(range(len(x)))
if self.target_index[self.index] is not None:
indices.pop(self.target_index[self.index])
if interp_idx is not None:
indices.pop(interp_idx)
self.green_circles = \
[self.canvas.create_oval(x[i]*self.zoom-4,
y[i]*self.zoom-4,
x[i]*self.zoom+4,
y[i]*self.zoom+4,
outline='green',
width=1)
for i in indices]
self.tkimage.paste(im)
def extrapolate(self, time):
"""fit path with spline, identify nearest source"""
x, y, t = [], [], []
for i in range(len(self.files)):
if self.target_index[i] is not None:
t.append(self.mjd[i])
x.append(self.ldac[i][self.target_index[i]]['XWIN_IMAGE'])
y.append(self.ldac[i][self.target_index[i]]['YWIN_IMAGE'])
k = min([len(t), 3])-1
if k >= 1:
# extrapolate position
fx = InterpolatedUnivariateSpline(numpy.array(t), numpy.array(x),
k=k)
fy = InterpolatedUnivariateSpline(numpy.array(t), numpy.array(y),
k=k)
# identify closest source
residuals = numpy.sqrt((self.ldac[self.index]['XWIN_IMAGE'] -
fx(time))**2 +
(self.ldac[self.index]['YWIN_IMAGE'] -
fy(time))**2)
return numpy.argmin(residuals)
else:
return None
# --------------------------------------------------------------------
if __name__ == "__main__":
# here
# define command line arguments
parser = argparse.ArgumentParser(
description='manual target identification')
parser.add_argument('-zoom', help='image zoom factor', default=0.5)
parser.add_argument('images', help='images to process', nargs='+')
args = parser.parse_args()
zoom = float(args.zoom)
filenames = args.images
root = Tk()
app = Clicker(root, zoom, filenames)
root.mainloop()
outf = open('positions.dat', 'w')
outf.write('# filename midtime_JD RA Dec\n' +
'# note that RA and Dec might be based on a fake plate solution and hence are not astrometric\n')
# recalculate target coordinates and write them into a file
for image_idx, image_name in enumerate(app.files):
# accurate position
if app.target_index[image_idx] is not None:
outf.write('%50.50s %9.5f %9.5f %18.9f\n' % (image_name,
app.ldac[image_idx][app.target_index[image_idx]]['ra_deg'],
app.ldac[image_idx][app.target_index[image_idx]
]['dec_deg'],
app.mjd[image_idx]))
# interpolated position
else:
app.index = image_idx
interp_idx = app.extrapolate(app.mjd[image_idx])
outf.write('%50.50s %9.5f %9.5f %18.9f\n' % (image_name,
app.ldac[image_idx][interp_idx]['ra_deg'],
app.ldac[image_idx][interp_idx]['dec_deg'],
app.mjd[image_idx]))
print(image_idx+1, 'target positions written to file positions.dat')
outf.close()