def fits_create(self, nspec, coords, system='ga'): """ Open a fits file for reading and create a primary HDU with the observation attributes. Inputs: - ``nspec``: Number of spectra to collect. - ``coords``: Coordinates of the target of observation. \ Format: (lon/ra, lat/dec) - ``system``: Coordinate system of ``coords`` (eq, ga). Return: - This function returns a primary HDU with a header containing \ the attributes of the observation. """ # Check that the user isn't a dingus if system != 'ga' and system != 'eq': raise ValueError('Invalid coordinate system: ' + system) # Create a header and write spectral info to it. obs_attr = _fits.Header() obs_attr['NSPEC'] = (nspec, 'Number of spectra recorded') obs_attr['BOFFILE'] = (self.boffile, 'FPGA binary code') obs_attr['MODE'] = (self.mode, 'Spectrometer mode') obs_attr['FPGA'] = (self.clock_rate, 'FPGA clock speed (Hz)') obs_attr['IADC'] = (self.iadc_rate, 'iADC clock speed (Hz)') obs_attr['DOWNSAMP'] = (self.downsample, 'ADC downsampling period.') obs_attr['SAMPRATE'] = (self.samp_rate, 'Downsampled clock speed (Hz)') obs_attr['BW'] = (self.bandwidth, 'Bandwidth of spectra (Hz)') obs_attr['NCHAN'] = (self.nchan, 'Number of frequency channels') obs_attr['RES'] = (self.resolution, 'Frequency resolution (Hz)') obs_attr['FFTSHIFT'] = (self.fft_shift, 'FFT Shifting instructions') obs_attr['ACCLEN'] = (self.acc_len, 'Number of clock cycles') obs_attr['INTTIME'] = (self.int_time, 'Integration time of spectra') obs_attr['SCALE'] = (self.scale, 'Average instead of sum on ROACH') # Set the coordinates. Both RA/Dec and galactic will be stored. obs_start_seconds = _time.time() obs_start = get_epoch(obs_start_seconds) obs_start_jd = julian_date(obs_start_seconds) if system == 'ga': lon, lat = coords_deg2rad(coords) galactic = _ephem.Galactic(lon, lat, epoch=obs_start) equatorial = _ephem.Equatorial(galactic) else: ra, dec = coords_deg2rad(coords) equatorial = _ephem.Equatorial(ra, dec, epoch=obs_start) galactic = _ephem.Galactic(equatorial) # Pack the coordinates into the FITS header. obs_attr['L'] = (ephem2deg(galactic.lon), 'Galactic longitude') obs_attr['B'] = (ephem2deg(galactic.lat), 'Galactic latitude') obs_attr['RA'] = (ephem2deg(equatorial.ra), 'Right Ascension') obs_attr['DEC'] = (ephem2deg(equatorial.dec), 'Declination') obs_attr['JD'] = (obs_start_jd, 'Julian date of start time') obs_attr['UTC'] = (obs_start, 'Starting date of accumulation') obs_attr['TIME'] = (obs_start_seconds, 'Seconds since epoch') return _fits.PrimaryHDU(header=obs_attr)
def galactic(self): ra, dec = self.QTH.radec_of(str(self.az), str(self.alt)) eq_grid = ephem.Equatorial(ra, dec) gal_lat, gal_lon = ephem.Galactic( eq_grid).lat / degree, ephem.Galactic(eq_grid).lon / degree return round(gal_lat, 0), round(gal_lon, 0)
def transform(in_position, in_system, out_system, observer=None): """Simple coordinate transforms between commonly used coordinate systems. position: input position as a float tuple (longitude, latitude) in degrees in_system, out_system: coordinate system strings; one of horizon: Alt, Az equatorial: RA, DEC galactic: GLON, GLAT observer: ephem.Observer (needed when converting to / from horizon system Returns: transformed input position as a float tuple (longitude, latitude) in degrees See http://stackoverflow.com/questions/11169523/how-to-compute-alt-az-for-given-galactic-coordinate-glon-glat-with-pyephem """ # Set the default observer observer = observer if observer else HESS() # Internally use radians; #in_position = np.radians(in_position) # Transform in_position to Equatorial coordinates ra, dec: if in_system == 'horizon': ra, dec = map(float, observer.radec_of(in_position[0], in_position[1])) elif in_system == 'equatorial': ra, dec = in_position elif in_system == 'galactic': galactic = ephem.Galactic(in_position[0], in_position[1]) equatorial = ephem.Equatorial(galactic) ra, dec = equatorial.ra.real, equatorial.dec.real else: raise RuntimeError('in_system = %s not supported' % in_system) # Here we have ra, dec in radians as floats # Now transform Equatorial coordinates to out_system: if out_system == 'horizon': equatorial = ephem.Equatorial(ra, dec) body = ephem.FixedBody() body._ra = equatorial.ra body._dec = equatorial.dec body._epoch = equatorial.epoch body.compute(observer) out_position = body.az, body.alt elif out_system == 'equatorial': out_position = ra, dec elif out_system == 'galactic': equatorial = ephem.Equatorial(ra, dec) galactic = ephem.Galactic(equatorial) out_position = galactic.lon.real, galactic.lat.real else: raise RuntimeError('out_system = %s not supported' % out_system) # Clip longitude to 0 .. 360 deg range if out_position[0] > 360: out_position[0] = out_position[0] - 360 # Return out position in radians return out_position
def eq_gal3(eqRA, eqDEC): coordset = ephem.Equatorial(np.radians(eqRA), np.radians(eqDEC), epoch='2000') g = ephem.Galactic(coordset) templon, templat=float(g.lon), float(g.lat) l_deg = np.degrees(templon) b_deg = np.degrees(templat) return b_deg, l_deg
def testcrdsys(self): """Test coordinate conversions for accuracy""" eq_ec_ga = [ [ ('19:59:28.3566','40:44:02.096'), ('317.7054323','59.3254895'), ('76.1898379','5.7554756')], [ ('12:30:49.4233','12:23:28.043'), ('182.0592608','14.4166861'), ('283.7777978','74.4911308')], [ ('13:25:27.6152','-43:01:08.805'), ('217.1433477','-31.3319020'), ('309.5158743','19.4173247')]] for eq,ec,ga in eq_ec_ga: eq_ec = a.coord.convert(eq,'eq','ec') eq_ga = a.coord.convert(eq,'eq','ga') ec_eq = a.coord.convert(ec,'ec','eq') ec_ga = a.coord.convert(ec,'ec','ga') ga_eq = a.coord.convert(ga,'ga','eq') ga_ec = a.coord.convert(ga,'ga','ec') eq_ck = e.Equatorial(eq[0], eq[1], epoch=e.J2000).get() ec_ck = e.Ecliptic(ec[0], ec[1], epoch=e.J2000).get() ga_ck = e.Galactic(ga[0], ga[1], epoch=e.J2000).get() self.assertAlmostEqual(eq_ec[0], ec_ck[0], 4) self.assertAlmostEqual(eq_ec[1], ec_ck[1], 4) self.assertAlmostEqual(eq_ga[0], ga_ck[0], 4) self.assertAlmostEqual(eq_ga[1], ga_ck[1], 4) self.assertAlmostEqual(ec_eq[0], eq_ck[0], 4) self.assertAlmostEqual(ec_eq[1], eq_ck[1], 4) self.assertAlmostEqual(ec_ga[0], ga_ck[0], 4) self.assertAlmostEqual(ec_ga[1], ga_ck[1], 4) self.assertAlmostEqual(ga_eq[0], eq_ck[0], 4) self.assertAlmostEqual(ga_eq[1], eq_ck[1], 4) self.assertAlmostEqual(ga_ec[0], ec_ck[0], 4) self.assertAlmostEqual(ga_ec[1], ec_ck[1], 4)
def convert_to_galactic(alpha, delta): gallongs = [] gallats = [] for coord_in_ra, coord_in_dec in zip(alpha, delta): coord = ephem.Equatorial( str(coord_in_ra * (24. / 360.)), str(coord_in_dec), epoch='2000') # input needs to be in HOURS as a STRING g = ephem.Galactic( coord, epoch='2000' ) # output is in degrees not hours--it's latitude/longitude spt = re.split('\:', str(g.lat)) gallat = float(spt[0]) / abs(float(spt[0])) * ( abs(float(spt[0])) + float(spt[1]) / 60. + float(spt[2]) / 3600.) spt = re.split('\:', str(g.long)) gallong = float(spt[0]) / abs(float(spt[0])) * ( abs(float(spt[0])) + float(spt[1]) / 60. + float(spt[2]) / 3600.) gallongs.append(gallong) gallats.append(gallat) return scipy.array(gallongs), scipy.array(gallats)
def convert_eq2ga(ra, dec, i_epoch=e.J2000, o_epoch=None, degree_in=True, degree_out=True): if o_epoch is None: o_epoch = i_epoch if degree_in: ra = e.hours(ra * np.pi / 180.) dec = e.degrees(dec * np.pi / 180.) else: ra = e.hours(ra * np.pi) dec = e.degrees(dec * np.pi) coord = e.Equatorial(ra, dec, epoch=i_epoch) coord = e.Galactic(coord, epoch=o_epoch) l, b = coord.lon, coord.lat if degree_out: l = l * 180. / np.pi b = b * 180. / np.pi return l, b
def gal2equ(l, b): """Convert Galactic coordinates to equatorial coordinates""" ra, dec = [0, 0] if haveEphem: gal = ephem.Galactic(l * degree, b * degree) ra, dec = [x / degree for x in gal.to_radec()] return ra, dec
def getav(data,i,dust,dist): # conversion from E(B-V) to Av from Schlafly & Finkbeiner fac = 2.742 dm = 5.*np.log10(dist)-5. ra = data['ra'][i]*np.pi/180. dec = data['dec'][i]*np.pi/180. equ = ephem.Equatorial(ra, dec, epoch=ephem.J2000) gal = ephem.Galactic(equ) dsquared = ((gal.lon*180./np.pi - dust['lon'])**2 + (gal.lat*180./np.pi - dust['lat'])**2 ) pos = np.argmin(dsquared) ebv = dust['vals'][pos,:,:] dms = np.arange(4.0,19.5,0.5) ebvs = np.zeros(20) for j in range(0,len(ebvs)): ebvs[j] = np.interp(dm,dms,ebv[j,:]) med = np.median(ebvs) std = np.std(ebvs) #print gal.lon*180./np.pi,gal.lat*180./np.pi,dm,med #pdb.set_trace() #return fac*gaussian(ebv_in,1.,np.median(ebvs),np.std(ebvs),0.) return med,std
def extract(self): if not self.active: return default ret = default ## do some tests on the data try: if self.ra < 0.0 or self.ra >= 360.0: ret.update({'ra': None}) else: ret.update({'ra': ephem.degrees(str(self.ra))}) except: ret.update({'ra': None}) try: if self.dec < -90.0 or self.dec > 90.0: ret.update({'dec': None}) else: ret.update({'dec': ephem.degrees(str(self.dec))}) except: ret.update({'dec': None}) if ret['dec'] is not None and ret['ra'] is not None: np = ephem.Equatorial(ret['ra'], ret['dec'], epoch='2000') else: return ret g = ephem.Galactic(np) e = ephem.Ecliptic(np) ret = {'galb': rad2deg*float(g.lat), 'gall': rad2deg*float(g.long), \ 'ecb': rad2deg*float(e.lat), 'ecl': rad2deg*float(e.long), \ 'ra': rad2deg*float(np.ra), 'dec': rad2deg*float(np.dec)} return ret
def azEl2Gal(Az, El, t, tel): djd = d + t/seconds_per_julian_day tel.date=djd ra, dec = tel.radec_of(Az,El) eq = ephem.Equatorial(ra,dec) gc = ephem.Galactic(eq) return gc.long, gc.lat
def __str__(self): """Verbose human-friendly string representation of target object.""" descr = str(self.name) if self.aliases: descr += ' (%s)' % (', '.join(self.aliases), ) descr += ', tags=%s' % (' '.join(self.tags), ) if 'radec' in self.tags: # pylint: disable-msg=W0212 descr += ', %s %s' % (self.body._ra, self.body._dec) if self.body_type == 'azel': descr += ', %s %s' % (self.body.az, self.body.el) if self.body_type == 'gal': l, b = ephem.Galactic( ephem.Equatorial(self.body._ra, self.body._dec)).get() descr += ', %.4f %.4f' % (rad2deg(l), rad2deg(b)) if self.flux_model is None: descr += ', no flux info' else: descr += ', flux defined for %g - %g MHz' % ( self.flux_model.min_freq_MHz, self.flux_model.max_freq_MHz) if self.flux_freq_MHz is not None: flux = self.flux_model.flux_density(self.flux_freq_MHz) if not np.isnan(flux): descr += ', flux=%.1f Jy @ %g MHz' % (flux, self.flux_freq_MHz) return descr
def coordinate_transform(self, coordinates: tuple, system_and_date: tuple): """ Transform coordinates from other systems to celestial coordinates Args: coordinates (tuple): system_and_date (tuple): Returns: """ position = np.radians(coordinates) # Convert coordinates from degrees to radians if system_and_date[1] == "Now": epoch = self.current_time() # Get the current time and date as the epoch else: epoch = system_and_date[1] self.observer.date = epoch if system_and_date[0] == "Horizontal": converted_ra, converted_dec = np.degrees(self.observer.radec_of(position[1], position[0])) elif system_and_date[0] == "Galactic": galactic_posit = ephem.Galactic(position[1], position[0], epoch=epoch) converted_ra, converted_dec = np.degrees(galactic_posit.to_radec()) # Convert from Galactic elif system_and_date[0] == "Ecliptic": ecliptic_position = ephem.Ecliptic(position[1], position[0], epoch=epoch) converted_ra, converted_dec = np.degrees(ecliptic_position.to_radec()) # Convert from Ecliptic coordinates else: converted_ra, converted_dec = coordinates return converted_ra, converted_dec # Return the coordinate tuple
def description(self): """Complete string representation of target object, sufficient to reconstruct it.""" names = ' | '.join([self.name] + self.aliases) tags = ' '.join(self.tags) fluxinfo = self.flux_model.description if self.flux_model is not None else None fields = [names, tags] if self.body_type == 'azel': # Check if it's an unnamed target with a default name if names.startswith('Az:'): fields = [tags] fields += [str(self.body.az), str(self.body.el)] if fluxinfo: fields += [fluxinfo] elif self.body_type == 'radec': # Check if it's an unnamed target with a default name if names.startswith('Ra:'): fields = [tags] # pylint: disable-msg=W0212 fields += [str(self.body._ra), str(self.body._dec)] if fluxinfo: fields += [fluxinfo] elif self.body_type == 'gal': # Check if it's an unnamed target with a default name if names.startswith('Galactic l:'): fields = [tags] l, b = ephem.Galactic( ephem.Equatorial(self.body._ra, self.body._dec)).get() fields += ['%.4f' % (rad2deg(l), ), '%.4f' % (rad2deg(b), )] if fluxinfo: fields += [fluxinfo] elif self.body_type == 'tle': # Switch body type to xephem, as XEphem only saves bodies in xephem edb format (no TLE output) tags = tags.replace(tags.partition(' ')[0], 'xephem tle') edb_string = self.body.writedb().replace(',', '~') # Suppress name if it's the same as in the xephem db string edb_name = edb_string[:edb_string.index('~')] if edb_name == names: fields = [tags, edb_string] else: fields = [names, tags, edb_string] elif self.body_type == 'xephem': # Replace commas in xephem string with tildes, to avoid clashing with main string structure # Also remove extra spaces added into string by writedb edb_string = '~'.join([ edb_field.strip() for edb_field in self.body.writedb().split(',') ]) # Suppress name if it's the same as in the xephem db string edb_name = edb_string[:edb_string.index('~')] if edb_name == names: fields = [tags] fields += [edb_string] return ', '.join(fields)
def add_plane(): for longi in linspace(0, 360., 100.): ga = ephem.Galactic(longi / degrad, 0. / degrad, epoch=2000) eq = ephem.Equatorial(ga, epoch=2000) add_point(float(eq.ra), float(eq.dec), flipRA=1, color='orange', label="Galactic Plane" if (longi == 0) else "")
def Trans_galaeq(longi, lati): l = longi * pi / 180 b = lati * pi / 180 tmp = ephem.Galactic(l, b, epoch='2000') eq = ephem.Equatorial(tmp) alpha = float(eq.ra) * 180 / pi delta = float(eq.dec) * 180 / pi aa = [alpha, delta] return (aa)
def galacticPlane(self): p = [] for t in range(0, 360): e = ephem.Equatorial(ephem.Galactic(t * pi / 180, 0, epoch=ephem.J2000), epoch=ephem.J2000) p.append((e.ra * 180 / pi, e.dec * 180 / pi)) return p
def Trans(alpha, delta): RA = alpha * pi / 180 DEC = delta * pi / 180 tmp = ephem.Equatorial(RA, DEC, epoch='2000') lb = ephem.Galactic(tmp) b = float(lb.lat) * 180 / pi l = float(lb.long) * 180 / pi aa = [l, b] return (aa)
def galactic(self, timestamp=None, antenna=None): """Calculate target's galactic (l, b) coordinates as seen from antenna at time(s). This calculates the galactic coordinates of the target, based on the J2000 *astrometric* equatorial coordinates. This is its position relative to the Galactic reference frame for the epoch of J2000. Parameters ---------- timestamp : :class:`Timestamp` object or equivalent, or sequence, optional Timestamp(s) in UTC seconds since Unix epoch (defaults to now) antenna : :class:`Antenna` object, optional Antenna which points at target (defaults to default antenna) Returns ------- l : :class:`ephem.Angle` object, or array of same shape as *timestamp* Galactic longitude, in radians b : :class:`ephem.Angle` object, or array of same shape as *timestamp* Galactic latitude, in radians Raises ------ ValueError If no antenna is specified, and no default antenna was set either """ if self.body_type == 'gal': l, b = ephem.Galactic( ephem.Equatorial(self.body._ra, self.body._dec)).get() if is_iterable(timestamp): return np.tile(l, len(timestamp)), np.tile(b, len(timestamp)) else: return l, b ra, dec = self.astrometric_radec(timestamp, antenna) if is_iterable(ra): lb = np.array([ ephem.Galactic(ephem.Equatorial(ra[n], dec[n])).get() for n in xrange(len(ra)) ]) return lb[:, 0], lb[:, 1] else: return ephem.Galactic(ephem.Equatorial(ra, dec)).get()
def clusterSample(): clusters = [{ 'name': 'M17', 'distance': 2, 'ra': '18:20:26', 'dec': '-17:10:01' }, { 'name': 'Wd2', 'distance': 5, 'ra': '10:23:58', 'dec': '-57:45:49' }, { 'name': 'Wd1', 'distance': 5, 'ra': '16:47:04', 'dec': '-45:51:05' }, { 'name': 'RSGC1', 'distance': 6, 'ra': '18:37:58', 'dec': '-06:52:53' }, { 'name': 'RSGC2', 'distance': 6, 'ra': '18:39:20', 'dec': '-06:05:10' }] py.close(1) py.figure(1, linewidth=2, figsize=(16, 10)) py.subplots_adjust(left=0.05, right=0.97, bottom=0.1, top=0.95, wspace=0.2, hspace=0.25) for ii in range(len(clusters)): clust = clusters[ii] obj = ephem.FixedBody() obj._ra = ephem.hours(clust['ra']) obj._dec = ephem.degrees(clust['dec']) obj._epoch = 2000 obj.compute() gal = ephem.Galactic(obj) longitude = math.degrees(float(gal.lon)) print '' print '%-10s %s %s l = %.1f' % \ (clust['name'], clust['ra'], clust['dec'], longitude) py.subplot(2, 3, ii + 1) properMotions(longitude, clust['distance'], clust['name'])
def transform_celestial(coords, systems): lons, lats = np.radians(coords['lon']), np.radians(coords['lat']) out = Table() out['lon'] = np.zeros(len(coords), dtype='float64') out['lat'] = np.zeros(len(coords), dtype='float64') for ii, (lon, lat) in enumerate(zip(lons, lats)): # Create coordinate in input system if systems['in'] == 'fk5': coord = ephem.Equatorial(lon, lat) elif systems['in'] == 'fk4': coord = ephem.Equatorial(lon, lat, epoch=ephem.B1950) elif systems['in'] == 'galactic': coord = ephem.Galactic(lon, lat) elif systems['in'] == 'ecliptic': coord = ephem.Ecliptic(lon, lat) else: raise ValueError() # Convert to appropriate output system # Retrieving output system coordinates is system specific # because the attribute names depend on the system if systems['out'] == 'fk5': coord = ephem.Equatorial(coord, epoch=ephem.J2000) lon, lat = coord.ra, coord.dec elif systems['out'] == 'fk4': coord = ephem.Equatorial(coord, epoch=ephem.B1950) lon, lat = coord.ra, coord.dec elif systems['out'] == 'galactic': coord = ephem.Galactic(coord) lon, lat = coord.lon, coord.lat elif systems['out'] == 'ecliptic': coord = ephem.Ecliptic(coord) lon, lat = coord.lon, coord.lat else: raise ValueError() out[ii]['lon'] = np.degrees(lon) out[ii]['lat'] = np.degrees(lat) return out
def chimera_handler(self, payload, root): t0 = time.time() # Check if it is a real GRB ra, dec = float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C1" ).text ), float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C2" ).text) packet_type = int( root.find("./What/Param[@name='Packet_Type']").attrib['value']) site = self.getSite() ephem_site = site.getEphemSite(site.ut()) grb = ephem.FixedBody() grb._ra, grb._dec = ra, dec grb.compute(ephem_site) # Conditions to pull the observation trigger # TODO: implement min_moon_distance -> Position(coord.fromD(grb.alt), coord.fromD(grb.az)) - site.moonpos() # In[8]: a = Position.fromAltAz(Coord.fromD(10), Coord.fromD(10)) # # In[9]: b = Position.fromAltAz(Coord.fromD(10), Coord.fromD(20)) # # In[11]: a.angsep(b).D # Out[11]: 10.0 moondist = Position.fromAltAz(Coord.fromD(float(grb.alt)), Coord.fromD(float(grb.az))).angsep( site.moonpos()) if moondist > self['obs-min_moondist']: self.log.debug("Moon is OK! Moon distance = %.2f deg" % moondist) else: self.log.debug("Moon is NOT OK! Moon distance = %.2f deg" % moondist) # TODO: check if Test_Notice != True (for INTEGRAL) if grb.alt >= self['obs-min_alt'] and packet_type in range( 1000): # self['obs-packets']: gal_coord = ephem.Galactic(grb) ebv = get_SFD_dust([gal_coord.long], [gal_coord.lat], dustmap=self.dust_file, interpolate=False) if ebv < self['obs-ebv_max']: self.log.debug('Total analysis time: %6.3f secs' % (time.time() - t0)) self.trigger_observation(ra, dec) else: self.log.debug( "Reject alert type %i. ALT = %.2f, RA = %.2f DEC = %.2f. Config: %d, %s" % (packet_type, grb.alt, ra, dec, self['obs-min_alt'], str(self['obs-packets'])))
def radec2gal(self): """ Compute the ra,dec (J2000) from Az,El location and time """ rads = np.pi / 180. radec2000 = ephem.Equatorial( rads*self.ra, rads*self.dec, epoch=ephem.J2000) # to convert to dec degrees need to replace on : with d self.epoch = "2000" gal = ephem.Galactic(radec2000) aparts = angles.phmsdms(str(gal.lon)) self.gallon = angles.sexa2deci(aparts['sign'], *aparts['vals']) aparts = angles.phmsdms(str(gal.lat)) self.gallat = angles.sexa2deci(aparts['sign'], *aparts['vals'])
def plot_galactic_plane(handles, labels): gp = [ephem.Galactic(str(lon), str(0)) for lon in range(0, 360)] galPlane = [ephem.Equatorial(coord) for coord in gp] # rewrap the ra to start at zero: that otherwise causes a problem in the plotting! temp = [(math.degrees(coord.ra), math.degrees(coord.dec)) for coord in galPlane] temp.sort(key=lambda x: x[0]) ra_galPlane = [t[0] for t in temp] dec_galPlane = [tt[1] for tt in temp] handles.append(plt.plot(ra_galPlane, dec_galPlane, 'b')) labels.append('galactic plane') # plt.plot([r+360 for r in ra_galPlane], dec_galPlane, 'b') # echo return handles, labels
def gal_index(ra, dec): p = ephem.Equatorial(str(ra), str(dec)) galactic = ephem.Galactic(p) glong = math.degrees(galactic.lon) glat = math.degrees(galactic.lat) glndx = int(glong) + 180 glndx %= 360 glndx /= args.increment glndx -= 1 gladx = int(glat) + 90 gladx /= args.increment gladx -= 1 return ((glndx, gladx))
def __init__(self, payload, root): t0 = time.time() # Check if it is a real GRB ra, dec = float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C1" ).text ), float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C2" ).text) packet_type = int( root.find("./What/Param[@name='Packet_Type']").attrib['value']) grb = ephem.FixedBody() grb._ra, grb._dec = ra, dec grb.compute(observatory) # Conditions to pull the observation trigger # TODO: implement min_moon_distance if grb.alt >= configuration[ 'min_grb_alt'] and packet_type in configuration[ 'packet_types']: gal_coord = ephem.Galactic(grb) ebv = get_SFD_dust([gal_coord.long], [gal_coord.lat], dustmap=dust_file, interpolate=False) if ebv < configuration['max_extinction']: print 'Total analysis time: %6.3f secs' % (time.time() - t0) link, html = archive(payload, root, configuration['events_dir'], configuration['events_wwwdir']) msg = 'GRB ALERT - %s - ra: %3.2f, dec: %3.2f, alt: %i deg, E_BV: %3.2f - %s' % ( get_notice_types_dict()[packet_type], ra, dec, int(grb.alt * 57.2957795), ebv, link) for chat_id in configuration["telegram_chat_ids"]: send_telegram_message(configuration['telegram_token'], chat_id, msg) for to in configuration['to_emails'].split(','): send_html_email( configuration['from_email'], to, 'GRB ALERT', html, configuration['smtp_server'], use_tls=configuration['smtp_usetls'] == "True", username=configuration['smtp_user'], password=configuration['smtp_password'])
def gc2azalt(gl,gb,ct3): global convert body_gl=gl*convert body_gb=gb*convert galactic_coord = ephem.Galactic(body_gl, body_gb) eq = ephem.Equatorial(galactic_coord) getlocal = ephem.Observer() getlocal.long, getlocal.lat = '116.97345','40.55666' # at Miyun getlocal.date = ct3 # UT body = ephem.FixedBody() body._ra = eq.ra body._dec = eq.dec body._epoch = ephem.J2000 body.compute(getlocal) return float(body.az)*180/np.pi,float(body.alt)*180/np.pi
def upload_to_archive(self, fitsfile, pngfile, txtfile): host = self.config.get('ARCHIVE', 'host') db = self.config.get('ARCHIVE', 'database') user = self.config.get('ARCHIVE', 'user') passwd = self.config.get('ARCHIVE', 'password') table = self.config.get('ARCHIVE', 'table') con = mdb.connect(host=host, passwd=passwd, db=db, user=user) # Read fitsdata f_fits = open(fitsfile, 'rb') fitsdata = f_fits.read() f_fits.close() f_png = open(pngfile, 'rb') pngdata = f_png.read() f_png.close() f_txt = open(txtfile, 'rb') txtdata = f_txt.read() f_txt.close() # Insert to database with con: cur = con.cursor() mysqlcmd = "INSERT INTO " + table + " SET file_fits=\'{0}\'".format( con.escape_string(fitsdata)) + "," mysqlcmd = mysqlcmd + "observer=\'" + self.observer + "\'," pos = ephem.Galactic(self.target) glon = str(pos.lon) glat = str(pos.lat) mysqlcmd = mysqlcmd + "glon=\'" + con.escape_string(glon) + "\'," mysqlcmd = mysqlcmd + "glat=\'" + con.escape_string(glat) + "\'," unixtime_sec = math.floor((self.site.date.datetime() - datetime(1970, 1, 1)).total_seconds()) mysqlcmd = mysqlcmd + "obsdate=" + str(unixtime_sec) + "," mysqlcmd = mysqlcmd + "obsfreq=" + str(1e-6 * self.obs_freq) + "," mysqlcmd = mysqlcmd + "bandwidth=" + str( 1e-6 * self.bandwidth) + "," mysqlcmd = mysqlcmd + "int_time=" + str(self.int_time) + "," mysqlcmd = mysqlcmd + "telescope=\'" + self.site.name + "\'," mysqlcmd = mysqlcmd + "file_png=\'{0}\'".format( con.escape_string(pngdata)) + "," mysqlcmd = mysqlcmd + "file_txt=\'{0}\'".format( con.escape_string(txtdata)) cur.execute(mysqlcmd) con.close() self.uploaded = True
def azel2radec(self): """ Compute the ra,dec (J2000) from Az,El location and time """ location = ephem.Observer() location.lon = str(self.tellon) location.lat = str(self.tellat) location.elevation = self.telelev strnow = self.utc.isoformat() # convert Time string format into value for Observer dates = strnow.split('T') datestr = dates[0] + ' ' + dates[1] location.date = datestr # compute Local Sidereal Time lst = location.sidereal_time() aparts = angles.phmsdms(str(lst)) self.lst = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=True) ## Must set the date before calculating ra, dec!!! # compute apparent RA,DEC for date of observations ra_a, dec_a = location.radec_of(str(self.telaz), str(self.telel)) fmt = 'Date = %s, LST = %s, %f (%f, %f)' # print fmt % (datestr, lst, self.lst, self.telaz, self.telel) radec = ephem.Equatorial(ra_a, dec_a, epoch=datestr) # print 'Ra,Dec %s,%s for %s' % (radec.ra, radec.dec, radec.epoch) radec2000 = ephem.Equatorial(radec, epoch=ephem.J2000) # print 'Ra,Dec %s,%s for %s' % (radec2000.ra, radec2000.dec, radec2000.epoch) # Hours aparts = angles.phmsdms(str(radec2000.ra)) self.ra = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=True) # to convert to dec degrees need to replace on : with d aparts = angles.phmsdms(str(radec2000.dec)) self.dec = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.epoch = "2000" gal = ephem.Galactic(radec2000) aparts = angles.phmsdms(str(gal.lon)) self.gallon = angles.sexa2deci(aparts['sign'], *aparts['vals']) aparts = angles.phmsdms(str(gal.lat)) self.gallat = angles.sexa2deci(aparts['sign'], *aparts['vals']) sun = ephem.Sun(location) aparts = angles.phmsdms(str(sun.az)) self.az_sun = angles.sexa2deci(aparts['sign'], *aparts['vals']) aparts = angles.phmsdms(str(sun.alt)) self.altsun = angles.sexa2deci(aparts['sign'], *aparts['vals'])
def clusterProperMotion(): name = 'Wd1' dist = distance / 1.0e3 ra = '16:47:04' dec = '-45:51:05' obj = ephem.FixedBody() obj._ra = ephem.hours(ra) obj._dec = ephem.degrees(dec) obj._epoch = 2000 obj.compute() gal = ephem.Galactic(obj) long = math.degrees(float(gal.long)) print '' print '%-10s %s %s l = %.1f' % (name, ra, dec, long) properMotions(long, dist, name)