-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfind_calibrator.py
221 lines (195 loc) · 9.01 KB
/
find_calibrator.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
import logging,datetime,math
import optparse
# configure the logging
logging.basicConfig(format='# %(levelname)s:%(name)s: %(message)s')
logger=logging.getLogger('metadata')
logger.setLevel(logging.WARNING)
import mwapy
from mwapy import metadata
import sys,os
from astropy.time import Time,TimeDelta
from astropy import constants as c, units as u
from astropy.coordinates import SkyCoord
import numpy
##################################################
def issamenight(obsid1, obsid2):
"""
issamenight(obsid1, obsid2)
checks whether they are the same night
assumes AWST=UTC+8
"""
t1=Time(obsid1, format='gps', scale='utc')
t2=Time(obsid2, format='gps', scale='utc')
if int(t1.jd)==int(t2.jd) and t1.datetime.hour>=10 and t2.datetime.hour>=10 and t1.datetime.hour<=24 and t2.datetime.hour<=24:
return True
return False
##################################################
def find_calibrator(obsid,
maxtimediff=TimeDelta(1*u.d),
maxseparation=180*u.deg,
sourcename=None,
notsourcename=['FDS'],
matchproject=True,
matchnight=True,
priority='time',
all=False):
"""
obsid, timediff, distance=find_calibrator(obsid,
maxtimediff=TimeDelta(1*u.d),
maxseparation=180*u.deg,
sourcename=None,
notsourcename=['FDS'],
matchproject=True,
matchnight=True,
priority='time',
all=False):
timediff is in days
distance is in degrees
"""
assert priority in ['time','distance']
starttime=Time(obsid, format='gps',scale='utc')-maxtimediff
stoptime=Time(obsid, format='gps',scale='utc')+maxtimediff
try:
baseobs=metadata.MWA_Observation(obsid)
except Exception,e:
logger.error('Cannot fetch info for observation %d:\n\t%s' % (obsid, e))
return None
if baseobs is None:
logger.error('Cannot fetch info for observation %d:\n\t%s' % (obsid, e))
return None
try:
basepointing=SkyCoord(baseobs.ra_phase_center, baseobs.dec_phase_center,
unit='deg', frame='icrs')
except:
basepointing=SkyCoord(baseobs.RA, baseobs.Dec,
unit='deg', frame='icrs')
basetime=Time(obsid, format='gps',scale='utc')
if sourcename is not None and len(sourcename)>0:
sourcename='%' + sourcename + '%'
else:
sourcename='%'
if matchproject:
results=metadata.fetch_observations(mintime=int(starttime.gps)-1,
maxtime=int(stoptime.gps)-1,
projectid=baseobs.projectid,
calibration=1,
obsname=sourcename,
cenchan=baseobs.center_channel)
else:
results=metadata.fetch_observations(mintime=int(starttime.gps)-1,
maxtime=int(stoptime.gps)-1,
calibration=1,
obsname=sourcename,
cenchan=baseobs.center_channel)
if len(results)==0:
return None
goodlist=numpy.zeros((len(results),),
dtype=[('obsid','i4'),
('distance','f4'),
('timediff','f4'),
('good',numpy.bool),
('obsname','a20')])
for i in xrange(len(results)):
result=results[i]
obs=metadata.MWA_Observation_Summary(result)
pointing=SkyCoord(obs.ra,obs.dec,unit='deg', frame='icrs')
separation=basepointing.separation(pointing)
good=True
good=good and separation < maxseparation
good=good and numpy.abs(Time(obs.obsid,format='gps',scale='utc')-basetime)<maxtimediff
good=good and (not matchnight or issamenight(baseobs.observation_number, obs.obsid))
if len(notsourcename)>0:
for s in notsourcename:
good=good and not (s in obs.obsname)
goodlist[i]['obsid']=obs.obsid
goodlist[i]['good']=good
goodlist[i]['distance']=separation.deg
goodlist[i]['timediff']=numpy.abs((Time(obs.obsid,format='gps',scale='utc')-basetime).jd)
goodlist[i]['obsname']=obs.obsname
goodlist=goodlist[goodlist['good']]
if len(goodlist)==0:
return None
if priority=='time':
goodlist=numpy.sort(goodlist, order='timediff')
elif priority=='distance':
goodlist=numpy.sort(goodlist, order='distance')
if not all:
return (goodlist[0]['obsid'],goodlist[0]['timediff'],goodlist[0]['distance'],goodlist[0]['obsname'])
else:
return (list(goodlist['obsid']),list(goodlist['timediff']),list(goodlist['distance']),list(goodlist['obsname']))
##################################################
def main():
usage="Usage: %prog [options] <obsid>\n"
o = optparse.OptionParser(usage=usage,version=mwapy.__version__ + ' ' + mwapy.__date__)
o.add_option('--separation',dest='separation',default=180,
type='float',
help='Maximum separation (deg) [default=%default]')
o.add_option('--timediff',dest='timediff',default='1d',
help='Maximum time difference (d, h, m, or s) [default=%default]')
o.add_option('--matchproject',dest='matchproject',default=False,
action='store_true',
help='Match project to original ObsID?')
o.add_option('--matchnight',dest='matchnight',default=False,
action='store_true',
help='Match night to original ObsID?')
o.add_option('--source',dest='source',default=None,
help='Calibrator source name [default=None]')
o.add_option('--notsource',dest='notsource',default='FDS',
help='Comma-separated list of source names to exclude [default=%default]')
o.add_option('--priority',dest='priority',default='time',
type='choice',
choices=['time','distance'],
help='Return the closest in time or distance? [default=%default]')
o.add_option('--all',dest='all',default=False,
action='store_true',
help='Return all possible matches?')
o.add_option('-v','--verbose',dest='verbose',default=False,
action='store_true',
help='Give verbose output?')
options, args = o.parse_args()
if len(args)==0:
logger.error('Must specify >1 obsids')
sys.exit(1)
if 'd' in options.timediff:
maxtimediff=TimeDelta(float(options.timediff[:-1])*u.d)
elif 'h' in options.timediff:
maxtimediff=TimeDelta(float(options.timediff[:-1])*u.h)
elif 'm' in options.timediff:
maxtimediff=TimeDelta(float(options.timediff[:-1])*u.m)
elif 's' in options.timediff:
maxtimediff=TimeDelta(float(options.timediff[:-1])*u.s)
maxseparation=options.separation*u.deg
matchproject=options.matchproject
matchnight=options.matchnight
priority=options.priority
for obsid in args:
result=find_calibrator(int(obsid),
maxtimediff=maxtimediff,
maxseparation=maxseparation,
matchproject=matchproject,
matchnight=matchnight,
sourcename=options.source,
notsourcename=options.notsource.split(','),
priority=priority,
all=options.all)
if result is None:
print "None"
elif not options.all:
print '# Obsid\t\tCalObsid\tTimediff(day)\tDistance(deg)\tSource'
print '%s\t%s\t%.3f\t\t%.1f\t\t%s' % (obsid,result[0],result[1],result[2],result[3])
if options.verbose:
o=metadata.MWA_Observation(int(result[0]))
print o
else:
print '# Obsid\t\tCalObsid\tTimediff(day)\tDistance(deg)\tSource'
for i in xrange(len(result[0])):
print '%s\t%s\t%.3f\t\t%.1f\t\t%s' % (obsid,result[0][i],
result[1][i],result[2][i],
result[3][i])
if options.verbose:
o=metadata.MWA_Observation(int(result[0][i]))
print o
sys.exit(0)
################################################################################
if __name__=="__main__":
main()