def main(): # Set up logging config.init_logger() # Listen for GCNs until the program is interrupted # (killed or interrupted with control-C). gcn.listen(handler=process_gcn)
def run_full_test(): logger.info('Started end-to-end testing') global observability_plot global skymap_plot global sms global testing global HasNS_thresh global client_list global channel_list observability_plot = False skymap_plot = False sms = False testing = True HasNS_thresh = 0.0 global gcnbot_client global gcnbot_channel global gcnbot_id gcnbot_client, gcnbot_id, gcnbot_channel = initialise_bot('gcnbot-test', 'token', name='testbot') client_list = [gcnbot_client] channel_list = [gcnbot_channel] logger.info('Listening for alerts...') gcn.listen(handler=process_gcn)
def pygcn_monitor(self, func, server='local', port='public'): """serve root elements via pygcn Parameters ---------- func : `function` function that was called once a gcn was received server: `str` pygcn server, defined in utils.gcn_server() options: local, eApps, Atlantic_2, Atlantic_3, Linode port: `str` pygcn port, defined in utils.gcn_server() options: public, LVC, AMON Examples -------- >>> from kobe import triggers >>> a = triggers() >>> a.pygcn_monitor(server='local',port='public') """ try: import gcn except: self.logger.info ('Error: no pygcn installed') return kwargs = self.setkeys(kwargs) if kwargs is None: return server, port = self.gcn_server(kwargs['server'], kwargs['port']) if server is None: return gcn.listen(handler = func, host=server, port=port)
def run_real(): logger.info('gcnbot deployed') global observability_plot global skymap_plot global sms global testing global HasNS_thresh global client_list global channel_list observability_plot = True skymap_plot = False sms = True testing = False HasNS_thresh = 0.0 global gcnbot_client global gcnbot_channel global gcnbot_id sydgw_client, sydgw_id, sydgw_channel = initialise_bot('gcnbot', 'sydgw-token', name='sydgw-bot') jagwar_client, jagwar_id, jagwar_channel = initialise_bot( 'alerts', 'jagwar-token', name='jagwar-bot') growth_client, growth_id, growth_channel = initialise_bot('alerts', 'growth-token', name='gcnbot') gcnbot_client, gcnbot_id, gcnbot_channel = initialise_bot('gcnbot-test', 'token', name='testbot') client_list = [growth_client, jagwar_client, sydgw_client, gcnbot_client] channel_list = [ growth_channel, jagwar_channel, sydgw_channel, gcnbot_channel ] logger.info('Listening for alerts...') gcn.listen(handler=process_gcn)
def main(): # Process a fits file or listen for GCNs until the program is interrupted # (killed or interrupted with control-C). global args global params args = parseargs() if args.graceid: urllib.request.urlretrieve( 'https://gracedb.ligo.org/apiweb/superevents/' + args.graceid + '/files/', "index.html") with open('index.html') as f: a = json.load(f) xmlfiles = [key for key in a.keys() if key.endswith('xml')] latestxml = sorted(xmlfiles)[-1] urllib.request.urlretrieve( 'https://gracedb.ligo.org/apiweb/superevents/' + args.graceid + '/files/' + latestxml, latestxml) payload = open(latestxml, 'rb').read() root = lxml.etree.fromstring(payload) process_gcn(payload, root) return else: gcn.listen(handler=process_gcn, port=8099)
slack_client.chat_postMessage(channel=SLACK_CHANNEL, text="No Galaxies Assigned") if plot_map: ax.add_feature(Nightshade(datetime.utcnow(), alpha=0.2)) plt.title("Map of Observable Sites") plt.savefig("map.png") if send_slack: slack_client.files_upload(channels=SLACK_CHANNEL, file="map.png", title=params['GraceID']) filename = download_file(params['skymap_fits'], cache=True) skyplot([filename, '--annotate', '--geo', '--contour', '50', '90']) plt.savefig("hp.png") if send_slack: slack_client.files_upload(channels=SLACK_CHANNEL, file="hp.png", title=params['GraceID']) return print("Starting Listener...") if send_slack: slack_client.chat_postMessage(channel=SLACK_CHANNEL, text="Starting Listener...") if test_alert: while True: print("starting test") import lxml.etree payload = open('MS181101ab-1-Preliminary.xml', 'rb').read() root = lxml.etree.fromstring(payload) process_gcn(payload, root) time.sleep(300) gcn.listen(handler=process_gcn)
def listen(): gcn.listen(handler=handle)
#save mjd to file open(os.path.join(outfolder,trigger_id+'_eventMJD.txt'), 'w').write(str(trigger_mjd)) # Read sky map skymap, header = get_skymap(root,outfolder,trigger_id) #Fire off analysis code if skymap_url.split('/')[-1] == 'bayestar.fits.gz': args = ['python', 'recycler.py', '--triggerpath='+config.trigger_outpath, '--triggerid='+trigger_id, '--mjd='+str(trigger_mjd)] print 'ARGSSSSSSSSSSSSSSSSSSSSS' print args subprocess.Popen(args) #Need to send an email here saying analysis code was fired print 'Finished downloading, fired off job, listening again...' import logging # Set up logger logging.basicConfig(level=logging.INFO) # Listen for GCNs until the program is interrupted # (killed or interrupted with control-C). print 'Listening...' gcn.listen(host='68.169.57.253', port=8096, handler=process_gcn) #IF YOU END UP HERE THEN SEND AN EMAIL AND REBOOT
mocfootprint = moc.serialize(format='json') with io.BytesIO() as ll: moc_string = json.dumps(mocfootprint) ll.write(moc_string.encode()) ll.seek(0) s3.upload_fileobj(ll, Bucket=config.AWS_BUCKET, Key=lat_moc_upload_path) print('Successfully Created LAT MOC File for {}'.format( gwa.graceid)) except: print('ERROR in LAT MOC creation for {}'.format( gwa.graceid)) ################### if not run_test: db.session.add(gwa) print("commiting\n") db.session.commit() else: print('Sleeping, you should kill') time.sleep(20) else: print("\nNot Ligo, Don't Care\n") print('LISTENING') gcn.listen(host='45.58.43.186', port=8099, handler=handler)
ra, dec = function.getFermiPointing(tos) pointing_footprint=function.makeLATFoV(ra,dec) skycoord = SkyCoord(pointing_footprint, unit="deg", frame="icrs") moc = MOC.from_polygon_skycoord(skycoord, max_depth=9) mocfootprint = moc.serialize(format='json') with io.BytesIO() as ll: moc_string = json.dumps(mocfootprint) ll.write(moc_string.encode()) ll.seek(0) s3.upload_fileobj(ll, Bucket=config.AWS_BUCKET, Key=lat_moc_upload_path) print('Successfully Created LAT MOC File for {}'.format(gwa.graceid)) except: print('ERROR in LAT MOC creation for {}'.format(gwa.graceid)) ################### if not run_test: db.session.add(gwa) print("commiting\n") db.session.commit() else: print('Sleeping, you should kill') time.sleep(20) else: print("\nNot Ligo, Don't Care\n") print('Listening!') gcn.listen(handler=handler)
s.sendmail(me, y, msg.as_string()) s.quit() print 'Im alive email sent...' Timer(43200,imAliveEmail).start() return if config.mode.lower() == 'test': pass elif config.mode.lower() == 'observation': pass else: KeyError('checkevent_config.py Mode must be set to either test or observation.\nExiting...') import logging # Set up logger logging.basicConfig(level=logging.INFO) #Start timer - use threading to say I'm Alive print 'Started Threading' imAliveEmail() # Listen for GCNs until the program is interrupted # (killed or interrupted with control-C). print 'Listening...' gcn.listen(host='68.169.57.253', port=8096, handler=process_gcn) #gcn.listen(host='68.169.57.253', port=8096, handler=process_gcn,im_alive_filename='/data/des41.a/data/desgw/maininjector/imalivetest.txt') #IF YOU END UP HERE THEN SEND AN EMAIL AND REBOOT
ra = -999 dec = -999 err = 0 if gcn_type in grb_full: try: ra = float(root[2].find('.//{*}C1').text) dec = float(root[2].find('.//{*}C2').text) err = float(root[2].find('.//{*}Error2Radius').text) except: pass if ra == -999: payload = f'GRB Notice: burst at {event_time} (approx. {obt_time} OBT), position is unavailable or unrecognised at the moment \n\n\n'+payload else: offset_at_evt, min_sep, at_time = check_plan(obt_time, ra, dec) buff = f'GRB Notice: burst at {event_time} (approx. {obt_time} OBT), position ({ra:.4f},{dec:.4f} with error radius {err:.2f} degree)\n' pos = SkyCoord(ra=ra, dec=dec, frame="fk5", unit="deg") l, b = pos.galactic.l.degree, pos.galactic.b.degree half = 'RU' if l>180.: half = 'DE' buff += f'Galactic (l,b) = ({l:.4f},{b:.4f}), on {half} side\n' if offset_at_evt!=-999: buff += f'Angle between tel.axis and burst is {offset_at_evt:.1f}\n' if min_sep!=-999: buff += f'In next 24h will pass in {min_sep:.1f} degrees in {(at_time/3600):.1f} hours\n' payload = buff + '\n\n\n'+payload sent_email(subject, payload) # Listen for VOEvents until killed with Control-C. gcn.listen(handler=parse_GCN)
parser.add_option('-p', '--port', help='Port to connect', action='store', dest='port', type='int', default=8099) parser.add_option('--scheduler-host', help='Hostname of scheduler', action='store', dest='scheduler_host', default='localhost') parser.add_option('--scheduler-port', help='Port number of scheduler', action='store', dest='scheduler_port', type='int', default=5557) parser.add_option('-f', '--fake', help='Initiate fake trigger', action='store_true', dest='is_fake', default=False) parser.add_option('--ra', help='RA', action='store', dest='ra', type='float', default=0.0) parser.add_option('--dec', help='Dec', action='store', dest='dec', type='float', default=0.0) (options,args) = parser.parse_args() scheduler_host = options.scheduler_host scheduler_port = options.scheduler_port base_path = options.base_path favor2 = Favor2() # TODO: make it configurable gracedb_username='******' gracedb_password='******' if options.is_fake: print "Initiating fake trigger at RA=%g Dec=%g" % (options.ra, options.dec) favor2.query("INSERT INTO scheduler_targets (ra, dec, name, type, timetolive, priority) VALUES (%s, %s, %s, %s, %s, 10) RETURNING id", (options.ra, options.dec, 'test', 'Swift', 3600), simplify=True) # We should also inform the scheduler that new high-priority target has been added message_to_scheduler('reschedule') else: print "Listening for VOEvents at %s:%d" % (options.host, options.port) print "Serving to scheduler at %s:%d" % (scheduler_host, scheduler_port) gcn.listen(host=options.host, port=options.port, handler=gcn_handler)
} for key, value in params.items(): print(key, '=', value) msg = '{msg}\n\ **{key}** = {value}'.format(msg=msg, key=key, value=value) try: pos2d = root.find('.//{*}Position2D') ra = float(pos2d.find('.//{*}C1').text) dec = float(pos2d.find('.//{*}C2').text) radius = float(pos2d.find('.//{*}Error2Radius').text) print('ra = {:g}, dec={:g}, radius={:g}'.format(ra, dec, radius)) msg = '{msg}\n\ Coord data available!\n\ RA={ra}\n\ DE={de}\n\ EB={eb}\n'.format(msg=msg, ra=ra, de=dec, eb=radius) except AttributeError: print("no coords") msg = msg + '\nNo coord data' send(msg, my_handle, my_token) if __name__ == "__main__": logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) send( 'GCN Alert system starting at {now}'.format( now=dt.datetime.now().isoformat()), my_handle, my_token) gcn.listen(handler=gcn_handler)
dataf = create_dataframe(finaldictsorted, ra_incontourlist, dec_incontourlist, probs_incontourlist, finalgalnamelist, dist_incontourlist, pdist_incontourlist1, Bmag_incontourlist, Slum_incontourlist1, contourlist, cumsumprobs) jsonlist.append(dataf[[ 'Galaxy name', 'Galaxy probability score', 'RA (degrees)', 'Dec (degrees)', 'Location probability score', 'Distance (Mpc)', 'Distance probability score', 'B magnitude', 'B luminosity probability score', 'Cumulative Score' ]].to_json()) jsonlist2.append(dataf[[ 'Galaxy name', 'Galaxy probability score', 'RA (degrees)', 'Dec (degrees)', 'Location probability score', 'Distance (Mpc)', 'Distance probability score', 'B magnitude', 'B luminosity probability score', 'Cumulative Score' ]].to_csv()) #createtxt(dataf,finalgalnamelist, finaldictsorted,graceid,prelim,levelsper,d,ccc) createjsonfile(jsonlist, graceid, prelim, levelsper, d) createasciifile(jsonlist2, graceid, prelim, levelsper, d) #payload = open('S190910d-1-Preliminary.xml', 'rb').read() #root = lxml.etree.fromstring(payload) #process_gcn(payload, root) gcn.listen(handler=process_gcn, iamalive_timeout=300)
freetime = 0 cycleTime = number * timeshift + freetime length = 60 * 60 * 24 for i in np.arange(0, length, cycleTime): thetime = Time(i * u.second, format=u'cxcsec') timegrid.append(thetime) timetable = Table() timetable["date"] = timegrid return timetable def clean_table(fields): '''This function just translates the rough fields table into a nice table of SkyCoords() objects''' coords = astropy.coordinates.SkyCoord(ra=fields["ra"] * u.deg, dec=fields["dec"] * u.deg, frame="fk5") fields["coords"] = coords del fields["ra"] del fields["prob"] del fields["dec"] return fields if runmode == "run": print("the program is now ready: listening for events") sys.stdout.flush() gcn.listen(port=8096, handler=process_gcn) elif runmode == "tools": print("The tools are loaded, ready for interactive mode (use ipython)")
except: try: ra, dec = function.getFermiPointing(tos) pointing_footprint=function.makeLATFoV(ra,dec) skycoord = SkyCoord(pointing_footprint, unit="deg", frame="icrs") moc = MOC.from_polygon_skycoord(skycoord, max_depth=9) mocfootprint = moc.serialize(format='json') with io.BytesIO() as ll: moc_string = json.dumps(mocfootprint) ll.write(moc_string.encode()) ll.seek(0) s3.upload_fileobj(ll, Bucket=config.AWS_BUCKET, Key=lat_moc_upload_path) print('Successfully Created LAT MOC File for {}'.format(gwa.graceid)) except: print('ERROR in LAT MOC creation for {}'.format(gwa.graceid)) ################### if not run_test: db.session.add(gwa) print("commiting\n") db.session.commit() else: print('Sleeping, you should kill') time.sleep(20) else: print("\nNot Ligo, Don't Care\n") gcn.listen(host='127.0.0.1', port=8099, handler=handler)