forked from deapplegate/wtgpipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backmask.py
298 lines (215 loc) · 7.61 KB
/
backmask.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
#!/usr/bin/env python
#####################
# Find something to mask in a coadded image, display position matched input images for masking purposes
######################
import astropy, astropy.io.fits as pyfits, sys, re, os, time, glob, subprocess
import backref_coaddpos as br
from optparse import OptionParser
from numpy import *
######################
__cvs_id__="$Id: backmask.py,v 1.7 2010-03-23 00:36:17 dapple Exp $"
######################
######################
# XPA Commands
######################
def xpaset(command, pipe=None):
print "command=",command
if pipe is None:
subprocess.check_call(('xpaset -p ds9 %s' % command).split())
else:
xpa = os.popen('xpaset ds9 %s' % command, 'w')
xpa.write(pipe)
xpa.close()
#####
def xpaget(command):
xpa = subprocess.Popen('xpaget ds9 %s' % command, shell=True, stdout=subprocess.PIPE).stdout
output = [x.strip() for x in xpa.readlines()]
xpa.close()
if len(output) == 0:
return None
if len(output) == 1:
return output[0]
return output
####################
def isDS9Running():
xpaaccess = os.popen('xpaaccess ds9')
answer = xpaaccess.readline()
isRunning = answer.strip()
xpaaccess.close()
return isRunning == "yes"
#####
def startDS9():
#return value indicates if ds9 was started by this program
if not isDS9Running():
#os.system('ds9 &')
os.system('/afs/slac/g/ki/software/local/bin/ds9 -view layout vertical -frame lock wcs &')
for count in xrange(200):
time.sleep(1)
if isDS9Running():
print "waited for ds9 to load for %s seconds" % (count)
return True
raise RuntimeException('Cannot Open DS9')
return False
####
def stopDS9():
if isDS9Running():
xpaset('exit')
####
def matchWCS(image):
curframe = xpaget('frame frameno')
image.matchWCS()
if curframe != '':
xpaset('frame %s' % curframe)
####
class Image:
def __init__(self, file, regionfile = None):
self.file = file
self.regionfile = regionfile
self.frameno = None
def isOpen(self):
return self.frameno is not None
def activeImage(self, newFrame=True):
if self.isOpen():
xpaset('frame %d' % self.frameno)
return
if newFrame:
xpaset('frame new')
self.frameno = int(xpaget('frame'))
print "Image %s now frame %d" % (self.file, self.frameno)
xpaset('file %s' % self.file)
xpaset('cmap BB')
xpaset('scale mode zscale')
if self.regionfile is not None and \
os.path.exists(self.regionfile):
xpaset('regions load %s' % self.regionfile)
def closeImage(self, saveRegions = True):
if not self.isOpen():
return
print "Closing %s at frame %d" % (self.file, self.frameno)
xpaset('frame %d' % self.frameno)
if saveRegions:
xpaset('regions strip no')
xpaset('regions system image')
print "Saving %s" % self.regionfile
xpaset('regions save %s' % self.regionfile)
xpaset('frame delete')
self.frameno = None
def matchWCS(self):
self.activeImage()
xpaset('match frames wcs')
######
class Regions:
def __init__(self, readfromDS9=False):
if readfromDS9:
self.pix = xpaget('regions -system image')
self.wcs = xpaget('regions -system wcs')
else:
self.pix = []
self.wcs = []
def load(self, wcs=True):
if wcs:
regionlist = ['fk5']
regionlist.extend(self.wcs)
else:
regionlist = self.pix
xpaset('regions', pipe=';'.join(regionlist))
def append(self, region):
self.pix.append(region[0])
self.wcs.append(region[1])
def __iter__(self):
return zip(self.pix, self.wcs).__iter__()
def __contains__(self, region):
pix, wcs = region
return pix in self.pix and wcs in self.wcs
def __len__(self):
return len(self.pix)
def readNewRegions(knownregions = Regions()):
allregions = Regions(readfromDS9=True)
newregions = Regions()
for region in allregions:
if region not in knownregions:
newregions.append(region)
return newregions, allregions
#################
def readCurPix():
return array([map(float, xpaget('pan').split())])
#################
def run_backmask(coaddimage, imagedict):
mapping = br.CoaddMapping([x.file for x in imagedict.itervalues()],
coaddimage.file)
print "mapping=",mapping
closeDS9 = startDS9()
coaddimage.activeImage()
knownregions = Regions(readfromDS9=True)
while 1:
sys.stdout.write("Enter to load Contributing Files (and plot new regions) [(q)uit]?")
response = raw_input()
if response == 'q':
break
coaddimage.activeImage()
curpix = readCurPix()
newregions, knownregions = readNewRegions(knownregions)
contribs = mapping.findContribs(curpix)
contribs.sort()
print "contribs=",contribs
print "imagedict=",imagedict
for contrib in contribs:
imagedict[contrib].activeImage()
newregions.load()
coaddimage.activeImage()
coaddimage.matchWCS()
print "Contributing files loaded"
sys.stdout.write("Enter when done [(a)bort]?")
response = raw_input()
saveRegions = (response != 'a')
for image in imagedict.itervalues():
image.closeImage(saveRegions = saveRegions)
coaddimage.activeImage()
#if closeDS9
# stopDS9()
##########################
##########################
def constructRegionFile(image, stripSuffix):
#assumes a lot about directory structure, and how you run this!
if os.path.islink(image):
realimage = os.readlink(image)
else:
realimage = image
if not os.path.isabs(realimage):
realimage = os.path.join(os.path.dirname(image),os.readlink(image))
dir, filename = os.path.split(realimage)
regiondir = '%s/reg' % dir
base, suffix, dummy = filename.rpartition(stripSuffix)
regionfile='%s/%s.reg' % (regiondir, base)
return regionfile
############################
def loadCoaddMasking(coaddfile, allimages):
#assumptions about filename and directory structures
coaddir, coadd = os.path.split(coaddfile)
coaddbase, fits = os.path.splitext(coadd)
print '# of Input Images Detected: %d' % len(allimages)
imagedict = {}
for image in allimages:
dir, filebase = os.path.split(image)
print "filebase=",filebase
match = re.match('(.+?_\d+)', filebase)
base = match.group(1)
print "base=",base
if os.path.exists(image):
print "Loading %s..." % image
print '...with region file: %s/reg/%s.reg' % (dir, base)
imagedict[image] = Image(image, '%s/reg/%s.reg' % (dir, base))
else:
print "Cannot find %s!!!" % image
coaddimage = Image(coaddfile, '%s/%s.backmask.reg' % (coaddir, coadd))
run_backmask(coaddimage, imagedict)
##########################
##########################
if __name__ == '__main__':
if len(sys.argv) < 3:
print "backmask.py /path/to/coadd.fits filesuffic"
print " For example: backmask.py /path/to/coadd.fits input images"
sys.exit(1)
coadd = sys.argv[1]
inputimages = sys.argv[2:]
loadCoaddMasking(coadd, inputimages)