def subirdatosVacas(diccionario): db = MySQLdb.connect('localhost', 'root', 'ufro_vacas', 'Vacas') cursor = db.cursor() creaTablaSiNoExiste(diccionario, db, cursor) Latitud = sexa2deci(diccionario['location'][0], diccionario['location'][1], diccionario['location'][2], 0) Longitud = sexa2deci(diccionario['location'][3], diccionario['location'][4], diccionario['location'][5], 0) v_s = 3.6 / 4096 * diccionario['bateria'] v_bat = (v_s - 0.7) * 16 / 5 + 0.7 print(diccionario['t_unix']) date = str( datetime.datetime.utcfromtimestamp( diccionario['t_unix'] + timeESP32).strftime("%Y-%m-%d %H:%M:%S")) tupla = (str(date), v_bat, (str(diccionario['sensors']['GPS'])).upper(), (str(diccionario['sensors']['IMU'])).upper(), (str(diccionario['sensors']['SD'])).upper(), (str(diccionario['sensors']['MIC'])).upper(), (str(not (diccionario['C_close']))).upper(), Latitud, Longitud) # Inserta los datos a la base de datos cursor.execute( """INSERT INTO Vaca{} (Fecha,Nivel_Bateria,Datos_GPS,Datos_IMU,\ Estado_SD,Datos_Microfono,Collar_Abierto,Latitud, Longitud)\ VALUES ('%s',%f,%s,%s,%s,%s,%s,%f,%f)""".format( diccionario['address']) % tupla) db.commit() db.close()
def save_datLoRa(): contador = 0 global cola1 global stop_th while True: while cola1.vacia(): if stop_th: break if stop_th: break #os.system("clear") dato = desempaquetar(cola1.extraer()) Latitud = sexa2deci(dato['location'][0], dato['location'][1], dato['location'][2], 0) Longitud = sexa2deci(dato['location'][3], dato['location'][4], dato['location'][5], 0) pickle.dump({ 'Latitud': Latitud, 'Longitud': Longitud }, open( "/home/pi/datos/vaca_ID{}.dat".format(dato['address']), 'wb'), protocol=2) print(dato) subirdatosVacas(dato) contador += 1 print("Server2 Iniciado") print("Radio LoRa encendida") print("{} Paquetes Recibidos".format(contador))
def test_sexa2deci(): assert sexa2deci(1, 1, 0, 0) == 1 assert sexa2deci(-1, 1, 0, 0) == -1 assert sexa2deci(1, 23, 59, 59.99999) == 23 + 59 / 60.0 + 59.99999 / 3600.0 assert sexa2deci(-1, 23, 59, 59.99999) == -1 * (23 + 59 / 60.0 + 59.99999 / 3600.0)
def save_datLoRa(): contador=0 global cola1 global stop_th while True: while cola1.vacia(): if stop_th: break if stop_th: break #os.system("clear") data = cola1.extraer() dato=desempaquetar(data[0])#Desempaquetado y extracción de la cola Latitud=sexa2deci(dato['location'][0],dato['location'][1],dato['location'][2],0) Longitud=sexa2deci(dato['location'][3],dato['location'][4],dato['location'][5],0) try: pickle.dump({'Latitud':Latitud,'Longitud':Longitud},open("/home/pi/datos/vaca_ID{}.dat".format(dato['address']),'wb'),protocol=2) except: debugmsg("Error al guardar en .dat") try: subirdatosVacas(dato) print(dato) print("RSSI : {}[dBm]".format(data[1])) except: debugmsg("Error al subir en Servidor") contador += 1 print("Server2 Iniciado") print("Radio LoRa encendida") print("{} Paquetes Recibidos".format(contador))
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 azel2radec(self): """ Compute the ra,dec (J2000) from Az,El location and time """ if ephemOK: 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] if ephemOK: 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)) radec = ephem.Equatorial(ra_a, dec_a, epoch=datestr) radec2000 = ephem.Equatorial(radec, epoch=ephem.J2000) # 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" # now update galactic coordinates if ephemOK: self.radec2gal() 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 subirdatosVacas(diccionario): creaTablaSiNoExiste(diccionario) global cursor global db Latitud = sexa2deci(diccionario['position'][0], diccionario['position'][1], diccionario['position'][2], 0) Longitud = sexa2deci(diccionario['position'][3], diccionario['position'][4], diccionario['position'][5], 0) tupla = (diccionario['address'], diccionario['t_unix'], diccionario['bateria'], diccionario['sensors']['GPS'], diccionario['sensors']['IMU'], diccionario['sensors']['SD'], diccionario['sensors']['MIC'], not diccionario['C_close'], Latitud, Longitud) # Inserta los datos a la base de datos cursor.execute( "INSERT INTO Vaca{0} (ID,Fecha,Nivel_Bateria,Datos_GPS,Datos_IMU,Estado_SD,Datos_Microfono,Collar_Abierto,Latitud, Longitud) VALUES (%s,%s,%s,%b,%b,%b,%b,%s,%f,%f)" .format(diccionario['address']), tupla) db.commit() db.close()
def calcazel(ra, dec, longitude=-79.8397, latitude=38.4331, elevation=800.): """ Compute the ra,dec (J2000) from Az,El location and time """ location = ephem.Observer() location.lon = angles.d2r(longitude) location.lat = angles.d2r(latitude) location.elevation = elevation now = datetime.datetime.utcnow() strnow = now.isoformat() dates = strnow.split('T') datestr = dates[0] + ' ' + dates[1] location.date = datestr lst = location.sidereal_time() fmt = 'Date = %s, LST = %s' print fmt % (datestr, lst) # first put ra,dec in ephemeris format radec2000 = ephem.Equatorial( ra, dec, epoch=ephem.J2000) # now compute ra, dec of date radec = ephem.Equatorial(radec2000.ra, radec2000.dec, epoch=datestr) print 'Ra,Dec = %s, %s (J2000)' % (radec2000.ra, radec2000.dec) gal = ephem.Galactic(radec2000) print 'Lon,Lat= %s, %s (Galactic)' % (gal.lon, gal.lat) object = ephem.FixedBody() object._ra = radec.ra object._dec = radec.dec object.compute(location) # need to turn dd:mm:ss into float aparts = angles.phmsdms(str(object.az)) az = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=False) aparts = angles.phmsdms(str(object.alt)) el = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=False) # print "Az: %s -> %f" % (str(object.az), az) # print "El: %s -> %f" % (str(object.alt), el) fmt = 'Az, El = %.2f, %.2f (degrees)' print fmt % (az, el) return az, el
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 read_spec_ast(self, fullname): """ Read an ascii radio Spectrum file or an event in radio samples and fill a Spectrum object """ # turn on/off printing verbose = True verbose = False # Read the file. try: if os.path.isfile(fullname): f2 = open(fullname, 'r') except: print("Can Not open File: %s" % (fullname)) self.nChan = 0 self.nSamples = 0 return # read the whole file into a single variable, which is a list of every row of the file. inlines = f2.readlines() f2.close() # initialize some variable to be lists: x1 = [] y1 = [] y2 = [] datacount = 0 linecount = 0 # scan the rows of the file stored in lines, and put the values into some variables: for line in inlines: parts = line.split() if linecount == 0: parts[1] = parts[1].upper() if parts[1] != 'FILE:': print("") print("read_spec_ascii input error!") print("") print("Input not an NSF Spectrum file:", fullname) exit() linecount = linecount + 1 # if a very short or blank line if len(line) < 3: continue if linecount == 2: self.noteA = line[2:].replace('\n', '') # if a comment or parameter line, decode value if line[0] == '#': # parse keywords as upper case: ie Ra == RA parts[1] = parts[1].upper() if parts[1] == 'UTC': timefmt = "%Y-%m-%d %H:%M:%S.%f" utc = datetime.datetime.strptime(parts[3] + " " + parts[4], timefmt) self.utc = utc if parts[1] == "SECONDS": self.seconds = float(parts[3]) if parts[1] == 'CENTERFREQ': self.centerFreqHz = float(parts[3]) if parts[1] == 'CENTERFREQ=': self.centerFreqHz = float(parts[2]) if parts[1] == 'BANDWIDTH': self.bandwidthHz = float(parts[3]) if parts[1] == 'DURATION': self.durationSec = float(parts[3]) if parts[1] == 'DELTAX': self.deltaFreq = float(parts[3]) if parts[1] == 'LST': lstparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(lstparts['sign'], *lstparts['vals']) self.lst = x * 15. # convert back to degrees if verbose: print(parts[3], x) if parts[1] == 'AZ': self.telaz = degree2float(parts[3], parts[1]) if parts[1] == 'EL': self.telel = degree2float(parts[3], parts[1]) if parts[1] == 'COUNT': self.count = int(parts[3]) if parts[1] == 'NCHAN': self.nChan = int(parts[3]) if self.nChan > self.nSamples: nData = max(self.nChan, self.nSamples) self.xdata = np.zeros(nData) self.ydataA = np.zeros(nData) self.ydataB = np.zeros(nData) if parts[1] == 'NSAMPLES': self.nSamples = int(parts[3]) if self.nChan < self.nSamples: nData = max(self.nChan, self.nSamples) self.xdata = np.zeros(nData) self.ydataA = np.zeros(nData) self.ydataB = np.zeros(nData) if parts[1] == 'BUNIT': otherparts = line.split('=') self.bunit = str(otherparts[1]).strip() if verbose: print('Bunit ', self.bunit) if parts[1] == 'NSPEC': self.nSpec = int(parts[3]) if parts[1] == 'NTIME': self.nTime = int(parts[3]) if self.nTime > 0: self.nSpec = 0 if parts[1] == 'NAVE': self.nave = int(parts[3]) if parts[1] == 'NMEDIAN': self.nmedian = int(parts[3]) if parts[1] == 'REFCHAN': self.refChan = float(parts[3]) if parts[1] == 'REFSAMPL': self.refSample = float(parts[3]) if parts[1] == 'FFT_RATE': self.fft_rate = int(parts[3]) if self.fft_rate < 1: self.fft_rate = 1 if parts[1] == 'ETAA': self.etaA = float(parts[3]) if parts[1] == 'ETAB': self.etaB = float(parts[3]) if parts[1] == 'POLANGLE': self.polAngle = float(parts[3]) if parts[1] == 'EPEAK': self.epeak = float(parts[3]) if parts[1] == 'ERMS': self.erms = float(parts[3]) if parts[1] == 'EMJD': self.emjd = float(parts[3]) # parse GAIN1 = 10. etc; but ignore GAINS = line apart = parts[1] ifind = apart.find("GAIN") if ifind >= 0: if verbose: print(parts) gainnumber = str(apart[ifind + 4]) if gainnumber.isdigit(): i = int(gainnumber) n = len(parts) self.gains[i - 1] = float(parts[n - 1]) if verbose: print('Gain %d: %f' % (i, self.gains[i - 1])) if parts[1] == 'OBSERVER': otherparts = line.split('=') self.observer = str(otherparts[1]).strip() if verbose: print('Observer: ', self.observer) if parts[1] == 'DEVICE': otherparts = line.split('=', 1) if len(otherparts) > 1: self.device = str(otherparts[1]).strip() else: print('Error parsing device : ', line) if verbose: print('Device : ', self.device) if parts[1] == 'DATADIR': otherparts = line.split('=', 1) if len(otherparts) > 1: self.datadir = str(otherparts[1]).strip() else: print('Error parsing datadir : ', line) if verbose: print('DataDir : ', self.datadir) if parts[1] == 'SITE': otherparts = line.split('=') self.site = str(otherparts[1]).strip() self.noteA = self.site # site is new note in interface if verbose: print('Site : ', self.site) if parts[1] == 'CITY': otherparts = line.split('=') self.city = str(otherparts[1]).strip() if verbose: print('City : ', self.city) if parts[1] == 'REGION': otherparts = line.split('=') self.region = str(otherparts[1]).strip() if verbose: print('Region : ', self.region) if parts[1] == 'COUNTRY': otherparts = line.split('=') self.country = str(otherparts[1]).strip() if verbose: print('Country : ', self.country) if parts[1] == 'NOTEA': otherparts = line.split('=') self.noteA = str(otherparts[1]).strip() if verbose: print('Note A : ', self.noteA) if parts[1] == 'NOTEB': otherparts = line.split('=') self.noteB = str(otherparts[1]).strip() if verbose: print('Note B : ', self.noteB) if parts[1] == 'AST_VERS': otherparts = line.split('=') if verbose: self.version = str(otherparts[1]).strip() if parts[1] == 'FRAME': otherparts = line.split('=') self.frame = str(otherparts[1]).strip() if verbose: print('FRAME : ', self.frame) if parts[1] == 'TELTYPE': otherparts = line.split('=') self.telType = str(otherparts[1]).strip() if verbose: print('Tel Type: ', self.telType) if parts[1] == 'LON' or parts[1] == 'GALLON': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.gallon = x if parts[1] == 'LAT' or parts[1] == 'GALLAT': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.gallat = x # if parse telescope geographic latitude and longitude into float if parts[1] == 'TELLON': self.tellon = degree2float(parts[3], parts[1]) if parts[1] == 'TELLAT': self.tellat = degree2float(parts[3], parts[1]) # parse ra, dec into float if parts[1] == 'RA': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.ra = x * 15. # convert back to degrees if verbose: print('RA', parts[3], aparts, x) if parts[1] == 'DEC': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.dec = x # if sun coordinates into a float if parts[1] == 'ALT_SUN': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.altsun = x if parts[1] == 'AZ_SUN': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.az_sun = x # this is the end of the if first character is a # IF statement continue # sometimes there are user comments in the top few lines; ignore if linecount < 5: continue # start data processing datacount = datacount + 1 p = line.split() nparts = len(p) if nparts < 2: continue if self.nSpec > 0: # if there are spectra in the file try: x1.append(float(p[1])) except: x1.append(0.0) try: y1.append(float(p[2])) except: y1.append(0.0) if self.nSpec > 1: try: y2.append(float(p[3])) except: y2.append(0.0) #else this file contains an event; a time series of samples if self.nTime > 0: if nparts == 2: # event time format: I, Q # p[0] is index, which is skipped in processing try: y1.append(float(p[0])) except: y1.append(0.0) try: y2.append(float(p[1])) except: y2.append(0.0) else: # event time format: index, dt, I, Q # p[0] is index, which is skipped in processing try: x1.append(float(p[1])) except: x1.append(0.0) try: y1.append(float(p[2])) except: y1.append(0.0) try: y2.append(float(p[3])) except: y2.append(0.0) # at this point all data and header keywords are read self.ydataA = np.array(y1) # always transfer values series nData = len(self.ydataA) if self.nSpec > 0: self.xdata = np.array(x1) # transfer x axis; channels or time if self.nSpec > 1: # if more than one spectrum self.ydataB = np.array(y2) # transfer it too self.nChan = nData self.nSamples = 0 if self.nTime > 0: self.nSamples = nData self.nChan = 0 self.ydataB = np.array(y2) # transfer Q samples dt = 1. / (self.bandwidthHz) # compute time per sample t = -dt * self.refSample # time tag relative to reference sample if verbose: print("Time Offset of First Sample (%d): %15.9f (s)" % (self.refSample, t)) self.xdata = np.zeros(self.nSamples) for iii in range(self.nSamples): self.xdata[iii] = t t += dt if self.refChan <= 1.: self.refChan = self.nChan / 2 return #end of read_spec_ascii
maxvel = 180. minvel = -180. # define the reference location and FWHM raStr = sys.argv[1] decStr = sys.argv[2] # will use sum within FWHM and take the reference as 1 to 2 FWHM radec2000 = ephem.Equatorial( raStr, decStr, epoch=ephem.J2000) print 'Ra,Dec = %s, %s (J2000)' % (radec2000.ra, radec2000.dec) #radec = ephem.Equatorial(radec2000.ra, radec2000.dec, epoch=datestr) gal = ephem.Galactic(radec2000) print 'Lon,Lat= %s, %s (Galactic)' % (gal.lon, gal.lat) # need to turn dd:mm:ss into float aparts = angles.phmsdms(raStr) ra0 = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=True) aparts = angles.phmsdms(decStr) dec0 = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=False) print 'ra,dec: ', ra0,dec0 # convert to radians ra0 = angles.d2r( ra0) dec0 = angles.d2r( dec0) c = 299792. # (v km/sec) nuh1 = 1420.4056 # neutral hydrogen frequency (MHz) thot = 285.0 # define hot and cold #thot = 272.0 # 30 Farenheit = 272 K tcold = 10.0 tmin = 20.0 tmax = 999.0 # define reasoanable value limits
def read_spec_ast(self, fullname): """ Read an ascii radio Spectrum file and return a radioSpectrum object """ # turn on/off printing verbose = True verbose = False # Read the file. f2 = open(fullname, 'r') # read the whole file into a single variable, which is a list of every row of the file. lines = f2.readlines() f2.close() # initialize some variable to be lists: x1 = [] y1 = [] y2 = [] datacount = 0 linecount = 0 # scan the rows of the file stored in lines, and put the values into some variables: for line in lines: parts = line.split() if linecount == 0: parts[1] = parts[1].upper() if parts[1] != 'FILE:': print "" print "read_spec_ascii input error!" print "" print "Input not an NSF Spectrum file:", fullname exit() linecount = linecount + 1 # if a very short or blank line if len(line) < 3: continue if linecount == 2: self.noteA = line[2:].replace('\n', '') # if a comment or parameter line, decode value if line[0] == '#': # parse keywords as upper case: ie Ra == RA parts[1] = parts[1].upper() if parts[1] == 'UTC': timefmt = "%Y-%m-%d %H:%M:%S.%f" utc = datetime.datetime.strptime(parts[3] + " " + parts[4], timefmt) self.utc = utc if parts[1] == 'CENTERFREQ': self.centerFreqHz = float(parts[3]) if parts[1] == 'CENTERFREQ=': self.centerFreqHz = float(parts[2]) if parts[1] == 'BANDWIDTH': self.bandwidthHz = float(parts[3]) if parts[1] == 'DURATION': self.durationSec = float(parts[3]) if parts[1] == 'DELTAX': self.deltaFreq = float(parts[3]) if parts[1] == 'LST': lstparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(lstparts['sign'], *lstparts['vals']) self.lst = x*15. # convert back to degrees if verbose: print parts[3], x if parts[1] == 'AZ': self.telaz = degree2float(parts[3], parts[1]) if parts[1] == 'EL': self.telel = degree2float(parts[3], parts[1]) if parts[1] == 'COUNT': self.count = int(parts[3]) if parts[1] == 'NCHAN': self.nChan = int(parts[3]) if parts[1] == 'BUNIT': otherparts = line.split('=') self.bunit = str( otherparts[1]).strip() if verbose: print 'Bunit ', self.bunit if parts[1] == 'NSPEC': self.nSpec = int(parts[3]) if parts[1] == 'NAVE': self.nave = int(parts[3]) if parts[1] == 'NMEDIAN': self.nmedian = int(parts[3]) if parts[1] == 'REFCHAN': self.refChan = float(parts[3]) if parts[1] == 'FFT_RATE': self.fft_rate = int(parts[3]) if self.fft_rate < 1: self.fft_rate = 1 if parts[1] == 'ETAA': self.etaA = float(parts[3]) if parts[1] == 'ETAB': self.etaB = float(parts[3]) if parts[1] == 'POLANGLE': self.polAngle = float(parts[3]) if parts[1] == 'LNA' or parts[1] == 'GAINS': # get one or more gains separated by ';' gains = [] for jjj in range(3, len(parts)): gainstr = parts[jjj].replace(';', ' ') gainstr = gainstr.replace(',', ' ') moreparts = gainstr.split() for kkk in range(len(moreparts)): gains.append(float(moreparts[kkk])) if verbose: print 'read: parts: ', parts print 'read: gains: ', gains self.gains = numpy.array(gains) if parts[1] == 'LNA=' or parts[1] == 'GAINS=': # get one or more gains separated by ';' gains = [] for jjj in range(2, len(parts)): gainstr = parts[jjj].replace(';', ' ') gainstr = gainstr.replace(',', ' ') moreparts = gainstr.split() for kkk in range(len(moreparts)): gains.append(float(moreparts[kkk])) self.gains = numpy.array(gains) apart = parts[1] if apart[0:3] == 'GAIN': i = int( apart[4]) if i > 0 and i < 6: n = len( parts) self.gains[i-1] = float( parts[n-1]) else: if apart[4] != 'S': print "Error parsing GAINn: ", line if parts[1] == 'OBSERVER': otherparts = line.split('=') self.observer = str( otherparts[1]).strip() if verbose: print 'Observer: ', self.observer if parts[1] == 'DEVICE': otherparts = line.split('=', 1) if len(otherparts) > 1: self.device = str( otherparts[1]).strip() else: print 'Error parsing device : ', line if verbose: print 'Device : ', self.device if parts[1] == 'DATADIR': otherparts = line.split('=', 1) if len(otherparts) > 1: self.datadir = str( otherparts[1]).strip() else: print 'Error parsing datadir : ', line if verbose: print 'DataDir : ', self.datadir if parts[1] == 'SITE': otherparts = line.split('=') self.site = str( otherparts[1]).strip() if verbose: print 'Site : ', self.site if parts[1] == 'CITY': otherparts = line.split('=') self.city = str( otherparts[1]).strip() if verbose: print 'City : ', self.city if parts[1] == 'REGION': otherparts = line.split('=') self.region = str( otherparts[1]).strip() if verbose: print 'Region : ', self.region if parts[1] == 'COUNTRY': otherparts = line.split('=') self.country = str( otherparts[1]).strip() if verbose: print 'Country : ', self.country if parts[1] == 'NOTEA': otherparts = line.split('=') self.noteA = str( otherparts[1]).strip() if verbose: print 'Note A : ', self.noteA if parts[1] == 'NOTEB': otherparts = line.split('=') self.noteB = str( otherparts[1]).strip() if verbose: print 'Note B : ', self.noteB if parts[1] == 'AST_VERS': otherparts = line.split('=') if verbose: self.version = str( otherparts[1]).strip() if parts[1] == 'FRAME': otherparts = line.split('=') self.frame = str( otherparts[1]).strip() if verbose: print 'FRAME : ', self.frame if parts[1] == 'TELTYPE': otherparts = line.split('=') self.telType = str( otherparts[1]).strip() if verbose: print 'Tel Type: ', self.telType if parts[1] == 'LON' or parts[1] == 'GALLON': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.gallon = x if parts[1] == 'LAT' or parts[1] == 'GALLAT': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.gallat = x # if parse telescope geographic latitude and longitude into float if parts[1] == 'TELLON': self.tellon = degree2float(parts[3], parts[1]) if parts[1] == 'TELLAT': self.tellat = degree2float(parts[3], parts[1]) # parse ra, dec into float if parts[1] == 'RA': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.ra = x * 15. # convert back to degrees if verbose: print 'RA', parts[3], aparts, x if parts[1] == 'DEC': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.dec = x # if sun coordinates into a float if parts[1] == 'ALT_SUN': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.altsun = x if parts[1] == 'AZ_SUN': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.az_sun = x # this is the end of the if first character is a # IF statement continue # sometimes there are user comments in the top few lines; ignore if linecount < 5: continue # start data processing datacount = datacount+1 p = line.split() np = len(p) if (np < 3): continue try: x1.append(float(p[1])) except: x1.append( 0.0) try: y1.append(float(p[2])) except: y1.append( 0.0) if self.nSpec > 1: try: y2.append(float(p[3])) except: y2.append( 0.0) # at this point all data and header keywords are read self.xdata = numpy.array(x1) # transfer self.ydataA = numpy.array(y1) # always transfer 1 spectrum if self.nSpec > 1: # if more than one spectrum self.ydataB = numpy.array(y2) # transfer it too ndata = len(self.xdata) if self.nChan != ndata: print "File header Miss-match and number of channels in data" print ": %f != %f" % (self.nChan, ndata) self.nChan = int(ndata) return
def read_spec_ast(self, fullname): """ Read an ascii radio Spectrum file and return a radioSpectrum object """ # Read the file. f2 = open(fullname, 'r') # read the whole file into a single variable, which is a list of every row of the file. lines = f2.readlines() f2.close() # initialize some variable to be lists: x1 = [] y1 = [] datacount = 0 linecount = 0 # scan the rows of the file stored in lines, and put the values into some variables: for line in lines: parts = line.split() linecount = linecount + 1 # if a very short or blank line if len(line) < 3: continue if linecount == 2: self.noteA = line[2:].replace('\n', '') # if a comment or parameter line, decode value if line[0] == '#': # parse keywords as upper case: ie Ra == RA parts[1] = parts[1].upper() if parts[1] == 'UTC': timefmt = "%Y-%m-%d %H:%M:%S.%f" utc = datetime.datetime.strptime(parts[3] + " " + parts[4], timefmt) self.utc = utc if parts[1] == 'CENTERFREQ': self.centerFreqHz = float(parts[3]) if parts[1] == 'CENTERFREQ=': self.centerFreqHz = float(parts[2]) if parts[1] == 'BANDWIDTH': self.bandwidthHz = float(parts[3]) if parts[1] == 'DELTAX': self.deltaFreq = float(parts[3]) if parts[1] == 'LST': lstparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(lstparts['sign'], *lstparts['vals']) self.lst = x*15. # convert back to degrees # print parts[3], x if parts[1] == 'AZ': self.telaz = degree2float(parts[3], parts[1]) if parts[1] == 'EL': self.telel = degree2float(parts[3], parts[1]) if parts[1] == 'COUNT': self.count = int(parts[3]) if parts[1] == 'NCHAN': self.nChan = int(parts[3]) if parts[1] == 'REFCHAN': self.refChan = float(parts[3]) if parts[1] == 'ETAA': self.etaA = float(parts[3]) if parts[1] == 'ETAB': self.etaB = float(parts[3]) if parts[1] == 'POLANGLE': self.polAngle = float(parts[3]) if parts[1] == 'LNA' or parts[1] == 'GAINS': # get one or more gains separated by ';' gains = [] for jjj in range(3, len(parts)): gainstr = parts[jjj].replace(';', ' ') gainstr = gainstr.replace(',', ' ') moreparts = gainstr.split() for kkk in range(len(moreparts)): gains.append(float(moreparts[kkk])) self.gains = numpy.array(gains) if parts[1] == 'LNA=' or parts[1] == 'GAINS=': # get one or more gains separated by ';' gains = [] for jjj in range(2, len(parts)): gainstr = parts[jjj].replace(';', ' ') gainstr = gainstr.replace(',', ' ') moreparts = gainstr.split() for kkk in range(len(moreparts)): gains.append(float(moreparts[kkk])) self.gains = numpy.array(gains) if parts[1] == 'DURATION': self.durationSec = time2float(parts[3], parts[1]) if parts[1] == 'LON' or parts[1] == 'GALLON': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.gallon = x if parts[1] == 'LAT' or parts[1] == 'GALLAT': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.gallat = x # if parse telescope geographic latitude and longitude into float if parts[1] == 'TELLON': self.tellon = degree2float(parts[3], parts[1]) if parts[1] == 'TELLAT': self.tellat = degree2float(parts[3], parts[1]) # parse ra, dec into float if parts[1] == 'RA': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.ra = x * 15. # convert back to degrees # print 'RA', parts[3], aparts, x if parts[1] == 'DEC': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.dec = x # if sun coordinates into a float if parts[1] == 'ALT_SUN': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.altsun = x if parts[1] == 'AZ_SUN': aparts = angles.phmsdms(parts[3]) x = angles.sexa2deci(aparts['sign'], *aparts['vals']) self.az_sun = x continue # sometimes there are user comments in the top few lines; ignore if linecount < 5: continue # start data processing datacount = datacount+1 p = line.split() x1.append(float(p[1])) y1.append(float(p[2])) # at this point all data and header keywords are read # self.xdata = numpy.array(x1)*1.e6 # convert to Hz self.xdata = numpy.array(x1) # convert to Hz self.ydataA = numpy.array(y1) #scale to a reasonable value for plotting ndata = len(self.xdata) if self.nChan != ndata: print "File header Miss-match and number of channels in data" print ": %f != %f" % (self.nChan, ndata) self.nChan = int(ndata) return
def test_sexa2deci(): assert sexa2deci(1, 1, 0, 0) == 1 assert sexa2deci(-1, 1, 0, 0) == -1 assert sexa2deci(1, 23, 59, 59.99999) == 23+59/60.0+59.99999/3600.0 assert sexa2deci(-1, 23, 59, 59.99999) == -1 * (23+59/60.0+59.99999/3600.0)