-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathRapidLco.py
executable file
·297 lines (276 loc) · 12.2 KB
/
RapidLco.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: ampel/contrib/hu/t3/rapidBase
# License: BSD-3-Clause
# Author: jnordin@physik.hu-berlin.de
# Date: 05.08.2019
# Last Modified Date: 20.08.2020
# Last Modified By: Jakob van Santen <jakob.van.santen@desy.de>
import datetime
from typing import Any
import requests
from ampel.contrib.hu.t3.RapidBase import RapidBase
from ampel.secret.NamedSecret import NamedSecret
from ampel.util.freeze import recursive_unfreeze
from ampel.view.TransientView import TransientView
from ampel.ztf.util.ZTFIdMapper import to_ztf_id
class RapidLco(RapidBase):
"""
Submit LCO triggers for candidates passing criteria.
"""
# LCO trigger info
lco_api: NamedSecret[str] = NamedSecret[str](label="lco/jnordin")
# A dict of LCO API triggers to be sent for each SN that fulfills all
# criteria. Assumed to have the following key content:
# 'trigger_name': {'start_delay':X (days), 'end_delay':Y (days), 'api_form':Z}
# Where the start and end delays define the allowed LCO time range and the api_form provides the request to be submitted.
# The following keys of the api_form will be changed: name, target:name, target:ra, target:dec, windows:end, windows:start
lco_payload: dict[str, Any] = {
"lco_u_rapid": {
"start_delay": 0,
"end_delay": 1,
"api_form": {
"group_id": "ZTF_rapid_sample",
"proposal": "SUPA2021A-002",
"ipp_value": 1.05,
"operator": "SINGLE",
"observation_type": "RAPID_RESPONSE",
"requests": [
{
"acceptability_threshold": 90,
"configurations": [
{
"type": "EXPOSE",
"instrument_type": "1M0-SCICAM-SINISTRO",
"instrument_configs": [
{
"bin_x": 1,
"bin_y": 1,
"exposure_count": "1",
"exposure_time": "750",
"mode": "full_frame",
"rotator_mode": "",
"extra_params": {"defocus": 0},
"optical_elements": {"filter": "up"},
},
{
"bin_x": 1,
"bin_y": 1,
"exposure_count": "1",
"exposure_time": "60",
"mode": "full_frame",
"rotator_mode": "",
"extra_params": {"defocus": 0},
"optical_elements": {"filter": "gp"},
},
],
"acquisition_config": {
"mode": "OFF",
"extra_params": {},
},
"guiding_config": {
"mode": "ON",
"optional": True,
"extra_params": {},
},
"target": {
"name": "ZTF_rapid_sample",
"type": "ICRS",
"ra": "x",
"dec": "y",
"proper_motion_ra": 0,
"proper_motion_dec": 0,
"epoch": 2000,
"parallax": 0,
},
"constraints": {
"max_airmass": 1.6,
"min_lunar_distance": 30,
},
}
],
"windows": [{"end": "x"}],
"location": {"telescope_class": "1m0"},
}
],
},
},
"lco_u_queue": {
"start_delay": 1,
"end_delay": 3,
"api_form": {
"group_id": "ZTF_rapid_follow",
"proposal": "SUPA2021A-002",
"ipp_value": 1.05,
"operator": "SINGLE",
"observation_type": "NORMAL",
"requests": [
{
"acceptability_threshold": 90,
"configurations": [
{
"type": "EXPOSE",
"instrument_type": "1M0-SCICAM-SINISTRO",
"instrument_configs": [
{
"bin_x": 1,
"bin_y": 1,
"exposure_count": "2",
"exposure_time": "500",
"mode": "full_frame",
"rotator_mode": "",
"extra_params": {"defocus": 0},
"optical_elements": {"filter": "up"},
},
{
"bin_x": 1,
"bin_y": 1,
"exposure_count": "1",
"exposure_time": "30",
"mode": "full_frame",
"rotator_mode": "",
"extra_params": {"defocus": 0},
"optical_elements": {"filter": "gp"},
},
],
"acquisition_config": {
"mode": "OFF",
"extra_params": {},
},
"guiding_config": {
"mode": "ON",
"optional": True,
"extra_params": {},
},
"target": {
"name": "ZTF_rapid_follow",
"type": "ICRS",
"ra": "x",
"dec": "x",
"proper_motion_ra": 0,
"proper_motion_dec": 0,
"epoch": 2000,
"parallax": 0,
},
"constraints": {
"max_airmass": 1.6,
"min_lunar_distance": 30,
},
}
],
"windows": [{"end": "x", "start": "x"}],
"location": {"telescope_class": "1m0"},
}
],
},
},
}
def react(
self, tran_view: TransientView, info: None | dict[str, Any]
) -> tuple[bool, dict[str, Any]]:
"""
Send a trigger to the LCO
"""
if not isinstance(info, dict):
return False, {"success": False}
assert isinstance(tran_view.id, int)
transient_name = to_ztf_id(tran_view.id)
# Look for coordinates in the T2 info dicts.
# Assuming ra and dec exists in there
ra, dec = None, None
for t2info in info.values():
if "ra" in t2info:
ra = t2info["ra"]
if "dec" in t2info:
dec = t2info["dec"]
if ra is None or dec is None:
# Look at the response
self.logger.info(
"No LCO trigger: Could not find ra/dec",
extra={
"target": transient_name,
},
)
# Step through all LCO submit forms
success = True # Will be set to false if any submit fails
submitted = []
responses = []
for submit_name, submit_info in self.lco_payload.items():
# Create submit dictionary
react_dict = recursive_unfreeze(submit_info["api_form"])
# Update with information
react_dict["name"] = submit_name + "_" + transient_name
react_dict["requests"][0]["configurations"][0]["target"]["name"] = (
transient_name
)
react_dict["requests"][0]["configurations"][0]["target"]["ra"] = str(ra)
react_dict["requests"][0]["configurations"][0]["target"]["dec"] = str(dec)
# Some keys are not necessarily there
timenow = datetime.datetime.now(tz=datetime.timezone.utc)
if "start" in react_dict["requests"][0]["windows"][0]:
dtime = datetime.timedelta(days=submit_info["start_delay"])
react_dict["requests"][0]["windows"][0]["start"] = "%s" % (
timenow + dtime
)
if "end" in react_dict["requests"][0]["windows"][0]:
dtime = datetime.timedelta(days=submit_info["end_delay"])
react_dict["requests"][0]["windows"][0]["end"] = "%s" % (
timenow + dtime
)
self.logger.debug(
"Starting LCO trigger",
extra={"target": transient_name, "react_dict": react_dict},
)
# Make a test to validate
testreply = requests.post(
"https://observe.lco.global/api/requestgroups/validate/",
headers={"Authorization": f"Token {self.lco_api.get()}"},
json=react_dict,
)
# Abort if we have errors
if len(testreply.json()["errors"]) > 0:
self.logger.info(
f"Validating LCO trigger fails for for {transient_name}",
extra={"target": transient_name, "react_dict": react_dict},
)
success = False
continue
# Submit full trigger
response = requests.post(
"https://observe.lco.global/api/requestgroups/",
headers={"Authorization": f"Token {self.lco_api.get()}"},
json=react_dict,
)
# Check whether this was successful
try:
response.raise_for_status()
except requests.exceptions.HTTPError:
self.logger.info(
f"Submit LCO fails for {transient_name}",
extra={
"target": transient_name,
"react_dict": react_dict,
"response": response.content,
},
)
success = False
# Look at the response
self.logger.info(
f"Submit LCO succeeds for {transient_name}",
extra={
"target": transient_name,
"react_dict": react_dict,
"response": response.json(),
},
)
submitted.append(react_dict)
responses.append(response.json())
# Document what we did
jcontent = {
"reactDicts": submitted,
"success": success,
"lcoResponses": responses,
}
# Note: out-commented because unused
# jup = JournalAttributes(extra=jcontent)
return success, jcontent