-
Notifications
You must be signed in to change notification settings - Fork 7
/
cone_search_ztf.py
354 lines (321 loc) · 15.5 KB
/
cone_search_ztf.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
# Author: Igor Andreoni
# ZTF alert cone search using Kowalski, returns summary table
import glob
import requests
import datetime
import numpy as np
from astropy.io import ascii
from astropy.table import Table
from astropy.time import Time
from penquins import Kowalski
def api(method, endpoint, data=None, token=None):
"""API request"""
headers = {'Authorization': f'{token}'}
response = requests.request(method, endpoint, json=data, headers=headers)
return response
def query_kowalski_cone(ra, dec, search_rad, jd_start=2458194, jd_end=2459406,
programid_list=[1], drb_min=0.64, ndethist_min=2, token=None):
"""
Cone search of ZTF alerts using Kowalski
Parameters
----------
ra float
Right ascension (equatorial)
dec float
Declination (equatorial)
jd_start float
JD of the start of the search
jd_end float
JD of the end of the search
programid_list list of int
list of ZTF program IDs
drb_min
min deep real/bogus score
ndethist_min int
min number of detections >3 sigma
token str
kowalski access token
Returns
-------
info dict
query output
"""
q = {
"query_type": "cone_search",
"query": {
"object_coordinates": {
"cone_search_radius": search_rad,
"cone_search_unit": "arcmin",
"radec": {
"object1": [
ra,
dec
]
}
},
"catalogs": {
"ZTF_alerts": {
"filter": {'candidate.jd': {'$gt': jd_start, '$lt': jd_end},
'candidate.drb': {'$gt': drb_min},
'candidate.programid': {'$in': programid_list},
'candidate.ndethist': {'$gte': ndethist_min},
},
"projection": {
"objectId": 1,
"candidate.ra": 1,
"candidate.dec": 1,
"candidate.jd": 1,
"candidate.drb": 1,
"candidate.ndethist": 1,
"candidate.jdstarthist": 1,
"candidate.jdendhist": 1,
"candidate.programid": 1,
"candidate.isdiffpos": 1,
"candidate.distpsnr1": 1,
"candidate.sgscore1": 1,
"candidate.srmag1": 1,
"candidate.distpsnr2": 1,
"candidate.sgscore2": 1,
"candidate.srmag2": 1,
"candidate.distpsnr3": 1,
"candidate.sgscore3": 1,
"candidate.srmag3": 1,
"candidate.magpsf":1,
"candidate.sigmapsf":1,
"candidate.distnr":1,
"candidate.magnr":1,
"candidate.sigmagnr":1,
"candidate.fid":1
}
}
}
},
"kwargs": {
#"hint": "jd_field_rb_drb_braai_ndethhist_magpsf_isdiffpos"
}
}
response = api('POST',
f'https://kowalski.caltech.edu/api/queries',
data=q, token=token)
print(f"Using a search radius of {search_rad} arcmin")
if response.status_code == 200:
info = response.json()['data']['ZTF_alerts']['object1']
return info
else:
print("FAILED kowalski query!")
print(f'HTTP code: {response.status_code}, {response.reason}')
print(f'{response.content}')
exit()
def query_kowalski_cone_nodrb(ra, dec, search_rad, jd_start=2458194, jd_end=2459406,
programid_list=[1], rb_min=0.5, ndethist_min=2, token=None):
"""
Cone search of ZTF alerts using Kowalski
Parameters
----------
ra float
Right ascension (equatorial)
dec float
Declination (equatorial)
jd_start float
JD of the start of the search
jd_end float
JD of the end of the search
programid_list list of int
list of ZTF program IDs
rb_min
min deep real/bogus score
ndethist_min int
min number of detections >3 sigma
token str
kowalski access token
Returns
-------
info dict
query output
"""
q = {
"query_type": "cone_search",
"query": {
"object_coordinates": {
"cone_search_radius": search_rad,
"cone_search_unit": "arcmin",
"radec": {
"object1": [
ra,
dec
]
}
},
"catalogs": {
"ZTF_alerts": {
"filter": {'candidate.jd': {'$gt': jd_start, '$lt': jd_end},
'candidate.rb': {'$gt': rb_min},
'candidate.programid': {'$in': programid_list},
'candidate.ndethist': {'$gte': ndethist_min},
},
"projection": {
"objectId": 1,
"candidate.ra": 1,
"candidate.dec": 1,
"candidate.jd": 1,
"candidate.drb": 1,
"candidate.ndethist": 1,
"candidate.jdstarthist": 1,
"candidate.jdendhist": 1,
"candidate.programid": 1,
"candidate.isdiffpos": 1,
"candidate.distpsnr1": 1,
"candidate.sgscore1": 1,
"candidate.srmag1": 1,
"candidate.distpsnr2": 1,
"candidate.sgscore2": 1,
"candidate.srmag2": 1,
"candidate.distpsnr3": 1,
"candidate.sgscore3": 1,
"candidate.srmag3": 1
}
}
}
},
"kwargs": {
#"hint": "jd_field_rb_drb_braai_ndethhist_magpsf_isdiffpos"
}
}
response = api('POST',
f'https://kowalski.caltech.edu/api/queries',
data=q, token=token)
print(f"Using a search radius of {search_rad} arcmin")
if response.status_code == 200:
info = response.json()['data']['ZTF_alerts']['object1']
return info
else:
print("FAILED kowalski query!")
print(f'HTTP code: {response.status_code}, {response.reason}')
print(f'{response.content}')
exit()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='ZTF alert cone search \
using Kowalski')
parser.add_argument('radec', metavar='RA, Dec', type=str, nargs='+',
help='RA and Dec (degrees)')
parser.add_argument('-r', dest='radius', type=float,
required=False, help='Search radius (arcmin)',
default=1)
parser.add_argument('--date-start', dest='date_start', type=str,
required=False,
help="Start date of the query, in ISO format. \
Example: '2017-08-17 12:41:04.4'", default=None)
parser.add_argument('--date-end', dest='date_end', type=str,
required=False,
help="End date of the query, in ISO format. \
Example: '2017-08-18 12:00:00.0'", default=None),
parser.add_argument('--ndethist', dest='ndethist_min', type=int,
required=False,
help='Minimum number of detections', default=1)
parser.add_argument('--pid', dest='programid_list', nargs='+',
required=False,
help='ZTF program IDs', default=[1,2,3])
parser.add_argument('--drb', dest='drb_min', type=float,
required=False,
help='Minimum drb score', default=0.64)
parser.add_argument('--out', dest='out', type=str,
required=False,
help='Output filename: if given, a CSV file will be\
created', default=None)
args = parser.parse_args()
# RA and Dec
ra, dec = float(args.radec[0]), float(args.radec[1])
# Radius
search_rad = args.radius
# Dates
if args.date_start is None:
date_start = Time.now() - datetime.timedelta(days=1)
else:
try:
date_start = Time(args.date_start, format='iso')
except ValueError:
print("Invalid start date. It must be a string in ISO format.")
print("Example: '2017-08-17 12:41:04.4'")
exit()
if args.date_end is None:
date_end = Time.now()
else:
try:
date_end = Time(args.date_end, format='iso')
except ValueError:
print("Invalid end date. It must be a string in ISO format.")
print("Example: '2018-01-01 12:41:04.4'")
exit()
# Program IDs
programid_list = [int(p) for p in args.programid_list]
# Read the secrets
secrets = ascii.read('/Users/igor/.secrets.csv', format='csv')
username = secrets['kowalski_user'][0]
password = secrets['kowalski_pwd'][0]
# Get the token
data={
"username": username,
"password": password
}
response = requests.request("POST",
'https://kowalski.caltech.edu/api/auth',
json=data)
token = response.json()['token']
# Query Kowalski
info_clean = query_kowalski_cone(ra, dec, search_rad, jd_start=date_start.jd, jd_end=date_end.jd,
programid_list=programid_list, drb_min=args.drb_min, ndethist_min=args.ndethist_min,
token=token)
# Object IDs
object_ids = set([c['objectId'] for c in info_clean])
if len(object_ids) == 0:
print("No candidates in the 'cleaned' alert stream!")
exit()
# Initialize dict for summary info
summary_info = {}
for object_id in object_ids:
summary_info[object_id] = {}
summary_info[object_id]["ra"] = np.mean([c['candidate']['ra'] for c in info_clean if c['objectId']==object_id])
summary_info[object_id]["dec"] = np.mean([c['candidate']['dec'] for c in info_clean if c['objectId']==object_id])
summary_info[object_id]["ndethist"] = np.max([c['candidate']['ndethist'] for c in info_clean if c['objectId']==object_id])
summary_info[object_id]["ndethist"] = np.max([c['candidate']['ndethist'] for c in info_clean if c['objectId']==object_id])
summary_info[object_id]["jdstarthist"] = np.min([c['candidate']['jdstarthist'] for c in info_clean if c['objectId']==object_id])
summary_info[object_id]["jdendhist"] = np.max([c['candidate']['jdendhist'] for c in info_clean if c['objectId']==object_id])
summary_info[object_id]["max_programid"] = np.max([c['candidate']['programid'] for c in info_clean if c['objectId']==object_id])
diff_pos = [c['candidate']['isdiffpos'] for c in info_clean if c['objectId']==object_id]
if "t" in diff_pos:
summary_info[object_id]["includes_diff_pos"] = 1
else:
summary_info[object_id]["includes_diff_pos"] = 0
if "f" in diff_pos:
summary_info[object_id]["includes_diff_neg"] = 1
else:
summary_info[object_id]["includes_diff_neg"] = 0
# Find one alert for crossmatches
for alert in info_clean:
if alert['objectId']==object_id:
summary_info[object_id]["distpsnr1"] = alert['candidate']['distpsnr1']
summary_info[object_id]["sgscore1"] = alert['candidate']['sgscore1']
summary_info[object_id]["srmag1"] = alert['candidate']['srmag1']
summary_info[object_id]["distpsnr2"] = alert['candidate']['distpsnr2']
summary_info[object_id]["sgscore2"] = alert['candidate']['sgscore2']
summary_info[object_id]["srmag2"] = alert['candidate']['srmag2']
summary_info[object_id]["distpsnr3"] = alert['candidate']['distpsnr3']
summary_info[object_id]["sgscore3"] = alert['candidate']['sgscore3']
summary_info[object_id]["srmag3"] = alert['candidate']['srmag3']
break
# Create a nice table
names = ['name'] + list(summary_info[list(summary_info.keys())[0]].keys())
columns = []
for k in summary_info[list(summary_info.keys())[0]].keys():
columns.append([summary_info[object_id][k] for object_id in object_ids])
columns = [list(object_ids)] + columns
tab = Table(columns, names=names)
print(f"Done!")
print(tab)
if args.out is not None:
outname = args.out
tab.write(outname, format='csv', overwrite=True)
print(f"Created output file: {outname}")
# Print and say goodbye
print(f"Found {len(tab)} objects in ZTF data")