Example #1
0
 def __init__(self, unit, locA, locB):
     if len(locA) != 3 or len(locB) != 3:
         print("Bad Locations given")
         return
     self.telescope = ep.Observer()
     self.telescope.lat = self.TELESCOPE_LATITUDE
     self.telescope.lon = self.TELESCOPE_LONGITUDE
     # Neglect the atmosphere b/c we're using radio waves
     self.telescope.pressure = 0
     # Approximate Elevation
     self.telescope.elevation = 30
     self.location = None
     if unit == sky_point.RADC:
         line = "thing,f," + self.loc2str(locA) + "," + self.loc2str(locB) + ",1"
         self.location = ep.readdb(line)
     elif unit == sky_point.GALACTIC:
         ga = ep.Galactic(self.loc2str(locA), self.loc2str(locB), epoch=ep.J2000)
         eq = ep.Equatorial(ga)
         line = "thing,f," + str(eq.ra) + "," + str(eq.dec) + ",1"
         self.location = ep.readdb(line)
     elif unit == sky_point.AZEL:
         ra, dec = self.telescope.radec_of(self.loc2str(locA), self.loc2str(locB))
         line = "thing,f," + str(ra) + "," + str(dec) + ",1"
         self.location = ep.readdb(line)
     elif unit == sky_point.HADC:
         ra = ep.hours(self.telescope.sidereal_time() - ep.degrees(self.loc2str(locA)))
         line = "thing,f," + str(ra) + "," + self.loc2str(locB) + ",1"
         self.location = ep.readdb(line)
     else:
         print("Error, Unknown Units")
         return
     self.location.compute(self.telescope)
Example #2
0
File: TNO.py Project: dwgerdes/TNO
def SNfields():
    C1 = ephem.readdb("C1,f,03:37:05.83,-27:06:41.8,23.0,2000")
    C2 = ephem.readdb("C2,f,03:37:05.83,-29:05:18.2,23.0,2000")
    C3 = ephem.readdb("C3,f,03:30:35.62,-28:06:00.0,24.0,2000")
    X1 = ephem.readdb("X1,f,02:17:54.17,-04:55:46.2,23.0,2000")
    X2 = ephem.readdb("X2,f,02:22:39.48,-06:24:43.6,23.0,2000")
    X3 = ephem.readdb("X3,f,02:25:48.00,-04:36:00.0,24.0,2000")
    S1 = ephem.readdb("S1,f,02:51:16.80, 00:00:00.0,23.0,2000")
    S2 = ephem.readdb("S2,f,02:44:46.66,-00:59:18.2,23.0,2000")
    E1 = ephem.readdb("E1,f,00:31:29.86,-43:00:34.6,23.0,2000")
    E2 = ephem.readdb("E2,f,00:38:00.00,-43:59:52.8,23.0,2000")
    fields = [C1, C2, C3, X1, X2, X3, S1, S2, E1, E2]
    for f in fields:
        f.compute()
    return fields
Example #3
0
def get_asteroid_by_id(asteroid_id):
    init_ephem_date = request.args.get('start_date', '')
    end_ephem_date = request.args.get('end_date', '')
    lat = request.args.get('lat', '')
    lon = request.args.get('lon', '')
    alt = request.args.get('alt', '')
    asteroid = mongo.db.asteroids.find_one_or_404({"_id": ObjectId(asteroid_id)})
    #Ceres,e,10.58682,80.3932,72.58981,2.7653485,10.5735206076,0.07913825,113.4104434,55400.0,102.709698181,3.34,0.12

    orbital_elements_tuple = (asteroid["name"], asteroid["e_type"], asteroid["i"],
                              asteroid["Node"], asteroid["q"], asteroid["a"],
                              asteroid["n"], asteroid["e"], asteroid["M"],
                              asteroid["epoch"], asteroid["D"], asteroid["H"], asteroid["G"],)
    x_ephem_format = "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" % orbital_elements_tuple
    asteroid_ephem = ephem.readdb(x_ephem_format)

    here = ephem.Observer()
    here.lat, here.lon, here.elev = '33:45:10', '-84:23:37', 320.0
    here.date = ephem.date('1997/2/15')
    end = ephem.date('1997/5/15')

    ephem_list = []
    while here.date < end:
        asteroid_ephem.compute(here)
        ephem_list.append({"here_date": here.date,
                      "ra": asteroid_ephem.ra,
                      "dec": asteroid_ephem.dec,
                      "mag": asteroid_ephem.mag})
        print here.date, asteroid_ephem.ra, asteroid_ephem.dec, asteroid_ephem.mag
        here.date += 5
    asteroid["ephem_list"] = ephem_list
    return dumps(asteroid)
Example #4
0
def readbsc(filename=None):
    ''' Read entire Bright Star Catalog and return a list of PyEphem sources
    '''
    if filename is None:
        filename = '../Star Pointing/BrightStarCatalog.txt'

    try:
        f = open(filename,'r')
    except:
        print 'readbsc: Could not open file',filename
        return None

    # Read two header lines (and ignore them)
    line = f.readline()
    line = f.readline()
    srcs = []

    # Loop over lines in file
    for line in f.readlines():
        srcs.append(ephem.readdb('HR'+line[1:5]+',f,'+line[6:17]+','+line[18:30]+','+line[53:57]+',2000'))
    f.close()
    # Do an initial compute so that name, ra, dec, etc. are accessible.  Will override with compute for
    # observer later.
    for src in srcs:
        src.compute()

    return srcs
Example #5
0
def hr_catalog(site=None):
    fp = open("star.lst", "r")
    lines = fp.readlines()
    fp.close()
    stars = {}

    p = re.compile('#')
    for line in lines: 
        if not p.match(line):
            hr = line[0:4].strip()
            name = line[5:12]
            h = line[13:15]
            m = line[16:18]
            s = line[19:21]
            ra = "%s:%s:%s" % (h, m, s)

            sign = line[22:23]
            d = line[24:26]
            m = line[27:29]
            s = line[30:32]
            dec = "%s%s:%s:%s" % (sign, d, m, s)
	 
            vmag = float(line[33:38])
            bmv = float(line[39:44])
            sed = line[45:48]
            sptype = line[49:63]
            dbstr = "%s,f|S|%s,%s,%s,%f,2000" % (name, sptype, ra, dec, vmag)
            stars[hr] = ephem.readdb(dbstr)
	    if site:
		stars[hr].compute(site)
    return stars
def make_gal_equator_line(b=0, sigma=60):
    try:
        gal_l = linspace(-180,180,400)
        gal_equator_ras = []
        gal_equator_decs = []
        for l in gal_l:
            gal_eq_ra, gal_eq_dec = gal2eq(l, ((b*20/(sigma*(2*pi)**0.5))*exp(-0.5*(l/sigma)**2)))
            gal_equator_ras.append(gal_eq_ra)
            gal_equator_decs.append(gal_eq_dec)
        gal_equator_alts = []
        gal_equator_azs = []
        for n in range(len(gal_equator_ras)):
            new_point = ephem.Equatorial(str(gal_equator_ras[n]/15.), str(gal_equator_decs[n]), epoch="2000")
            ephem_line = ("EquatorSeg"+",f|M|F7," + str(new_point.ra) + "," + 
                str(new_point.dec) + ",0,2000")
            gal_equator_calced = ephem.readdb(ephem_line)
            gal_equator_calced.compute(observatory)
            if gal_equator_calced.alt > 0:
                gal_equator_alts.append(gal_equator_calced.alt)
                gal_equator_azs.append(gal_equator_calced.az)
        gal_equator_azs = array(gal_equator_azs) # similar to angle around the circle
        gal_equator_alts = array(gal_equator_alts) # similar to radius from center (zenith)
        gal_equator_zenith_radii = 90 - gal_equator_alts*180/pi
        gal_equator_azs = gal_equator_azs + pi/2
        gal_equator_plot_x = gal_equator_zenith_radii * cos(gal_equator_azs)
        gal_equator_plot_y = gal_equator_zenith_radii * sin(gal_equator_azs)
        gal_equator_plot_data = zip(gal_equator_plot_x, gal_equator_plot_y)
        # gal_equator_plot_data.sort()
        gal_equator_plot_data = array(gal_equator_plot_data)
        previous_point = array([])
        sep_list_x = []
        sep_list_y = []
        for point in gal_equator_plot_data:
            if previous_point.any():
                sep_list_x.append(point[0] - previous_point[0])
                sep_list_y.append(point[1] - previous_point[1])
            previous_point = point
        sep_array_x = array(sep_list_x)
        sep_array_y = array(sep_list_y)
        sep_array = (sep_array_x**2 + sep_array_y**2)**0.5
        if max(abs(sep_array)) > 2:
            while max(abs(sep_array)) > 2:
                jump_index = where(abs(sep_array) == max(abs(sep_array)))[0][0]+1
                gal_equator_plot_data_reordered = append(gal_equator_plot_data[jump_index:], gal_equator_plot_data[:jump_index], axis=0)
                gal_equator_plot_data = gal_equator_plot_data_reordered
                previous_point = array([])
                sep_list_x = []
                sep_list_y = []
                for point in gal_equator_plot_data:
                    if previous_point.any():
                        sep_list_x.append(point[0] - previous_point[0])
                        sep_list_y.append(point[1] - previous_point[1])
                    previous_point = point
                sep_array_x = array(sep_list_x)
                sep_array_y = array(sep_list_y)
                sep_array = (sep_array_x**2 + sep_array_y**2)**0.5
            
        return gal_equator_plot_data
    except:
        return array([[]])
Example #7
0
File: MOPplot.py Project: OSSOS/MOP
def load_edbfile(file=None):
    """Load the targets from a file"""
    import ephem,string,math
    if file is None:
        import tkFileDialog
	try:
            file=tkFileDialog.askopenfilename()
        except:
            return 
    if file is None or file == '':
        return
    f=open(file)
    lines=f.readlines()
    f.close()
    for line in lines:
        p=line.split(',')
	name=p[0].strip().upper()
	mpc_objs[name]=ephem.readdb(line)
	mpc_objs[name].compute()
        objInfoDict[name]="%6s %6s %6s\n" % ( string.center("a",6),
				            string.center("e",6),
	 				    string.center("i",6) ) 
        objInfoDict[name]+="%6.2f %6.3f %6.2f\n" % (mpc_objs[name]._a,mpc_objs[name]._e,math.degrees(mpc_objs[name]._inc))
        objInfoDict[name]+="%7.2f %7.2f\n" % ( mpc_objs[name].earth_distance, mpc_objs[name].mag)
    doplot(mpc_objs)
Example #8
0
	def __init__ (self, im, location, fprefix='./',  wrpng=1, pltmoon=0):
		self._wrpng = wrpng;
		self._im = im;
		self._fprefix = fprefix;
		self._pltmoon = pltmoon;
		self._loc = location;

		# Available locations
		if self._loc.lower() == 'lofar':
			self._obssite = ephem.Observer();
			self._obssite.pressure = 0; # To prevent refraction corrections.
			self._obssite.lon, self._obssite.lat = '6.869837540','52.915122495'; # CS002 on LOFAR
		elif self._loc.lower() == 'dwingeloo':
			self._obssite = ephem.Observer();
			self._obssite.pressure = 0; # To prevent refraction corrections.
			self._obssite.lon, self._obssite.lat = '6.396297','52.812204'; # Dwingeloo telescope
		else:
			print 'Unknown observatory site!'

		if self._pltmoon == 1:
			self._moon = ephem.Moon();
			self._casa = ephem.readdb('Cas-A,f|J, 23:23:26.0, 58:48:00,99.00,2000');

		if matplotFound ==0 & ephemFound == 0:
			print 'Matplotlib or pyephem not found! PNG Images written to disk.'
			self._wrpng = 1;
		else:
			self._imgplt = plt.imshow (abs(self._im._skymap[:,:]), extent = [self._im._l[0], self._im._l[-1], self._im._m[0], self._im._m[-1]]);
			plt.colorbar();
Example #9
0
def Calc(path, mag_cut):
    print "Starting Skycalc..."
    #mag_cut = raw_input("Highest value of magnitude of the stars: ")
    print "Calculating star positions. Please wait."  
    #os.chdir("/home/germano/workspace/SkyCalc/ImageFiles")
    images = glob.glob(path + "*.fits")

    for i in images:
        f = pf.open(i)
        h, d = f[0].header, f[0].data

        Obs = ephem.Observer()

        #Obs data    
        Obs.lat = '-30:10:20.86692'
        Obs.long = '-70:48:00.15364'
        Obs.elevation = 2123.090
        Obs.date = ephem.date(re.sub('-','/',h['date'])+' '+h['utshut'])
        star_pos = [] 
        
        #Position calculations
        BSC = path + 'BSC.edb' #Bright Star Catalog

        for line in fileinput.input(BSC):  
            star = ephem.readdb(line)
            star.compute(Obs)
            if (float(star.mag) < mag_cut):
                line = line.split(',')
                line[6].rstrip()
                star_pos.append([float(star.alt) , float(star.az), float(star.mag), float(star.name), float(line[6])])      

        star_position = open(i + '.out', 'w')
        np.savetxt(star_position, star_pos, '%s')
        star_position.close()
Example #10
0
 def pyephem_declaration(self, ObsPyephem):
     ''' Define the star in Pyephem to make astrometric calculations '''
     pyephem_star = ephem.FixedBody()
     pyephem_star = ephem.readdb('"' + str(self.name) + '"' + ",f|S|A0," + str(self.RA1950) + '|0' +
                                 "," + str(self.DEC1950) + '|0' + "," + str(self.Vmag) + ',1950,0"')
     pyephem_star.compute(ObsPyephem)
     return pyephem_star
Example #11
0
def build_stars():
    global stars
    import ephem

    for line in db.strip().split("\n"):
        star = ephem.readdb(line)
        stars[star.name] = star
Example #12
0
    def setUp(self):
        self.observer = ephem.Observer()
        self.observer.lon = "-6.1136"
        self.observer.lat = "53.2744"
        self.observer.elevation = 100
        self.observer.date = ephem.Date("2014-10-27 23:00:00")
        self.observer.epoch = "2000"

        self.target = ephem.readdb("P10frjh,e,7.43269,35.02591,162.97669," +
                                   "0.6897594,1.72051182,0.5475395," +
                                   "195.80709,10/10/2014,2000,H26.4,0.15")
        self.target.compute(self.observer)
        tjnow = ephem.Equatorial(self.target.ra, self.target.dec,
                                 epoch=self.observer.date)
        self.targetj2000 = ephem.Equatorial(tjnow, epoch='2000')

        self.observer.date = self.observer.date+ephem.minute
        self.target.compute(self.observer)
        tjnow = ephem.Equatorial(self.target.ra, self.target.dec,
                                 epoch=self.observer.date)
        self.targetj2000plus = ephem.Equatorial(tjnow, epoch='2000')
        self.rarate = str(float(self.targetj2000plus.ra -
                                self.targetj2000.ra))
        self.decrate = str(float(self.targetj2000plus.dec -
                                 self.targetj2000.dec))
Example #13
0
 def get_distance_to_earth(self, time: Node.clock, object: str):
     """Gets the distance to the Earth from `object`"""
     new_time = datetime.datetime(*time.time_obj[:7])
     try:
         return getattr(ephem, object.title())(new_time).earth_distance
     except AttributeError:
         with open("astro_db.txt") as astro_db:
             name = ""
             line = astro_db.readline()
             while name.lower() != object.lower():
                 assert line.startswith("* ")
                 name, launch_date, updated_date = line[2:].split(":")
                 name = name[:-9]
                 if name.lower() != object.lower():
                     line = astro_db.readline()
                     while line[0] != "*" or line.startswith("* Good from "):
                         line = astro_db.readline()
             year = int(astro_db.readline()[-5:])
             while year < new_time.year:
                 astro_db.readline()
                 line = astro_db.readline()
                 line = line.split("  (")[0]
                 year = int(line[-4:])
             line = astro_db.readline()
         object = ephem.readdb(line)
         object.compute(new_time)
         return object.earth_distance
Example #14
0
def filter_data(data,datetime, mag=False, alt=False, az=False, VI=False, ra_dec=False, dist=False):
    """
    Parameters:
    1. data base of standard stars
    2. local datetime entered in the form of 'YY MMM DD hh:mm:ss'
    3. magnitude, altitude, azimuth and V-I restritions, list, [min_value, max_value]
    4. ra_dec: specify ra and dec:
        if dist=False, specify the range of ra and dec, list, in dms,[min_ra,max_ra,min_dec,max_dec]
        if dist==True, one values of ra and dec, list, in dms, [ra,dec]
    5. dist: if True, specify distance from one value od ra and dec, list , in dms, [ra_range, dec_range]
    Returns:
    Pandas DataFrame for the information of the stars given the ristrictions
    """
    thob.date = gmtime(mktime(strptime(datetime,'%y %b %d %H:%M:%S')))[:6]
    namel = []
    azl = []
    altl = []
    magl = []
    VIl = []
    ral = []
    decl = []
    selected=[]
        #apply function to series pd.Series.apply or pd.DataFrame.apply data['RAJ2000'] = data['RAJ2000'].apply(dms_to_radian)
    if ra_dec and dist:
        try:
            ra,ra_dist=Angle([ra_dec[0],dist[0]],unit=u.hour); dec,dec_dist=Angle([ra_dec[1],dist[1]],unit=u.degree)
            for i in range(len(data)-1):
                if ((ra-ra_dist)<Angle(data['RAJ2000'][i],unit=u.hour)<(ra+ra_dist)) and \
                        ((dec-dec_dist)<Angle(data['DEJ2000'][i],unit=u.degree)<(dec+dec_dist)):selected.append(i)
        except:
            print 'ValueError: ra_dec must be list of 2 values [ra,dec] if dist==True'
    elif ra_dec and not dist:
        try:
            min_ra,max_ra = Angle([min_ra,max_ra],unit=u.hour)
            min_dec,max_dec = Angle([min_dec,max_dec],unit=u.degree)
            for i in range(len(data-1)):
                if data[min_ra<data['RAJ2000'][i]<max_ra and min_dec<data['DEJ2000'][i]<max_dec]: selected.append(i)
        except:
            print 'ValueError: ra_dec must be list of 4 values [min_ra,max_ra,min_dec,max_dec] if dist==False'
    else: selected = range(len(data)-1)
    data = data.loc[selected,:]
    for i in selected:
        dataline = data['SimbadName'][i]+','+'f'+','+data['RAJ2000'][i]+','+data['DEJ2000'][i]+','+str(data['Vmag'][i])
        body = ephem.readdb(dataline)
        body.compute(thob)
        if mag and alt and az and VI:
            if np.radians(alt[0]) < body.alt < np.radians(alt[1]) and \
                np.radians(az[0]) < body.az < np.radians(az[1]) and \
                mag[0]< body.mag < mag[1] and \
                VI[0]< data['V-I'][i] <VI[1]:
                namel.append(body.name);azl.append(body.az);altl.append(body.alt)
                magl.append(body.mag);VIl.append(data['V-I'])
                ral.append(radian_to_dms(body.ra));decl.append(radian_to_dms(body.dec))
        else:
            namel.append(body.name);azl.append(body.az);altl.append(body.alt)
            magl.append(body.mag);VIl.append(data['V-I'])
            ral.append(radian_to_dms(body.ra));decl.append(radian_to_dms(body.dec))
    filtered_data = pd.DataFrame.from_dict(dict([('Name',namel), ('Az',azl), ('Alt',altl),('Ra',ral),('Dec',decl),('Mag',magl),('V-I',VIl)]))
    return filtered_data
Example #15
0
def stellar(date):
    """returns a list of lists with name, SHA and Dec all navigational stars for epoch of date."""
    out = []
    for line in db.strip().split("\n"):
        st = ephem.readdb(line)
        st.compute(date)
        out.append([st.name, nadeg(2 * math.pi - ephem.degrees(st.g_ra).norm), nadeg(st.g_dec)])
    return out
Example #16
0
def readEphemFile(filename):
    catfile = open(filename)
    projobjs = []
    for line in catfile:
        obj = ephem.readdb(line)
        if obj is not None:
            projobjs.append(obj)
    return projobjs
Example #17
0
 def ephem_object(self):
     if self.ephemeride[:7] == 'pyephem':
         return getattr(ephem, self.ephemeride.split(':')[1])()
     else:
         try:
             return ephem.readdb(self.ephemeride)
         except:
             return None
Example #18
0
def main():
 # Try some SN fields:
    C1 = ephem.readdb("C1,f,03:37:05.83,-27:06:41.8,23.0,2000")
    C1.compute()
    C1field = DECamField(C1.ra, C1.dec)
    print C1field.ra, C1field.dec
    print C1field.contains(C1.ra, C1.dec+ephem.degrees('0.979'))
    print C1field.contains(ephem.degrees('04:00:00'),ephem.degrees('-30:00:00'))
Example #19
0
def set_source(name):
    """
    Returns an ephem object from the 
    source catalog.
    """

    name = name.lower()

    if name == 'sun':
        source = ephem.Sun()
    if name == 'mars':
        source = ephem.Mars()
    if name == 'jupiter':
        source = ephem.Jupiter()
    if name == 'lmc':
        source = ephem.readdb("LMC,f|G,5:23:34,-69:45:24,0.9,2000,3.87e4|3.3e4")
    if name == '3c273':
        source = ephem.readdb("3C273,f|G,12:29:06.6997,+02:03:08.598,12.8,2000,34.02|25.17")
    if name == 'sgra':
        source = ephem.readdb("sgrA,f|J,17:45:40.036,-29:00:28.17,0,2000")
    if name == 'g90':
        source = ephem.readdb("G90,f|J,21:13:44,48:12:27.17,0,2000")
    if name == 'g180':
        source = ephem.readdb("G180,f|J,05:43:11,29:1:20,0,2000")
    if name == 'orion':
        source = ephem.readdb("Orion,f|J,05:35:17.3,-05:23:28,0,2000")
    if name == 'rosett':
        source = ephem.readdb("Rosett,f|J,06:31:51,04:54:47,0,2000")
    #else:
        #print "Source not found in catalogue."
        #source = None
    
    return source
Example #20
0
def build_navStars():

    global navStarObj, navStarNum, navStarName
    
    for line in navStarDB:
        star = ephem.readdb(line[1])
        navStarObj[star.name] = star
        navStarNum[star.name] = line[0]
        navStarName[line[0]] = star.name
Example #21
0
 def test_github_58(self):
     t = ephem.readdb("P10frjh,e,7.43269,35.02591,162.97669,"
                      "0.6897594,1.72051182,0.5475395,"
                      "195.80709,10/10/2014,2000,H26.4,0.15")
     t.compute('2014/10/27')
     self.assertAlmostEqual(t.earth_distance, 0.0296238418669, 10)
     self.assertAlmostEqual(t.mag, 20.23, 2)
     self.assertAlmostEqual(t.phase, 91.1195, 2)
     self.assertAlmostEqual(t.radius, 0, 2)
     self.assertAlmostEqual(t.size, 0.00103452138137, 12)
Example #22
0
    def getEphemSpecialObj(self, target, objects):
        "Uses the given dict of ephemeris to calculate ra & dec"

        try:
            line, type = objects[target.source]
            comet = ephem.readdb(line)
            return comet
        except:
            self.errors.append("Unknown Error w/ comet: %s\n" % target.source)
            return None
Example #23
0
    def __init__(self, name, ra, dec, equinox):
        super(Body, self).__init__()

        self.name = name
        self.ra = ra
        self.dec = dec
        self.equinox = equinox

        xeph_line = "%s,f|A,%s,%s,0.0,%s" % (name[:20], ra, dec, equinox)
        self._body = ephem.readdb(xeph_line)
	def comet(self,name=''):
		url="http://www.minorplanetcenter.org/iau/Ephemerides/Comets/Soft03Cmt.txt"
		f=urllib.urlopen(url)
		s=f.read().split('\n')
		#Elimino texto sobrante
		s=filter(lambda x:x!='' and x[0]!='#',s)
		#busco una entrada concreta
		CometID=name
		comet=filter(lambda x:x.find(CometID)!=-1, s)
		print comet[0]
		return ephem.readdb(comet[0])
Example #25
0
 def readInDB(self, path):
     #returns list of Star objects from all stars in DB
     db = readFile(path)
     starList = [ ] 
     for line in db.splitlines():
         if line.startswith("#") or line == "": continue
         line = line.strip()
         body = ephem.readdb(line)
         if body.name == "Benetnasch": continue #duplicate of Alkaid
         starList.append(Star(body.name, body))
     return starList
Example #26
0
def pointing_plan(tonightsplan, orig_keys, survey_centers, nexttile, filters,
                  obs):
    time_elapsed = 0
    n_exp = 0

    for f in filters:
        if survey_centers['used_tile_{:s}'.format(f)][nexttile] == 1:
            continue

        n_exp += 1

        survey_centers['used_tile_{:s}'.format(f)][nexttile] = 1

        tile_str = ','.join([
            str(survey_centers['TILEID'][nexttile]),
            'f',
            survey_centers['RA_STR'][nexttile],
            survey_centers['DEC_STR'][nexttile],
            '20'
        ])
        this_tile = ephem.readdb(tile_str)
        this_tile.compute(obs)

        # Compute airmass
        airm = alt2airmass(float(this_tile.alt))

        # Compute moon separation
        moon.compute(obs)
        moon_dist = ephem.separation(
            (this_tile.az, this_tile.alt),
            (moon.az, moon.alt)
        )
        moon_alt = np.degrees(moon.alt)

        # Add this exposure to tonight's plan
        for key in orig_keys:
            tonightsplan[key].append(survey_centers[key][nexttile])

        tonightsplan['exp_time'].append(exp_time_filters[f])
        tonightsplan['approx_datetime'].append(obs.date)
        tonightsplan['airmass'].append(airm)
        ha = survey_centers['RA'][nexttile] - np.degrees(obs.sidereal_time())
        tonightsplan['ha'].append(ha/15.)
        tonightsplan['approx_time'].append(obs.date)
        tonightsplan['filter'].append(f)
        tonightsplan['moon_sep'].append(moon_dist)
        tonightsplan['moon_alt'].append(moon_alt)
        tonightsplan['lst'].append(np.degrees(obs.sidereal_time()))

        delta_t = exp_time_filters[f] + overheads
        time_elapsed += delta_t
        obs.date = obs.date + delta_t * s_to_days

    return time_elapsed, n_exp
	def neo(self,name=''):

		f=urllib.urlopen(url)
		s=f.read().split('\n')
		#Elimino texto sobrante
		s=filter(lambda x:x!='' and x[0]!='#',s)
		#busco una entrada concreta
		NeoID=name
		Neo=filter(lambda x:x.find(NeoID)!=-1, s)
		print Neo[0]
		return ephem.readdb(Neo[0])
Example #28
0
File: TNO.py Project: dwgerdes/TNO
def compute_TNOs(date):
# date is a pyephem date object
    comment='#'
    alltno=[]
    with open('Soft03Distant.txt') as cat:
        for line in cat:
            if line[0]!=comment: alltno.append(ephem.readdb(line))
    for transNeptunianFlyingRock in alltno:
        transNeptunianFlyingRock.compute(date)
    tno = [t for t in alltno if t.dec<ephem.degrees('05:00:00')]  # dec>5 is outside out footprint for sure.
    return tno
Example #29
0
def compute_alt_az(ra,dec,obsvat,date_time):
    obj = ephem.readdb("obj,f|M|F7,"+ra+","+dec+"0,2000")

    obsvat_data = return_observatory(obsvat)
    obsvat = ephem.Observer()
    obsvat.lat = obsvat_data[2]
    obsvat.lon = obsvat_data[1]
    obsvat.elevation = obsvat_data[3]
    obsvat.date = date_time

    obj.compute(obsvat)

    return obj.alt*180./pi,obj.az*180/pi
Example #30
0
def set_object(objname):
	if any(objname.lower() == planet for planet in planets):
		i = planets.index(objname.lower())
		obj = ep_planets[i]
		obj.compute(winer)
		objra = obj.ra; objdec = obj.dec
		ids = ''
	else:
		(rahr, decdeg, ids) = sesame_resolve(objname)
		objra = hr2hms(rahr); objdec = deg2dms(decdeg)
		db_str = '%s,f|M|x,%s,%s,0.0,2000' % (objname,objra,objdec)
		obj = ep.readdb(db_str); obj.compute(winer)
	return objra,objdec,ids, obj
Example #31
0
print(len(J), 'tiles in pass 1 plan')

#A = json.loads(open('pass1_byhand_v2.json').read())

nexti = 0
newJ = []

for j in J:
    print()
    obs.date = ephem.Date(str(j['approx_datetime']))

    rastr  = ra2hms (j['RA' ])
    decstr = dec2dms(j['dec'])
    ephemstr = str('%s,f,%s,%s,20' % (j['object'], rastr, decstr))
    #print(ephemstr)
    etile = ephem.readdb(ephemstr)
    etile.compute(obs)

    print('Tile', j['object'], 'at', j['approx_datetime'],
          'RA,Dec', j['RA'],j['dec'])
    airmass = get_airmass(float(etile.alt))
    print('Airmass:', airmass)
    lst = obs.sidereal_time()
    print('LST', lst)
    lsthr = np.rad2deg(float(obs.sidereal_time())) / 15.
    #    print('lst', lst)


    #if lsthr < 12. and lsthr > 25./60. and lsthr < 2.+25./60.: #lsthr < 3.+37./60:  # 00:25

    #### LST range to replace
Example #32
0
 def __setstate__(self, state):
     self.__dict__.update(state)
     self.body = ephem.readdb(self.xeph_line)
Example #33
0
 def test_github_193(self):
     ic = ephem.readdb('IC1101,f,15:10:56.10,+05:44:41.2,0,2000')
     ic.compute()
     c = ephem.constellation(ic)
     self.assertEqual(c, ('Vir', 'Virgo'))
Example #34
0
def print_almanac(targets):
    obsDateUTC = datetime.datetime.utcnow()

    NMSkies = ephem.Observer()
    NMSkies.lat = '32:53:23'
    NMSkies.long = '-105:28:41'
    NMSkies.elevation = 7300
    NMSkies.date = obsDateUTC
    NMSkies.horizon = '0'

    db_file = "/Users/dragonfly/Dropbox/ProjectDocuments/Databases/Xephem/NGC.edb"

    # Times will be listed in the local timezone even for the remote
    # location. This is a feature not a bug!
    localtimezone = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()

    # Sun rise/set
    sunsetUTC = NMSkies.next_setting(ephem.Sun(), use_center=True)
    sunriseUTC = NMSkies.next_rising(ephem.Sun(), use_center=True)
    sunsetMST = ephem.localtime(sunsetUTC)
    sunriseMST = ephem.localtime(sunriseUTC)

    # Sun altitude
    s = ephem.Sun()
    s.compute(NMSkies)
    sunalt = float(s.alt) * 180 / math.pi

    # Sun hour angle
    lst = NMSkies.sidereal_time()
    sun_ha = (lst - s.ra) * 180 / math.pi / 15.0
    if sun_ha > 12:
        sun_ha = sun_ha - 24.0
    if sun_ha < -12:
        sun_ha = sun_ha + 24.0

    # Moon altitude
    m = ephem.Moon()
    m.compute(NMSkies)
    moonalt = float(m.alt) * 180 / math.pi

    # Moon phase
    moonphase = float(m.moon_phase)

    # Moonrise/set
    moonriseUTC = NMSkies.next_rising(ephem.Moon(), use_center=True)
    moonsetUTC = NMSkies.next_setting(ephem.Moon(), use_center=True)
    moonriseMST = ephem.localtime(moonriseUTC)
    moonsetMST = ephem.localtime(moonsetUTC)

    # Times for flats. Evening flats should start when the sun is at -5.
    # Morning flats should start when the sun is at -10 (these are guesses).
    # So just set these to be the horizons and re-compute time of sunrise and sunset.
    NMSkies.horizon = '-5'
    eveningFlatUTC = NMSkies.next_setting(ephem.Sun(), use_center=True)
    eveningFlatMST = ephem.localtime(eveningFlatUTC)
    NMSkies.horizon = '-10'
    morningFlatUTC = NMSkies.next_rising(ephem.Sun(), use_center=True)
    morningFlatMST = ephem.localtime(morningFlatUTC)

    # Time until flats in seconds
    hoursUntilEveningFlats = 24 * (eveningFlatUTC - ephem.now())
    secondsUntilEveningFlats = int(3600 * hoursUntilEveningFlats)

    # Work out what we should probably be doing
    if sunalt > 0:
        action = 'Park'
    elif sunalt > -12:
        if sun_ha >= 0:
            action = 'EveningFlat'
        else:
            action = 'MorningFlat'
    else:
        action = 'Observe'

    # Output suggested action to the user
    print 'Location                 ', 'NewMexicoSkies'
    print 'TimeZoneForListedTimes   ', localtimezone
    print 'SuggestedAction          ', action
    print 'SiderealTime             ', str(lst)
    print 'Sunset                   ', ephem.Date(sunsetMST)
    print 'Sunrise                  ', ephem.Date(sunriseMST)
    print 'SunAltitude              %-+9.3f      [deg]' % sunalt
    print 'SunHourAngle             %-+9.3f      [hour]' % sun_ha
    print 'MoonAltitude             %-+9.3f      [deg]' % moonalt
    print 'Moonrise                 ', ephem.Date(moonriseMST)
    print 'Moonset                  ', ephem.Date(moonsetMST)
    print 'MoonPhase                 %-9.2f' % moonphase
    print 'StartEveningFlats        ', ephem.Date(eveningFlatMST)
    print 'StartMorningFlats        ', ephem.Date(morningFlatMST)
    print 'HoursUntilEveningFlats   ', hoursUntilEveningFlats
    print 'SecondsUntilEveningFlats ', secondsUntilEveningFlats

    if targets:
        print ''
        print 'Name          Altitude    Azimuth     HA         MoonSep     Rise       Transit    Set'

    for name in targets:
        target_line = ""
        for db_line in open(db_file):
            if name in db_line:
                target_line = db_line
                break
        if (target_line):
            target = ephem.readdb(target_line)
            target.compute(NMSkies)
            target_alt = float(target.alt) * 180 / math.pi
            target_rt = target.rise_time
            target_tt = target.transit_time
            target_st = target.set_time
            target_az = float(target.az) * 180 / math.pi
            target_ha = (lst - target.ra) * 180 / math.pi / 15.0
            target_moon_sep = (ephem.separation(target, m)) * 180 / math.pi
            if target_ha > 12:
                target_ha = target_ha - 24.0
            if target_ha < -12:
                target_ha = target_ha + 24.0

            riseTimeString = str(
                ephem.Date(ephem.localtime(
                    ephem.Date(target_rt)))).split(' ')[1]
            transitTimeString = str(
                ephem.Date(ephem.localtime(
                    ephem.Date(target_tt)))).split(' ')[1]
            setTimeString = str(
                ephem.Date(ephem.localtime(
                    ephem.Date(target_st)))).split(' ')[1]

            outline = "%-10s  %+9.3f   %+9.3f  %+9.3f   %+9.3f   %10s %10s %10s" % \
                      ("\'"+name+"\'", target_alt, target_az, target_ha, target_moon_sep, \
                      riseTimeString, transitTimeString, setTimeString)
            print outline

    return None
Example #35
0
    def export2pyephem(self, center='500@10', equinox=2000.):
        """Call JPL HORIZONS website to obtain orbital elements based on the
        provided targetname, epochs, and center code and create a
        PyEphem (http://rhodesmill.org/pyephem/) object. This function
        requires PyEphem to be installed.
        
        Parameters
        ----------
        center        : str
           center body (default: 500@10 = Sun)
        equinox       : float
           equinox (default: 2000.0)

        Results
        -------
        list of PyEphem objects, one per epoch
        
        Examples
        --------
        >>> import callhorizons
        >>> import numpy
        >>> import ephem

        >>> ceres = callhorizons.query('Ceres')
        >>> ceres.set_epochrange('2016-02-23 00:00', '2016-02-24 00:00', '1h')
        >>> ceres_pyephem = ceres.export2pyephem()

        >>> nau = ephem.Observer() # setup observer site
        >>> nau.lon = -111.653152/180.*numpy.pi
        >>> nau.lat = 35.184108/180.*numpy.pi
        >>> nau.elevation = 2100 # m
        >>> nau.date = '2015/10/5 01:23' # UT 
        >>> print 'next rising: %s' % nau.next_rising(ceres_pyephem[0])
        >>> print 'next transit: %s' % nau.next_transit(ceres_pyephem[0])
        >>> print 'next setting: %s' % nau.next_setting(ceres_pyephem[0])

        """

        try:
            import ephem
        except ImportError:
            print "ERROR: cannot import module PyEphem"
            return None

        # obtain orbital elements
        self.get_elements(center)

        objects = []
        for el in self.data:
            n = 0.9856076686 / numpy.sqrt(el['a']**3)  # mean daily motion
            epoch_djd = el['datetime_jd'] - 2415020.0  # Dublin Julian date
            epoch = ephem.date(epoch_djd)
            epoch_str = "%d/%f/%d" % (epoch.triple()[1], epoch.triple()[2],
                                      epoch.triple()[0])

            # export to PyEphem
            objects.append(
                ephem.readdb(
                    "%s,e,%f,%f,%f,%f,%f,%f,%f,%s,%i,%f,%f" %
                    (el['targetname'], el['incl'], el['node'], el['argper'],
                     el['a'], n, el['e'], el['meananomaly'], epoch_str,
                     equinox, el['H'], el['G'])))

        return objects
Example #36
0
 def test_github_196(self):
     line = ('2010 LG61,e,123.8859,317.3744,352.1688,7.366687,'
             '0.0492942,0.81371070,163.4277,04/27.0/2019,2000,H,0.15')
     elems = ephem.readdb(line)
     self.assertEqual(str(elems._H), 'nan')
Example #37
0
 def _recalc_body(self):
     self.xeph_line = "%s,f|A,%s,%s,0.0,%s" % (self.name[:20], self.ra,
                                               self.dec, self.equinox)
     self.body = ephem.readdb(self.xeph_line)
Example #38
0
def Juno():
    return ephem.readdb(
        'Juno,e,12.991,170.542,246.787,2.6692,0.22601,0.2575,205.808,11/5/1990,2000.0,5.31,0.30'
    )
Example #39
0
def Pallas():
    return ephem.readdb(
        'Pallas,e,34.804,173.323,309.796,2.7703,0.21375,0.2347,273.779,10/1/1989,2000.0,4.13,0.15'
    )
Example #40
0
def Eris():
    #warning: hand-compiled
    readable = 'Eris, e, 44.176, 35.890, 151.315, 67.662, 0.00177, 0.442, 204.63, 6/31/2016, 2007.0, -1.2, 0.6'
    return ephem.readdb(readable.replace(' ', ''))
Example #41
0
    def process_file(self, fn):
        ext = self.opt.ext

        expscriptpat  = os.path.join(self.scriptdir, self.expscriptpattern)
        slewscriptpat = os.path.join(self.scriptdir, self.slewscriptpattern)
        
        print('%s: found new image %s' % (str(ephem.now()), fn))

        nopass1path = os.path.join(self.scriptdir, 'nopass1')
        dopass1 = not os.path.exists(nopass1path)
        if not dopass1:
            print('Not considering Pass 1 because file exists:', nopass1path)
        nopass2path = os.path.join(self.scriptdir, 'nopass2')
        dopass2 = not os.path.exists(nopass2path)
        if not dopass2:
            print('Not considering Pass 2 because file exists:', nopass2path)
        
        # Read primary FITS header
        phdr = fitsio.read_header(fn)
        expnum = phdr.get('EXPNUM', 0)
    
        obstype = phdr.get('OBSTYPE','').strip()
        print('obstype:', obstype)
        if obstype in ['zero', 'focus', 'dome flat']:
            print('Skipping obstype =', obstype)
            return False
        elif obstype == '':
            print('Empty OBSTYPE in header:', fn)
            return False
    
        exptime = phdr.get('EXPTIME')
        if exptime == 0:
            print('Exposure time EXPTIME in header =', exptime)
            return False
    
        filt = str(phdr['FILTER'])
        filt = filt.strip()
        filt = filt.split()[0]
        if filt == 'solid':
            print('Solid (block) filter.')
            return False
    
        # Measure the new image
        kwa = {}
        if ext is not None:
            kwa.update(ext=ext)
        ps = None
        M = measure_raw(fn, ps=ps, **kwa)
    
        # Sanity checks
        ok = (M['nmatched'] >= 20) and (M.get('zp',None) is not None)
        if not ok:
            print('Failed sanity checks in our measurement of', fn, '-- not updating anything')
            # FIXME -- we could fall back to pass 3 here.
            return False
        
        # Choose the pass
        trans  = M['transparency']
        seeing = M['seeing']
        skybright = M['skybright']
        
        # eg, nominal = 20, sky = 19, brighter is 1 mag brighter than nom.
        nomsky = self.nom.sky(M['band'])
        brighter = nomsky - skybright
    
        print('Transparency: %6.02f' % trans)
        print('Seeing      : %6.02f' % seeing)
        print('Sky         : %6.02f' % skybright)
        print('Nominal sky : %6.02f' % nomsky)
        print('Sky over nom: %6.02f   (positive means brighter than nom)' %
              brighter)
    
        transcut = 0.9
        seeingcut = 1.25
        brightcut = 0.25
        
        transok = trans > transcut
        seeingok = seeing < seeingcut
        brightok = brighter < brightcut
    
        pass1ok = transok and seeingok and brightok
        pass2ok = transok or  seeingok
        
        nextpass = 3
        if pass1ok and dopass1:
            nextpass = 1
    
        elif pass2ok and dopass2:
            nextpass = 2
    
        print('Transparency cut: %s       (%6.2f vs %6.2f)' %
              (('pass' if transok else 'fail'), trans, transcut))
        print('Seeing       cut: %s       (%6.2f vs %6.2f)' %
              (('pass' if seeingok else 'fail'), seeing, seeingcut))
        print('Brightness   cut: %s       (%6.2f vs %6.2f)' %
              (('pass' if brightok else 'fail'), skybright, nomsky+brightcut))
        print('Pass 1 = transparency AND seeing AND brightness: %s' % pass1ok)
        if pass1ok and not dopass1:
            print('Pass 1 forbidden by observer!')
        print('Pass 2 = transparency OR  seeing               : %s' % pass2ok)
        if pass2ok and not dopass2:
            print('Pass 2 forbidden by observer!')
        print('Selected pass:'******'UTC now is', str(now))
        for i,j in enumerate(J):
            tstart = ephem.Date(str(j['approx_datetime']))
            if tstart > now:
                print('Found tile', j['object'], 'which starts at', str(tstart))
                iplan = i
                break
        if iplan is None:
            print('Could not find a JSON observation in pass', nextpass,
                  'with approx_datetime after now =', str(now),
                  '-- latest one', str(tstart))
            return False
    
        # Read the current sequence number
        print('%s: reading sequence number' % (str(ephem.now())))
        f = open(self.seqnumpath, 'r')
        s = f.read()
        f.close()
        seqnum = int(s)
        print('%s: sequence number: %i' % (str(ephem.now()), seqnum))
        
        # How many exposures ahead should we write?
        Nahead = 10
    
        # Set observing conditions for computing exposure time
        self.obs.date = now
    
        P = fits_table()
        P.type = []
        P.tilename = []
        #P.tileid = []
        P.filter = []
        P.exptime = []
        P.ra = []
        P.dec = []
        P.passnumber = []
        
        iahead = 0
        for ii,jplan in enumerate(J[iplan:]):
            if iahead >= Nahead:
                break
            tilename = str(jplan['object'])
            nextseq = seqnum + 1 + iahead
    
            print('Considering planning tile %s for exp %i' % (tilename, nextseq))
            
            # Check all planned tiles before this one for a duplicate tile.
            dup = False
            for s in range(nextseq-1, 0, -1):
                t = self.planned_tiles[s]
                if t == tilename:
                    dup = True
                    print('Wanted to plan tile %s (pass %i element %i) for exp %i'
                          % (tilename, nextpass, iplan+ii, nextseq),
                          'but it was already planned for exp %i' % s)
                    break
            if dup:
                continue
    
            self.planned_tiles[nextseq] = tilename
            iahead += 1
    
            # Find this tile in the tiles table.
            tile = get_tile_from_name(tilename, self.tiles)
            ebv = tile.ebv_med
    
            nextband = str(jplan['filter'])[0]
    
            print('Selected tile:', tile.tileid, nextband)
            rastr  = ra2hms (jplan['RA' ])
            decstr = dec2dms(jplan['dec'])
            ephemstr = str('%s,f,%s,%s,20' % (tilename, rastr, decstr))
            etile = ephem.readdb(ephemstr)
            etile.compute(self.obs)
            airmass = get_airmass(float(etile.alt))
            print('Airmass of planned tile:', airmass)
    
            if M['band'] == nextband:
                nextsky = skybright
            else:
                # Guess that the sky is as much brighter than canonical
                # in the next band as it is in this one!
                nextsky = ((skybright - nomsky) + self.nom.sky(nextband))

            fid = self.nom.fiducial_exptime(nextband)
            expfactor = exposure_factor(fid, self.nom,
                                        airmass, ebv, seeing, nextsky, trans)
            print('Exposure factor:', expfactor)
            exptime = expfactor * fid.exptime
    
            ### HACK -- safety factor!
            print('Exposure time:', exptime)
            exptime *= 1.1
            exptime = int(np.ceil(exptime))
            print('Exposure time with safety factor:', exptime)

            exptime = np.clip(exptime, fid.exptime_min, fid.exptime_max)
            print('Clipped exptime', exptime)
            if nextband == 'z':
                # Compute cap on exposure time to avoid saturation /
                # loss of dynamic range.
                t_sat = self.nom.saturation_time(nextband, nextsky)
                if exptime > t_sat:
                    exptime = t_sat
                    print('Reduced exposure time to avoid z-band saturation: %.1f' % exptime)
            exptime = int(exptime)
    
            print('Changing exptime from', jplan['expTime'], 'to', exptime)
            jplan['expTime'] = exptime
    
            status = ('Exp %i: Tile %s, Pass %i, RA %s, Dec %s' %
                      (nextseq, tilename, nextpass, rastr, decstr))
    
            print('%s: updating exposure %i to tile %s' %
                  (str(ephem.now()), nextseq, tilename))
    
            expscriptfn = expscriptpat % (nextseq)
            exptmpfn = expscriptfn + '.tmp'
            f = open(exptmpfn, 'w')
            f.write(('# Exp %i Tile: %s, set at Seq %i, %s\n' %
                     (nextseq, tilename, seqnum, str(ephem.now()))) +
                    expscript_for_json(jplan, status=status))
            f.close()
    
            slewscriptfn = slewscriptpat % (nextseq)
            slewtmpfn = slewscriptfn + '.tmp'
            f = open(slewtmpfn, 'w')
            f.write(slewscript_for_json(jplan))
            f.close()
    
            os.rename(exptmpfn, expscriptfn)
            print('Wrote', expscriptfn)
            os.rename(slewtmpfn, slewscriptfn)
            print('Wrote', slewscriptfn)
    
            self.obs.date += (exptime + self.nom.overhead) / 86400.
    
            print('%s: updated exposure %i to tile %s' %
                  (str(ephem.now()), nextseq, tilename))
    
            P.tilename.append(tilename)
            #P.tileid.append(tile.tileid)
            P.filter.append(nextband)
            P.exptime.append(exptime)
            P.ra.append(jplan['RA'])
            P.dec.append(jplan['dec'])
            P.passnumber.append(nextpass)
            P.type.append('P')
    
        for i,J in enumerate([self.J1,self.J2,self.J3]):
            passnum = i+1
            for j in J:
                tstart = ephem.Date(str(j['approx_datetime']))
                if tstart < now:
                    continue
                P.tilename.append(str(j['object']))
                filt = str(j['filter'])[0]
                P.filter.append(filt)
                P.exptime.append(j['expTime'])
                P.ra.append(j['RA'])
                P.dec.append(j['dec'])
                P.passnumber.append(passnum)
                P.type.append('%i' % passnum)
    
        P.to_np_arrays()
        fn = 'mosbot-plan.fits'
        tmpfn = fn + '.tmp'
        P.writeto(tmpfn)
        os.rename(tmpfn, fn)
        print('Wrote', fn)
        
        return True
ArraySite.date = dateAndTime

splitSideTime = str(ArraySite.sidereal_time()).split(':')

sideTime = float(splitSideTime[0]) + float(splitSideTime[1])/60 + float(splitSideTime[2])/60/60
print "LST: ", sideTime

# Latitude and longitude for galactic coordinates;
#ga = ephem.Galactic('202.5','36.4236')
ga = ephem.Galactic('225.703','10.8069')
eq = ephem.Equatorial(ga)

print "Long: ", ephem.degrees(225.703/360*2*3.1415926)
print "Lat: ", ephem.degrees(10.8069/360*2*3.1415926)

bodyString = "Test,f|M|F7," + str(eq.ra) + "," + str(eq.dec) + ",0,2012"
#print bodyString
testPS = ephem.readdb(bodyString)
testPS.compute(ArraySite)
#print testPS.dec
print "RA: ", ephem.degrees(eq.ra)
print "Dec: ", ephem.degrees(eq.dec)
print "Azimuth: ", testPS.az
print "Altitude: ", testPS.alt



#print eq.ra
#print eq.dec

#print ga.long, ga.lat
Example #43
0
def filter_data(data,
                datetime,
                mag=False,
                alt=False,
                az=False,
                VI=False,
                ra_dec=False,
                dist=False):
    """
    Parameters:
    1. data base of standard stars
    2. local datetime entered in the form of 'YY MMM DD hh:mm:ss'
    3. magnitude, altitude, azimuth and V-I restritions, list, [min_value, max_value]
    4. ra_dec: specify ra and dec AS TUPLE:
        if dist=False, specify the range of ra and dec, list, in dms,[min_ra,max_ra,min_dec,max_dec]
        if dist==True, one values of ra and dec, list, in dms, [ra,dec]
    5. dist: if True, specify distance from one value od ra and dec, list , in dms, [ra_range, dec_range]
    Returns:
    Pandas DataFrame for the information of the stars given the ristrictions
    """
    thob.date = gmtime(mktime(strptime(datetime, '%y %b %d %H:%M:%S')))[:6]
    namel = []
    azl = []
    altl = []
    magl = []
    VIl = []
    ral = []
    decl = []
    selected = []
    #apply function to series pd.Series.apply or pd.DataFrame.apply data['RAJ2000'] = data['RAJ2000'].apply(dms_to_radian)
    if ra_dec and dist:
        try:
            ra, ra_dist = Angle([ra_dec[0], dist[0]], unit=u.hour)
            dec, dec_dist = Angle([ra_dec[1], dist[1]], unit=u.degree)
            for i in range(len(data) - 1):
                if ((ra-ra_dist)<Angle(data['RAJ2000'][i],unit=u.hour)<(ra+ra_dist)) and \
                        ((dec-dec_dist)<Angle(data['DEJ2000'][i],unit=u.degree)<(dec+dec_dist)):
                    selected.append(i)
        except:
            print 'ValueError: ra_dec must be list of 2 values [ra,dec] if dist==True'
    elif ra_dec and not dist:
        try:
            min_ra, max_ra = Angle([min_ra, max_ra], unit=u.hour)
            min_dec, max_dec = Angle([min_dec, max_dec], unit=u.degree)
            for i in range(len(data - 1)):
                if data[min_ra < data['RAJ2000'][i] < max_ra
                        and min_dec < data['DEJ2000'][i] < max_dec]:
                    selected.append(i)
        except:
            print 'ValueError: ra_dec must be list of 4 values [min_ra,max_ra,min_dec,max_dec] if dist==False'
    data = data.loc[selected, :]
    for i in selected:
        dataline = data['SimbadName'][i] + ',' + 'f' + ',' + data['RAJ2000'][
            i] + ',' + data['DEJ2000'][i] + ',' + str(data['Vmag'][i])
        body = ephem.readdb(dataline)
        body.compute(thob)

        if mag or alt or az or VI:
            namel.append(body.name)
            ral.append(radian_to_dms(body.ra))
            decl.append(radian_to_dms(body.dec))
            if alt and az:
                if np.radians(alt[0]) < body.alt < np.radians(alt[1]) and \
                    np.radians(az[0]) < body.az < np.radians(az[1]):
                    azl.append(body.az)
                    altl.append(body.alt)
                else:
                    azl.append('NaN')
                    altl.append('NaN')
            elif mag:
                if mag[0] < body.mag < mag[1]:
                    magl.append(body.mag)
                else:
                    magl.append('NaN')
            elif VI:
                if VI[0] < data['V-I'][i] < VI[1]:
                    VIl.append(data['V-I'][i])
                else:
                    VIl.append('NaN')

        else:
            namel.append(body.name)
            azl.append(body.az)
            altl.append(body.alt)
            magl.append(body.mag)
            VIl.append(data['V-I'])
            ral.append(radian_to_dms(body.ra))
            decl.append(radian_to_dms(body.dec))

    filtered_data = pd.DataFrame.from_dict(
        dict([('Name', namel), ('Az', azl), ('Alt', altl), ('Ra', ral),
              ('Dec', decl), ('Mag', magl), ('V-I', VIl)]))

    return filtered_data
Example #44
0
def Vesta():
    return ephem.readdb(
        'Vesta,e,7.139,104.015,149.986,2.3607,0.27174,0.0906,152.190,11/5/1990,2000.0,3.16,0.34'
    )
Example #45
0
def Hygiea():
    return ephem.readdb(
        'Hygiea,e,3.840,283.833,315.832,3.1365,0.17743,0.1202,104.089,11/5/1990,2000.0,5.37,0.15'
    )
Example #46
0
import ephem

# http://rhodesmill.org/pyephem/quick.html
me = ephem.Observer()
me.lon, me.lat, me.elevation = '108.5000', '34.5000', 800.0
line1 = "BEIDOU G1"
line2 = "1 36287U 10001A   18194.84994825 -.00000297  00000-0  00000-0 0  9999"
line3 = "2 36287   1.4745   3.9768 0004214 156.8560 216.8921  1.00270561 31144"
sat = ephem.readtle(line1, line2, line3)

me.date = '2018/7/14'  # ephem.now()
sat.compute(me)

print(sat.az * 180.0 / 3.1416)  # 卫星的方位角
print(sat.alt * 180.0 / 3.1416)  # 卫星的仰角
print(sat.range_velocity)  # 卫星相对于观察者的运动速率,为正,表示卫星正在远离观察者

ephwy = ephem.readdb(
    "C/1995 O1 (Hale-Bopp),e,89.0083,283.3220,130.5617,179.4002,0.0004102,0.99494219,0.0000,03/29.7186/1997,2000,g -2.0,4.0"
)
ephwy.compute('2018/7/14')
print(ephwy.name)
print("%s %s" % (ephwy.ra, ephwy.dec))
print("%s %s" % (ephem.constellation(ephwy), ephwy.mag))
Example #47
0
    def process_file(self, fn):
        ext = self.opt.ext
        print('%s: found new image %s' % (str(ephem.now()), fn))

        nopass1path = 'nopass1'
        dopass1 = not os.path.exists(nopass1path)
        if not dopass1:
            print('Not considering Pass 1 because file exists:', nopass1path)
        nopass2path = 'nopass2'
        dopass2 = not os.path.exists(nopass2path)
        if not dopass2:
            print('Not considering Pass 2 because file exists:', nopass2path)
        
        # Read primary FITS header
        phdr = fitsio.read_header(fn)
        expnum = phdr.get('EXPNUM', 0)
    
        obstype = phdr.get('OBSTYPE','').strip()
        print('Obstype:', obstype)
        if obstype in ['zero', 'focus', 'dome flat']:
            print('Skipping obstype =', obstype)
            return False
        elif obstype == '':
            print('Empty OBSTYPE in header:', fn)
            return False
    
        exptime = phdr.get('EXPTIME')
        if exptime == 0:
            print('Exposure time EXPTIME in header =', exptime)
            return False
    
        filt = str(phdr['FILTER'])
        filt = filt.strip()
        filt = filt.split()[0]
        ## DECam?
        if filt == 'solid':
            print('Solid (block) filter.')
            return False

        obj = phdr.get('OBJECT', '')
        print('Object:', obj)
        
        # Measure the new image
        kwa = {}
        if ext is not None:
            kwa.update(ext=ext)
        ps = None
        M = measure_raw(fn, ps=ps, **kwa)
    
        # Sanity checks
        ok = (M['nmatched'] >= 20) and (M.get('zp',None) is not None)
        if not ok:
            print('Failed sanity checks in our measurement of', fn, '-- not updating anything')
            # FIXME -- we could fall back to pass 3 here.
            return False
        
        # Choose the pass
        trans  = M['transparency']
        seeing = M['seeing']
        skybright = M['skybright']
        
        # eg, nominal = 20, sky = 19, brighter is 1 mag brighter than nom.
        nomsky = self.nom.sky(M['band'])
        brighter = nomsky - skybright
    
        print('Transparency: %6.02f' % trans)
        print('Seeing      : %6.02f' % seeing)
        print('Sky         : %6.02f' % skybright)
        print('Nominal sky : %6.02f' % nomsky)
        print('Sky over nom: %6.02f   (positive means brighter than nom)' %
              brighter)
    
        transcut = 0.9
        seeingcut = 1.25
        brightcut = 0.25
        
        transok = trans > transcut
        seeingok = seeing < seeingcut
        brightok = brighter < brightcut
    
        pass1ok = transok and seeingok and brightok
        pass2ok = transok or  seeingok
        
        nextpass = 3
        if pass1ok and dopass1:
            nextpass = 1
    
        elif pass2ok and dopass2:
            nextpass = 2
    
        print('Transparency cut: %s       (%6.2f vs %6.2f)' %
              (('pass' if transok else 'fail'), trans, transcut))
        print('Seeing       cut: %s       (%6.2f vs %6.2f)' %
              (('pass' if seeingok else 'fail'), seeing, seeingcut))
        print('Brightness   cut: %s       (%6.2f vs %6.2f)' %
              (('pass' if brightok else 'fail'), skybright, nomsky+brightcut))
        print('Pass 1 = transparency AND seeing AND brightness: %s' % pass1ok)
        if pass1ok and not dopass1:
            print('Pass 1 forbidden by observer!')
        print('Pass 2 = transparency OR  seeing               : %s' % pass2ok)
        if pass2ok and not dopass2:
            print('Pass 2 forbidden by observer!')
        print('Selected pass:'******'Could not find a JSON observation in pass', nextpass,
                  'with approx_datetime after now =', str(ephem.now()))
            return False
        
        # Update the exposure times in plan J based on measured conditions.
        print('Updating exposure times for pass', nextpass)
        for jplan in J:
            tilename = str(jplan['object'])
            # Find this tile in the tiles table.
            tile = get_tile_from_name(tilename, self.tiles)
            ebv = tile.ebv_med
            nextband = str(jplan['filter'])[0]
            #print('Selected tile:', tilename, nextband)
            rastr  = ra2hms (jplan['RA' ])
            decstr = dec2dms(jplan['dec'])
            ephemstr = str('%s,f,%s,%s,20' % (tilename, rastr, decstr))
            etile = ephem.readdb(ephemstr)
            etile.compute(self.obs)
            airmass = get_airmass(float(etile.alt))
            #print('Airmass of planned tile:', airmass)
    
            if M['band'] == nextband:
                nextsky = skybright
            else:
                # Guess that the sky is as much brighter than canonical
                # in the next band as it is in this one!
                nextsky = ((skybright - nomsky) + self.nom.sky(nextband))

            fid = self.nom.fiducial_exptime(nextband)
            expfactor = exposure_factor(fid, self.nom,
                                        airmass, ebv, seeing, nextsky, trans)
            print('Tile', tilename)
            print('Exposure factor:', expfactor)
            exptime = expfactor * fid.exptime
    
            ### HACK -- safety factor!
            #print('Exposure time:', exptime)
            exptime *= 1.1
            exptime = int(np.ceil(exptime))
            #print('Exposure time with safety factor:', exptime)

            exptime = np.clip(exptime, fid.exptime_min, fid.exptime_max)
            #print('Clipped exptime', exptime)
            if nextband == 'z':
                # Compute cap on exposure time to avoid saturation /
                # loss of dynamic range.
                t_sat = self.nom.saturation_time(nextband, nextsky)
                if exptime > t_sat:
                    exptime = t_sat
                    print('Reduced exposure time to avoid z-band saturation: %.1f' % exptime)
            exptime = int(exptime)
    
            print('Changing exptime from', jplan['expTime'], 'to', exptime)
            jplan['expTime'] = exptime
            
        self.plan_tiles(J)
        return True
Example #48
0
    few_data = all_data[::5]

    fig, ax = plt.subplots()
    for i in range(len(few_data)):
        fig.canvas.mpl_connect('buttom_press_event', onclick)
        ax.matshow(few_data[i], cmap='gray_r')
        fig.show()

        print xco
        print yco
    sys.exit(1)

print '\t\tCalculando posiciones de estrellas'
if len(args.star) > 1:
    star = ephem.readdb("%s,f|S|A0,%s,%s,2.00,2000" % tuple(args.star))
else:
    star = ephem.star(args.star[0])
x, y = np.zeros((2, noche.sum()))
flux = np.zeros(noche.sum())
airmass = np.zeros(noche.sum())
dateflo = np.zeros(noche.sum())
datetim = []

YY, XX = np.ogrid[:all_data[0].shape[0], :all_data[0].shape[1]]
sigma_clip = SigmaClip(sigma=3)

for i in ProgressBar(noche.sum()):
    loc.date = dates[noche][i]
    star.compute(loc)
    el = float(repr(star.alt))  #*180/np.pi
Example #49
0
 def test_constellation(self):
     oneb = readdb('Orion Nebula,f,5.59,-5.45,2,2000.0,')
     oneb.compute('1999/2/28')
     self.assertEqual(constellation(oneb), ('Ori', 'Orion'))
Example #50
0
def kaitproc(inlist, clobber=globclob, verbose=globver):

    infiles = iraffiles(inlist)

    # Big loop
    for image in infiles:

        # Fix bad header keywords
        root, ext = image.split('.')
        fimg = pyfits.open(image)
        fimg.verify('fix')
        image2 = '%s.fits' % root
        print fimg[0].header
        fimg.writeto(image2)
        #iraf.imcopy(image, image2)

        # Update the WCS keywords
        update_head(image2, ['CD1_1', 'CD2_2', 'CD1_2', 'CD2_1', 'PIXSCALE'],
                    [CD11, CD22, CD12, CD21, PIXSCALE])
        update_head(
            image2,
            ['WCSDIM', 'LTM1_1', 'LTM2_2', 'WAT0_001', 'WAT1_001', 'WAT2_001'],
            [
                2, 1.0, 1.0, 'system=image', 'wtype=tan axtype=ra',
                'wtype=tan axtype=dec'
            ])
        delete_head(image2,
                    ['CROTA1', 'CROTA2', 'CDELT1', 'CDELT2', 'CSOURCE'])

        # Update RA and Dec to J2000.0
        [ra0, dec0, epoch] = get_head(image2, ['RA', 'DEC', 'EPOCH'])
        point = ephem.readdb('Point,f|M|F7,%s,%s,0.0,%f' % (ra0, dec0, epoch))
        point.compute(epoch='2000.0')
        coo = astrocoords(str(point.a_ra), str(point.a_dec))
        update_head(
            image2, ['RA', 'DEC', 'EPOCH', 'CRVAL1', 'CRVAL2'],
            [coo.sxg()[0],
             coo.sxg()[1], 2000.0,
             coo.radeg(),
             coo.dcdeg()])

        # Need Date to determine gain and readnoise (camera switch in May 2007)
        dateobs = get_head(image2, "DATE-OBS")
        tobs = DateTime(int(dateobs[6:]), int(dateobs[3:5]), int(dateobs[:2]))
        if tobs - TFL > 0:
            gain = FL_GAIN
            readn = FL_READN
        else:
            gain = AP_GAIN
            readn = AP_READN
        update_head(image2, ['GAIN', 'READN'], [gain, readn])

        # Clean cosmic rays
        #tmpimg=iraf.mktemp("iqcr")+".fits"
        #check_exist("%s_%s.fits" % (root,CRSFX),"w",clobber)
        #iraf.lacos_im(image2,tmpimg,"%s_%s.fits" % (root,CRSFX),
        #gain=gain,readn=readn,skyval=0.0,sigclip=4.5,
        #sigfrac=0.5,objlim=2.0,niter=1)
        #iraf.imdel(image2,verify=no,go_ahead=yes)
        #iraf.imcopy(tmpimg,image2,verbose=no)
        #iraf.imdel(tmpimg,verify=no,go_ahead=yes)

        # Detect Objects
        iraf.iqobjs(image2,
                    SIGMA,
                    SATVAL,
                    skyval="0.0",
                    masksfx=MASKSFX,
                    wtimage="",
                    fwhm=FWHM,
                    pix=PIXSCALE,
                    aperture=2 * FWHM / PIXSCALE,
                    gain=gain,
                    minlim=no,
                    clobber=yes,
                    verbose=no)

        # Fit WCS
        iraf.iqwcs(image2,
                   objkey='OBJECT',
                   rakey='RA',
                   deckey='DEC',
                   pixscl=PIXSCALE,
                   pixtol=0.05,
                   starfile='!STARFILE',
                   nstar=40,
                   catalog='web',
                   ubhost="localhost",
                   diffuse=yes,
                   clobber=yes,
                   verbose=verbose)

        # Calculate zero-point
        if get_head(image2, 'IQWCS'):
            object = get_head(image2, 'OBJECT')
            iraf.iqzeropt(image2,
                          REFMAG,
                          starfile="!STARFILE",
                          catalog=object.replace(" ", "_") + ".cat",
                          pixtol=3.0,
                          useflags=yes,
                          maxnum=50,
                          method="mean",
                          rejout=1,
                          fencelim=0.50,
                          sigma=1.5,
                          maxfrac=0.25,
                          zptkey=ZPTKEY,
                          zpukey=ZPUKEY,
                          clobber=yes,
                          verbose=verbose)

    print 'Exiting Successfully'
    return
Example #51
0
def Ceres():
    readable = 'Ceres, e, 10.607, 80.702, 71.274, 2.7685, 0.21396, 0.0780, 287.265, 10/1/1989, 2000.0, 3.32, 0.11'
    return ephem.readdb(readable.replace(' ', ''))