RunTwilightRVStandard

Bases: KPFTranslatorFunction

Executes a twilight observation of one a selected RV standard star. This script performs all necessary instrument actions from sart up to shut down.

Sequence of Actions (and who performs them) once this script is invoked: - (Script): run StartOfNight - (Script): Start Sci OB + Slew Cal - (OA): Slew to target - (OA): Perform autofoc - (Script): Obtain science data - (OA): Release to regular use, OA can park or do other tasks - (Script): run EndOfNight - (Script): run Calibration

Source code in kpf/scripts/RunTwilightRVStandard.py
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
class RunTwilightRVStandard(KPFTranslatorFunction):
    '''Executes a twilight observation of one a selected RV standard star. This
    script performs all necessary instrument actions from sart up to shut down.

    Sequence of Actions (and who performs them) once this script is invoked:
    - (Script): run StartOfNight
    - (Script): Start Sci OB + Slew Cal
    - (OA): Slew to target
    - (OA): Perform autofoc
    - (Script): Obtain science data
    - (OA): Release to regular use, OA can park or do other tasks
    - (Script): run EndOfNight
    - (Script): run Calibration
    '''
    @classmethod
    def pre_condition(cls, args, logger, cfg):
        pass

    @classmethod
    @add_script_log(Path(__file__).name.replace(".py", ""))
    def perform(cls, args, logger, cfg):

        # ---------------------------------
        # Select Target
        # ---------------------------------
        horizon = 30*u.deg
        starlist_file = Path(f'/s/sdata1701/OBs/kpftwilight/starlist.txt')
        all_targets = rank_targets(starlist_file, horizon=horizon)
        if len(all_targets) == 0:
            log.error(f'No targets available above horizon ({horizon:.1f})')
            return

        targname = all_targets[0].targname
        sciOBfile = starlist_file.parent / f'{targname}.yaml'
        with open(sciOBfile, 'r') as f:
            sciOB = yaml.safe_load(f)

        calOBfile = Path('/s/sdata1701/OBs/kpftwilight/twilight_program_cal.yaml')
        if calOBfile.exists() is False:
            log.error(f"Could not load OB file: {calOBfile}")
            return
        with open(calOBfile, 'r') as f:
            calOB = yaml.safe_load(f)

        log_string = f"Selected: {targname} at {all_targets[0].alt():.1f}, "\
                     f"priority={all_targets[0].priority}"
        log.debug(log_string)
        if args.get('test_only', False) is True:
            print(log_string)
            return

        # ---------------------------------
        # Start Of Night
        # ---------------------------------
        msg = ["",
               "-------------------------------------------------------------",
               "Thank you for executing a KPF Twilight Stability Measurement.",
               "If you encounter urgent problems or questions contact one of",
               "the KPF SAs.  Contact info:",
               "    Josh Walawender: 808-990-4294 (cell)",
               "",
               "Please load the starlist at",
               f"{starlist_file}",
               "",
               f"Our target will be:",
               f"  {targname}",
               "",
               "If the instrument has not been in use, you will presumably",
               "need to run the Start Of Night script.  This will open the AO",
               "hatch and configure AO and KPF for observing.  This is not",
               "needed if KPF has been observing immediately prior to this.",
               "Do you wish to run the Start Of Night Script? [Y/n]",
               "-------------------------------------------------------------",
               "",
               ]
        for line in msg:
            print(line)
        user_input = input()
        if user_input.lower() in ['n', 'no', 'cancel']:
            log.warning('User opted to skip Start Of Night script')
        else:
            StartOfNight.execute({})

        SetProgram.execute({'progname': 'K444'})
        SetObserver.execute({'observer': 'OA'})

        # Wrap operations in try/except to ensure we get to end of night
        try:
            log.info(f"Configuring for Acquisition")
            ConfigureForAcquisition.execute(sciOB)

            # ---------------------------------
            # OA Focus
            # ---------------------------------
            msg = ["",
                   "-------------------------------------------------------------",
                   "The instrument is being configured now, please begin slewing",
                   "to the target. Once you are on target:",
                   " - Focus on target using autfoc",
                   " - Then place the target on the KPF PO",
                   "When those steps are done, press Enter to continue.",
                   "-------------------------------------------------------------",
                   "",
                   ]
            for line in msg:
                print(line)
            user_input = input()

            # Open an xshow for exposure status
            cmd = ['xshow', '-s', 'kpfexpose', 'EXPOSE', 'ELAPSED', 'EXPOSURE']
            xshow_proc = subprocess.Popen(cmd,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE)

            # ---------------------------------
            # Execute Observation
            # ---------------------------------
            WaitForConfigureAcquisition.execute(sciOB)
            log.info(f"Configuring for Science")
            ConfigureForScience.execute(sciOB)
            WaitForConfigureScience.execute(sciOB)

            # Execute Sequences
            check_script_running()
            set_script_keywords(Path(__file__).name, os.getpid())
            # Execute the Cal Sequence
            observations = sciOB.get('SEQ_Observations', [])
            for observation in observations:
                observation['Template_Name'] = 'kpf_sci'
                observation['Template_Version'] = sciOB['Template_Version']
                observation['Gmag'] = sciOB['Gmag']
                log.debug(f"Automatically setting TimedShutter_CaHK: {sciOB['TriggerCaHK']}")
                observation['TimedShutter_CaHK'] = sciOB['TriggerCaHK']
                observation['TriggerCaHK'] = sciOB['TriggerCaHK']
                observation['TriggerGreen'] = sciOB['TriggerGreen']
                observation['TriggerRed'] = sciOB['TriggerRed']
                observation['TriggerGuide'] = (sciOB.get('GuideMode', 'off') != 'off')
                # Wrap in try/except so that cleanup happens
                try:
                    ExecuteSci.execute(observation)
                except Exception as e:
                    log.error("ExecuteSci failed:")
                    log.error(e)
            clear_script_keywords()
        except Exception as e:
            log.error(f'Encountered exception during operations')
            log.error(e)
            log.error(traceback.format_exc())

        # Cleanup
        CleanupAfterScience.execute(sciOB)

        # Close xshow
        xshow_proc.terminate()

        # ---------------------------------
        # Done with telescope
        # ---------------------------------
        log.debug('Observations complete. Alerting OA.')

        msg = ["",
               "-------------------------------------------------------------",
               "Observation complete. Do you wish to run end of night and",
               "perform a calibration set? Please answer yes if this is a",
               "morning twilight or if some other instrument will be observing.",
               "",
               "Regardless of the choice below, you may perform other tasks as",
               "needed after answering.",
               "",
               "Run End of Night and then start calibrations? [Y/n]",
               "-------------------------------------------------------------",
               "",
               ]
        for line in msg:
            print(line)
        user_input = input()
        if user_input.lower() in ['y', 'yes']:
            EndOfNight.execute({})
            RunCalOB.execute(calOB)

        # Send email
        email = {
                 'To': 'kpf_info@keck.hawaii.edu,ahoward@caltech.edu,sphalverson@gmail.com',
#                  'To': 'jwalawender@keck.hawaii.edu',
                 'Subject': 'KPF Twilight Program Completed',
                 'Message': 'A KPF twilight observation has been completed.'}
        SendEmail.execute(email)
        print()
        print('Script complete.')
        time.sleep(120)


    @classmethod
    def post_condition(cls, args, logger, cfg):
        pass

    @classmethod
    def add_cmdline_args(cls, parser, cfg=None):
        parser.add_argument('--test', dest="test_only",
                            default=False, action="store_true",
                            help='Only execute the target selection code')
        return super().add_cmdline_args(parser, cfg)