def __init__(self, name, start_time=None, stop_time=None, step_size=None, center=None): """ @rtype: Ephemeris @param name: Body to build an ephemeris for @param start_time: start time of the ephemeris @type start_time: Time @param stop_time: stop time of the ephemeris @type stop_time: Time @param step_size: size of time step for ephemeris @type step_size: Quantity """ self.name = str(name) # make sure the input quantities are reasonable. if start_time is None: start_time = Time.now() self._start_time = Time(start_time, scale='utc') if stop_time is None: stop_time = Time.now() + 1.0 * units.day self._stop_time = Time(stop_time, scale='utc') step_size = step_size is None and 1 or step_size if not isinstance(step_size, Quantity): step_size *= units.day self.step_size = step_size if center is None: center = 568 self._center = center self._ephemeris = None self._elements = None self._current_time = None self._data = None
def test_timedelta(fmt, tmpdir): t1 = Time(Time.now()) t2 = Time(Time.now()) td = TimeDelta(t2 - t1, format=fmt) tree = dict(timedelta=td) assert_roundtrip_tree(tree, tmpdir)
def get_daltdaz(obj_name, ipt_lon, ipt_lat, dt=60): import astropy.units as u from astropy.time import Time if type(dt) is not u.quantity.Quantity: dt *= u.s alt_0, az_0 = get_altaz(obj_name, ipt_lon, ipt_lat, t=Time.now()) alt_1, az_1 = get_altaz(obj_name, ipt_lon, ipt_lat, t=Time.now() + dt) dalt = (alt_1 - alt_0) / dt.value daz = (az_1 - az_0) / dt.value return dalt, daz
def test_ut1_iers_auto(self): tnow = Time.now() iers_a = iers.IERS_Auto.open() tnow.delta_ut1_utc, status = iers_a.ut1_utc(tnow, return_status=True) assert status == iers.FROM_IERS_A_PREDICTION tnow_ut1_jd = tnow.ut1.jd assert tnow_ut1_jd != tnow.jd
def test_is_time(): assert time.is_time(datetime.utcnow()) is True assert time.is_time('2017-02-14 08:08:12.999') is True assert time.is_time(Time.now()) is True assert time.is_time(None) is False assert time.is_time('2016-14-14 19:08') is False
def plan(self, now=False, samefov=False): coords = self.coords names = self.names comments = self.comments if hasattr(self, 'samefov'): coords = self.samefov['coords'] names = self.samefov['names'] comments = self.samefov['comments'] if not hasattr(self, 'instants') or now == True: self.instant_list(Time.now() + self.fuse) instants = self.instants coord_prec = precess(coords, instants[0]) culmination, lixo, lixo2, alwaysup, neverup = sky_time(coord_prec, instants[0], limalt=self.limheight, rise_set=True, site=self.site, fuse=self.fuse) altura, time_rest = height_time(coord_prec, instants, limalt=self.limheight, time_left=True, site=self.site, fuse=self.fuse) self.titles = [] ra, dec = text_coord(coords) self.obs = {} for i in np.arange(len(instants)): x = np.argsort(time_rest[i].sec) k = np.where(altura[i,x] >= self.limheight) q = x[k] b = '\n\n---LT: {} (UT: {}), N_objects={} ----------------------------------------------------------------'.format(instants[i,0].iso.split(' ')[1][0:5], (instants[i,0] - self.fuse).iso.split(' ')[1][0:5], len(q)) self.titles.append(b) if len(q) == 0: self.obs[instants[i,0].iso] = {'names': np.char.array([]), 'comments': np.char.array([]), 'ra': np.char.array([]), 'dec': np.char.array([]), 'height': np.char.array([]), 'culmination': np.char.array([]), 'time_left': np.char.array([]), 'rest': []} continue self.obs[instants[i,0].iso] = {'names': names[q], 'comments': '(' + np.char.array(comments[q]) + ')', 'ra': ra[q], 'dec': dec[q], 'height': np.char.array([alt_formatter(j) for j in altura[i,q].value]), 'culmination': np.char.array(culmination[0,q].iso).rpartition(' ')[:,2].rpartition(':')[:,0],\ 'time_left': np.char.array([int_formatter(j) for j in time_rest[i,q].sec/3600.0]) + ':' + np.char.array([int_formatter(j) for j in (time_rest[i,q].sec - (time_rest[i,q].sec/3600.0).astype(int)*3600)/60]), 'rest': ['']*len(q)} for j in alwaysup: m = np.where(q == j) self.obs[instants[i,0].iso]['time_left'][m] = np.char.array('Always up')
def get_current_state_planet_or_moon(body): """ Get observational parameters for a SS target """ # get middle of night: t = Time.now().utc.datetime b = None # I don't like red exec("b = ephem.{:s}()".format(body.title())) b.compute(ephem.Date(t), epoch="2000") # fix zero padding ra = str(b.a_ra) if ra.index(":") == 1: ra = "0" + ra dec = str(b.a_dec) if dec.index(":") == 1: dec = "0" + dec elif dec.index(":") == 2 and dec[0] == "-": dec = "-0" + dec[1:] # compute rates in arcsec/s: dt = datetime.timedelta(seconds=1) b.compute(ephem.Date(t + dt), epoch="2000") ra_p1 = b.a_ra * 180.0 / np.pi * 3600.0 dec_p1 = b.a_dec * 180.0 / np.pi * 3600.0 b.compute(ephem.Date(t - dt), epoch="2000") ra_m1 = b.a_ra * 180.0 / np.pi * 3600.0 dec_m1 = b.a_dec * 180.0 / np.pi * 3600.0 ra_rate = (ra_p1 - ra_m1) / 2.0 dec_rate = (dec_p1 - dec_m1) / 2.0 return ra, dec, ra_rate, dec_rate
def get_current_state_asteroid(_asteroid, _kernel): """ :param _asteroid: :param _kernel: DE421 SPK kernel :return: current J2000 ra/dec of a moving object current J2000 ra/dec rates of a moving object if mag <= self.m_lim """ # radec, radec_dot, _ = get_asteroid_state(_asteroid, Time(str(datetime.datetime(2016,10,15,12)), # format='iso').tdb.mjd, _kernel) radec, radec_dot, _ = get_asteroid_state(_asteroid, Time.now().tdb.mjd, _kernel) # reformat ra = "{:02.0f}:{:02.0f}:{:02.3f}".format(*hms(radec[0])) dec = dms(radec[1]) # fix zero padding for dec if dec[0] >= 0: dec = "{:02.0f}:{:02.0f}:{:02.3f}".format(dec[0], abs(dec[1]), abs(dec[2])) else: dec = "{:03.0f}:{:02.0f}:{:02.3f}".format(dec[0], abs(dec[1]), abs(dec[2])) """ !!! NOTE: ra rate must be with a minus sign !!! """ ra_rate = "{:.5f}".format(-radec_dot[0]) dec_rate = "{:.5f}".format(radec_dot[1]) return ra, dec, ra_rate, dec_rate
def take_exposure(self, seconds=1.0 * u.second, filename=None, dark=False, blocking=False): """ Take an exposure for given number of seconds """ assert self.is_connected, self.logger.error("Camera must be connected for take_exposure!") assert filename is not None, self.logger.warning("Must pass filename for take_exposure") if isinstance(seconds, u.Quantity): seconds = seconds.to(u.second) seconds = seconds.value self.logger.debug( 'Taking {} second exposure on {}: {}'.format( seconds, self.name, filename)) # Set up a Timer that will wait for the duration of the exposure then copy a dummy FITS file # to the specified path and adjust the headers according to the exposure time, type. start_time = Time.now() exposure_event = Event() exposure_thread = Timer(interval=seconds, function=self._fake_exposure, args=[seconds, start_time, filename, exposure_event, dark]) exposure_thread.start() if blocking: exposure_event.wait() return exposure_event
def read(self): sum_image = None image = None count = Configuration.day_averaging_frames if self.night: count = Configuration.night_averaging_frames for i in range(count): if self.capture.grab(): if cv2.__version__[0] == '3': _, image = self.capture.retrieve(flag = self.channel) else: _, image = self.capture.retrieve(channel = self.channel) if sum_image is None: sum_image = np.int32(image) else: sum_image += np.int32(image) time = Time.now() self.checkDaytime() return np.uint8(sum_image / count), time
def setTimeConstraints(startHA=190000.0, stopHA=240000.0, date=Time.now()): ''' Set the upper and lower bounds for the constraints which are relevant to viewing time. (Does not constrain the wds list.) Takes floats for startHA, stopHA. Takes an astropy Time object for the date. ''' global constraints siderealAdjust = calcSiderealAdjustment(time = date) startRA = startHA + siderealAdjust stopRA = stopHA + siderealAdjust # Account for the 24 hour clock, and roll over if we pass midnight on either if startRA > 240000.0: startRA = startRA - 240000.0 if stopRA > 240000.0: stopRA = stopRA - 240000.0 # If the inputs are negative, also roll over those if startRA < 0: startRA = 240000.0 + startRA if stopRA < 0: stopRA = 240000.0 + stopRA # the stop time is the "upper bound", so it's first in the tuple constraints['ra'] = (stopRA, startRA)
def _get_header_dict(coords='u'): if coords == 'u': d = dict(ctype1='CAR', ctype2='CAR', cunit1='wavelength (u)', cunit2='wavelength (v)', crval1=0.0, crval2=0.0, cdelt1=conf.du, cdelt2=conf.dv, date=Time.now().isot) elif coords == 'k': d = dict(ctype1='CAR', ctype2='CAR', cunit1='wave number (k)', cunit2='wave number (k)', crval1=0.0, crval2=0.0, cdelt1=conf.dkx, cdelt2=conf.dky, date=Time.now().isot) else: d = {} return d
def parse(cls, filename, date=None, _parser=_LCHParser, **kwargs): """Parse a closure file or stream into regions. Closure files contain starlists lines followed by listings of opening blocks when laser propogation is permitted. This object parses these into individual :class:`Region` objects which contain a list of :class:`Opening` periods. Parameters ---------- filename : str or fileobj Filename or readable file object for the parser. date : :class:`~astropy.time.Time` String, or Time value which will be used to set the date for the closure file. Returns ------- regions : :class:`Regions` The parsed regions. """ date = Time.now() if date is None else date with get_readable_fileobj(filename) as stream: parser = _parser(stream.name, date, regioncls=cls) return parser(stream, **kwargs)
def parse_openings_compact_format(line, date=None): """Parse openings which are in the short format.""" # Setup the reference date date = Time.now() if date is None else date date.out_subfmt = 'date' date_str = date.iso # Match the regular expression. match = _openings_compact_re.match(line) if not match: raise ValueError("Can't parse line as opening: '{}'".format(line)) data = match.groupdict("") # Handle date types for time_key in "Start End".split(): data[time_key] = Time(datetime.datetime.utcfromtimestamp(int(data[time_key])), scale='utc') # Handle quantity types for delta_key in "Opening Closure".split(): if delta_key in data and len(data[delta_key]): if ":" in data[delta_key]: minutes, seconds = map(float,data[delta_key].split(":")) else: minutes = 0 seconds = float(data[delta_key]) data[delta_key] = minutes * u.minute + seconds * u.second return data
def parse_openings_line(line, date=None): """Parse an openings line. :param line: The text line to parse as an opening. :param date: The date for this openings line. """ # Setup the reference date date = Time.now() if date is None else date date.out_subfmt = 'date' date_str = date.iso # Match the regular expression. match = _openings_re.match(line) if not match: raise ValueError("Can't parse line as opening: '{}'".format(line)) data = match.groupdict("") # Handle date types for time_key in "Start End".split(): data[time_key] = Time("{date:s} {time:s}".format(date=date_str, time=data[time_key]), scale='utc') # Handle quantity types for delta_key in "Opening Closure".split(): if delta_key in data and len(data[delta_key]): if ":" in data[delta_key]: minutes, seconds = map(float,data[delta_key].split(":")) else: minutes, seconds = 0, float(data[delta_key]) data[delta_key] = minutes * u.minute + seconds * u.second return data
def __str__(self, obs_time=Time.now()): # not very elegant msg = "="*30+"\nName:\t\t%s\nDate:\t%s\n" %(self.name, self.time) try: msg+= "Moon Altitude:\t%s\n"%self.moonalt.hour except AttributeError: msg+= "Moon Altitude:\tNone\n" try: # let's behave like real people and use a correct iso system msg+= "Moon Azimuth:\t%s\n"%self.moonaz.degree except AttributeError: msg+= "Moon Azimuth:\tNone\n" try: msg+= "Sun Altitude:\t%s\n"%self.sunalt.hour except AttributeError: msg+= "Sun Altitude:\tNone\n" try: # let's behave like real people and use a correct iso system msg+= "Sun Azimuth:\t%s\n"%self.sunaz.degree except AttributeError: msg+= "Sun Azimuth:\tNone\n" return msg
def rsync_data_log(config,data_type): """Function to rsync data using authentication from file and log the output to a text file. """ # Construct config parameter keys to extract data locations and appropriate log file name: remote_location = config_pars[data_type]['remote_location'] local_location = config_pars[data_type]['local_location'] log_root_name = config_pars[data_type]['log_root_name'] # Contruct and execute rsync commandline: ts = Time.now() # Defaults to UTC ts = ts.now().iso.split('.')[0].replace(' ','T').replace(':','').replace('-','') log_path = path.join( config['rsync_log_directory'], config[log_root_name] + '_' + ts + '.log' ) command = 'rsync -azu ' + \ config['user_id'] + '@' + config['url'] + config[remote_location] + ' ' + \ config[local_location] + ' ' + \ '--password-file=' + config['auth'] + ' ' + \ '--log-file=' + log_path args = command.split() p = subprocess.Popen(args) p.wait() return log_path
def run(self): astroTime = Time.now() altazframe = AltAz(obstime=astroTime, location = EarthLocation(lat=49*u.deg, lon=15*u.deg, height=300*u.m)) self.sunLoc = get_sun(astroTime).transform_to(altazframe).altaz print "" print "#############################" groups = rospy.get_param('/blind/') self.groups = groups self.group = groups self.inTemp = float(self._sql('SELECT value FROM weather WHERE sensors_id = 6 order by id desc LIMIT 1;')[0][0]) self.outLum = float(self._sql('SELECT AVG(value) FROM weather WHERE sensors_id = 4 and date > %i;' %(int(time.time() - int(rospy.get_param('/blind/global/min_light_delay', 30)*60))) )[0][0]) for i, group_id in enumerate(sorted(groups)): print "=====", i, "====", group_id, "====" if 'group' in group_id: group = groups[group_id] if group['rw'] == 'd': break rospy.loginfo(">> %s" % repr(group_id)) if not self.isWindOk(): self.openBlind(group_id) rospy.logerr("blind '%s' is in wind alarm" %group_id) print "chyba vetru" else: if self.isModeAuto(group_id): print "vitr OK - automaticky mod - ", rospy.loginfo("blind '%s' is in auto" %group_id) if self.isMorgen(group_id): print "je dopoledne - ", self.areMorgenCondOk(group_id) else: print "je odpoledne - ", self.areAfternoonCondOk(group_id) #self.closeBlind(group_id) elif self.isModeManual(group_id): print "vitr OK - manualni mod - " ''' print "pohyb", group['status'] != group['status_driver'], group['status'], group['status_driver'] #if group['status'] == 'open': # print "STATUS **********************", #else: # print "STATUS ######################", #if group['status_driver'] == 'open': # print " DRIVER **********************" #else: # print " DRIVER ######################" #if group['status'] != group['status_driver']: # self.moveBlind(group_id, group['status']) ''' else: print "vitr OK - chyba modu - ", rospy.loginfo("blind '%s' is in dimised/manual" %group_id) pass print ""
def write_header_to_file(outfile, host, Nacc=8192, fpga_clk_T=1e-08, Nchan=2048, ra='NULL', dec='NULL'): ''' prepends data file with LoFASM spectrometer header. fpga_clk_T is the period of the FPGA clock in seconds Nchan is the number of FFT bins in the spectrometer Nacc is the number of accumulations averaged before dumping ''' stamp_mjd = str(Time.now().mjd).split('.') FFT_clk_cycles = Nchan >> 1 integration_time = fpga_clk_T * FFT_clk_cycles * Nacc BW = 200.0 Nbins = 2048 msec_day = 86400 * 1000 hdr_len = fmt_header_entry('108') hdr_ver = fmt_header_entry('3') hdr_sig = fmt_header_entry('LoCo') fmt_ver = fmt_header_entry('1') # data format version station = fmt_header_entry(host) fstart = fmt_header_entry('0') fstep = fmt_header_entry(str(BW/Nbins).split('.')[1]) #mhz num_bins = fmt_header_entry(str(Nbins)) mjd_day = fmt_header_entry(stamp_mjd[0]) mjd_msec = fmt_header_entry(float('.'+stamp_mjd[1])*msec_day) int_time = fmt_header_entry(str(integration_time)) ra_coord = fmt_header_entry(ra, 10) dec_coord = fmt_header_entry(dec, 10) header_str = hdr_sig + hdr_ver + hdr_len + station + num_bins + fstart +\ fstep + mjd_day + mjd_msec + int_time + fmt_ver + ra_coord + dec_coord outfile.write(header_str)
def _get_system_provenance(): """ return JSON string containing provenance for all things that are fixed during the runtime""" bits, linkage = platform.architecture() return dict( ctapipe_version=ctapipe.__version__, ctapipe_resources_version=ctapipe_resources.__version__, ctapipe_svc_path=os.getenv("CTAPIPE_SVC_PATH"), executable=sys.executable, platform=dict( architecture_bits=bits, architecture_linkage=linkage, machine=platform.machine(), processor=platform.processor(), node=platform.node(), version=platform.version(), system=platform.system(), release=platform.release(), libcver=platform.libc_ver(), num_cpus=psutil.cpu_count(), boot_time=Time(psutil.boot_time(), format='unix').isot, ), python=dict( version_string=sys.version, version=platform.python_version_tuple(), compiler=platform.python_compiler(), implementation=platform.python_implementation(), ), arguments=sys.argv, start_time_utc=Time.now().isot, )
def main(): parser = argparse.ArgumentParser(description='Perform LACosmic cleaning of images') parser.add_argument('filenames',nargs='+',help='List of files to clean.') parser.add_argument('-odir',metavar='outdir',required=True,type=str,help='Output directory for files.') #parser.add_argument('-mode',choices=['lacosmic','median'],default='lacosmic',help='Specify mode of operation (default=lacosmic)') parser.add_argument('-sclip',metavar='sigclip',type=float,default=5,help='Laplacian-to-noise limit for cosmic ray detection. Lower values will flag more pixels as cosmic rays (default=5).') parser.add_argument('-sfrac',metavar='sigfrac',type=float,default=0.3,help='Fractional detection limit for neighboring pixels. For cosmic ray neighbor pixels, a Laplacian-to-noise detection limit of sigfrac * sigclip will be used. (default=0.3).') parser.add_argument('-objlim',type=float,default=5,help='Minimum contrast between Laplacian image and the fine structure image. Increase this value if cores of bright stars are flagged as cosmic rays (default=5).') parser.add_argument('-satlevel',type=float,default=65535,help='Saturation level of the image (electrons). This value is used to detect saturated stars and pixels at or above this level are added to the mask (default=65535)') parser.add_argument('-niter',type=int,default=5,help='umber of iterations of the LA Cosmic algorithm to perform (default=5).') #parser.add_argument('-thresh',metavar='threshold',type=float,default=5,help='Threshold for detecting cosmic rays [median] (default=5).') #parser.add_argument('-mbox',type=float,default=11,help='Median box for detecting cosmic rays [mbox] (default=11).') parser.add_argument('-njobs',type=int,default=1,help='Process images in parallel. "-1" is all CPUs (default=1).') parser.add_argument('--c',action='store_true',help='Clobber (overwrite) on output') args = parser.parse_args() ccds = (CCDData.read(fname,unit='adu') for fname in args.filenames) with Parallel(args.njobs,verbose=11) as parallel: cleaned = parallel(delayed(cosmicray_lacosmic)(ccd,sigclip=args.sclip,sigfrac=args.sfrac,niter=args.niter,objlim=args.objlim,satlevel=args.satlevel) for ccd in ccds) outfiles = (os.path.join(args.odir,os.path.basename(fname)) for fname in args.filenames) for hdu,outfile in zip(cleaned,outfiles): if isinstance(hdu,CCDData): hdu = hdu.to_hdu(hdu_mask=None,hdu_uncertainty=None) header = hdu[0].header header.add_history('clean.py - %s' % Time(Time.now(),format='fits')) header['CLEANED'] = (True,'Cleaned with LACosmics') header['CLNMTHD'] = (CLNMTHD,'Method used to clean') try: hdu.writeto(outfile,overwrite=args.c) except OSError as e: raise OSError("File '%s' already exists. Re-run with --c flag to overwrite existing files." % outfile) from e
def _get_goes_sat_num(self, start, end): """Parses the query time to determine which GOES satellite to use.""" goes_operational = { 2: TimeRange('1980-01-04', '1983-05-01'), 5: TimeRange('1983-05-02', '1984-08-01'), 6: TimeRange('1983-06-01', '1994-08-19'), 7: TimeRange('1994-01-01', '1996-08-14'), 8: TimeRange('1996-03-21', '2003-06-19'), 9: TimeRange('1997-01-01', '1998-09-09'), 10: TimeRange('1998-07-10', '2009-12-02'), 11: TimeRange('2006-06-20', '2008-02-16'), 12: TimeRange('2002-12-13', '2007-05-09'), 13: TimeRange('2006-08-01', '2006-08-01'), 14: TimeRange('2009-12-02', '2010-11-05'), 15: TimeRange('2010-09-01', Time.now()), } sat_list = [] for sat_num in goes_operational: if ((start >= goes_operational[sat_num].start and start <= goes_operational[sat_num].end and (end >= goes_operational[sat_num].start and end <= goes_operational[sat_num].end))): # if true then the satellite with sat_num is available sat_list.append(sat_num) if not sat_list: # if no satellites were found then raise an exception raise Exception('No operational GOES satellites within time range') else: return sat_list
def _get_IERS_A_table(warn_update=14*u.day): """ Grab the locally cached copy of the IERS Bulletin A table. Check to see if it's up to date, and warn the user if it is not. This will fail and raise OSError if the file is not in the cache. """ if IERS_A_in_cache(): path = download_file(iers.IERS_A_URL, cache=True, show_progress=True) table = iers.IERS_A.open(path) # Use polar motion flag to identify last observation before predictions index_of_last_observation = ''.join(table['PolPMFlag_A']).index('IP') time_of_last_observation = Time(table['MJD'][index_of_last_observation], format='mjd') time_since_last_update = Time.now() - time_of_last_observation # If the IERS bulletin is more than `warn_update` days old, warn user if warn_update < time_since_last_update: warnmsg = ("Your version of the IERS Bulletin A is {:.1f} days " "old. ".format(time_since_last_update.to(u.day).value) + IERS_A_WARNING) warnings.warn(warnmsg, OldEarthOrientationDataWarning) return table else: raise OSError("No IERS A table has been downloaded.")
def verbose(config,record): '''Function to output logging information if the verbose config flag is set''' if bool(config['verbose']) == True: ts = Time.now() # Defaults to UTC ts = ts.now().iso.split('.')[0].replace(' ','T') print ts+': '+record
def current_time(flatten=False, datetime=False, pretty=False): """ Convenience method to return the "current" time according to the system If the system is running in a simulator mode this returns the "current" now for the system, which does not necessarily reflect now in the real world. If not in a simulator mode, this simply returns `current_time()` Returns: (astropy.time.Time): `Time` object representing now. """ pocs_time = os.getenv('POCSTIME') if pocs_time is not None and pocs_time > '': _time = Time(os.getenv('POCSTIME')) else: _time = Time.now() if flatten: _time = flatten_time(_time) if pretty: _time = _time.isot.split('.')[0].replace('T', ' ') if datetime: _time = _time.datetime return _time
def create_plan(self, path='.', now=False, sort='Time_left'): """ """ if not hasattr(self, 'instants') or now == True: self.instant_list(Time.now() + self.fuse) nome = '{}/Plano_{}.dat'.format(path, self.instants[0][0].iso.split(' ')[0]) self.plan() #### imprime os dados de cada objeto para cada instante #### output = open(nome, 'w') output.write('Observational Plan to the night: {}\n\n'.format(self.instants[0][0].iso.split(' ')[0])) output.write('Latitude: {} Longitude: {}\nMinimum height: {}\nField Size: {}\n\n'.format(self.site.latitude, self.site.longitude, self.limheight, self.limdist)) output.write('Height: Height above the horizons (deg)\nTleft: Time left to reach minimum height (hh:mm)\n\n') for i in np.arange(len(self.instants), dtype=np.int16): obs = self.obs[np.where(self.obs['time'] == self.instants[i,0].iso)] obs.sort(sort) output.write('\n---LT: {} (UT: {}) ----------------------------------------------------------------\n'.format(obs.meta['LT'][i].iso.rpartition(' ')[2].rpartition(':')[0], obs.meta['UT'][i].iso.rpartition(' ')[2].rpartition(':')[0])) if 'moon_h' in obs.meta: output.write('Moon height: {:4.1f}\n\n'.format(obs.meta['moon_h'][i])) for i in obs['RA_J2000_DEC', 'Height', 'Time_left', 'D_moon', 'Culmination', 'Objects', 'Comments'].pformat(max_lines=-1, max_width=-1): output.write(i + '\n') night = self.__resume_night__(self.instants[0]) night.sort('Objects') output.write('\n\n' + '-'*100 + '\n') output.write('---Observability of the Targets----------------------------------------------------------------------\n') output.write('-'*100 + '\n') for i in night['RA_J2000_DEC', 'Rise', 'Culmination', 'Set', 'Objects','Comments'].pformat(max_lines=-1, max_width=-1): output.write(i + '\n') output.close()
def observe(): """Dummy function to check if tests / docs work. """ time = Time.now() pos = get_sun(time) print('Current time: {}'.format(time)) print('Sun location: {}'.format(pos)) return time, pos
def set_time_now(self): """ """ self._time_astropy = Time.now() self._time_astropy.delta_ut1_utc = 0 self._time_astropy.location = ALMA self._ALMA_ephem.date = ephem.now()
def wait_until_files_exist(self, filenames, transition=None, callback=None, timeout=150): """ Loop to wait for the existence of files on the system """ assert filenames, self.logger.error("Filename(s) required for loop") filenames = listify(filenames) self.logger.debug("Waiting for files: {}".format(filenames)) _files_exist = False # Check if all files exist exist = [os.path.exists(f) for f in filenames] if type(timeout) is not u.Quantity: timeout = timeout * u.second end_time = Time.now() + timeout self.logger.debug("Timeout for files: {}".format(end_time)) while not all(exist): if Time.now() > end_time: # TODO Interrupt the camera properly raise error.Timeout("Timeout while waiting for files") break self.sleep() exist = [os.path.exists(f) for f in filenames] else: self.logger.debug("All files exist, now exiting loop") _files_exist = True if transition is not None: if hasattr(self, transition): trans = getattr(self, transition) trans() else: self.logger.debug("Can't call transition {}".format(transition)) if callback is not None: if hasattr(self, callback): cb = getattr(self, callback) cb() else: self.logger.debug("Can't call callback {}".format(callback)) return _files_exist
def range_time(min_date, max_date=Time.now()): time = Times( min_value=datetime.datetime(1981, 1, 1, 0, 0), max_value=datetime.datetime(datetime.datetime.utcnow().year, 1, 1, 0, 0), ) time = time.filter(lambda x: min_date < x < max_date) return time_attr(time=time)
def gps_now(): """Return the current GPS time as a float using Astropy. """ from astropy.time import Time return float(Time.now().gps)
import tnsVis from astropy.time import Time from astropy import units as u time = '2019-08-26 12:37:55' ra = '21:50:00' dec = '+10:00:53' discDate = Time.strptime(time, "%Y-%m-%d %H:%M:%S") vis = tnsVis.tnsVis(28.762, -17.879, 2363, ra, dec, discDate, airmassConstraint=2) print(vis.objVis()) diffdate = vis.time_since_discovery() diffdate.format = 'sec' print(diffdate.value) print(vis.visible_time(Time.now())) vis.plot(Time.now()) # Check if observable # Check time above airmass 2
def __init__( self, survey_name: str = None, survey_specs: dict = None, ): self.survey_name = survey_name self.load_specs(survey_specs) # read as JSON start_time = time.time() req = urllib.request.Request(self.survey_url) try: response = urllib.request.urlopen(req) except urllib.error.URLError as e: if hasattr(e, "reason"): log.error("Failed to reach server '{}': {}".format( self.survey_url, e.reason)) elif hasattr(e, "code"): log.error( "Server '{}' could not fulfill request: code {}".format( self.survey_url, e.code)) return self.raw_table = json.loads(response.read().decode()) self.update = Time.now() pulsar = [] period = [] DM = [] RA = [] Dec = [] for key in self.raw_table.keys(): pulsar.append(key) if self.ra_key is not None and self.dec_key is not None: coord = SkyCoord( extract_from_json(self.raw_table[key], self.ra_key), extract_from_json(self.raw_table[key], self.dec_key), unit=("hour", "deg"), ) else: try: coord = name_to_position(pulsar[-1]) except: log.warning( "No RA/Dec available and unable to parse pulsar '{}' to determine coordiates; assuming (0,0)" .format(pulsar[-1])) coord = SkyCoord(0 * u.deg, 0 * u.deg) RA.append(coord.ra.deg) Dec.append(coord.dec.deg) if self.period_units == "ms": try: period.append( float( extract_from_json(self.raw_table[key], self.period_key))) except TypeError: period.append(np.nan) elif self.period_units == "s": try: period.append( float( extract_from_json(self.raw_table[key], self.period_key)) * 1000) except TypeError: period.append(np.nan) DM.append(extract_from_json(self.raw_table[key], self.dm_key)) self.data = Table([ Column(pulsar, name="PSR"), Column(RA, name="RA", unit=u.deg, format="%.6f"), Column(Dec, name="Dec", unit=u.deg, format="%.6f"), Column(period, name="P", unit=u.ms, format="%.2f"), Column(DM, name="DM", unit=u.pc / u.cm**3, format="%.2f"), ]) end_time = time.time() log.info( "Read data for {} pulsars for survey '{}' in {:.2f}s at {}".format( len(self.data), self.survey_name, end_time - start_time, self.update.to_value("iso", subfmt="date_hm"), )) self.data.meta["url"] = self.survey_url self.data.meta["survey"] = self.survey_name self.data.meta["date"] = self.update
def __init__( self, survey_name: str = None, survey_specs: dict = None, ): self.survey_name = survey_name self.load_specs(survey_specs) start_time = time.time() # parse as a HTML table try: self.page = requests.get(self.survey_url) except requests.exceptions.ConnectionError: log.error("Unable to read URL '{}'".format(self.survey_url)) return self.update = Time.now() self.soup = BeautifulSoup(self.page.content, "html.parser") tables = self.soup.find_all(name="table") if self.survey_name == "SUPERB": # so far this works for SUPERB self.raw_table = tables[1].find(name="tr") elif self.survey_name == "HTRU-S Low-latitude": self.raw_table = tables[1] elif self.survey_name == "DMB" or self.survey_name == "GBT350": # this is very hacky # but the HTML seems to be missing /tr tags which breaks the parsing s = str(tables[0].findChildren("tr")[0]) sout = s.replace("<tr>", "</tr><tr>")[5:].replace("<td>", "</td><td>") soup2 = BeautifulSoup(sout, "html.parser") self.raw_table = soup2 else: self.raw_table = tables[self.table_index] self.rows = self.raw_table.find_all(name="tr") pulsar = [] period = [] DM = [] RA = [] Dec = [] for row in self.rows[self.start_row:]: # iterate over each row in the table # each row represents a pulsar (usually) cols = row.find_all(name="td") if ((len(cols) < 3) or ("pulsar" in cols[self.pulsar_column].text.lower()) or ("name" in cols[self.pulsar_column].text.lower())): continue name = cols[self.pulsar_column].text # replace some dashes with minus signs name = name.replace(chr(8211), "-") name = name.replace(chr(8722), "-") name = re.sub(r"[^J\d\+-\.A-Za-z]", "", name) if name.startswith("FRB") or len(name) == 0: continue pulsar.append(name.strip()) P = cols[self.period_column].text # special cases and unit conversion P = re.sub(r"[^\d\.]", "", P) if self.period_units == "ms": try: period.append(float(P)) except ValueError: period.append(np.nan) elif self.period_units == "s": try: period.append(float(P) * 1000) except ValueError: period.append(np.nan) try: dm = re.sub(r"[^\d\.]", "", cols[self.DM_column].text) DM.append(float(dm)) except ValueError as e: log.error("Error parsing DM value of '{}' for pulsar '{}': {}". format(cols[self.DM_column].text, pulsar[-1], e)) return if self.ra_column is None or self.dec_column is None: try: coord = name_to_position(pulsar[-1]) except: log.warning( "Unable to parse pulsar '{}' to determine coordiates; assuming (0,0)" .format(pulsar[-1])) coord = SkyCoord(0 * u.deg, 0 * u.deg) else: ra_text = re.sub(r"[^\d:\.]", "", cols[self.ra_column].text) # some of the HTML tables have a non-breaking hyphen (Unicode 8209) # instead of a hyphen # convert it dec_text = cols[self.dec_column].text if chr(8209) in dec_text: dec_text = dec_text.replace(chr(8209), "-") dec_text = re.sub(r"[^\d:\.\+-]", "", dec_text) if len(ra_text) == 0 or len(dec_text) == 0: try: coord = name_to_position(pulsar[-1]) except: log.warning( "No RA/Dec available and unable to parse pulsar '{}' to determine coordiates; assuming (0,0)" .format(pulsar[-1])) coord = SkyCoord(0 * u.deg, 0 * u.deg) else: try: coord = SkyCoord( ra_text, dec_text, frame=self.coordinate_frame, unit=(self.ra_unit, self.dec_unit), ).icrs except ValueError as e: log.error( "Error parsing position values of '{},{}' for pulsar '{}': {}" .format( cols[self.ra_column].text, cols[self.dec_column].text, pulsar[-1], e, )) return if coord is None: log.warning( "Unable to parse pulsar '{}'; assuming (0,0).".format( pulsar[-1])) coord = SkyCoord(0 * u.deg, 0 * u.deg) RA.append(coord.ra.deg) Dec.append(coord.dec.deg) if (len(pulsar) >= 2 and pulsar[-1] == pulsar[-2] and period[-1] == period[-2] and DM[-1] == DM[-2]): log.warning( f"Identified apparent duplicate:\n\t{pulsar[-1]} {period[-1]} {DM[-1]}\n\t{pulsar[-2]} {period[-2]} {DM[-2]}\nDeleting..." ) # it's a duplicate del pulsar[-1] del period[-1] del DM[-1] del RA[-1] del Dec[-1] self.data = Table([ Column(pulsar, name="PSR"), Column(RA, name="RA", unit=u.deg, format="%.6f"), Column(Dec, name="Dec", unit=u.deg, format="%.6f"), Column(period, name="P", unit=u.ms, format="%.2f"), Column(DM, name="DM", unit=u.pc / u.cm**3, format="%.2f"), ]) end_time = time.time() log.info( "Read data for {} pulsars for survey '{}' in {:.2f}s at {}".format( len(self.data), self.survey_name, end_time - start_time, self.update.to_value("iso", subfmt="date_hm"), )) self.data.meta["url"] = self.survey_url self.data.meta["survey"] = self.survey_name self.data.meta["date"] = self.update
def _start_observation_worker(self, obs_config, reload=True): """ Start observation on worker node: #. Candidate clustering #. Extraction of filterbank data #. ML classification :param dict obs_config: Observation config :param bool reload: reload service settings (default: True) """ self.logger.info("Starting observation on worker node") # reload config if reload: self.load_config() # create result dir if full processing is enabled if self.full_processing_enabled: try: util.makedirs(obs_config['result_dir']) except Exception as e: self.logger.error("Failed to create results directory") raise OfflineProcessingException("Failed to create result directory: {}".format(e)) # TAB or IAB mode if obs_config['ntabs'] == 1: obs_config['mode'] = 'IAB' trigger_output_file = "{output_dir}/triggers/data/data_00_full.hdf5".format(**obs_config) else: obs_config['mode'] = 'TAB' trigger_output_file = "{output_dir}/triggers/data/data_full.hdf5".format(**obs_config) # wait until end time + delay start_processing_time = Time(obs_config['parset']['task.stopTime']) + TimeDelta(self.delay, format='sec') self.logger.info("Sleeping until {}".format(start_processing_time.iso)) util.sleepuntil_utc(start_processing_time, event=self.stop_event) # fold pulsar if this is beam 0 and a test pulsar is being observed try: source = obs_config['parset']['task.source.name'] ref_beam = int(obs_config['parset']['task.source.beam']) # Requires access to parset if source in self.test_pulsars and (obs_config['beam'] == ref_beam): self.logger.info("Test pulsar detected: {}".format(source)) self._fold_pulsar(source, obs_config) except Exception as e: self.logger.error("Pulsar folding failed: {}".format(e)) # run calibration tools if this is a calibrator scan # these have "drift" in the source name try: source = obs_config['parset']['task.source.name'] if 'drift' in source: # split into actual source name and which beams were scanned name, beam_range = source.split('drift') # parse beam range, can be one beam or start/end beam if len(beam_range) == 2: # one beam drift_beams = [int(beam_range)] elif len(beam_range) == 4: # start and end beam sbeam = int(beam_range[:2]) ebeam = int(beam_range[2:]) drift_beams = range(sbeam, ebeam + 1) else: self.logger.error("Failed to parse beam range for calibrator scan: {}".format(source)) drift_beams = [] # run calibration tools if this is a calibrator scan of this beam if name in self.calibrators and (obs_config['beam'] in drift_beams): self.logger.info("Calibrator scan through this beam detected: {}".format(source)) self._run_calibration_tools(name, obs_config) except Exception as e: self.logger.error("Calibration tools failed: {}".format(e)) # if full processing is disabled, there is nothing more to do if not self.full_processing_enabled: self.logger.info("Full processing disabled - not running further offline processing") return # create trigger directory trigger_dir = "{output_dir}/triggers".format(**obs_config) try: util.makedirs(trigger_dir) except Exception as e: self.logger.error("Failed to create triggers directory") raise OfflineProcessingException("Failed to create triggers directory: {}".format(e)) # change to trigger directory try: os.chdir(trigger_dir) except Exception as e: self.logger.error("Failed to cd to triggers directory {}: {}".format(trigger_dir, e)) # create subdir try: util.makedirs('data') except Exception as e: self.logger.error("Failed to create triggers/data directory") raise OfflineProcessingException("Failed to create triggers/data directory: {}".format(e)) # merge the trigger files self.logger.info("Merging raw trigger files") numcand_raw = self._merge_triggers(obs_config) # Run clustering for each SB in TAB mode if enabled if self.process_sb and obs_config['mode'] == 'TAB': self.logger.info("Clustering candidates in SB mode") tstart = Time.now() # spread the SBs over the allowed number of threads # output grouped pulses file will only be generated by thread including SB00 chunks = np.array_split(range(obs_config['nsynbeams']), self.numthread) numcand_all = np.zeros(self.numthread) filterbank_prefix = "{output_dir}/filterbank/CB{beam:02d}".format(**obs_config) threads = [] self.logger.info("Starting trigger clustering with {} threads".format(self.numthread)) for ind, chunk in enumerate(chunks): # pick the SB range sbmin, sbmax = min(chunk), max(chunk) # create thread thread = threading.Thread(target=self._cluster, args=[obs_config, filterbank_prefix], kwargs={'out': numcand_all, 'sbmin': sbmin, 'sbmax': sbmax, 'ind': ind}) thread.daemon = True threads.append(thread) thread.start() # wait until all are done for thread in threads: thread.join() # gather results if self.process_sb: # each element equal numcand_grouped = int(numcand_all[0]) else: # each element is one TAB numcand_grouped = int(np.sum(numcand_all[numcand_all != -1])) # Run clustering for IAB / each TAB else: self.logger.info("Clustering candidates in {} mode".format(obs_config['mode'])) tstart = Time.now() if obs_config['mode'] == 'IAB': filterbank_file = "{output_dir}/filterbank/CB{beam:02d}.fil".format(**obs_config) numcand_grouped = self._cluster(obs_config, 0, filterbank_file) elif obs_config['mode'] == 'TAB': numcand_all = np.zeros(obs_config['ntabs']) # max numtread tabs per run; so ntabs / numthread chunks n_chunk = int(np.ceil(obs_config['ntabs'] / float(self.numthread))) chunks = np.array_split(range(obs_config['ntabs']), n_chunk) self.logger.info("Starting trigger clustering with {} chunks ""of {} threads".format(n_chunk, self.numthread)) # start the threads for tab_set in chunks: threads = [] for tab in tab_set: filterbank_file = "{output_dir}/filterbank/CB{beam:02d}_{tab:02d}.fil".format(tab=tab, **obs_config) thread = threading.Thread(target=self._cluster, args=[obs_config, filterbank_file], kwargs={'out': numcand_all, 'tab': tab}) thread.daemon = True threads.append(thread) thread.start() # wait until all are done for thread in threads: thread.join() # gather results numcand_grouped = int(np.sum(numcand_all[numcand_all != -1])) tend = Time.now() self.logger.info("Trigger clustering took {}s".format((tend - tstart).sec)) # Create one hdf5 file for entire CB if obs_config['mode'] == 'TAB': self.logger.info("Merging output HDF5 files") numcand_merged = self._merge_hdf5(obs_config, trigger_output_file) # TEMP so that IAB still works else: numcand_merged = 9999 # Run classifier if numcand_merged != 0: self.logger.info("Classifying candidates") output_prefix = self._classify(obs_config, trigger_output_file) else: self.logger.info("No candidates post-merge. Not running classifier") output_prefix = '' # Merge PDFs if numcand_merged > 0: self.logger.info("Merging classifier output files") self._merge_plots(obs_config) else: self.logger.info("No candidates found post-classifier, not creating merged PDF") # Centralize results self.logger.info("Gathering results") kwargs = {'output_prefix': output_prefix, 'data_file': trigger_output_file, 'numcand_raw': numcand_raw, 'numcand_grouped': numcand_grouped} self._gather_results(obs_config, **kwargs) self.logger.info("Finished processing of observation {output_dir}".format(**obs_config)) return
def plot_obsplan(ax_obj, utc=True): """ Sets plot parameters for plotting the trajectory of objects in sky. Args: ax_obj : Axes object over which the observatory planning plot is displayed utc : Boolean value to be determine whether UTC or Local Time is to be used for plotting Returns: None """ def sign(value): return (value > 0) - (value < 0) lat_deg = '%7.4f' % Angle(OBS_LAT + ' degrees').degree long_deg = '%7.4f' % Angle(OBS_LONG + ' degrees').degree text_ns = 'N' text_ew = 'E' if not sign(lat_deg): text_ns = 'S' if not sign(long_deg): text_ew = 'W' degree_sign = '$^\circ$' text_name = OBS_NAME + ' [+' + str(OBS_TIMEZONE) + 'h]\n' text_lat = 'Latitude : ' + lat_deg + degree_sign + text_ns text_long = ', Longitude : ' + long_deg + degree_sign + text_ew text_alt = ', Altitude : ' + str(OBS_ALT) + 'm' display_text = text_name + text_lat + text_long + text_alt + '\n' if utc: ax_obj.set_xlabel('UTC Time' + '\n\n' + 'DATE : ' + date_obs, fontsize=20) sunset = datetime_utc_sunset sunrise = datetime_utc_sunrise night_start = datetime_utc_night_start night_end = datetime_utc_night_end time_current = Time.now() else: ax_obj.set_xlabel('Local Time (IST)' + '\n\n' + 'DATE : ' + date_obs, fontsize=20) sunset = datetime_utc_sunset + +OBS_TIMEZONE * u.hour sunrise = datetime_utc_sunrise + OBS_TIMEZONE * u.hour night_start = datetime_utc_night_start + OBS_TIMEZONE * u.hour night_end = datetime_utc_night_end + OBS_TIMEZONE * u.hour time_current = Time.now() + OBS_TIMEZONE * u.hour ax_obj.grid(True) ax_obj.set_facecolor('lightgray') ax_obj.legend(shadow=True, loc=1) ax_obj.set_ylim(0, 90, 10) ax_obj.set_xlim(sunset.value, sunrise.value) ax_obj.set_title(display_text, fontsize=20) ax_obj.set_ylabel('Elevation (In Degrees)', fontsize=20) ax_obj.xaxis.set_major_locator(HourLocator()) ax_obj.xaxis.set_major_formatter(DateFormatter('%H:%M:%S')) ax_obj.tick_params(axis='both', which='major', labelsize=12) if datetime_utc_sunset.value < time_current.utc.datetime < datetime_utc_sunrise.value: ax_obj.axvline(x=time_current.value, linestyle='--', color='k') ax_obj.text(time_current.value, (ax_obj.get_ybound()[0] + ax_obj.get_ybound()[-1]) / 2, 'Current Time', rotation=-90, color='k') ax_obj.text(ax_obj.get_xbound()[0], telescope_horizon + 1, 'Telescope Horizon') ax_obj.text(ax_obj.get_xbound()[0], telescope_zenith - 2, 'Telescope Zenith') ax_obj.text(sunset.value, ax_obj.get_ybound()[1] + 6, 'Sunset', rotation=+50, color='k', fontsize=12) ax_obj.text(sunrise.value, ax_obj.get_ybound()[1] + 6, 'Sunrise', rotation=+50, color='k', fontsize=12) ax_obj.text(night_start.value, ax_obj.get_ybound()[1] + 7, 'Twilight', rotation=+50, color='k', fontsize=12) ax_obj.text(night_end.value, ax_obj.get_ybound()[1] + 7, 'Twilight', rotation=+50, color='k', fontsize=12) ax_obj.text(night_start.value, ax_obj.get_ybound()[0] + 13, 'Nautical Dusk', rotation=-90, color='k') ax_obj.text(night_end.value, ax_obj.get_ybound()[0] + 13, 'Nautical Dawn', rotation=-90, color='k') ax_obj.axvline(x=night_start.value, linestyle='--', color='k') ax_obj.axvline(x=night_end.value, linestyle='--', color='k') ax_obj.fill_between(ax_obj.get_xbound(), telescope_horizon - 0.5, telescope_horizon + 0.5, facecolor='royalblue') ax_obj.fill_between(ax_obj.get_xbound(), telescope_zenith - 0.5, telescope_zenith + 0.5, facecolor='royalblue') ax_obj.fill_between(ax_obj.get_xbound(), telescope_horizon + 0.5, telescope_zenith - 0.5, facecolor='white') ax_obj.fill_between([sunset.value, night_start.value], telescope_horizon + 0.5, telescope_zenith - 0.5, facecolor='paleturquoise') ax_obj.fill_between([night_end.value, sunrise.value], telescope_horizon + 0.5, telescope_zenith - 0.5, facecolor='paleturquoise') list_secz = [] for altitude in ax_obj.get_yticks(): if (1 / math.cos(math.radians(90 - altitude))) < 10: list_secz.append('%5.2f' % (1 / math.cos(math.radians(90 - altitude)))) else: list_secz.append('NaN') print ax_obj.get_yticks() ax2 = ax_obj.twinx() ax2.set_ylim(0, 90) ax2.set_yticks(ax_obj.get_yticks()) ax2.set_yticklabels(list_secz) ax2.set_ylabel('Airmass', fontsize=20) ax2.tick_params(axis='both', which='major', labelsize=12) ax_obj.autoscale_view() fig.autofmt_xdate() plt.show() plt.close(fig)
clearcache = True argv.remove( '--clearcache' ) # Allows --clearcache to be either before or after date items else: clearcache = False year = argv[0] month = argv[1] day = argv[2] t = Time(year + '-' + month + '-' + day + ' 20:00:00') except: print( 'Error interpreting command line arguments--will analyze data from yesterday.' ) # No arguments (or no arguments given), so default to yesterday's data to analyze mjdnow = Time.now().mjd t = Time(mjdnow - 1, format='mjd') clearcache = True # Reread year month day to preserve leading 0, and make time an array year, month, day = t.iso.split('-') day = day.split(' ')[0] t = Time([t.iso]) # Change to standard working directory and delete any existing IDB files there datstr = t[0].iso[:10].replace('-', '') + '/' outpath = '/data1/dgary/HSO/' + datstr if not os.path.exists(outpath): os.mkdir(outpath) fitsoutpath = '/data1/eovsa/fits/synoptic/' os.chdir(outpath) os.system('rm -rf IDB*') # Run first (and lengthy!) task to create corrected IDB files for the entire day
def retrieve_image(self): urllib.urlretrieve(self.params['url'], "current.JPG") self.im_masked, self.im_original = util.loadallsky(self.fimage, return_complete=True) self.last_im_refresh = Time.now()
# logging.debug(f'get_mount_altaz: computerd az = {altaz.az.degree}') return altaz.alt.degree, altaz.az.degree if __name__ == '__main__': LONG_FORMAT = '%(asctime)s.%(msecs)03d [%(filename)20s:%(lineno)3s - %(funcName)20s() ] %(levelname)-8s %(message)s' SHORT_FORMAT = '%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s' logging.basicConfig(filename='test_iers_altaz.log', filemode='a', level=logging.DEBUG, format=LONG_FORMAT, datefmt='%Y-%m-%d %H:%M:%S') # add to screen as well log = logging.getLogger() formatter = logging.Formatter(LONG_FORMAT) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) log.addHandler(ch) cur_radec = SkyCoord("1:12:43.2 +1:12:43", unit=(u.hourangle, u.deg)) print(cur_radec) location = EarthLocation.from_geodetic(-272 * u.deg, 36 * u.deg, 140 * u.m) observer = Observer(location=location, name='TestSite', timezone='US/Eastern') alt, az = get_altaz_from_radec(cur_radec, observer, Time.now()) print(f'Current mount alt/az is {alt:3.1f} {az:4.1f}')
def plot(self, title='', cblabel='', sources=True, time=None, filename=None, circle=None, **kwargs): """ """ if 'cmap' not in kwargs.keys(): kwargs['cmap'] = 'YlGnBu_r' if 'vmin' not in kwargs.keys(): kwargs['vmin'] = self.image.min() if 'vmax' not in kwargs.keys(): kwargs['vmax'] = self.image.max() cbar = True if 'cbar' in kwargs.keys(): cbar = kwargs['cbar'] del kwargs['cbar'] import matplotlib.pyplot as plt from matplotlib.colorbar import ColorbarBase from matplotlib.ticker import LinearLocator from matplotlib.colors import Normalize from matplotlib.cm import get_cmap from mpl_toolkits.axes_grid1.inset_locator import inset_axes from astropy.visualization.wcsaxes import SphericalCircle fig = plt.figure(figsize=(7, 7)) ax = plt.subplot(projection=self.wcs) im = ax.imshow(self.image, origin='lower', interpolation='nearest', **kwargs) ax.coords.grid(True, color='white', ls='solid', alpha=0.5) axra = ax.coords[0] axdec = ax.coords[1] axra.set_axislabel('RA') axra.set_major_formatter('d') axra.set_ticks(number=10) axdec.set_axislabel('Dec') axdec.set_major_formatter('d') axdec.set_ticks(number=10) if cbar: cax = inset_axes( ax, width='5%', height='100%', loc='lower left', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0, ) cb = ColorbarBase(cax, cmap=get_cmap(name='YlGnBu_r'), orientation='vertical', norm=Normalize(vmin=kwargs['vmin'], vmax=kwargs['vmax']), ticks=LinearLocator()) cb.solids.set_edgecolor('face') cb.set_label(cblabel) cb.formatter.set_powerlimits((0, 0)) if sources: phase_center = radec(ra=self.center[0], dec=self.center[1]) if time is None: time = Time.now() srcs = radio_sources(time=time) for k in srcs.keys(): src = radec(ra=srcs[k][0], dec=srcs[k][1]) if phase_center.separation( src).deg > self.npix_x / 2 * self.resol: # Source not in FoV continue ax.text(src.ra.deg, src.dec.deg, k.title(), transform=ax.get_transform('icrs'), color='white') if circle is not None: r1 = SphericalCircle(center=(circle[0] * u.deg, circle[1] * u.deg), radius=circle[2] / 2 * u.deg, resolution=100, edgecolor='white', facecolor='none', transform=ax.get_transform('icrs')) ax.add_patch(r1) r2 = SphericalCircle(center=(circle[0] * u.deg, circle[1] * u.deg), radius=circle[2] * u.deg, resolution=100, edgecolor='white', linestyle=':', facecolor='none', transform=ax.get_transform('icrs')) ax.add_patch(r2) ax.set_title(title) # plt.tight_layout() if filename is None: plt.show() else: plt.savefig(filename, dpi=300) return
def plot_skymap(self, maxpts=None, trials=5, jobs=1, enable_multiresolution=True, objid=None, instruments=None, geo=False, dpi=600, transparent=False, colorbar=False, contour=[50, 90], annotate=True, cmap='cylon', load_pickle=False): """ Generate a fits file and sky map from a result Code adapted from ligo.skymap.tool.ligo_skymap_from_samples and ligo.skymap.tool.plot_skymap. Note, the use of this additionally required the installation of ligo.skymap. Parameters ---------- maxpts: int Number of samples to use, if None all samples are used trials: int Number of trials at each clustering number jobs: int Number of multiple threads enable_multiresolution: bool Generate a multiresolution HEALPix map (default: True) objid: st Event ID to store in FITS header instruments: str Name of detectors geo: bool Plot in geographic coordinates (lat, lon) instead of RA, Dec dpi: int Resolution of figure in fots per inch transparent: bool Save image with transparent background colorbar: bool Show colorbar contour: list List of contour levels to use annotate: bool Annotate image with details cmap: str Name of the colormap to use load_pickle: bool, str If true, load the cached pickle file (default name), or the pickle-file give as a path. """ try: from astropy.time import Time from ligo.skymap import io, version, plot, postprocess, bayestar, kde import healpy as hp except ImportError as e: logger.info("Unable to generate skymap: error {}".format(e)) return check_directory_exists_and_if_not_mkdir(self.outdir) logger.info('Reading samples for skymap') data = self.posterior if maxpts is not None and maxpts < len(data): logger.info('Taking random subsample of chain') data = data.sample(maxpts) default_obj_filename = os.path.join( self.outdir, '{}_skypost.obj'.format(self.label)) if load_pickle is False: try: pts = data[['ra', 'dec', 'luminosity_distance']].values cls = kde.Clustered2Plus1DSkyKDE distance = True except KeyError: logger.warning( "The results file does not contain luminosity_distance") pts = data[['ra', 'dec']].values cls = kde.Clustered2DSkyKDE distance = False logger.info('Initialising skymap class') skypost = cls(pts, trials=trials, multiprocess=jobs) logger.info('Pickling skymap to {}'.format(default_obj_filename)) with open(default_obj_filename, 'wb') as out: pickle.dump(skypost, out) else: if isinstance(load_pickle, str): obj_filename = load_pickle else: obj_filename = default_obj_filename logger.info('Reading from pickle {}'.format(obj_filename)) with open(obj_filename, 'rb') as file: skypost = pickle.load(file) skypost.multiprocess = jobs logger.info('Making skymap') hpmap = skypost.as_healpix() if not enable_multiresolution: hpmap = bayestar.rasterize(hpmap) hpmap.meta.update(io.fits.metadata_for_version_module(version)) hpmap.meta['creator'] = "bilby" hpmap.meta['origin'] = 'LIGO/Virgo' hpmap.meta['gps_creation_time'] = Time.now().gps hpmap.meta['history'] = "" if objid is not None: hpmap.meta['objid'] = objid if instruments: hpmap.meta['instruments'] = instruments if distance: hpmap.meta['distmean'] = np.mean(data['luminosity_distance']) hpmap.meta['diststd'] = np.std(data['luminosity_distance']) try: time = data['geocent_time'] hpmap.meta['gps_time'] = time.mean() except KeyError: logger.warning('Cannot determine the event time from geocent_time') fits_filename = os.path.join(self.outdir, "{}_skymap.fits".format(self.label)) logger.info('Saving skymap fits-file to {}'.format(fits_filename)) io.write_sky_map(fits_filename, hpmap, nest=True) skymap, metadata = io.fits.read_sky_map(fits_filename, nest=None) nside = hp.npix2nside(len(skymap)) # Convert sky map from probability to probability per square degree. deg2perpix = hp.nside2pixarea(nside, degrees=True) probperdeg2 = skymap / deg2perpix if geo: obstime = Time(metadata['gps_time'], format='gps').utc.isot ax = plt.axes(projection='geo degrees mollweide', obstime=obstime) else: ax = plt.axes(projection='astro hours mollweide') ax.grid() # Plot sky map. vmax = probperdeg2.max() img = ax.imshow_hpx((probperdeg2, 'ICRS'), nested=metadata['nest'], vmin=0., vmax=vmax, cmap=cmap) # Add colorbar. if colorbar: cb = plot.colorbar(img) cb.set_label(r'prob. per deg$^2$') if contour is not None: cls = 100 * postprocess.find_greedy_credible_levels(skymap) cs = ax.contour_hpx((cls, 'ICRS'), nested=metadata['nest'], colors='k', linewidths=0.5, levels=contour) fmt = r'%g\%%' if rcParams['text.usetex'] else '%g%%' plt.clabel(cs, fmt=fmt, fontsize=6, inline=True) # Add continents. if geo: geojson_filename = os.path.join(os.path.dirname(plot.__file__), 'ne_simplified_coastline.json') with open(geojson_filename, 'r') as geojson_file: geoms = json.load(geojson_file)['geometries'] verts = [ coord for geom in geoms for coord in zip(*geom['coordinates']) ] plt.plot(*verts, color='0.5', linewidth=0.5, transform=ax.get_transform('world')) # Add a white outline to all text to make it stand out from the background. plot.outline_text(ax) if annotate: text = [] try: objid = metadata['objid'] except KeyError: pass else: text.append('event ID: {}'.format(objid)) if contour: pp = np.round(contour).astype(int) ii = np.round( np.searchsorted(np.sort(cls), contour) * deg2perpix).astype(int) for i, p in zip(ii, pp): text.append(u'{:d}% area: {:d} deg$^2$'.format( p, i, grouping=True)) ax.text(1, 1, '\n'.join(text), transform=ax.transAxes, ha='right') filename = os.path.join(self.outdir, "{}_skymap.png".format(self.label)) logger.info("Generating 2D projected skymap to {}".format(filename)) plt.savefig(filename, dpi=500)
def status(self, status): status += Time.now().iso set_tag(self.target.expnum, self.tag, status)
def test_orbit_from_ephem_with_no_epoch_is_today(): # This is not that obvious http://stackoverflow.com/q/6407362/554319 body = Earth ss = Orbit.from_body_ephem(body) assert (Time.now() - ss.epoch).sec < 1
def yse_pa(msb_name, pa=None): print(msb_name) # every MSB on the same PA survey_field_msb = SurveyFieldMSB.objects.get(name=msb_name) transients_in_field_query = [] for sf in survey_field_msb.survey_fields.all(): # find the interesting transients in the field d = sf.dec_cen * np.pi / 180 width_corr = 3.3 / np.abs(np.cos(d)) # Define the tile offsets: ra_offset = cd.Angle(width_corr / 2., unit=u.deg) dec_offset = cd.Angle(3.3 / 2., unit=u.deg) transients_in_field_query += [ Q(ra__gt=sf.ra_cen - ra_offset.degree) & Q(ra__lt=sf.ra_cen + ra_offset.degree) & Q(dec__gt=sf.dec_cen - dec_offset.degree) & Q(dec__lt=sf.dec_cen + dec_offset.degree) & Q(tags__name='YSE') ] query_full = transients_in_field_query[0] for q in transients_in_field_query[1:]: query_full = np.bitwise_or(query_full, q) transients_in_field = Transient.objects.filter(query_full) scf = SkyCoord(sf.ra_cen, sf.dec_cen, unit=u.deg) tg = TransientTag.objects.filter(name='YSE good cell') transients_best = transients_in_field.filter(tags__in=tg) transients_2best = transients_in_field.filter( Q(status__name='Interesting') & ~Q(tags__in=tg)) transients_3best = transients_in_field.filter( Q(status__name='FollowupRequested') & ~Q(tags__in=tg)) transients_4best = transients_in_field.filter( Q(status__name='Following') & ~Q(tags__in=tg)) # figure out the PA for today, best airmass t = Time.now() time_start = '05:00:00' time_end = '15:00:00' night_start = tel.twilight_evening_astronomical(t, which="previous") night_end = tel.twilight_morning_astronomical(t, which="previous") hourmin, hourmax = int(night_start.iso.split()[-1].split(':')[0]), int( night_end.iso.split()[-1].split(':')[0]) airmass, times = np.array([]), np.array([]) for hour in range(hourmin, hourmax + 1): time_obs = '%s %02i:%s:00' % (t.iso.split()[0], hour, time_start.split(':')[1]) time = Time(time_obs) altaz = tel.altaz(time, scf) if altaz.alt.value < 0: continue airmass = np.append(airmass, 1 / np.cos( (90. - altaz.alt.value) * np.pi / 180.)) times = np.append(times, time) time = times[airmass == np.min(airmass)] parallactic_angle = tel.parallactic_angle(time[0], scf) if pa is not None: rotator_angles = np.array([180 - pa + parallactic_angle.deg]) else: rotator_angles = np.linspace(-44, -183, 30) len_good, list_full = [], [] for rotator_angle in rotator_angles: good_list = [] pa = 180 - (-parallactic_angle.deg + rotator_angle) for i, transient_list in enumerate([ transients_4best, transients_3best, transients_2best, transients_best ]): for transient in transient_list: cmd = "echo %.7f %.7f | /Users/David/Dropbox/research/YSE_FieldSelection/YSE_scheduler/findcells/pscoords in=sky out=cell ra=%.7f dec=%.7f pa=%.1f dx=0 dy=0 dpa=0 sc=38.856" % ( transient.ra, transient.dec, sf.ra_cen, sf.dec_cen, pa) output = subprocess.check_output(cmd, shell=True) ota, cell, centerx, centery = output.split() if 'OTA' + ota.decode('utf-8') in goodcells.keys( ) and cell.decode('utf-8') in goodcells['OTA' + ota.decode('utf-8')]: if i < 3: good_list += [transient.name] else: good_list += [transient.name] * 4 len_good += [len(good_list)] list_full += [ [t for t in np.unique(good_list)], ] iGood = np.argsort(len_good)[::-1][0:5] best_idx = sample(iGood.tolist(), 1) best_rotator = rotator_angles[ best_idx] #[np.array(len_good) == np.max(len_good)] list_good = np.array(list_full)[best_idx][ 0] #[np.array(len_good) == np.max(len_good)] best_pa = 180 - (-parallactic_angle.deg + best_rotator[0]) return best_pa, list_good
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.")
def get_ephemerides_async(self, targetname, objtype='asteroid', epoch=None, epoch_step='1d', epoch_nsteps=1, location=500, coordtype=1, timescale='UTC', planetary_theory='INPOP', ephtype=1, refplane='equator', elements='ASTORB', radial_velocity=False, get_query_payload=False, get_raw_response=False, cache=True): """ Query the `IMCCE Miriade <http://vo.imcce.fr/webservices/miriade/>`_ `ephemcc <http://vo.imcce.fr/webservices/miriade/?ephemcc>`_ service. Parameters ---------- targetname : str Name of the target to be queried. objtype : str, optional Type of the object to be queried. Available are: ``'asteroid'``, ``'comet'``, ``'dwarf planet'``, ``'planet'``, ``'satellite'``. Default: ``'asteroid'`` epoch : `~astropy.time.Time` object, float, str,``None``, optional Start epoch of the query. If a float is provided, it is expected to be a Julian Date; if a str is provided, it is expected to be an iso date of the form ``'YYYY-MM-DD HH-MM-SS'``. If ``None`` is provided, the current date and time are used as epoch. Default: ``None`` epoch_step : str, optional Step size for ephemerides calculation. Must consist of a decimal number followed by a single character: (d)ays, (h)ours, (m)inutes or (s)econds. Default: ``'1d'`` epoch_nsteps : int, optional Number of increments of ``epoch_step`` starting from ``epoch`` for which ephemerides are calculated. Maximum number of steps is 5000. Default: 1 location : str, optional Location of the observer on Earth as a code or a set of coordinates. See the `Miriade manual <http://vo.imcce.fr/webservices/miriade/?documentation#field_7>`_ for details. Default: geocentric location (``'500'``) coordtype : int, optional Type of coordinates to be calculated: ``1``: spherical, ``2``: rectangular, ``3``: local coordinates (azimuth and elevation), ``4``: hour angle coordinates, ``5``: dedicated to observation, ``6``: dedicated to AO observation. Default: ``1`` timescale : str, optional The time scale used in the computation of the ephemerides: ``'UTC'`` or ``'TT'``. Default: ``'UTC'`` planetary_theory : str, optional Planetary ephemerides set to be utilized in the calculations: ``'INPOP'``, ``'DE405'``, ``'DE406'``. Default: ``'INPOP'`` ephtype : int, optional Type of ephemerides to be calculated: ``1``: astrometric J2000, ``2``: apparent of the date, ``3``: mean of the date, ``4``: mean J2000, Default: ``1`` refplane : str, optional Reference plane: ``'equator'`` or ``'ecliptic'``. Default: ``'equator'`` elements : str, optional Set of osculating elements to be used in the calculations: ``'ASTORB'`` or ``'MPCORB'``. Default: ``'ASTORB'`` radial_velocity : bool, optional Calculate additional information on the target's radial velocity. Default: ``False`` get_query_payload : bool, optional When set to ``True`` the method returns the HTTP request parameters as a dict, default: ``False`` get_raw_response : bool, optional Return raw data as obtained by Miriade without parsing the data into a table, default: ``False`` cache : bool, optional If ``True`` the query will be cached. Default: ``True`` Notes ----- The following parameters can be queried using this function. Note that different ``coordtype`` setting provide different sets of parameters; number in parentheses denote which ``coordtype`` settings include the parameters. +------------------+-----------------------------------------------+ | Column Name | Definition | +==================+===============================================+ | ``target`` | Target name (str, 1, 2, 3, 4, 5, 6 ) | +------------------+-----------------------------------------------+ | ``epoch`` | Ephemerides epoch (JD, float, 1, 2, 3, 4, 5, | | | 6) | +------------------+-----------------------------------------------+ | ``RA`` | Target RA at ``ephtype`` (deg, float, 1) | +------------------+-----------------------------------------------+ | ``DEC`` | Target declination at ``ephtype`` (deg, | | | float, 1, 4, 5) | +------------------+-----------------------------------------------+ | ``RAJ2000`` | Target RA at J2000 (deg, float, 5, 6) | +------------------+-----------------------------------------------+ | ``DECJ2000`` | Target declination at J2000 (deg, float, 5, 6)| +------------------+-----------------------------------------------+ | ``AZ`` | Target azimuth (deg, float, 3, 5) | +------------------+-----------------------------------------------+ | ``EL`` | Target elevation (deg, float, 3, 5) | +------------------+-----------------------------------------------+ | ``delta`` | Distance from observer (au, float, 1, 2, 3, | | | 4, 5, 6) | +------------------+-----------------------------------------------+ | ``delta_rate`` | Rate in observer distance (km/s, float, | | | 1, 5, 6) | +------------------+-----------------------------------------------+ | ``V`` | Apparent visual magnitude (mag, float, 1, 2, | | | 3, 4, 5, 6) | +------------------+-----------------------------------------------+ | ``alpha`` | Solar phase angle (deg, 1, 2, 3, 4, 5, 6) | +------------------+-----------------------------------------------+ | ``elong`` | Solar elongation angle (deg, 1, 2, 3, 4, 5, 6)| +------------------+-----------------------------------------------+ | ``RAcosD_rate`` | Rate of motion in RA * cos(DEC) (arcsec/min, | | | float, 1, 5, 6) | +------------------+-----------------------------------------------+ | ``DEC_rate`` | Rate of motion in DEC (arcsec/min, float, 1, | | | 5, 6) | +------------------+-----------------------------------------------+ | ``x`` | X position state vector (au, float, 2) | +------------------+-----------------------------------------------+ | ``y`` | Y position state vector (au, float, 2) | +------------------+-----------------------------------------------+ | ``z`` | Z position state vector (au, float, 2) | +------------------+-----------------------------------------------+ | ``vx`` | X velocity state vector (au/d, float, 2) | +------------------+-----------------------------------------------+ | ``vy`` | Y velocity state vector (au/d, float, 2) | +------------------+-----------------------------------------------+ | ``vz`` | Z velocity state vector (au/d, float, 2) | +------------------+-----------------------------------------------+ | ``rv`` | Radial velocity (km/s, float, 2) | +------------------+-----------------------------------------------+ | ``heldist`` | Target heliocentric distance (au, float, 2, | | | 5, 6) | +------------------+-----------------------------------------------+ | ``x_h`` | X heliocentric position vector (au, float, 2) | +------------------+-----------------------------------------------+ | ``y_h`` | Y heliocentric position vector (au, float, 2) | +------------------+-----------------------------------------------+ | ``z_h`` | Z heliocentric position vector (au, float, 2) | +------------------+-----------------------------------------------+ | ``vx_h`` | X heliocentric vel. vector (au/d, float, 2) | +------------------+-----------------------------------------------+ | ``vy_h`` | Y heliocentric vel. vector (au/d, float, 2) | +------------------+-----------------------------------------------+ | ``vz_h`` | Z heliocentric vel. vector (au/d, float, 2) | +------------------+-----------------------------------------------+ | ``hourangle`` | Target hour angle (deg, float, 4, 5) | +------------------+-----------------------------------------------+ | ``siderealtime`` | Local sidereal time (hr, float, 5, 6) | +------------------+-----------------------------------------------+ | ``refraction`` | Atmospheric refraction (arcsec, float, 5, 6) | +------------------+-----------------------------------------------+ | ``airmass`` | Target airmass (float, 5, 6) | +------------------+-----------------------------------------------+ | ``posunc`` | Positional uncertainty (arcsec, float, 5, 6) | +------------------+-----------------------------------------------+ Examples -------- >>> from astroquery.imcce import Miriade >>> from astropy.time import Time >>> epoch = Time('2019-01-01', format='iso') >>> Miriade.get_ephemerides('3552', epoch=epoch) # doctest: +SKIP <Table masked=True length=1> target epoch RA ... DEC_rate delta_rate d deg ... arcs / min km / s bytes20 float64 float64 ... float64 float64 ----------- -------------------- ------------------ ... ---------- ------------ Don Quixote 2458484.5 16.105294999999998 ... -0.25244 31.4752734 """ URL = conf.ephemcc_server TIMEOUT = conf.timeout if isinstance(epoch, (int, float)): epoch = Time(epoch, format='jd') elif isinstance(epoch, str): epoch = Time(epoch, format='iso') elif epoch is None: epoch = Time.now() request_payload = OrderedDict([ ('-name', targetname), ('-type', objtype[0].upper()+objtype[1:]), ('-ep', str(epoch.jd)), ('-step', epoch_step), ('-nbd', epoch_nsteps), ('-observer', location), ('-output', '--jul'), ('-tscale', timescale), ('-theory', planetary_theory), ('-teph', ephtype), ('-tcoor', coordtype), ('-rplane', {'equator': 1, 'ecliptic': 2}[refplane]), ('-oscelem', elements), ('-mime', 'votable')]) if radial_velocity: request_payload['-output'] += ',--rv' if get_query_payload: return request_payload # query and parse response = self._request('GET', URL, params=request_payload, timeout=TIMEOUT, cache=cache) self._query_uri = response.url self._get_raw_response = get_raw_response return response
if (arg[0] == "-") and arg[1].isdigit(): sys.argv[i] = ' ' + arg a = argparse.ArgumentParser() a.add_argument("-obs_loc", type=str, help="Name of the observatory", required=True) a.add_argument("-source_name", type=str, help="Name of source --\ Either present in the list 'sources.list' or\ Resolvable by astropy (uses SIMBAD)") a.add_argument("-source_coords", type=str, nargs=2, help="RA (hourangle) and Dec (degree) of the source") a.add_argument( "-obs_time", type=str, help= "Time of observation in UTC (fmt=YYYY-mm-ddTHH:MM:SS). Def = Time.now()", default=str(Time.now())) a.add_argument( "-precision", type=float, help= "Precision (in seconds) when computing the rise and set times (def = 60 secs)", default=60) args = a.parse_args() main()
def getSiderialTimeHA(self): sdr = self.time.sidereal_time('mean', longitude=jgeminfo.LONGITUDE).hourangle return sdr def getHA(self): sdr = self.getSiderialTimeHA() objra = self.objcoord.ra.hourangle print(objra) ha = sdr - objra if ha < -12: ha+=24 elif ha > 12: ha-=24 return(ha) if __name__ == '__main__': # if len(sys.args != 3): # exit(1) # print(sys.argv[1]) now = Time.now() print(now) objcoord = SkyCoord(sys.argv[1], sys.argv[2], unit=(u.hourangle,u.deg), frame='icrs') altaz=ObjAltAzHa(float(sys.argv[1]), float(sys.argv[2]), now) # print(altaz.getSiderialTime(now)) alt, az = altaz.getAltAz() ha = altaz.getHA() print("Alt: %6.1f, Az: %6.1f, HA: %6.1f" % (alt, az, ha))
import sys import NuRadioReco.detector.detector as detector from astropy.time import Time import numpy as np det = detector.Detector(json_filename=sys.argv[1], antenna_by_depth=False) det.update(Time.now()) f = open(sys.argv[1] + '.csv', 'w') station_ids = det.get_station_ids() for station_id in station_ids: loc = det.get_absolute_position(station_id) f.write("{}, {}, {}\n".format(station_id, loc[0], loc[1]))
def whatsInBetween(self): #temp var to hold obs info obs = {'time':[], 'id':[]} #init observatory location observatory_location = EarthLocation(lat=self.observatory.latitude*u.deg, lon=self.observatory.longitude*u.deg, height=self.observatory.altitude*u.m) #build alt-az coordinate frame for observatory over next ? hours (e.g., nearest sunset to next sunrise) #start time is sunset or current time, if later... now = Time.now() if (now > self.sunset_time): obs_time = Time.now() else: obs_time = self.sunset_time delta_obs_time = np.linspace(0, (self.sunrise_time-obs_time).sec/3600., 1000)*u.hour #array of times between sunset and sunrise times = obs_time + delta_obs_time #celestial frame for this observatory over times frame = AltAz(obstime=times, location=observatory_location) #loop thru observations, suggest the next best target based on time of max alt. for observation in self.observations: #skip obs that are complete/inactive if observation.active == False: logger.debug('Observation (%s) is not active. Skipping...'%observation.target.getName()) continue #skip foreground obs if observation.sequence.repeat != Sequence.CONTINUOUS: logger.debug('Observation (%s) is not background type. Skipping...'%observation.target.getName()) continue #build target altaz relative to observatory target_ra = observation.target.getRa() target_dec = observation.target.getDec() input_coordinates = target_ra + " " + target_dec try: target_coordinates = SkyCoord(input_coordinates, unit=(u.hourangle, u.deg)) except: continue target_altaz = target_coordinates.transform_to(frame) #when is target above minimum altitude? #when is it above min_obs_alt? valid_alt_times = times[np.where(target_altaz.alt >= observation.min_obs_alt*u.degree)] #when does the max alt occur? if len(valid_alt_times) > 0: #set min and max obs times observation.min_obs_time = Time(np.min(times[np.where(target_altaz.alt > observation.min_obs_alt*u.degree)])) observation.max_obs_time = Time(np.max(times[np.where(target_altaz.alt > observation.min_obs_alt*u.degree)])) #if target is observable now, add it to the list if observation.min_obs_time < Time.now(): obs['id'].append(observation.id) #remember the end time too obs['time'].append(np.max(times[np.where(target_altaz.alt > observation.min_obs_alt*u.degree)])) #get earliest max. time from valid targets if len(obs) > 0: #the winner! id = np.argmin(obs['time']) #set obs start time self.observations[obs['id'][id]].obs_start_time = Time.now() else: logger.info("No active background observations exist.") return None logger.debug('Next background observation is %s.'%self.observations[obs['id'][id]].target.name) return self.observations[obs['id'][id]]
async def planObserving(): mjd = round(offsetNow()) now = Time.now() now.format = "mjd" mjd_now = now.value form = await request.form args = request.args redo = False # parse POST/GET args if "mjd" in args: # deprecated? mjd = int(args["mjd"]) redo = True if "redo" in args: # deprecated? redo = True if "rmField" in form: rmField = int(form["rmField"]) await wrapBlocking(opsdb.Queue.rm, rmField) elif "flush" in form: await wrapBlocking(opsdb.Queue.flushQueue) elif "redo" in form: redo = True if "replace" in form: replace = int(form["replace"]) else: replace = False if "backup" in form: replacementField = int(form["backup"]) oldField = int(form["prev"]) else: replacementField = None if "remainder" in form: redoFromField = True else: redoFromField = False errors = list() templateDict = getTemplateDictBase() # date = datetime.datetime.utcnow() # date = datetimenow.date() scheduler = await wrapBlocking(Scheduler) mjd_evening_twilight, mjd_morning_twilight = await wrapBlocking( scheduler.getNightBounds, mjd) if mjd_morning_twilight - mjd_now < 1 / 24 / 4: # 15 minutes # Night's basically over, we're doing tomorrow errors.append("END OF NIGHT. Scheduling tomorrow") mjd += 1 mjd_evening_twilight, mjd_morning_twilight = await wrapBlocking( scheduler.getNightBounds, mjd) startTime = Time(mjd_evening_twilight, format="mjd").datetime endTime = Time(mjd_morning_twilight, format="mjd").datetime evening_twilight_dark, morning_twilight_dark = await wrapBlocking( scheduler.getDarkBounds, mjd) evening_twilight_utc = Time(evening_twilight_dark, format="mjd").datetime morning_twilight_utc = Time(morning_twilight_dark, format="mjd").datetime if replacementField is not None: # replacing a field if redoFromField: # is it bad enough to redo the rest of the queue? errors.append(await scheduler.rescheduleAfterField( replacementField, mjd_morning_twilight)) else: # ok just the one then! await scheduler.replaceField(oldField, replacementField) if redo: # clear the queue await wrapBlocking(opsdb.Queue.flushQueue) # redo the whole queue, but check if it's during the night # winter = evening_twilight_utc.month < 3 # if not winter and evening_twilight_utc.month < 4: # winter = evening_twilight_utc.day < 20 # fall = evening_twilight_utc.month > 10 # if not fall and evening_twilight_utc.month > 9: # fall = evening_twilight_utc.day > 22 # if winter or fall: # # either before 3/20 or after 9/22 # mjd_evening_twilight = evening_twilight_dark # mjd_morning_twilight = morning_twilight_dark if mjd_now > mjd_evening_twilight: start_mjd = mjd_now else: start_mjd = mjd_evening_twilight errors.append(await scheduler.queueFromSched(start_mjd, mjd_morning_twilight)) schedule = { "queriedMJD": mjd, "timeBarStartUTC": startTime, "timeBarEndUTC": endTime, "eveningTwilightUTC": evening_twilight_utc, "morningTwilightUTC": morning_twilight_utc } brightDark = scheduler.nightSchedule(evening_twilight_dark, morning_twilight_dark) schedule.update(**brightDark) for k, v in brightDark.items(): if v is None: continue brightDark[k] = v.strftime("%H:%M") queue = await wrapBlocking(Queue) if len(queue.fields) == 0: viz = None else: # queue.scheduleFields(mjd_evening_twilight, mjd_morning_twilight) viz = await ApogeeViz(schedule, queue.fields).export() if replace: # make replace the fieldID to be replaced, or False field = queue.fieldDict[replace] args = await scheduler.choiceFields(field.startTime, exp=len(field.designs), oldPos=[field.ra, field.dec]) # backups = await backupDicts(*args, sched=scheduler, mjd=field.startTime, # prev=replace) backups = await backupDicts(*args, sched=scheduler, mjd=mjd_now, prev=replace) # for f in viz["plateRows"]: # if f["fieldID"] == field.fieldID: # for k in ["mjd_start", "dec", "tableItems", "trueHA"]: # print(f["fieldID"], k, f[k]) else: backups = list() exps = await wrapBlocking(getRecentExps, mjd) almanac = await wrapBlocking(getAlmanac, mjd) for d in queue.designs: d.priority = queue.fieldDict[d.field_pk].priority templateDict.update({ # "apogeeViz": ApogeeViz(schedule, apogeePlateList).export() if apogeePlateList else None, "apogeeViz": viz, "mjd": mjd, "almanac": (*almanac, brightDark), "queue": queue.designs, "backups": backups, "exposures": exps, "errorMsg": errors }) # findAndConvertDatetimes(templateDict) return await render_template("planObserving.html", **templateDict)
def run_on_event(channel_id, bypass=False, program_ids=[1,2], outdir="forcedphot"): thread_ts = time.time() #response = web_client.chat_postMessage( # channel=channel_id, # text='testing') if not bypass: try: converations = web_client.conversations_list( channel=channel_id ) channel_slack_id = channel_id for converation in converations: for chan in converation.data["channels"]: if chan["name"] == channel_id.replace("#",""): channel_slack_id = chan["id"] delay_thresh = 15.0 payload = web_client.conversations_history( channel=channel_slack_id, oldest=thread_ts-delay_thresh ) except: return if len(payload["messages"]) == 0: return doTrigger, trigger_action, name, ra, dec = False, 'forced', 'ZTF21abinaiu', 310.480103, 11.70041 for mess in payload["messages"]: print(mess) message_ts = float(mess["ts"]) if np.abs(message_ts - thread_ts) > delay_thresh: continue txt = mess['text'] txtsplit = list(filter(None,txt.split(" "))) if len(txtsplit) == 0: continue if txtsplit[0] == "trigger": doTrigger = True if len(txtsplit) == 4: name = txtsplit[1] ra = float(txtsplit[2]) dec = float(txtsplit[3]) user = mess['user'] if not doTrigger: return else: user, message_ts = 'test', thread_ts # options: gp,rp,ip,zs,Y name, ra, dec = 'ZTF21abinaiu', 310.480103, 11.70041 message = [] message.append("Hi <@{0}>! You are interested in forced photometry, right? Let me get right on that for you.".format(user)) message.append('Received request %.1f seconds ago...' % (np.abs(message_ts - thread_ts))) message.append("We are looking into %s for you" % name) web_client.chat_postMessage( channel=channel_id, text="\n".join(message) ) tstart = Time.now() - TimeDelta(100*u.day) tend = Time.now() fig = do_forcephot(outdir, name, ra, dec, tstart.jd, tend.jd, ncpu=1, limit=100, do_mcmc=True, program_ids=program_ids, verbose=False) upload_fig(fig, user, "forced.png", channel_id) message = [] message.append('Forced photometry complete') web_client.chat_postMessage( channel=channel_id, text="\n".join(message) )
async def handle_data_message(self, message, manager_rcv): """Handle a data message. Sends the message to the corresponding groups based on the data of the message. Parameters ---------- message: `dict` dictionary containing the message parsed as json. The expected format of the message for a telemetry or an event is as follows: .. code-block:: json { "category": "event/telemetry", "data": [{ "csc": "ScriptQueue", "salindex": 1, "data": { "stream1": { "<key11>": "<value11>", "<key12>": "<value12>", }, "stream2": { "<key21>": "<value21>", "<key22>": "<value22>", }, } }] } """ data = message["data"] category = message["category"] producer_snd = message[ "producer_snd"] if "producer_snd" in message else None # Store pairs of group, message to send: to_send = [] tracing = {} # Iterate over all stream groups for csc_message in data: csc = csc_message["csc"] salindex = csc_message["salindex"] data_csc = csc_message["data"] csc_message["data"] = data_csc streams = data_csc.keys() streams_data = {} # Individual groups for each stream for stream in streams: sub_category = category msg_type = "subscription_data" group_name = "-".join( [sub_category, csc, str(salindex), stream]) msg = { "type": msg_type, "category": category, "csc": csc, "salindex": salindex, "data": { stream: data_csc[stream] }, "subscription": group_name, } to_send.append({"group": group_name, "message": msg}) streams_data[stream] = data_csc[stream] # Higher level groups for all streams of a category-csc-salindex group_name = "-".join([category, csc, str(salindex), "all"]) msg = { "type": "subscription_data", "category": category, "csc": csc, "salindex": salindex, "data": { csc: streams_data }, "subscription": group_name, } to_send.append({"group": group_name, "message": msg}) # Top level for "all" subscriptions of the same category group_name = "{}-all-all-all".format(category) msg = { "type": "subscription_all_data", "category": category, "data": data } to_send.append({"group": group_name, "message": msg}) if settings.TRACE_TIMESTAMPS: tracing = { "producer_snd": producer_snd, "manager_rcv_from_producer": manager_rcv, "manager_snd_to_group": Time.now().tai.datetime.timestamp(), } for group_msg in to_send: group_msg["message"]["tracing"] = tracing # print("to_send: ", to_send, flush=True) # Send all group-message pairs concurrently: await asyncio.gather(*[ self.channel_layer.group_send(**group_msg) for group_msg in to_send ])
def simulate_data_pyoof(I_coeff, K_coeff, wavel, d_z, illum_func, telgeo, noise, resolution, box_factor, work_dir=None): """ Routine to generate data and test the pyoof package algorithm. It has the default setting for the pyoof FITS file input. Parameters ---------- I_coeff : `list` List which contains 4 parameters, the illumination amplitude, :math:`A_{E_\\mathrm{a}}`, the illumination taper, :math:`c_\\mathrm{dB}` and the two coordinate offset, :math:`(x_0, y_0)`. The illumination coefficients must be listed as follows, ``I_coeff = [i_amp, c_dB, x0, y0]``. K_coeff : `~numpy.ndarray` Constants coefficients, :math:`K_{n\\ell}`, for each of them there is only one Zernike circle polynomial, :math:`U^\\ell_n(\\varrho, \\varphi)`. wavel : `~astropy.units.quantity.Quantity` Wavelength, :math:`\\lambda`, of the observation in length units. d_z : `~astropy.units.quantity.Quantity` Radial offset :math:`d_z`, added to the sub-reflector in length units. This characteristic measurement adds the classical interference pattern to the beam maps, normalized squared (field) radiation pattern, which is an out-of-focus property. The radial offset list must be as follows, ``d_z = [d_z-, 0., d_z+]`` all of them in length units. illum_func : `function` Illumination function, :math:`E_\\mathrm{a}(x, y)`, to be evaluated with the key ``I_coeff``. The illumination functions available are `~pyoof.aperture.illum_parabolic` and `~pyoof.aperture.illum_gauss`. telgeo : `list` List that contains the blockage distribution, optical path difference (OPD) function, and the primary radius (`float`) in lenght units. The list must have the following order, ``telego = [block_dist, opd_func, pr]``. noise : `float` Noise amplitude added to the generated data. The noise comes from a random Gaussian, see `~numpy.random.normal`. resolution : `int` Fast Fourier Transform resolution for a rectangular grid. The input value has to be greater or equal to the telescope resolution and with power of 2 for faster FFT processing. It is recommended a value higher than ``resolution = 2 ** 8``. box_factor : `int` Related to the FFT resolution (**resolution** key), defines the image pixel size level. It depends on the primary radius, ``pr``, of the telescope, e.g. a ``box_factor = 5`` returns ``x = np.linspace(-5 * pr, 5 * pr, resolution)``, an array to be used in the FFT2 (`~numpy.fft.fft2`). work_dir : `str` Default is `None`, it will store the FITS file in the current directory, for other provide the desired path. Returns ------- pyoof_fits : `~astropy.io.fits.hdu.hdulist.HDUList` The output fits file is stored in the directory ``'data_generated/'``. Every time the function is executed a new file will be stored (with increased numbering). The file is ready to use for the `~pyoof` package. Raises ------ `ValueError` If the known a priori radial offset ``d_z`` is different than: ``[d_z-, 0., d_z+]``, negative, zero, and positive float. """ if (d_z[0] > 0) or (d_z[1] != 0) or (d_z[2] < 0): raise ValueError( "Radial offset must match: [d_z-, 0., d_z+] convention") if work_dir is None: work_dir = os.getcwd() freq = light_speed / wavel bw = 1.22 * apu.rad * wavel / (2 * telgeo[2]) # beamwidth in radians size_in_bw = 8 * bw plim = [ -size_in_bw.to_value(apu.rad), size_in_bw.to_value(apu.rad), -size_in_bw.to_value(apu.rad), size_in_bw.to_value(apu.rad) ] * apu.rad plim_u, plim_v = plim[:2], plim[2:] # Generating power pattern and spatial frequencies u, v, P = [], [], [] for i in range(3): _u, _v, _radiation = radiation_pattern(K_coeff=K_coeff, I_coeff=I_coeff, d_z=d_z[i], wavel=wavel, illum_func=illum_func, telgeo=telgeo, resolution=resolution, box_factor=box_factor) uu, vv = np.meshgrid(_u, _v) power_pattern = np.abs(_radiation)**2 # trim the power pattern power_pattern[(plim_u[0] > uu)] = np.nan power_pattern[(plim_u[1] < uu)] = np.nan power_pattern[(plim_v[0] > vv)] = np.nan power_pattern[(plim_v[1] < vv)] = np.nan power_trim_1d = power_pattern[~np.isnan(power_pattern)] size_trim = int(np.sqrt(power_trim_1d.size)) # new size of the box # Box to be trimmed in uu and vv meshed arrays box = ((plim_u[0] < uu) & (plim_u[1] > uu) & (plim_v[0] < vv) & (plim_v[1] > vv)) # reshaping trimmed arrys power_trim = power_trim_1d.reshape(size_trim, size_trim) u_trim = uu[box].reshape(size_trim, size_trim) v_trim = vv[box].reshape(size_trim, size_trim) u.append(u_trim) v.append(v_trim) P.append(power_trim) # adding noise! if noise == 0: power_noise = np.array(P) else: power_noise = (np.array(P) + np.random.normal(0., noise, np.array(P).shape)) u_to_save = [u[i].to_value(apu.rad).flatten() for i in range(3)] v_to_save = [v[i].to_value(apu.rad).flatten() for i in range(3)] p_to_save = [power_noise[i].flatten() for i in range(3)] # Writing default fits file for OOF observations table_hdu0 = fits.BinTableHDU.from_columns([ fits.Column(name='U', format='E', array=u_to_save[0]), fits.Column(name='V', format='E', array=v_to_save[0]), fits.Column(name='BEAM', format='E', array=p_to_save[0]) ]) table_hdu1 = fits.BinTableHDU.from_columns([ fits.Column(name='U', format='E', array=u_to_save[1]), fits.Column(name='V', format='E', array=v_to_save[1]), fits.Column(name='BEAM', format='E', array=p_to_save[1]) ]) table_hdu2 = fits.BinTableHDU.from_columns([ fits.Column(name='U', format='E', array=u_to_save[2]), fits.Column(name='V', format='E', array=v_to_save[2]), fits.Column(name='BEAM', format='E', array=p_to_save[2]) ]) # storing data if not os.path.exists(os.path.join(work_dir, 'data_generated')): os.makedirs(os.path.join(work_dir, 'data_generated')) for j in ["%03d" % i for i in range(101)]: name_file = os.path.join(work_dir, 'data_generated', f'test{j}.fits') if not os.path.exists(name_file): prihdr = fits.Header() prihdr['FREQ'] = freq.to_value(apu.Hz) prihdr['WAVEL'] = wavel.to_value(apu.m) prihdr['MEANEL'] = 0 prihdr['OBJECT'] = f'test{j}' prihdr['DATE_OBS'] = Time.now().isot prihdr['COMMENT'] = 'Generated data pyoof package' prihdr['AUTHOR'] = 'Tomas Cassanelli' prihdu = fits.PrimaryHDU(header=prihdr) pyoof_fits = fits.HDUList( [prihdu, table_hdu0, table_hdu1, table_hdu2]) for i in range(3): pyoof_fits[i + 1].header['DZ'] = d_z[i].to_value(apu.m) pyoof_fits[1].name = 'MINUS OOF' pyoof_fits[2].name = 'ZERO OOF' pyoof_fits[3].name = 'PLUS OOF' pyoof_fits.writeto(name_file) break return pyoof_fits
def track(self, target_or_ra, dec=None, duration=0, start_time=None, verbose=True): """ Given a target name and a tracking duration in seconds, start tracking the source. If the 'dec' keyword is not None, the target is intepreted to be a RA. If the duration is less than or equal to zero the default of 12 hours is used. .. note:: The tracking can be canceled at any time with a control-C. """ # Force to string target_or_ra = str(target_or_ra) if dec is not None: dec = str(dec) # Load in where we are obs = EarthLocation.from_geocentric( *self.control_instance.station.ecef, unit=u.m) # Resolve the name into coordinates if target_or_ra.lower() in solar_system_ephemeris.bodies: if target_or_ra.lower().startswith('earth'): raise ValueError(f"Invalid target: '{target_or_ra}'") sc = get_body(target_or_ra.lower(), Time.now(), location=obs) if verbose: print(f"Resolved '{target_or_ra}' to {target_or_ra.lower()}") else: if dec is not None: ra = Angle(target_or_ra, unit='hourangle') dec = Angle(dec, unit='deg') sc = SkyCoord(ra, dec, frame='fk5') if verbose: print( f"Resolved '{target_or_ra}, {dec}' to RA {sc.ra}, Dec. {sc.dec}" ) else: sc = SkyCoord.from_name(target_or_ra) if verbose: print( f"Resolved '{target_or_ra}' to RA {sc.ra}, Dec. {sc.dec}" ) # Figure out the duration of the tracking if duration <= 0: duration = 86400.0 / 2 # Set the pointing update time offset - this is half the update interval # so that we should end up with a nice scalloped pattern puto = TimeDelta(min([duration, self.update_interval]) / 2.0, format='sec') # Set the tracking stop time if start_time is None: start_time = time.time() t_stop = start_time + duration try: # Go! t = time.time() while t < t_stop: ## Get a time marker so that we can account for how long the ## update takes t_mark = time.time() ## Figure out where the target will be in puto seconds aa = sc.transform_to( AltAz(obstime=Time.now() + puto, location=obs)) az = aa.az.deg alt = aa.alt.deg if verbose: print( f"At {time.time():.1f}, moving to azimuth {aa.az}, altitude {aa.alt}" ) ## Point self.control_instance.set_beam_pointing(az, alt, degrees=True, load_time=t_mark + 2) ## Find how much time we used and when we should sleep until t_used = time.time() - t_mark t_sleep_until = t + self.update_interval - t_used ## Sleep to wait it out in increments of 0.01 s so that a control-C ## doesn't take forever to register while t < t_sleep_until and t < t_stop: time.sleep(0.01) t = time.time() except KeyboardInterrupt: # We gave up, end it now pass
""" from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import astropy.units as u from astropy.time import Time, TimeDelta from ..vlbi_base.header import (four_word_struct, eight_word_struct, HeaderParser, VLBIHeaderBase) from ..mark5b.header import Mark5BHeader __all__ = ['VDIFHeader', 'VDIFBaseHeader', 'VDIFSampleRateHeader'] # This gets updated with all EDV headers at the end. ref_max = int(2. * (Time.now().jyear - 2000.)) + 1 ref_epochs = Time([ '{y:04d}-{m:02d}-01'.format(y=2000 + ref // 2, m=1 if ref % 2 == 0 else 7) for ref in range(ref_max) ], format='isot', scale='utc', precision=9) class VDIFHeader(VLBIHeaderBase): """VDIF Header, supporting different Extended Data Versions. Will initialize a header instance appropriate for a given EDV. See http://www.vlbi.org/vdif/docs/VDIF_specification_Release_1.1.1.pdf
def write_event_file(events, parameters, filename, overwrite=False): from astropy.time import Time, TimeDelta mylog.info("Writing events to file %s." % filename) t_begin = Time.now() dt = TimeDelta(parameters["exposure_time"], format='sec') t_end = t_begin + dt col_x = pyfits.Column(name='X', format='D', unit='pixel', array=events["xpix"]) col_y = pyfits.Column(name='Y', format='D', unit='pixel', array=events["ypix"]) col_e = pyfits.Column(name='ENERGY', format='E', unit='eV', array=events["energy"] * 1000.) col_dx = pyfits.Column(name='DETX', format='D', unit='pixel', array=events["detx"]) col_dy = pyfits.Column(name='DETY', format='D', unit='pixel', array=events["dety"]) col_id = pyfits.Column(name='CCD_ID', format='D', unit='pixel', array=events["ccd_id"]) chantype = parameters["channel_type"] if chantype == "PHA": cunit = "adu" elif chantype == "PI": cunit = "Chan" col_ch = pyfits.Column(name=chantype.upper(), format='1J', unit=cunit, array=events[chantype]) col_t = pyfits.Column(name="TIME", format='1D', unit='s', array=events['time']) cols = [col_e, col_x, col_y, col_ch, col_t, col_dx, col_dy, col_id] coldefs = pyfits.ColDefs(cols) tbhdu = pyfits.BinTableHDU.from_columns(coldefs) tbhdu.name = "EVENTS" tbhdu.header["MTYPE1"] = "sky" tbhdu.header["MFORM1"] = "x,y" tbhdu.header["MTYPE2"] = "EQPOS" tbhdu.header["MFORM2"] = "RA,DEC" tbhdu.header["TCTYP2"] = "RA---TAN" tbhdu.header["TCTYP3"] = "DEC--TAN" tbhdu.header["TCRVL2"] = parameters["sky_center"][0] tbhdu.header["TCRVL3"] = parameters["sky_center"][1] tbhdu.header["TCDLT2"] = -parameters["plate_scale"] tbhdu.header["TCDLT3"] = parameters["plate_scale"] tbhdu.header["TCRPX2"] = parameters["pix_center"][0] tbhdu.header["TCRPX3"] = parameters["pix_center"][1] tbhdu.header["TCUNI2"] = "deg" tbhdu.header["TCUNI3"] = "deg" tbhdu.header["TLMIN2"] = 0.5 tbhdu.header["TLMIN3"] = 0.5 tbhdu.header["TLMAX2"] = 2.0 * parameters["num_pixels"] + 0.5 tbhdu.header["TLMAX3"] = 2.0 * parameters["num_pixels"] + 0.5 tbhdu.header["TLMIN4"] = parameters["chan_lim"][0] tbhdu.header["TLMAX4"] = parameters["chan_lim"][1] tbhdu.header["TLMIN6"] = -0.5 * parameters["num_pixels"] tbhdu.header["TLMAX6"] = 0.5 * parameters["num_pixels"] tbhdu.header["TLMIN7"] = -0.5 * parameters["num_pixels"] tbhdu.header["TLMAX7"] = 0.5 * parameters["num_pixels"] tbhdu.header["EXPOSURE"] = parameters["exposure_time"] tbhdu.header["TSTART"] = 0.0 tbhdu.header["TSTOP"] = parameters["exposure_time"] tbhdu.header["HDUVERS"] = "1.1.0" tbhdu.header["RADECSYS"] = "FK5" tbhdu.header["EQUINOX"] = 2000.0 tbhdu.header["HDUCLASS"] = "OGIP" tbhdu.header["HDUCLAS1"] = "EVENTS" tbhdu.header["HDUCLAS2"] = "ACCEPTED" tbhdu.header["DATE"] = t_begin.tt.isot tbhdu.header["DATE-OBS"] = t_begin.tt.isot tbhdu.header["DATE-END"] = t_end.tt.isot tbhdu.header["RESPFILE"] = os.path.split(parameters["rmf"])[-1] tbhdu.header["PHA_BINS"] = parameters["nchan"] tbhdu.header["ANCRFILE"] = os.path.split(parameters["arf"])[-1] tbhdu.header["CHANTYPE"] = parameters["channel_type"] tbhdu.header["MISSION"] = parameters["mission"] tbhdu.header["TELESCOP"] = parameters["telescope"] tbhdu.header["INSTRUME"] = parameters["instrument"] tbhdu.header["RA_PNT"] = parameters["sky_center"][0] tbhdu.header["DEC_PNT"] = parameters["sky_center"][1] tbhdu.header["ROLL_PNT"] = parameters["roll_angle"] tbhdu.header["AIMPT_X"] = parameters["aimpt_coords"][0] tbhdu.header["AIMPT_Y"] = parameters["aimpt_coords"][1] if parameters["dither_params"]["dither_on"]: tbhdu.header["DITHXAMP"] = parameters["dither_params"]["x_amp"] tbhdu.header["DITHYAMP"] = parameters["dither_params"]["y_amp"] tbhdu.header["DITHXPER"] = parameters["dither_params"]["x_period"] tbhdu.header["DITHYPER"] = parameters["dither_params"]["y_period"] start = pyfits.Column(name='START', format='1D', unit='s', array=np.array([0.0])) stop = pyfits.Column(name='STOP', format='1D', unit='s', array=np.array([parameters["exposure_time"]])) tbhdu_gti = pyfits.BinTableHDU.from_columns([start, stop]) tbhdu_gti.name = "STDGTI" tbhdu_gti.header["TSTART"] = 0.0 tbhdu_gti.header["TSTOP"] = parameters["exposure_time"] tbhdu_gti.header["HDUCLASS"] = "OGIP" tbhdu_gti.header["HDUCLAS1"] = "GTI" tbhdu_gti.header["HDUCLAS2"] = "STANDARD" tbhdu_gti.header["RADECSYS"] = "FK5" tbhdu_gti.header["EQUINOX"] = 2000.0 tbhdu_gti.header["DATE"] = t_begin.tt.isot tbhdu_gti.header["DATE-OBS"] = t_begin.tt.isot tbhdu_gti.header["DATE-END"] = t_end.tt.isot hdulist = [pyfits.PrimaryHDU(), tbhdu, tbhdu_gti] pyfits.HDUList(hdulist).writeto(filename, overwrite=overwrite)
wdsMaster['col3'].name = numObjs wdsMaster['col7'].name = posAngleFirst wdsMaster['col8'].name = posAngleLast wdsMaster['col9'].name = sepFirst wdsMaster['col10'].name = sepLast wdsMaster['col11'].name = priMag wdsMaster['col12'].name = secMag wdsMaster['col13'].name = spectralType wdsMaster['col14'].name = priRaProperMotion wdsMaster['col15'].name = priDecProperMotion # Constriant parameters # Constraints is the actual numbers -- upper and lower bounds for # different properties. constraints = {} observing_date = Time.now() def getWdsInterestingHere(): ''' Gets the WDS table constrained to what stars are both interesting and viewable. ''' global wdsInterestingHere return wdsInterestingHere def getWdsInteresting(): ''' Gets the WDS table constrained to what stars are interesting. '''
'rf_gain': 50, 'if_gain': 0, 'bb_gain': 0, 'frequency': 1420e6, 'bandwidth': 2.5e6, 'channels': 1024, 't_sample': 1, 'duration': 5 } # Calibrate #print('[*] CALIBRATING...') #virgo.observe(obs_parameters=calibration, obs_file='calibration.dat') #print('[+] CALIBRATION COMPLETE') current_time = Time.now() for i in range(0, 360, 5): print('i: '+str(i)) # Get RA/Dec if i != 0: while Time.now() < current_time-(duration*u.second/2)+(1199.88*u.second): #1199.88*u.second): sleep(1) current_time = Time.now() print('[!] Time RIGHT NOW:') print(current_time) current_time = current_time+(duration*u.second/2) #Convert Alt/Az to RA/Dec AltAzcoordiantes = SkyCoord(alt = altitude*u.deg, az = 0*u.deg, obstime = current_time, frame = 'altaz', location = athens)
scipy_optimize_options=scipy_optimize_options) # TODO: Create plots of the output # TODO: 3. Scatter plots of one value versus another if __name__ == '__main__': # Use Dask to to fit the spectra client = distributed.Client() print('Dask processing of {:n} spectra'.format(nx*ny)) # Name of the model we are considering observation_model_name = observation_model.name # Get the start time t_start = Time.now() # Do the model fits results = client.map(dask_fit_fourier_pl_c, powers) z = client.gather(results) # Get the end time and calculate the time taken t_end = Time.now() print('Time taken to ', (t_end-t_start).to(u.s)) # Now go through all the results and save out the results # Total number of outputs = 2*n_parameters + 3 # For short hand call n_parameters 'n' instead # 0 : n-1 : parameter values # n : 2n-1 : error in parameter values # 2n + 0 : AIC