示例#1
1
def get_sunrise_sunset(date, lon= -122.3783, lat= 47.7128):

    """Function accepts a date string, and location float coordinates
    Function returns local, sunrise and sunset time
    datetime objects"""

    import ephem

    # Make an observer
    o = ephem.Observer()

    # PyEphem takes and returns only UTC times. 19:00 is Noon PDT, 20:00 is Noon PST
    # Using a string conversion and operation, which is probably slow
    # and could use optimization
    o.date = str(date) + ' 19:00'

    # Location of Carkeek Park
    o.lon = str(lon)  # Note that lon should be in string format
    o.lat = str(lat)  # Note that lat should be in string format

    # Elevation of the beach extending from Carkeek Park
    o.elev = 0

    sunrise=o.previous_rising(ephem.Sun())  # Sunrise
    sunset =o.next_setting(ephem.Sun())  # Sunset

    # convert sunrise and sunset to localtime (PDT/PST)
    local_sunrise = ephem.localtime(ephem.date(sunrise))
    local_sunset = ephem.localtime(ephem.date(sunset))

    return {'sunrise': local_sunrise, 'sunset': local_sunset}
示例#2
0
def date_from_designation(packed):
	isdigit = str.isdigit
	if isdigit(packed[0]) == False and  isdigit(packed[1:3]) == True and (packed[0] in ['I','J','K']) and len(packed.strip())==7: 
		try:
	        	packdt = str(packed).strip()
	    	except ValueError:
	        	print("ValueError: Input is not convertable to string.")
		
		year=give_number(packdt[0]) + packdt[1:3]
		halfmonth=float(give_number(packdt[3]))-9
		if halfmonth>9:
			halfmonth-=1
		month=str(np.ceil(halfmonth/2))
		#print "HALFMONTH:",packdt[3],halfmonth,month,halfmonth % 2
		if (halfmonth % 2)==1:
			day='01'
		else:
			day='15'
		d=year+'/'+month+'/'+day
		dd=ephem.date(d+" 00:00:00")

		#print packdt[4:]
		#print packed,d,dd
	else:
		dd=ephem.date(0)
	return dd
示例#3
0
def readAllocatedTime(startDay="1900/1/1", endDay="3000/1/1"):
    """Read a log file to determine how much each PI was allocated."""
    filename = "AllocatedTime.dat"
    f = open(filename, 'r')

    if type(startDay) == str:
        startDay = pyEphem.date(startDay).datetime()
    if type(endDay) == str:
        endDay = pyEphem.date(endDay).datetime()

    allocatedTime = {}
    for line in f.readlines():
        if line[0] == '#':
            # Comment string, skip
            continue

        date, PI = line.strip().split()
        date = pyEphem.date(date).datetime()
        mmt = MMTEphem.ephem(date)
        if (abs((date-startDay).total_seconds()) < 24*3600.) | \
           (abs((date-endDay).total_seconds()) < 24*3600.):
            # This night is not in the current run
            continue

        nightLength = (mmt.morningTwilight - mmt.eveningTwilight)
        nightLength = nightLength.total_seconds() / 3600.0

        if PI in allocatedTime:
            allocatedTime[PI] += nightLength
        else:
            allocatedTime[PI] = nightLength

    return allocatedTime
示例#4
0
def synthetic_model_kbos(date, maglimit=24.5, kbotype='resonant'):
    ra = []
    dist = []
    hlat = []
    for line in open('L7SyntheticModel-v09.txt'):
        if line[0]=='#':
            continue
        kbo = ephem.EllipticalBody()
        values = line.split()
        kbo._a = float(values[0])
        kbo._e = float(values[1])
        kbo._inc = float(values[2])
        kbo._Om = float(values[3])
        kbo._om = float(values[4])
        kbo._M = float(values[5])
        kbo._H = float(values[6])
        kbo._epoch_M = ephem.date(2453157.50000 - ephem.julian_date(0))
        kbo._epoch = kbo._epoch_M
        kbo.name = values[8]  # values[9] and [10] encode the type of resonance eg. 2:1 - add that if wanted

        kbo.compute(ephem.date(date))
        if (kbo.mag < maglimit):# and (kbo.name == kbotype):
            ra.append(kbo.ra)
            dist.append(kbo.sun_distance)
            hlat.append(kbo.hlat)

    return ra, dist, hlat
示例#5
0
def createTableSun(observer, year, dayStep=1):
    """ Create table with rising and setting times for the sun
    
    observer is an ephem observer, year is an int giving the desired year, dayStep int specifying the
    distance of days between computations.
    returned table contains pairs of setting/rising times for the night of each day of the year
    returned dates/times are ephem.date, i.e. UTC as float subclass.
    """

    import ephem
    import datetime
    object = ephem.Sun()
    # we start on Jan 1st 0am UTC.
    startDate = ephem.date((year, 1, 1, 0, 0))
    # compute days in year
    days = (datetime.date(year + 1, 1, 1) - datetime.date(year, 1, 1)).days
    res = list()
    #print "days",days
    for day in range(0, days):
        currentDate = ephem.date(startDate + day)
        year, month, day, hour, minute, second = currentDate.tuple()
        observer.date = currentDate
        nextSetting = observer.next_setting(object)
        observer.date = nextSetting
        nextRising = observer.next_rising(object)
        #print nextRising,nextSetting
        res.append((currentDate, nextSetting, nextRising))
    return res
示例#6
0
 def local_mean_time(self, d, reverse=False):
     '''Adjust GMT to local time.
        We don't know time zone, but we can adjust for actual
        local noon since we know the Observer's longitude:
     '''
     return ephem.date(ephem.date(d) \
                 + float(self.observer.lon) * 12 / math.pi * ephem.hour)
示例#7
0
文件: obsim.py 项目: patreya/obsim
def create_new_src_input(config):
    N_src = config['N_src']
    duration = [ config['min_duration'], config['max_duration'] ]
    priority =  [ config['min_priority'], config['max_priority'] ]
    src_input = obsim.create_source(N_src, duration , priority )
    loc = obsim.init_loc(config)
    start_date_time, end_date_time = obsim.get_start_end_dates(config)
    src = obsim.init_src()
    src_data=[]
    removed_src = 0
    j = 0
    tz_offset = config['time_zone'] * ephem.hour
    for i in range(0, N_src):
        src.name = str(src_input[i][0])
        src._ra = str(src_input[i][1])
        src._dec = str(src_input[i][2])
        loc.date = start_date_time
        src.compute(loc)
        try:
            rise_time = obsim.src_rise_time(src, loc, start_date_time, end_date_time)
            rise_time_local = ephem.date(rise_time + tz_offset)
            try:
                set_time = obsim.src_set_time(src, loc, start_date_time, end_date_time)
                set_time_local = ephem.date(set_time + tz_offset)
                src_data.append ([str(j), str(src_input[i][1]), str(src_input[i][2]), str(int(src_input[i][3])), str(src_input[i][4]), str(rise_time_local), str(set_time_local)])
                j += 1
            except Exception, Notup:
                removed_src += 1
        except Exception, Notup:
             removed_src += 1
示例#8
0
    def sun_position(self, date) :
        if not self.drawing_area :
            print "no drawing area"
            return
        if not self.xgc :
            print "no GC"
            return

        # We don't know time zone, but we can adjust for actual
        # local noon since we know the Observer's longitude:
        adjtime = ephem.date(ephem.date(date) \
                        - float(self.observer.lon) * 12 / math.pi * ephem.hour)
        observer.date = adjtime

        self.sun.compute(self.observer)

        # Y scale is 90 degrees (PI/2), horizon to zenith:
        # y = self.height - int(float(self.sun.alt) * self.height / math.pi * 2)

        # So make X scale 90 degrees too, centered around due south.
        # Want az = PI to come out at x = width/2,
        # az = PI/2 to be 0, 3*PI/2 = width.
        # x = int(float(self.sun.az) * self.width / math.pi * 2 - self.width / 2) % self.width

        self.project(self.sun.az, self.sun.alt, 4)
示例#9
0
文件: lunes.py 项目: pawkw/lunes
    def find(self, month, day, hour=0, minute=0, second=0, year=0):
        if year == 0:
            date = ephem.date((self.year, month, day, hour, minute, second))
            if date < self.start or date > self.end:
                date = ephem.date(
                    (self.year + 1, month, day, hour, minute, second))
        else:
            date = ephem.date((year, month, day, hour, minute, second))

        if date < self.start or date > self.end:
            return False

        month = 0
        for x in self.monthList:
            month += 1
            if date < x.end:
                break
        lune = 0
        for x in self.month(month).luneList:
            lune += 1
            if date < x.end:
                break
        if lune == 0:
            print("Lune could not be found.")
            quit()
        return month, lune
示例#10
0
def readAllocatedTime(startDay="1900/1/1", endDay="3000/1/1"):
    """Read a log file to determine how much each PI was allocated."""
    filename = "AllocatedTime.dat"
    f = open(filename, 'r')

    if type(startDay) == str:
        startDay = pyEphem.date(startDay).datetime()
    if type(endDay) == str:
        endDay = pyEphem.date(endDay).datetime()

    allocatedTime = {}
    for line in f.readlines():
        if line[0] == '#':
            # Comment string, skip
            continue

        date, PI = line.strip().split()
        date = pyEphem.date(date).datetime()
        mmt = MMTEphem.ephem(date)
        if (abs((date-startDay).total_seconds()) < 24*3600.) | \
           (abs((date-endDay).total_seconds()) < 24*3600.):
            # This night is not in the current run
            continue

        nightLength = (mmt.morningTwilight - mmt.eveningTwilight)
        nightLength = nightLength.total_seconds() / 3600.0

        if PI in allocatedTime:
            allocatedTime[PI] += nightLength
        else:
            allocatedTime[PI] = nightLength

    return allocatedTime
def test_totrate_nu():
	t0=ephem.date('2014/01/01')
	t1=ephem.date('2015/01/01')
	M_det=500.e6
	time_arr,rate_arr,N_nu,dt,N_atmo,N_dsnb,alpha=tot_rate_nu(M_det,E_thr,t0,t1)
	N_solar=N_nu-N_atmo-N_dsnb
	print N_solar,N_atmo,N_dsnb,N_nu
示例#12
0
def get_sunrise_sunset(date, lon=-122.3783, lat=47.7128):
    """Function accepts a date string, and location float coordinates
    Function returns local, sunrise and sunset time
    datetime objects"""

    import ephem

    # Make an observer
    o = ephem.Observer()

    # PyEphem takes and returns only UTC times. 19:00 is Noon PDT, 20:00 is Noon PST
    # Using a string conversion and operation, which is probably slow
    # and could use optimization
    o.date = str(date) + ' 19:00'

    # Location of Carkeek Park
    o.lon = str(lon)  # Note that lon should be in string format
    o.lat = str(lat)  # Note that lat should be in string format

    # Elevation of the beach extending from Carkeek Park
    o.elev = 0

    sunrise = o.previous_rising(ephem.Sun())  # Sunrise
    sunset = o.next_setting(ephem.Sun())  # Sunset

    # convert sunrise and sunset to localtime (PDT/PST)
    local_sunrise = ephem.localtime(ephem.date(sunrise))
    local_sunset = ephem.localtime(ephem.date(sunset))

    return {'sunrise': local_sunrise, 'sunset': local_sunset}
示例#13
0
 def local_to_gmt(self, d, reverse=False):
     '''Adjust GMT to local time.
        We don't know time zone, but we can adjust for actual
        local noon since we know the Observer's longitude:
     '''
     return ephem.date(ephem.date(d) \
                 - float(self.observer.lon) * 12 / math.pi * ephem.hour)
示例#14
0
文件: obsim.py 项目: patreya/obsim
def get_next_src(src_data, N_src, src, loc, curr_time, tz_offset, curr_tel_pos, slew_rate, schedule):
    for i in range(0, N_src):
        src_obs_status = src_data[i][7]
        curr_time_local =  ephem.date(curr_time + tz_offset)
        if (src_obs_status == '0'):
            src_rise_time_local = ephem.Date(src_data[i][5])
            src_rise_time = ephem.Date(src_rise_time_local  - tz_offset)
            src_az, src_alt = obsim.get_src_az_alt(src, loc, src_data[i][1], src_data[i][2], curr_time)
            az_diff, alt_diff = obsim.calc_angle_difference(src_az, src_alt, curr_tel_pos[0], curr_tel_pos[1])
            slew_time = (math.degrees(az_diff)/slew_rate[0] + math.degrees(alt_diff)/slew_rate[0])*ephem.second
            src_obs_start_time = ephem.Date(curr_time + slew_time)
            if (src_obs_start_time >= src_rise_time):
                src_set_time_local = ephem.Date(src_data[i][6])
                src_set_time = ephem.Date(src_set_time_local  - tz_offset)
                src_obs_duration = float(src_data[i][3])*ephem.second
                src_obs_end_time = ephem.Date(src_obs_start_time + src_obs_duration)
                if ( src_obs_end_time < src_set_time):
                    src_az_end, src_alt_end = obsim.get_src_az_alt(src, loc, src_data[i][1], src_data[i][2], src_obs_end_time)
                    curr_time_local =  ephem.date(curr_time + tz_offset)
                    src_obs_end_time_local =  ephem.date(src_obs_end_time + tz_offset)
                    schedule.append( [ int(src_data[i][0]), str(curr_time_local), str(src_obs_end_time_local), int(round(slew_time*24.0*3600.0)), int(round(src_obs_duration*24.0*3600.0)), (src_data[i][4]) ] )
                    status=[1, i, src_obs_end_time, src_az_end, src_alt_end]
                    return schedule, status
    status=[0] 
    return schedule, status
示例#15
0
def import_lastrun_data(opt):
    mjd_yesterday = ephem.date(ephem.julian_date(ephem.date(
        opt.date))) - 2400000.5

    data_to_date = query_for_observations(mjd_yesterday, opt.cal, OSSOS_RUNIDS)
    for row in data_to_date:
        storage.populate(row['dataset_name'])
示例#16
0
def calculate_julian_century(datetime):
    """
    Given a datetime object return the julian century from the 2000 epoch.

    :param datetime:
        A datetime object containing the date to be converted to a
        Julian centuries since 2000/01/01 12:00.

    :return:
        A floating point value representing the Julian centuries since
        the 2000/01/01 12:00 epoch.
    """

    # Convert the scene timestamp to a julian date
    d = ephem.date(datetime)
    jdate = ephem.julian_date(d)

    # Get the J2000 epoch
    epoch = ephem.date((2000, 1, 1, 12.00))
    j2_epoch = ephem.julian_date(epoch)

    # Note:
    # This differes from online sources such as
    # http://www.pietro.org/astro_util_staticdemo/FDetailDateConversions.htm
    # http://en.wikipedia.org/wiki/Equinox_(celestial_coordinates)
    # which use:
    # 2000 + (jdate - epoch) / 365.25
    century = (jdate - j2_epoch) / 36525

    return century
示例#17
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)
示例#18
0
def tot_rate_dm(M,E_thr,m_DM,t0,t1,steps=365):
        #this is the time integral over the recoil rate
	#NO SIGMA IN HERE AS EVERYTHING SCALES WITH IT!!!!
	t0_f=float(t0)
	t1_f=float(t1)
	time=np.zeros(steps)
	rate=np.zeros(steps)
	time[0]=0.

	if dm_mod==True:
		time_grid=np.linspace(t0_f,t1_f,steps)
		dT=(t1_f-t0_f)/steps
		rate[0]=0.
		for ii in range (steps-1):
			time1_f=time_grid[ii+1]
			time1=ephem.date(time1_f)
		        mu_p=m_DM*mP/(m_DM+mP)
		        rate[ii+1]=(1./(2.*m_DM*mu_p**2)*rho0*M*dT*days*A**2/0.1/GeVkg/GeVkg*keVJ*\
					rec_int(m_DM,E_thr,time1))
			time[ii+1]=(time1_f-t0_f)
		summed_rate=sum(rate)

	if dm_mod==False:
		mu_p=m_DM*mP/(m_DM+mP)
		time0=ephem.date(t0_f)
		summed_rate=(1./(2.*m_DM*mu_p**2)*rho0*M*(t1_f-t0_f)*days*A**2/0.1/GeVkg/GeVkg*keVJ*\
                                        rec_int(m_DM,E_thr,time0))
		
	return time,rate,summed_rate,dT
示例#19
0
    def mouseReleaseEvent(self, evt):
        if self.editing is not None:
            rect = self.rx[self.editing].rect()
            pos = evt.pos()
            self.rx[self.editing].setRect(rect.x(), rect.y(), rect.width(), pos.y()-rect.y()+ self.verticalScrollBar().value())
            rect = self.rx[self.editing].rect()
            
            print 'release', self.rx[self.editing].rect()
            if rect.height() / self.scale_y > 0.1:
                print 'Start time', str(ephem.date(ephem.now() + ((rect.y() - self.orig_y) / self.scale_y) * ephem.minute))
                print 'Duration', rect.height() / self.scale_y
                print 'Centre Frequency', (rect.x() + rect.width()/2 - self.orig_x) / self.scale_x + (self.fx0 * 1e6)

                self.rx[self.editing].setParams(ephem.date(ephem.now() + ((rect.y() - self.orig_y) / self.scale_y) * ephem.minute),
                                                rect.height() / self.scale_y,
                                                (rect.x() + rect.width()/2 - self.orig_x) / self.scale_x + (self.fx0 * 1e6))

                for f in self.scene().items(rect):
                    print f
                    if isinstance(f, PlannerSat):
                        print f.name, f.mode, f.freq, f.params
                        self.rx[self.editing].addChannel(f.name, f.mode, f.freq, f.tle, f.params)
            else:
                self.rx[self.editing].hide()
                self.rx[self.editing] = None
                self.rx = self.rx[:-1]
                self.editing = None
	else:
	    QtGui.QGraphicsView.mouseReleaseEvent(self, evt)
示例#20
0
def keplerian_sheared_field_locations(ax, kbos, opp_date, names):
    ## Now we work out how far to move the fields at different lunations
    seps = {}
    dates = {}

    for month in newMoons:
      for night in range(-7,8):
        epoch = "%s.%s" % ( month, string.zfill(night,2))
        dates[epoch] = ephem.date(ephem.date(newMoons[month]) + night)
        seps[epoch]={'dra': 0, 'ddec': 0}

    for kbo in kbos:
      ra=kbo.ra
      dec=kbo.dec
      for epoch in dates:
        date = ephem.date(dates[epoch])
        kbo.compute(date)
        seps[epoch]['dra'] += kbo.ra - ra
        seps[epoch]['ddec'] += kbo.dec - dec

    ## plot source locations at the start
    ## middle and end of semester
#    colours  = {'Aug13': 'g', 'Oct13': 'b', 'Dec13': 'r'}
#    alpha = {'Aug13': 0.3, 'Oct13': 0.7, 'Dec13': 0.3}
#    zorder = {'Aug13': 1, 'Oct13': 5, 'Dec13': 2}
    for month in ['Aug13', 'Oct13', 'Dec13']:
      ra = []
      dec = []
      date = ephem.date(newMoons[month])
      for kbo in kbos:
        kbo.compute(date)
        ra.append(math.degrees(kbo.ra))
        dec.append(math.degrees(kbo.dec))
#      ax.plot(ra,dec,colours[month]+'.', alpha=alpha[month], zorder=zorder[month])

    ## Now plot the boxes for each month, shifting
    ## from the discovery set by the average motion of
    ## L7 kbos in the discovery field
    for month in seps:
      seps[month]['dra'] /= float(len(kbos))
      seps[month]['ddec'] /= float(len(kbos))

    sorted_epochs = sorted(dates.iteritems(), key=operator.itemgetter(1))

    for idx in range(len(ras)):
      name = names[idx]
#      f = file('%s.xml' % ( name), 'w')
      #f2 = file('%s.no.xml' % ( name), 'w')
      #f2.write(etHeader)
      # f.write(etHeader)
      for epoch in sorted_epochs:
        epoch = epoch[0]
        date = dates[epoch]
        ra = ras[idx] + seps[epoch]['dra']
        dec = decs[idx] + seps[epoch]['ddec']
        tdate = date.tuple()
        zf = string.zfill

        sdate = "%4s-%2s-%2s %2s:%2s:%2s" % ( tdate[0], zf(tdate[1],2), zf(tdate[2],2), zf(tdate[3],2),zf(tdate[4],2),zf(int(tdate[5]),2))
示例#21
0
def test_rate_DM():
	M=500.e6
	m_DM=10.
	sigma=1.e-47
        t0=ephem.date('2014/01/01')
        t1=ephem.date('2015/01/01')
	time_arr,rate_arr,N_DM,dt=tot_rate_dm(M,E_thr,m_DM,t0,t1,steps=365)
	print N_DM*sigma
示例#22
0
def result():
    config = ConfigProject()

    info = config.get_geographic_settings()
    infosun = config.get_moonsun_settings()

    max_solar_elevation = float(infosun[0])  # -12
    max_lunar_elevation = float(infosun[2])  # 8
    # max_lunar_phase = infosun[3]

    now_datetime = datetime.datetime.utcnow().replace(hour=12).replace(
        minute=00).replace(second=0)
    obs = ephem.Observer()

    obs.lat = info[0]
    obs.lon = info[1]
    obs.elevation = float(info[2])
    obs.date = ephem.date(now_datetime)

    sun = ephem.Sun()
    sun.compute(obs)
    moon = ephem.Moon()
    moon.compute(obs)
    j = 0
    flag = 0
    for i in range(1, 3000):

        obs.date = ephem.date(now_datetime)
        sun = ephem.Sun()
        sun.compute(obs)

        moon = ephem.Moon()
        moon.compute(obs)
        frac = moon.moon_phase

        ag_s = float(repr(sun.alt))
        s_ag = math.degrees(ag_s)
        ag_m = float(repr(moon.alt))
        m_ag = math.degrees(ag_m)

        if float(s_ag) < max_solar_elevation and float(
                m_ag) < max_lunar_elevation:
            if flag == 0:
                flag = 1
                start = now_datetime
        elif (float(s_ag) > max_solar_elevation
              or float(m_ag) > max_lunar_elevation) and flag == 1:
            flag = 0
            end = now_datetime
            break

        now_datetime += timedelta(minutes=j)

        j += 1

    obs_time = end - start

    return start, end, obs_time
示例#23
0
def create_ascii_table(observation_table, outfile):
    """Given a table of observations create an ascii log file for easy parsing.
    Store the result in outfile (could/should be a vospace dataNode)

    observation_table: astropy.votable.array object
    outfile: str (name of the vospace dataNode to store the result to)

    """

    logging.info("writing text log to %s" % outfile)

    stamp = "#\n# Last Updated: " + time.asctime() + "\n#\n"
    header = "| %20s | %20s | %20s | %20s | %20s | %20s | %20s |\n" % (
        "EXPNUM", "OBS-DATE", "FIELD", "EXPTIME(s)", "RA", "DEC", "RUNID")
    bar = "=" * (len(header) - 1) + "\n"

    if outfile[0:4] == "vos:":
        temp_file = tempfile.NamedTemporaryFile(suffix='.txt')
        fout = temp_file
    else:
        fout = open(outfile, 'w')

    t2 = None
    fout.write(bar + stamp + bar + header)

    populated = storage.list_dbimages()
    for i in range(len(observation_table) - 1, -1, -1):
        row = observation_table.data[i]
        if row['dataset_name'] not in populated:
            storage.populate(row['dataset_name'])
        str_date = str(
            ephem.date(row.StartDate + 2400000.5 -
                       ephem.julian_date(ephem.date(0))))[:20]
        t1 = time.strptime(str_date, "%Y/%m/%d %H:%M:%S")
        if t2 is None or math.fabs(time.mktime(t2) -
                                   time.mktime(t1)) > 3 * 3600.0:
            fout.write(bar)
        t2 = t1
        ra = str(ephem.hours(math.radians(row.RA)))
        dec = str(ephem.degrees(math.radians(row.DEC)))
        line = "| %20s | %20s | %20s | %20.1f | %20s | %20s | %20s |\n" % (
            str(row.dataset_name),
            str(
                ephem.date(row.StartDate + 2400000.5 -
                           ephem.julian_date(ephem.date(0))))[:20],
            row.TargetName[:20], row.ExposureTime, ra[:20], dec[:20],
            row.ProposalID[:20])
        fout.write(line)

    fout.write(bar)

    if outfile[0:4] == "vos:":
        fout.flush()
        storage.copy(fout.name, outfile)
    fout.close()

    return
示例#24
0
def jd_to_hjd(jd, planet):
    """ converts jd to hjd for a given target

    :param star: exodata star object
    """
    ra_target, dec_target = (planet.system.ra.degree) * np.pi / 180, (
        planet.system.dec.degree) * np.pi / 180

    try:
        hjd = []

        for julian_date in jd:
            # calculate the position of the sun on the sky for this date

            sun = ephem.Sun()
            sun.compute(ephem.date(julian_date - 2415020))
            ra_sun, dec_sun = float(sun.ra), float(sun.dec)

            # calculate the correction coefficients

            a = 149597870700.0 / ephem.c
            b = np.sin(dec_target) * np.sin(dec_sun)
            c = np.cos(dec_target) * np.cos(dec_sun) * np.cos(ra_target -
                                                              ra_sun)

            # apply the correction and save the result as the heliocentric_julian_date keyword

            heliocentric_julian_date = julian_date - (a *
                                                      (b + c)) / (24.0 * 60.0 *
                                                                  60.0)

            hjd.append(heliocentric_julian_date)

        return np.array(hjd)

    except TypeError:

        julian_date = jd

        # calculate the position of the sun on the sky for this date

        sun = ephem.Sun()
        sun.compute(ephem.date(julian_date - 2415020))
        ra_sun, dec_sun = float(sun.ra), float(sun.dec)

        # calculate the correction coefficients

        a = 149597870700.0 / ephem.c
        b = np.sin(dec_target) * np.sin(dec_sun)
        c = np.cos(dec_target) * np.cos(dec_sun) * np.cos(ra_target - ra_sun)

        # apply the correction and save the result as the heliocentric_julian_date keyword

        heliocentric_julian_date = julian_date - (a * (b + c)) / (24.0 * 60.0 *
                                                                  60.0)

        return heliocentric_julian_date
示例#25
0
    def closeout(self):
        '''Time to figure out what we have and print it.'''

        # Find the list of minimum separations between each pair.
        startdate = ephem.date('3000/1/1')
        enddate = ephem.date('0001/1/1')
        minseps = []
        for i, b1 in enumerate(self.bodies):
            for b2 in self.bodies[i + 1:]:
                minsep = 360  # degrees
                closest_date = None
                for pair in self.pairs:
                    if pair.date < startdate:
                        startdate = pair.date
                    if pair.date > enddate:
                        enddate = pair.date
                    if b1 in pair and b2 in pair:
                        if pair.sep < minsep:
                            minsep = pair.sep
                            closest_date = pair.date
                # Not all pairs will be represented. In a triple conjunction,
                # the two outer bodies may never get close enough to register
                # as a conjunction in their own right.
                if minsep < max_sep:
                    minseps.append((closest_date, minsep, b1, b2))
        minseps.sort()

        if output_format == "csv":
            s = '"Conjunction of ' + self.andjoin(self.bodies) + '",'
            s += datestr(startdate) + "," + datestr(enddate) + ",,"
            s += "\""
            for m in minseps:
                s += " %s and %s will be closest on %s (%s)." % \
                     (m[2], m[3], friendlydate(m[0]), sepstr(m[1]))
            s += "\",,astronomy/starry_moon.jpg,240,169,\"<a href='http://commons.wikimedia.org/wiki/File:Sachin_Nigam_-_starry_moon_%28by-sa%29.jpg'>starry moon on Wikimedia Commons</a>\""
            print(s)
        elif output_format == "sql":
            s = "('Conjunction of " + self.andjoin(self.bodies) + "', "
            s += "'astronomy', 'naked eye', "
            s += "'" + datestr(startdate) + "', '" + datestr(enddate) + "', "
            s += "'"
            for m in minseps:
                s += " %s and %s will be closest on %s (%s)." % \
                     (m[2], m[3], friendlydate(m[0]), sepstr(m[1]))
            s += "', "
            s += "'astronomy/starry_moon.jpg', "
            s += "240, 169, "
            s += "'<a href=\"http://commons.wikimedia.org/wiki/File:Sachin_Nigam_-_starry_moon_%28by-sa%29.jpg\">starry moon on Wikimedia Commons</a>' ),"
            print(s)
        else:
            print("Conjunction of", self.andjoin(self.bodies), end=' ')
            print("lasts from %s to %s." %
                  (datestr(startdate), datestr(enddate)))
            for m in minseps:
                print("  %s and %s are closest on %s (%s)." % \
                    (m[2], m[3], friendlydate(m[0]), sepstr(m[1])))
示例#26
0
    def closeout(self):
        '''Time to figure out what we have and print it.'''

        # Find the list of minimum separations between each pair.
        startdate = ephem.date('3000/1/1')
        enddate = ephem.date('0001/1/1')
        minseps = []
        for i, b1 in enumerate(self.bodies):
            for b2 in self.bodies[i+1:]:
                minsep = 360  # degrees
                closest_date = None
                for pair in self.pairs:
                    if pair.date < startdate:
                        startdate = pair.date
                    if pair.date > enddate:
                        enddate = pair.date
                    if b1 in pair and b2 in pair:
                        if pair.sep < minsep:
                            minsep = pair.sep
                            closest_date = pair.date
                # Not all pairs will be represented. In a triple conjunction,
                # the two outer bodies may never get close enough to register
                # as a conjunction in their own right.
                if minsep < max_sep:
                    minseps.append((closest_date, minsep, b1, b2))
        minseps.sort()

        if output_format == "csv":
            s = '"Conjunction of ' + self.andjoin(self.bodies) + '",'
            s += datestr(startdate) + "," + datestr(enddate) + ",,"
            s += "\""
            for m in minseps:
                s += " %s and %s will be closest on %s (%s)." % \
                     (m[2], m[3], friendlydate(m[0]), sepstr(m[1]))
            s += "\",,astronomy/starry_moon.jpg,240,169,\"<a href='http://commons.wikimedia.org/wiki/File:Sachin_Nigam_-_starry_moon_%28by-sa%29.jpg'>starry moon on Wikimedia Commons</a>\""
            print(s)
        elif output_format == "sql":
            s = "('Conjunction of " + self.andjoin(self.bodies) + "', "
            s += "'astronomy', 'naked eye', "
            s += "'" + datestr(startdate) + "', '" + datestr(enddate) + "', "
            s += "'"
            for m in minseps:
                s += " %s and %s will be closest on %s (%s)." % \
                     (m[2], m[3], friendlydate(m[0]), sepstr(m[1]))
            s += "', "
            s += "'astronomy/starry_moon.jpg', "
            s += "240, 169, "
            s += "'<a href=\"http://commons.wikimedia.org/wiki/File:Sachin_Nigam_-_starry_moon_%28by-sa%29.jpg\">starry moon on Wikimedia Commons</a>' ),"
            print(s)
        else:
            print("Conjunction of", self.andjoin(self.bodies), end=' ')
            print("lasts from %s to %s." % (datestr(startdate), datestr(enddate)))
            for m in minseps:
                print("  %s and %s are closest on %s (%s)." % \
                    (m[2], m[3], friendlydate(m[0]), sepstr(m[1])))
示例#27
0
文件: ObsStatus.py 项目: OSSOS/MOP
def create_ascii_table(observation_table, outfile):
    """Given a table of observations create an ascii log file for easy parsing.
    Store the result in outfile (could/should be a vospace dataNode)

    observation_table: astropy.votable.array object
    outfile: str (name of the vospace dataNode to store the result to)

    """

    logging.info("writing text log to %s" % outfile)

    stamp = "#\n# Last Updated: " + time.asctime() + "\n#\n"
    header = "| %20s | %20s | %20s | %20s | %20s | %20s | %20s |\n" % (
        "EXPNUM", "OBS-DATE", "FIELD", "EXPTIME(s)", "RA", "DEC", "RUNID")
    bar = "=" * (len(header) - 1) + "\n"

    if outfile[0:4] == "vos:":
        temp_file = tempfile.NamedTemporaryFile(suffix='.txt')
        fout = temp_file
    else:
        fout = open(outfile, 'w')

    t2 = None
    fout.write(bar + stamp + bar + header)

    populated = storage.list_dbimages()
    for i in range(len(observation_table) - 1, -1, -1):
        row = observation_table.data[i]
        if row['dataset_name'] not in populated:
            storage.populate(row['dataset_name'])
        str_date = str(ephem.date(row.StartDate +
                                  2400000.5 -
                                  ephem.julian_date(ephem.date(0))))[:20]
        t1 = time.strptime(str_date, "%Y/%m/%d %H:%M:%S")
        if t2 is None or math.fabs(time.mktime(t2) - time.mktime(t1)) > 3 * 3600.0:
            fout.write(bar)
        t2 = t1
        ra = str(ephem.hours(math.radians(row.RA)))
        dec = str(ephem.degrees(math.radians(row.DEC)))
        line = "| %20s | %20s | %20s | %20.1f | %20s | %20s | %20s |\n" % (
            str(row.dataset_name),
            str(ephem.date(row.StartDate + 2400000.5 -
                           ephem.julian_date(ephem.date(0))))[:20],
            row.TargetName[:20],
            row.ExposureTime, ra[:20], dec[:20], row.ProposalID[:20])
        fout.write(line)

    fout.write(bar)

    if outfile[0:4] == "vos:":
        fout.flush()
        storage.copy(fout.name, outfile)
    fout.close()

    return
示例#28
0
 def compute(self):
     obs = self.obs
     for m in range(1, 13):
         for d in range(1, 33): # yeah I know its sloppy but it works
             obs.date = '%d/%d/%d 13:00' % (self.year, m,  d)
             obs.date = ephem.date(ephem.date('%d/%d/%d 13:00' % (self.year, m,  d)) - float(self.obs.lon) * 12 / math.pi * ephem.hour)
             self.sun.compute(obs)
             y = float(100 - float(self.sun.alt) * 100 / math.pi)
             x = float(float(self.sun.az) * 100 / math.pi / 2)
             self.x.append(x)
             self.y.append(y)
示例#29
0
def create_list_of_angles(body, observer):
    current_time = body.rise_time
    end_time = body.set_time
    format_string = ("  @ {0:5s} it will be at {1:>11s} degrees north and " +
                     " {2:>10s} degrees above horizon.")
    while current_time < end_time:
        observer.date = ephem.date(current_time)
        body.compute(observer)
        time = ephem_time_to_datetime_string(ephem.date(current_time), '%H:%M')
        print(format_string.format(time, str(body.az), str(body.alt)))
        current_time = current_time + ephem.minute
    print("")
def time_for_altitude(obj, alt, startvals, date):
    CTA_N.date = date

    def rel_pos(when):
        CTA_N.date = when
        obj.compute(CTA_N)
        return obj.alt - alt

    start = float(ephem.date(startvals)) - 0.08
    end = float(ephem.date(startvals)) + 0.08
    start, end = min(start, end), max(start, end)
    return ephem.date(ephem.newton(rel_pos, start, end))
示例#31
0
def synthetic_model_kbos(
        at_date=parameters.NEWMOONS[parameters.DISCOVERY_NEW_MOON],
        maglimit=24.5,
        kbotype=False,
        arrays=False):
    # # build a list of Synthetic KBOs
    print "LOADING SYNTHETIC MODEL KBOS FROM: {}".format(parameters.L7MODEL)
    kbos = []
    if arrays:  # much easier to use for plt.scatter()
        ra = []
        dist = []
        hlat = []
    lines = storage.open_vos_or_local(parameters.L7MODEL).read().split('\n')
    counter = 0
    for line in lines:
        if len(line) == 0 or line[
                0] == '#':  # skip initial column descriptors and the final blank line
            continue
        kbo = ephem.EllipticalBody()
        values = line.split()
        kbo.name = values[8]
        if kbotype and (kbo.name == kbotype) and (values[9] == '3'):
            kbo._a = float(values[0])
            kbo._e = float(values[1])
            kbo._inc = float(values[2])
            kbo._Om = float(values[3])
            kbo._om = float(values[4])
            kbo._M = float(values[5])
            kbo._H = float(values[6])
            epoch = ephem.date(2453157.50000 - ephem.julian_date(0))
            kbo._epoch_M = epoch
            kbo._epoch = epoch
            date = ephem.date(at_date)
            kbo.compute(date)
            counter += 1

            # ## only keep objects that are brighter than limit
            if (kbo.mag < maglimit):
                kbos.append(kbo)
                if arrays:
                    ra.append(kbo.ra)
                    dist.append(kbo.sun_distance)
                    hlat.append(kbo.hlat)

    print '%d synthetic model kbos brighter than %d retained from %d in L7 model'.format(
        len(kbos), maglimit, counter)
    if not arrays:
        return kbos
    else:
        return ra, dist, hlat
示例#32
0
def main():
    o = Orbit(file="VP113.obs")
    body = o.ellipticalBody("VP113")
    body.compute("1998/01/01")
    print "PyEphem ra, dec", ephem.hours(body.a_ra), body.a_dec
    d = ephem.date("1998/01/01")
    i = 0
    while i < 1:
        pos = o.predict_pos(d)
        ra, dec, err = pos["ra"], pos["dec"], pos["err"]
        print ephem.date(d), "\t", pos["ra"], "\t", pos["dec"], "\t", round(pos["err"]["a"], 3), "\t", round(
            pos["err"]["b"], 3
        ), "\t", round(pos["err"]["PA"], 2)
        d += 100
        i += 1
示例#33
0
文件: rose_topdown.py 项目: OSSOS/MOP
def plot_planets_plus_Pluto(ax, date=parameters.NEWMOONS[parameters.DISCOVERY_NEW_MOON]):
    for planet in [ephem.Saturn(), ephem.Uranus(), ephem.Neptune(), ephem.Pluto()]:
        planet.compute(ephem.date(date))
        fc = plot_fanciness.ALMOST_BLACK
        if planet.name == 'Pluto':
            alpha = 0.35
            size = 10
            fs = 5
        else:
            alpha = 0.7
            size = 20
            fs = 10
        ax.scatter(planet.ra, planet.sun_distance,
                   marker='o',
                   s=size,
                   facecolor=fc,
                   edgecolor=fc,
                   alpha=alpha)
        if planet.name == 'Saturn':
            ax.annotate(planet.name, (planet.ra + (math.radians(3)), planet.sun_distance - 2), size=fs)
        elif planet.name == 'Uranus':
            ax.annotate(planet.name, (planet.ra - (math.radians(12)), planet.sun_distance + 1), size=fs)
        else:
            ax.annotate(planet.name, (planet.ra - (math.radians(0.5)), planet.sun_distance + 2), size=fs)

        # Neptune's orbit has e = 0.01, so can get away with a circle
        if planet.name == 'Neptune':
            orb = np.arange(0, 2 * np.pi, (2 * np.pi) / 360)
            ax.plot(orb, np.repeat(planet.sun_distance, len(orb)), color='b', linestyle=':', linewidth=0.4, alpha=0.7)

    return
示例#34
0
def round_date_5second(dt):
    # This routine goes to the nearest time that ends in a 5 second.
    d = dt.datetime()
    dsecd = d.second % 10
    dd = 5 - dsecd
    dt = ephem.date(dt + dd * ephem.second)
    return dt
示例#35
0
def tstr2jd(tstr, ifmt='%m/%d/%y %H:%M:%S', tz=''):
    try:
        #tstr = strftime('%Y/%m/%d %H:%M:%S',
        #    gmtime(mktime(strptime(tstr+' '+tz, ifmt+' %Z'))))
        tstr = strftime('%Y/%m/%d %H:%M:%S', strptime(tstr, ifmt))
        return a.phs.ephem2juldate(ephem.date(tstr))
    except(ValueError): return []
示例#36
0
def extend(target, year='Y4', chisq_cut=10, teff_min=0.3):
    '''
    Identifies matches to the target object in the SE catalog from the given year and returns them as a dataframe.
    :param target: dataframe of observations
    :param year: DES observing year to be searched, e.g. 'Y4'
    :param chisq_cut: delta_chisq cut for matches, default=10
    :param teff_min: minimum t_eff of exposures to consider
    :return: dataframe of matches
    '''
    matched_good = pd.DataFrame()
    orbit = getOrbit(target)
    search_exps = search_exposures(target, orbit, year=year, teff_min=teff_min)
    if len(search_exps):
        print 'Number of exposures to be searched: ', len(search_exps)
        print (search_exps[['expnum', 'date','band','ccd','nite','t_eff','fwhm_asec']]).head(20)
        matched_obs = find_observations(search_exps, target, orbit, year=year, nsigma=5)
    else:
        matched_obs = []
        print 'No exposures to search'

    if len(matched_obs):
        matched_obs['ccd'] = matched_obs.apply(lambda row: get_ccd(row, search_exps), axis=1)
        matched_obs['ccd'] = matched_obs['ccd'].astype(int)
        matched_good = matched_obs[matched_obs['delta_chisq'] < chisq_cut]
        print 'Number of good matches: ', len(matched_good)
        if len(matched_good) > 0:
            matched_good['date'] = matched_good.apply(lambda row: str(ephem.date(row['date'])), axis=1)
            matched_good['ra'] = matched_good.apply(lambda row: str(ephem.hours(np.radians(row['ra']))), axis=1)
            matched_good['dec'] = matched_good.apply(lambda row: str(ephem.degrees(np.radians(row['dec']))), axis=1)
            try:
                matched_good['mag'] = matched_good.apply(lambda row: round(mag_calib(row), 2), axis=1)
            except TypeError as e:
                print e

    return matched_good
示例#37
0
def _kbos_from_survey_sym_model_input_file(model_file):
    """
    Load a Survey Simulator model file as an array of ephem EllipticalBody objects.
    @param model_file:
    @return:
    """
    lines = storage.open_vos_or_local(model_file).read().split('\n')
    kbos = []
    for line in lines:
        if len(line) == 0 or line[
                0] == '#':  # skip initial column descriptors and the final blank line
            continue
        kbo = ephem.EllipticalBody()
        values = line.split()
        kbo.name = values[8]
        kbo.j = values[9]
        kbo.k = values[10]
        kbo._a = float(values[0])
        kbo._e = float(values[1])
        kbo._inc = float(values[2])
        kbo._Om = float(values[3])
        kbo._om = float(values[4])
        kbo._M = float(values[5])
        kbo._H = float(values[6])
        epoch = ephem.date(2453157.50000 - ephem.julian_date(0))
        kbo._epoch_M = epoch
        kbo._epoch = epoch
        kbos.append(kbo)
    return kbos
示例#38
0
def plot_planets(ax, plot, date, hill_sphere=False):
#     # only add the planets that would actually fall in this plot
#     plot_polygon = Polygon.Polygon(((plot[0],plot[2]),
#                                    (plot[0],plot[3]),
#                                    (plot[1],plot[3]),
#                                    (plot[0],plot[3]),
#                                    (plot[0],plot[2])))
# #    print plot_polygon
    mass = {"Sun":1.989*10**30, "Mars":639*10**21, "Jupiter":1.898*10**27, "Saturn":568.3*10**24, "Uranus":86.81*10**24, "Neptune":102.4*10**24}  # kg
    for planet in [ephem.Mars(), ephem.Jupiter(), ephem.Saturn(), ephem.Uranus(), ephem.Neptune()]:
        planet.compute(ephem.date(date))
        pos = (math.degrees(planet.ra), math.degrees(planet.dec))
#        if plot_polygon.isInside(math.degrees(planet.ra), math.degrees(planet.dec)):
        ax.scatter(pos[0], pos[1],
                 marker='o',
                 s=30,
                 facecolor='#E47833',
                 edgecolor='#E47833')
        ax.annotate(planet.name, (pos[0]+.4, pos[1]+0.15)) #(pos[0]+.9, pos[1]+0.5))  # offset to make it readable

        if hill_sphere:
            print planet.name, planet.sun_distance, mass[planet.name],
            hs_radius = (planet.sun_distance*ephem.meters_per_au)*((mass[planet.name]/3*mass['Sun'])**(1/3.))
            angular_size = planet.earth_distance*hs_radius  # FIXME
            print 'Hill sphere', hs_radius, hs_radius/ephem.meters_per_au, angular_size
            ax.add_patch(plt.Circle(pos, radius=angular_size, fill=False))

    return ax
示例#39
0
def calcaltaz(scanlist, sc, sr, format='str', intchunk=2):
    """ Calculates a single (alt,az) per scan in scanlist.
    """

    vla = ephem.Observer()
    vla.lat = '34:04:43.497'
    vla.long = '-107:37:03.819'
    vla.elevation = 2124
    src = ephem.FixedBody()

    altaz = []
    for scan in scanlist:
        inttime = (sc[scan]['endmjd'] -
                   sc[scan]['startmjd']) * 24 * 3600 / sc[1]['nints']
        src._ra, src._dec = [(sr[srn]['ra'], sr[srn]['dec'])
                             for srn in sr.keys()
                             if sc[scan]['source'] == sr[srn]['source']][0]
        for nskip in range(0, sc[scan]['nints'] - intchunk + 1, intchunk):
            vla.date = ephem.date(
                jd_to_date(sc[scan]['startmjd'] + nskip * inttime /
                           (24 * 3600) + 2400000.5))
            src.compute(vla)
            if format == 'str':
                altaz.append('(%.1f, %.1f)' %
                             (n.degrees(src.alt), n.degrees(src.az)))
            elif format == 'float':
                altaz.append((n.degrees(src.alt), n.degrees(src.az)))

    return n.array(altaz)
示例#40
0
def sidereal(time,idate):
    """
    Turns a time in UTC (defined since initial) into LST.
    time is in hours and idate is in 'YYYY/MM/DD'
    """
    initial = eph.date('2013/6/1')
    guad = eph.Observer()
    guad.lon = '-118.3'
    guad.lat = '28.8833'
    
    single = eph.date(initial+time/24.)
    guad.date = single
    single_time = guad.sidereal_time()
    sidereal_hour = single_time*12./pi

    return sidereal_hour
示例#41
0
def sidereal(time,idate,longitude,latitude):
    """
    Turns a time in UTC (defined since initial) into LST.
    time is in hours and idate is in 'YYYY/MM/DD'
    """
    initial = eph.date('2013/6/1')
    site = eph.Observer()
    site.lon = longitude
    site.lat = latitude
    
    single = eph.date(initial+time/24.)
    site.date = single
    single_time = site.sidereal_time()
    sidereal_hour = single_time*12./np.pi

    return sidereal_hour
示例#42
0
    def update_mjd(self, mjd):
        """
        observer : ephem.Observer object
        """

        self.observer.date = ephem.date(time.Time(mjd, format='mjd').datetime)

        self.altitudes_rad = []
        self.azimuth_rad = []
        self.eclip = []
        for sat in self.sat_list:
            try:
                sat.compute(self.observer)
            except ValueError:
                self.advance_epoch()
                sat.compute(self.observer)
            self.altitudes_rad.append(sat.alt)
            self.azimuth_rad.append(sat.az)
            self.eclip.append(sat.eclipsed)

        self.altitudes_rad = np.array(self.altitudes_rad)
        self.azimuth_rad = np.array(self.azimuth_rad)
        self.eclip = np.array(self.eclip)
        # Keep track of the ones that are up and illuminated
        self.above_alt_limit = np.where(
            (self.altitudes_rad >= self.alt_limit_rad)
            & (self.eclip == False))[0]
示例#43
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()
示例#44
0
    def getNetMaxLatitude(self, t=None):
        if (t is None):
            t = ephem.date(datetime.utcnow())

        #print(ephem.Date(t))

        start = t

        difference = self.longitude_difference(t)

        if (difference > 0):
            #print("Descending phase %s" % difference)
            while difference > 0:
                t += ephem.minute
                difference = self.longitude_difference(t)
        else:
            #print("Ascending phase %s" % difference)
            while difference < 0:
                t += ephem.minute
                difference = self.longitude_difference(t)

        tn = self.bisect(self.optimizeDiff, t - (ephem.minute * 2), t)
        position = self.getPosition(tn)

        #print("Next pass is at %s position %s %s" % (ephem.Date(tn),position[0],position[1]))
        daysDiff = tn - start
        minutesDiff = daysDiff * 24 * 60
        #print("Wait minutes ", minutesDiff)
        return (tn, position[0], position[1])
示例#45
0
def make_az_data(star, date=None, observatory='Mount Graham'):
    lbt = get_observatory(observatory=observatory)
    print lbt
    if date:
        lbt.date = date
    else:
        lbt.date = defaultDate
    sun = ephem.Sun()
    sun.compute(lbt)

    #start on the hour before sunset
    set_time = list(sun.set_time.tuple())
    set_time[-2] = 0
    set_time[-1] = 0
    start = ephem.Date(tuple(set_time))
    end = lbt.next_rising(sun)
    night_minutes = 24 * 60. * (end - start)
    times = []
    azs = []
    alts = []
    for tt in np.linspace(start, end, night_minutes):
        lbt.date = tt
        star.compute(lbt)
        z = (np.pi / 2.) - star.alt
        secz = (1. / np.cos(z))
        if 180. / np.pi * ((np.pi / 2.) - star.alt) < 90:
            azs.append(star.az)
            alts.append(180. / np.pi * ((np.pi / 2.) - star.alt))
            times.append(ephem.date(tt).datetime())
    return times, alts, azs
示例#46
0
def query_atm(cursor):

    site = ephem.Observer()
    day = Time(ephem.date(site.date - 1.).datetime(), format='datetime',
               scale='utc').mjd * 24 * 3600
    print('%d' % (day * 1E9))
    sql = str(
        'SELECT ARCHIVE_UID, ANTENNA_NAME, RECEIVER_BAND_ENUMV,'
        'baseband_name_enumv, CAL_DATA_ID,'
        'T_REC_VAL, T_SYS_VAL,'
        'SYSCAL_TYPE_ENUMV, POLARIZATION_TYPES_VAL,'
        'SB_GAIN_VAL, FREQUENCY_RANGE_VAL,'
        'START_VALID_TIME '
        'FROM SCHEDULING_AOS.ASDM_CALATMOSPHERE '
        'WHERE START_VALID_TIME > %d' % (day * 1E9))
    print(sql)
    print("Executing QUERY, please wait...")
    cursor.execute(sql)

    df = []

    for value in cursor:
        r = list(value)
        for i in [5, 6, 8, 9, 10]:
            r[i] = value[i].read()
        df.append(r)

    df = pd.DataFrame(
        pd.np.array(df),
        columns=['UID', 'ANTENNA', 'BAND', 'BB', 'SCAN_ID', 'TREC_VAL',
                 'TSYS_VAL', 'CALTYPE', 'POL_VAL', 'SBGAIN_VAL',
                 'FREQ_RANGE_VAL', 'START_VALID_TIME'])
    return df
示例#47
0
def sun_times(date):
    """
    Return the sunrise and sunset times at the site on the specified
    date.  Times are just horizon crossing, they do not account for
    mountains being in the way or wahtever.

    If date is a float or int, it is interpreted as a ctime and two
    ctimes are returned.  If date is any other format, it is handed
    straight to pyephem and two ephem.Dates are returned.

    Conveniently, sunset at our site is always within a few hours
    _before_ 0:00 UTC, and sunrise is always well after midnight.  So
    there will be no ambiguity if you always ask about 0:00 <date>.
    """

    obs = ephem.Observer()
    obs.lat = '-22.9585'
    obs.long = '-67.7876'
    sun = ephem.Sun()
    ctime = hasattr(date, '__float__')
    if ctime:
        d = datetime.datetime.utcfromtimestamp(date)
        t = d.year, d.month, d.day, d.hour, d.minute, d.second + d.microsecond * 1e-6
        date = ephem.date(t)
    obs.date = date
    rise_set = [obs.next_rising(sun), obs.next_setting(sun)]
    if ctime:
        return [
            calendar.timegm(ephemdate_to_datetime(d).timetuple())
            for d in rise_set
        ]
    return rise_set
示例#48
0
def query_delay(cursor):

    site = ephem.Observer()
    day = Time(ephem.date(site.date - 1.).datetime(), format='datetime',
               scale='utc').mjd * 24 * 3600
    print('%d' % (day * 1E9))
    sql = str(
        'SELECT ARCHIVE_UID, ANTENNA_NAME, ATM_PHASE_CORRECTION_ENUMV,'
        'BASEBAND_NAME_ENUMV, RECEIVER_BAND_ENUMV, CAL_DATA_ID,'
        'REF_ANTENNA_NAME,'
        'DELAY_OFFSET_VAL, POLARIZATION_TYPES_VAL,'
        'START_VALID_TIME, NUM_RECEPTOR, NUM_SIDEBAND, DELAY_ERROR_VAL '
        'FROM SCHEDULING_AOS.ASDM_CALDELAY '
        'WHERE START_VALID_TIME > %d' % (day * 1E9))
    print(sql)
    print("Executing QUERY, please wait...")
    cursor.execute(sql)
    df = []
    for value in cursor:
        r = list(value)
        for i in [7, 8, 12]:
            r[i] = value[i].read()
        df.append(r)

    df = pd.DataFrame(
        pd.np.array(df),
        columns=['UID', 'ANTENNA', 'ATM_CORR', 'BB', 'BAND', 'SCAN', 'REF_ANT',
                 'DELAY_OFF', 'POL_T', 'TIME', 'NUM_RECEP', 'NUM_SB',
                 'DELAY_ERR'])
    return df
示例#49
0
 def time_now():
     rho.date = ephem.now()  # Calculate now at rho
     s_time.set(str(ephem.localtime(ephem.now()).strftime("%H:%M:%S")))
     s_utc.set(str(ephem.date(ephem.now()).datetime().strftime("%H:%M:%S")))
     s_lst.set(str(rho.sidereal_time()))
     s.after(500,
             time_now)  # Call the function after 500 ms to update the time.
示例#50
0
def test_ephem_date():
    from ..types import ea_date
    import astropy.time
    import ephem
    astropy_Time = ea_date(ephem.date("2000/01/01"))
    assert astropy_Time == astropy.time.Time("2000-01-01", scale='utc')
    assert isinstance(astropy_Time, astropy.time.Time)
示例#51
0
文件: obsim.py 项目: patreya/obsim
def get_schedule_by_priority(src_data, config):
    N_src = np.shape(src_data)[0]
    print "Using schedule by priority algorithm for %s sources" % N_src
    src_data = np.column_stack((src_data, np.zeros(N_src, dtype=int)))
    start_date_time, end_date_time = obsim.get_start_end_dates(config)
    tz_offset = config['time_zone'] * ephem.hour
    wait_time = config['priority_wait_time'] * ephem.second
    loc = obsim.init_loc(config)
    src = obsim.init_src()
    # Initializing current position and time
    curr_time = start_date_time
    curr_tel_pos = [ ephem.degrees(str(config["telescope_azimuth"])), ephem.degrees(str(config["telescope_altitude"])) ]
    slew_rate = [ config["slew_rate_az"], config["slew_rate_alt"] ]
    schedule = []
    while (curr_time < end_date_time):
        schedule, status = get_next_src(src_data, N_src, src, loc, curr_time, tz_offset, curr_tel_pos, slew_rate, schedule)
        if (status[0]):
            src_data[status[1]][7] = 1
            curr_time = status[2]
            curr_tel_pos = [status[3], status[4]]
        else:
            from_time_local =  ephem.Date(curr_time + tz_offset)
            curr_time = ephem.Date(curr_time + wait_time)
            if (curr_time > end_date_time):
                curr_time = end_date_time
            curr_time_local =  ephem.date(curr_time + tz_offset)
            time_diff = (curr_time_local - from_time_local)*24.*3600
            schedule.append( [ 'Wait', str(from_time_local), str(curr_time_local), int(round(time_diff)), '0', '0' ] )
    return schedule               
示例#52
0
def ephem_time_from_tcs():
	ut = outval['UT'] #get Time from TCS
	date = time.gmtime()
	year, month, day = date[0], date[1], date[2]
	
	
	return ephem.date("{0}/{1}/{2} {3}".format(year, month, day, ut))
示例#53
0
def time2angle(venue):
	'''
	Cygnus A RA: 19h 59m 28.3566s
	Cygnus A Dec: +40 deg 44' 02.096"

	At Carl's using http://www.latlong.net/convert-address-to-lat-long.html
	37.980012 deg lat
	-122.185800 deg long

	venue format is tuple
	'''
	HERA = ep.Observer()
	HERA.long =  ep.degrees('-122.185800')
	HERA.lat = ep.degrees('37.980012')
	HERA.date = venue
	HERA.epoch = ep.date(venue)
	sidereal_time = HERA.sidereal_time()
	#print ('Sidereal time:  %s') %str(sidereal_time)

	astro_obj = ep.FixedBody()
	astro_obj._ra = ep.hours('19:59:28.3566')
	astro_obj._dec = ep.degrees('40:44:02.096')
	astro_obj.compute(HERA)

	coordinates_given_time = (ep.degrees(astro_obj.az), ep.degrees(astro_obj.alt))
	transit_time = ep.localtime(astro_obj.transit_time)
	transit_alt = ep.degrees(astro_obj.transit_alt)
	rise_time_on_given_date = ep.localtime(astro_obj.rise_time)
	rise_az_on_given_date = ep.degrees(astro_obj.rise_az)
	set_time_on_given_date = ep.localtime(astro_obj.set_time)
	set_az_on_given_date = ep.degrees(astro_obj.set_az)
	return coordinates_given_time, transit_time, \
		transit_alt, rise_time_on_given_date, rise_az_on_given_date, \
		set_time_on_given_date, set_az_on_given_date, sidereal_time
示例#54
0
    def residuals(self, obsdf, date_col='date', ra_col='ra', dec_col='dec'):
        '''
        Returns the residuals (in arcseconds) for the observations in obscat as a numpy array. Ordering is same as time-order of the observations, 
        from earliest to latest.
        obsdf is a pandas dataframe containing the observations. 
        date, ra, dec are in the column names specified.
        date is an ephem.date object
        ra, dec are ephem.Angle objects (typically hours, degrees) 
        '''
        resids = []
        obsdf.sort_values('expnum', ascending=True, inplace=True)
        for ind, obs in obsdf.iterrows():
            if obs[date_col][0] != '#':
                pos_pred = self.predict_pos(
                    ephem.date(obs[date_col]) + 0.53 * ephem.second +
                    float(obs['exptime']) * ephem.second / 2)
                ra_pred, dec_pred = pos_pred['ra'], pos_pred['dec']
                sep = ephem.separation(
                    (ephem.hours(obs[ra_col]), ephem.degrees(obs[dec_col])),
                    (ra_pred, dec_pred))
                resid = sep * (180 / np.pi) * 3600  # convert to arcseconds
                resids.append(resid)

    #            print obs['expnum'], resid
        return np.array(resids)
示例#55
0
def setObserverData(station, predictionDate, verbose):
    """
    setObserverData sets the info for the station from which the info is calculated
    Parameters:
        station: info over the observation station (name, lat, lon)
        predictionDate: date for doing the prediction
    Returns:
        observer contains all info about location and date for prediction
    """
    # read in the station info (name, latitude, longitude) in degrees
    observer = Station()
    if station is None:
        observer = RMA
    else:
        observer.parse(station)

    # read in the predDate
    if predictionDate is None:
        observer.date = ephem.date(
            ephem.now())  # today at midnight for default start
    else:
        observer.date = ephem.Date(predictionDate)
    # print('observer.date: %04d/%02d/%02d\n' % ephem.date(observer.date).triple())

    if verbose:
        observer.statPrint()

    return observer
示例#56
0
 def gmt_for_time_on_date(self, edate, timetuple):
     '''Returns the ephem.date for the GMT corresponding to localtime
        timetuple on the given ephem.date.
     '''
     tup = list(edate.tuple())
     tup[3], tup[4], tup[5] = timetuple
     return self.local_to_gmt(ephem.date(tuple(tup)), reverse=True)
示例#57
0
 def __init__(self,
              year,
              observer=ephem.city('Copenhagen'),
              weekly=True,
              on_days=range(7),
              outformat=None):
     self.sun_rise_sun_set = {}
     start = ephem.Date((year, 1, 1, 0))
     for i in range(367):
         d = ephem.date(start + (24 * ephem.hour * i))
         if weekly:
             on_days = [0]
         if (d.datetime().weekday() in on_days):
             observer.date = d
             sunrise = observer.next_rising(ephem.Sun())
             sunset = observer.next_setting(ephem.Sun())
             if d.datetime().year == year:
                 if outformat == 'text':
                     self.sun_rise_sun_set[d.datetime()] = 'sol %s-%s' \
                                                           % (utc2localtime(sunrise.datetime(), format='hhmm'),
                                                              utc2localtime(sunset.datetime(), format='hhmm'))
                 elif outformat == 'symbols':
                     self.sun_rise_sun_set[d.datetime()] = '🌞 %s-%s' \
                                                           % (utc2localtime(sunrise.datetime(), format='hhmm'),
                                                              utc2localtime(sunset.datetime(), format='hhmm'))
示例#58
0
def setObserverData(station, predictionDate, verbose):
    """
    setObserverData sets the info for the station from which the info is calculated
    Parameters:
        station: info over the observation station (name, lat, lon)
        predictionDate: date for doing the prediction
    Returns:
        observer contains all info about location and date for prediction
    """
    # read in the station info (name, latitude, longitude) in degrees
    observer = Station()
    if station is None:
        observer = RMA
    else:
        observer.parse(station)

    # read in the predDate
    if predictionDate is None:
        observer.date = ephem.date(ephem.now())  # today at midnight for default start
    else:
        observer.date = ephem.Date(predictionDate)
    # print('observer.date: %04d/%02d/%02d\n' % ephem.date(observer.date).triple())

    if verbose:
        observer.statPrint()

    return observer
示例#59
0
文件: function.py 项目: Fingel/gwtm
def getGeoCenter(datetime, lon, lat):
    # Define the observer to be at the location of the spacecraft
    observer = ephem.Observer()

    # Convert the longitude to +E (-180 to 180)
    if lon > 180:
        lon = (lon % 180) - 180

    lon_deg, lon_min = deg2dm(lon)
    lat_deg, lat_min = deg2dm(lat)

    lon_string = '%s:%s' % (lon_deg, lon_min)
    lat_string = '%s:%s' % (lat_deg, lat_min)

    observer.lon = lon_string
    observer.lat = lat_string

    # Set the time of the observations
    observer.date = ephem.date(datetime)

    # Get the ra and dec (in radians) of the point in the sky at altitude = 90 (directly overhead)
    ra_zenith_radians, dec_zenith_radians = observer.radec_of('0', '90')

    # convert the ra and dec to degrees
    ra_zenith = np.degrees(ra_zenith_radians)
    dec_zenith = np.degrees(dec_zenith_radians)

    ra_geocenter = (ra_zenith + 180) % 360
    dec_geocenter = -1 * dec_zenith

    return ra_geocenter, dec_geocenter