Exemplo n.º 1
0
def hname(ra):
    one = str(
        (int(str(ephem.hours(ra * n.pi / 180)).split(':')[0]) + 100000))[-2::]
    two = str(
        (int(str(ephem.hours(ra * n.pi / 180)).split(':')[1]) + 100000))[-2::]
    ret = one + two
    return ret
Exemplo n.º 2
0
def calc_local_hour(yr, month, day, H_UTC, min_UTC, lon):
    # function to calculate the local solar time
    # (i.e. the hour angle of the sun + 12 h)
    # inputs
    # date UTC : yr, month, day, H_UTC, min_UTC
    # lon: longitude in degrees East
    # outputs
    # local solar hour (decimal)

    import ephem
    import datetime

    sun = ephem.Sun()
    # set date, longitude manually
    o = ephem.Observer()
    o.date = datetime.datetime(yr, month, day, H_UTC, min_UTC,
                               0)  # some utc time ; could replace 0 by seconds
    o.lon = lon * ephem.degree  #
    sun.compute(o)
    hour_angle = o.sidereal_time() - sun.ra
    solartime = ephem.hours(hour_angle +
                            ephem.hours('12:00')).norm  # norm for 24h
    # nb: lat has no impact on solar time
    time_str = str(solartime)
    h, m, s = time_str.split(':')
    local_h = int(h) + int(m) / 60. + float(s) / 3600.

    return local_h
Exemplo n.º 3
0
def string2RADEC(st):
   '''Given a string, try to convert into internal ephem angle.'''
   fields = map(str,st.strip().split())
   if len(fields) == 2:
      # Try RA DEC in decimal degrees
      try:
         RA,DEC = map(float, fields)
         return RA,DEC
      except:
         # Try as sexadecimal notation
         try:
            RA,DEC = hours(fields[0]),degrees(fields[1])
            return RA*180/pi,DEC*180/pi
         except:
            # Fail!
            return None,None
   elif len(fields) in [4,6]:
      # assume RA and DEC have the same number of fields
      try:
         nf = len(fields)
         RA = ":".join(fields[0:nf/2])
         DEC = ":".join(fields[nf/2:])
         RA,DEC = hours(RA)*180/pi,degrees(DEC)*180/pi
         return RA,DEC
      except:
         # Fail!
         return None,None
   else:
      # Dunno!
      return None,None
Exemplo n.º 4
0
def equation_of_time(date):
    """returns equation of time, the suns transit time, 
    the moons transit-, antitransittime, age and percent illumination
    """
    obs = ephem.Observer()
    obs.date = date

    s = ephem.Sun()
    m = ephem.Moon()
    s.compute(date)
    m.compute(date)
    transs = str(obs.next_transit(s, start=date))[-8:-3]
    antim = str(obs.next_antitransit(m, start=date))[-8:-3]
    transm = str(obs.next_transit(m, start=date))[-8:-3]

    m.compute(date + 0.5)
    phase = int(round(m.phase))
    age = int(round((date + 0.5) - ephem.previous_new_moon(date + 0.5)))

    s.compute(date - 0.1)
    obs.date = date - 0.1
    eqt00 = ephem.hours(round((obs.next_antitransit(s) - date) * 86400) / 86400 * 2 * math.pi)
    eqt00 = str(eqt00)[-8:-3]
    eqt12 = ephem.hours(round((obs.next_transit(s) - (date + 0.5)) * 86400) / 86400 * 2 * math.pi)
    eqt12 = str(eqt12)[-8:-3]

    return eqt00, eqt12, transs, transm, antim, age, phase
Exemplo n.º 5
0
 def click(event):
     global cnt
     if event.button == 3:
         lon, lat = map(event.xdata, event.ydata, inverse=True)
         if opts.osys == 'eq': lon = (360 - lon) % 360
         lon *= a.img.deg2rad
         lat *= a.img.deg2rad
         ra, dec = ephem.hours(lon), ephem.degrees(lat)
         x, y, z = a.coord.radec2eq((ra, dec))
         flx = h[(x, y, z)]
         print '#%d (RA,DEC): (%s, %s), Jy: %f' % (cnt, ra, dec, flx)
         cnt += 1
     elif event.button == 2:
         lon, lat = map(event.xdata, event.ydata, inverse=True)
         if opts.osys == 'eq': lon = (360 - lon) % 360
         lon *= a.img.deg2rad
         lat *= a.img.deg2rad
         ra, dec = ephem.hours(lon), ephem.degrees(lat)
         x, y, z = a.coord.radec2eq((ra, dec))
         #flx = h[(x,y,z)]
         crd = [mk_arr(c, dtype=np.double) for c in (x, y, z)]
         px, wgts = h.crd2px(*crd, **{'interpolate': 1})
         flx = np.sum(h[px], axis=-1)
         print '#%d (RA,DEC): (%s, %s), Jy: %f (4px sum)' % (cnt, ra, dec,
                                                             flx)
         cnt += 1
     else:
         return
Exemplo n.º 6
0
	def hourAngle(self,ra):
		self.observer.date=ephem.now()
		self.sideral=self.observer.sidereal_time()
		ra_=ephem.hours(ra-self.sideral).znorm
		if ra_==ephem.hours("24:00:00"):
			ra=ephem.hours("00:00:00")
		return ra_		
Exemplo n.º 7
0
    def _solartime(lon, lat, date=date, rtn_as_epoch=True):
        """
        Get solartime for location (lat, lon) and date

        Returns
        ---
        (float) Epoch time
        """
        # --- get sunrise and sunset for location
        o = ephem.Observer()
        # set lat (decimal?), lon (decimal?), and date (UTC)
        o.lat = str(lat)
        o.long = str(lon)
        o.date = date
        # planetary body
        s = ephem.Sun()
        # Compute sun vs observer
        s.compute(o)
        # below code was adapted from stackoverflow (Credit: J.F. Sebastian)
        # http://stackoverflow.com/questions/13314626/local-solar-time-function-from-utc-and-longitude
        # sidereal time == ra (right ascension) is the highest point (noon)
        hour_angle = o.sidereal_time() - s.ra
        s_time = ephem.hours(hour_angle +
                             ephem.hours('12:00')).norm  # norm for 24h
        # ephem.hours is a float number that represents an angle in radians
        # and converts to/from a string as "hh:mm:ss.ff".
        s_time = "%s" % s_time
        if len(s_time) != 11:
            s_time = '0' + s_time
        # return as datetime
        s_time = datetime.datetime.strptime(s_time[:8], '%H:%M:%S')
        if rtn_as_epoch:
            s_time = unix_time(s_time)
        return s_time
Exemplo n.º 8
0
def convert_eq2ga(ra,
                  dec,
                  i_epoch=e.J2000,
                  o_epoch=None,
                  degree_in=True,
                  degree_out=True):

    if o_epoch is None:
        o_epoch = i_epoch

    if degree_in:
        ra = e.hours(ra * np.pi / 180.)
        dec = e.degrees(dec * np.pi / 180.)
    else:
        ra = e.hours(ra * np.pi)
        dec = e.degrees(dec * np.pi)

    coord = e.Equatorial(ra, dec, epoch=i_epoch)
    coord = e.Galactic(coord, epoch=o_epoch)

    l, b = coord.lon, coord.lat

    if degree_out:
        l = l * 180. / np.pi
        b = b * 180. / np.pi

    return l, b
Exemplo n.º 9
0
 def click(event):
     global cnt
     if event.button == 3: 
         lon,lat = map(event.xdata, event.ydata, inverse=True)
         print event.xdata,type(event.xdata)
         if opts.osys == 'eq': lon = (360 - lon) % 360
         lon *= a.img.deg2rad; lat *= a.img.deg2rad
         ra,dec = ephem.hours(lon), ephem.degrees(lat)
         x,y,z = a.coord.radec2eq((ra,dec))
         flx = h[(x,y,z)]
         print '#%d (RA,DEC): (%s, %s), Jy: %f' % (cnt, ra, dec, flx)
         cnt += 1
     elif event.button==2:
         lon,lat = map(event.xdata, event.ydata, inverse=True)
         if opts.osys == 'eq': lon = (360 - lon) % 360
         lon *= a.img.deg2rad; lat *= a.img.deg2rad
         ra,dec = ephem.hours(lon), ephem.degrees(lat)
         x,y,z = a.coord.radec2eq((ra,dec))
         #flx = h[(x,y,z)]
         crd = [mk_arr(c, dtype=n.double) for c in (x,y,z)]
         px,wgts = h.crd2px(*crd, **{'interpolate':1})
         flx = n.sum(h[px],axis=-1)
         print '#%d (RA,DEC): (%s, %s), Jy: %f (4px sum)' % (cnt, ra, dec, flx)
         cnt += 1
     else: return
Exemplo n.º 10
0
 def dLocation(self):
     self.s = ephem.Sun()
     self.s.compute(epoch=ephem.now())
     if self.nameEdit.text():
         self.text1.setText(self.nameEdit.text())
         font03 = QFont("Arial", 16)
         font03.setBold(True)
         self.text1.setFont(font03)
         if not self.dateandtimeEdit.text():
             self.o.date = ephem.now()  # 00:22:07 EDT 06:22:07 UT+1
     else:
         if self.dateandtimeEdit.text():
             self.o.date = self.dateandtimeEdit.text()
             self.text1.setText("<b>Obliczenia dla:</b><br/> " +
                                self.dateandtimeEdit.text())
             font03 = QFont("Arial", 16)
             font03.setBold(True)
             self.text1.setFont(font03)
         else:
             self.o.date = ephem.now()  # 00:22:07 EDT 06:22:07 UT+1
     #self.o.date = ephem.now()  # 00:22:07 EDT 06:22:07 UT+1
     self.s.compute(self.o)
     hour_angle = self.o.sidereal_time() - self.s.ra
     t = ephem.hours(hour_angle +
                     ephem.hours('12:00')).norm  # .norm for 0..24
     self.rad = str(ephem.hours(hour_angle + ephem.hours('12:00')).norm)
     # self.result.setText("R.A.: " + str(self.s.a_ra) + "                DEC.: " + str(self.s.a_dec))
     # self.result2.setText("HOUR ANGLE: " + str(self.rad) + " SIDERAL TIME: " + str(self.o.sidereal_time()))
     # self.result3.setText("SUN Altitude: " + str(self.s.alt) + "       SUN Azimuth: " + str(self.s.az))
     self.result4.setText("R.A.: " + str(self.s.a_ra))
     self.result5.setText("DEC.: " + str(self.s.a_dec))
     self.result6.setText("HOUR ANGLE: " + str(self.rad))
     self.result7.setText("SIDERAL TIME: " + str(self.o.sidereal_time()))
     self.result8.setText("SUN Altitude: " + str(self.s.alt))
     self.result9.setText("SUN Azimuth: " + str(self.s.az))
Exemplo n.º 11
0
 def hourAngle(self, ra):
     self.observer.date = ephem.now()
     self.sideral = self.observer.sidereal_time()
     ra_ = ephem.hours(ra - self.sideral).znorm
     if ra_ == ephem.hours("24:00:00"):
         ra = ephem.hours("00:00:00")
     return ra_
Exemplo n.º 12
0
    def get_target_info_table(self, target, time_start=None, time_stop=None,
                              time_interval=5):
        """Prints a table of hourly airmass data"""
        history = self.get_target_info(target, time_start=time_start,
                                       time_stop=time_stop,
                                       time_interval=time_interval)
        text = []
        format_hdr = '%(date)-16s  %(utc)5s  %(lmst)5s  %(ha)5s  %(pa)7s %(am)6s %(ma)6s %(ms)7s'
        header = dict(date='Date', utc='UTC', lmst='LMST',
                      ha='HA', pa='PA', am='AM', ma='MnAlt', ms='MnSep')
        hstr = format_hdr % header
        text.append(hstr)
        text.append('_'*len(hstr))

        format_line = '%(date)-16s  %(utc)5s  %(lmst)5s  %(ha)5s  %(pa)7.2f %(am)6.2f %(ma)6.2f %(ms)7.2f'

        for info in history:
            s_date = info.lt.astimezone(self.tz_local).strftime('%d%b%Y  %H:%M')
            s_utc = info.lt.astimezone(self.tz_utc).strftime('%H:%M')
            s_ha = ':'.join(str(ephem.hours(info.ha)).split(':')[:2])
            s_lmst = ':'.join(str(ephem.hours(info.lmst)).split(':')[:2])
            pa = float(numpy.degrees(info.pang))
            am = float(info.airmass)
            ma = float(numpy.degrees(info.moon_alt))
            ms = float(numpy.degrees(info.moon_sep))
            line = dict(date=s_date, utc=s_utc, lmst=s_lmst,
                        ha=s_ha, pa=pa, am=am, ma=ma, ms=ms)
            s_data = format_line % line
            text.append(s_data)
        return '\n'.join(text)
Exemplo n.º 13
0
    def __init__(self, ra=None, dec=None, obj=None, session=None):
        """Tracks an object in the sky and collects data.

        Takes either a pyephem object, or a ra and dec (not both)
        Arguments:
            ra (radians): Right ascension of object
            dec (radians): Declination of object
            obj (ephem.Body): Pyephem object
            session (str): Name of observing session (name of data file)
        """
        self.obs = ephem.Observer()
        self.obs.long, self.obs.lat = ephem.hours(np.deg2rad(LONG)), ephem.degrees(np.deg2rad(LAT))
        logger.info("Observer set at (long, lat): {long_}, {lat}".format(long_=self.obs.long, lat=self.obs.lat))

        if obj and not (ra or dec):
            self.source = obj
        elif (ra and dec) and not obj:
            self.source = ephem.FixedBody()
            self.source._ra = ephem.hours(ra)
            self.source._dec = ephem.degrees(dec)
            self.source._epoch = ephem.J2000  # for precessing
        else:
            raise Exception("Only use either (ra, dec) or an ephem obj.")

        self.last_home = None
        self.session = session
Exemplo n.º 14
0
def equation_of_time(date):
    """returns equation of time, the suns transit time, 
    the moons transit-, antitransittime, age and percent illumination
    """
    obs = ephem.Observer()
    obs.date = date
    
    s = ephem.Sun()
    m = ephem.Moon()
    s.compute(date)
    m.compute(date)
    transs = str(obs.next_transit(s,start=date))[-8:-3]
    antim = str(obs.next_antitransit(m,start=date))[-8:-3]
    transm = str(obs.next_transit(m,start=date))[-8:-3]
    
    m.compute(date+0.5)
    phase = int(round(m.phase))
    age = int(round((date+0.5)-ephem.previous_new_moon(date+0.5)))
    
    s.compute(date-0.1)
    obs.date = date-0.1
    eqt00 = ephem.hours(round((obs.next_antitransit(s)-date)*86400)/86400*2*math.pi)
    eqt00 = str(eqt00)[-8:-3]
    eqt12 = ephem.hours(round((obs.next_transit(s)-(date+0.5))*86400)/86400*2*math.pi)
    eqt12 = str(eqt12)[-8:-3]
    
    return eqt00,eqt12,transs,transm,antim,age,phase
Exemplo n.º 15
0
 def get_target_info_table(self, target, time_start=None, time_stop=None):
     """Prints a table of hourly airmass data"""
     history = self.get_target_info(target,
                                    time_start=time_start,
                                    time_stop=time_stop)
     text = ''
     format = '%-16s  %-5s  %-5s  %-5s  %-5s  %-5s %-5s\n'
     header = ('Date       Local', 'UTC', 'LMST', 'HA', 'PA', 'AM', 'Moon')
     hstr = format % header
     text += hstr
     text += '_' * len(hstr) + '\n'
     for info in history:
         s_lt = info.lt.strftime('%d%b%Y  %H:%M')
         s_utc = info.ut.strftime('%H:%M')
         s_ha = ':'.join(str(ephem.hours(info.ha)).split(':')[:2])
         s_lmst = ':'.join(str(ephem.hours(info.lmst)).split(':')[:2])
         #s_pa = round(info.pang*180.0/np.pi, 1)
         s_pa = round(info.pang, 1)
         s_am = round(info.airmass, 2)
         s_ma = round(info.moon_alt, 1)
         if s_ma < 0:
             s_ma = ''
         s_data = format % (s_lt, s_utc, s_lmst, s_ha, s_pa, s_am, s_ma)
         text += s_data
     return text
Exemplo n.º 16
0
def click(event):
    global cnt
    if event.button == 3: 
        lon,lat = map(event.xdata, event.ydata, inverse=True)
        lon = (180 + kwds['ra'] - lon) % 360
        lon *= a.img.deg2rad; lat *= a.img.deg2rad
        ra,dec = ephem.hours(lon), ephem.degrees(lat)
        xpx = n.around(event.xdata / (kwds['d_ra'] * a.img.deg2rad))
        ypx = n.around(event.ydata / (kwds['d_dec'] * a.img.deg2rad))
        flx = d[ypx,xpx]
        if opts.mode.startswith('log'): flx = 10**flx
        print '#%d (RA,DEC): (%s, %s), PX: (%d,%d) Jy: %f' % \
            (cnt, ra, dec, xpx, ypx, flx)
        cnt += 1
    elif event.button == 2: 
        p.figure(200)
        lon,lat = map(event.xdata, event.ydata, inverse=True)
        p.plot(cube[lat,lon,:])
        lon = (180 + kwds['ra'] - lon) % 360
        lon *= a.img.deg2rad; lat *= a.img.deg2rad
        ra,dec = ephem.hours(lon), ephem.degrees(lat)
        xpx = n.around(event.xdata / (kwds['d_ra'] * a.img.deg2rad))
        ypx = n.around(event.ydata / (kwds['d_dec'] * a.img.deg2rad))
        flx = d[ypx,xpx]
        if opts.mode.startswith('log'): flx = 10**flx
        p.title('#%d (RA,DEC): (%s, %s), PX: (%d,%d) Jy: %f' % \
            (cnt, ra, dec, xpx, ypx, flx))
        cnt += 1
    else: return
Exemplo n.º 17
0
def click(event):
    global cnt
    if event.button == 3:
        lon, lat = map(event.xdata, event.ydata, inverse=True)
        lon = (180 + kwds['ra'] - lon) % 360
        lon *= a.img.deg2rad
        lat *= a.img.deg2rad
        ra, dec = ephem.hours(lon), ephem.degrees(lat)
        xpx = n.around(event.xdata / (kwds['d_ra'] * a.img.deg2rad))
        ypx = n.around(event.ydata / (kwds['d_dec'] * a.img.deg2rad))
        flx = d[ypx, xpx]
        if opts.mode.startswith('log'): flx = 10**flx
        print '#%d (RA,DEC): (%s, %s), PX: (%d,%d) Jy: %f' % \
            (cnt, ra, dec, xpx, ypx, flx)
        cnt += 1
    elif event.button == 2:
        p.figure(200)
        lon, lat = map(event.xdata, event.ydata, inverse=True)
        p.plot(cube[lat, lon, :])
        lon = (180 + kwds['ra'] - lon) % 360
        lon *= a.img.deg2rad
        lat *= a.img.deg2rad
        ra, dec = ephem.hours(lon), ephem.degrees(lat)
        xpx = n.around(event.xdata / (kwds['d_ra'] * a.img.deg2rad))
        ypx = n.around(event.ydata / (kwds['d_dec'] * a.img.deg2rad))
        flx = d[ypx, xpx]
        if opts.mode.startswith('log'): flx = 10**flx
        p.title('#%d (RA,DEC): (%s, %s), PX: (%d,%d) Jy: %f' % \
            (cnt, ra, dec, xpx, ypx, flx))
        cnt += 1
    else:
        return
Exemplo n.º 18
0
def solartime(observer, sun=None):
    """
    Get Solartime  for location of 'observer' relative to 'sun'

    Parameters
    -------
    observer (ephem observer object): Location of the observer
    sun (ephem sun object): Which dun to use? (default: our sun)

    Returns
    -------
    (float)

    Notes
    -------
     - Credit: J.F. Sebastian
    http://stackoverflow.com/questions/13314626/local-solar-time-function-from-utc-and-longitude
    """
    import ephem
    if isinstance(sun, type(None)):
        ephem.Sun()
    # Astronomical math - compute the angle between the sun and observe
    sun.compute(observer)
    # sidereal time == ra (right ascension) is the highest point (noon)
    hour_angle = observer.sidereal_time() - sun.ra
    return ephem.hours(hour_angle + ephem.hours('12:00')).norm  # norm for 24h
Exemplo n.º 19
0
    def test_drx_alt_update(self):
        """Test updating TRK_RADEC values with other phase centers."""

        project = idf.parse_idf(altFile)
        project.runs[0].scans[0].start = "MST 2011 Feb 23 17:00:15"
        project.runs[0].scans[0].duration = timedelta(seconds=15)
        project.runs[0].scans[0].frequency1 = 75e6
        project.runs[0].scans[0].frequency2 = 76e6
        project.runs[0].scans[0].ra = ephem.hours('5:30:00')
        project.runs[0].scans[0].dec = ephem.degrees('+22:30:00')
        project.runs[0].scans[0].alt_phase_centers[0].ra = ephem.hours(
            '5:35:00')
        project.runs[0].scans[0].alt_phase_centers[1].ra = ephem.hours(
            '5:25:00')

        self.assertEqual(project.runs[0].scans[0].mjd, 55616)
        self.assertEqual(project.runs[0].scans[0].mpm, 15000)
        self.assertEqual(project.runs[0].scans[0].dur, 15000)
        self.assertEqual(project.runs[0].scans[0].freq1, 1643482384)
        self.assertEqual(project.runs[0].scans[0].freq2, 1665395482)
        self.assertAlmostEqual(project.runs[0].scans[0].ra, 5.5, 6)
        self.assertAlmostEqual(project.runs[0].scans[0].dec, 22.5, 6)
        self.assertAlmostEqual(
            project.runs[0].scans[0].alt_phase_centers[0].ra, 5.583333, 6)
        self.assertAlmostEqual(
            project.runs[0].scans[0].alt_phase_centers[1].ra, 5.416667, 6)
Exemplo n.º 20
0
def angle_from_hours(s):
    """Creates angle object from sexagesimal string in hours or number in radians."""
    try:
        # Ephem expects a number or platform-appropriate string (i.e. Unicode on Py3)
        return ephem.hours(s)
    except TypeError:
        # If input is neither, assume that it really wants to be a string
        return ephem.hours(_just_gimme_an_ascii_string(s))
Exemplo n.º 21
0
    def data(self, index, role):
        if not index.isValid():
            print("whaat?")
            return QVariant()
        sb = self.arraydata[index.row()]
        col = index.column()
        if role == Qt.DisplayRole:
            if col in [8, 10]:
                if sb[col] < 0:
                    neg = '-'
                    ha_t = str(ephem.hours(str(abs(sb[col]))))
                    # noinspection PyCallByClass
                    ha = QTime.fromString(ha_t, 'h:m:s.z')
                else:
                    neg = ''
                    ha_t = str(ephem.hours(str(sb[col])))
                    # noinspection PyCallByClass
                    ha = QTime.fromString(ha_t, 'h:m:s.z')
                hastr = QString("%1").arg(neg + ha.toString('h:mm'))
                return QVariant(hastr)
            elif col == 6:
                h = ephem.hours(str(sb[col] / 15.))
                return QVariant(str(h)[:-3])
            elif col == 7:
                d = ephem.degrees(str(sb[col]))
                return QVariant(str(d)[:-2])
            elif col in [0, 16, 17, 18, 21, 22, 23, 24]:
                return QVariant(QString("%1").arg(sb[col], 0, 'f', 2))
            elif col in [9, 19, 20, 25]:
                return QVariant(QString("%1").arg(sb[col], 0, 'f', 1))
            elif col in [14, 15]:
                return QVariant(QString("%1").arg(sb[col], 0, 10))

            return QVariant(str(self.arraydata[index.row()][index.column()]))
        elif role == Qt.TextAlignmentRole:
            if col in [0, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                       22, 24, 25, 26]:
                return QVariant(int(Qt.AlignRight | Qt.AlignVCenter))
            if col in [11, 12, 13]:
                return QVariant(int(Qt.AlignCenter | Qt.AlignVCenter))
            return QVariant(int(Qt.AlignLeft | Qt.AlignVCenter))
        elif role == Qt.BackgroundColorRole:
            if 0 == index.row() % 2:
                c = QVariant(QColor(235, 245, 255))
            else:
                c = QVariant(QColor(250, 250, 250))
            # if sb[19] >= 8.5 and sb[23] <= 0.75 * 1.15:
            # changed line to reflect not longer observable in C34-6
            # if sb[22] > 0.57 and sb[0] > 0:
            #    c = QVariant(QColor(130, 250, 82))
            if sb[16] > 1.3 and sb[18] > 1.3:
                c = QVariant(QColor(255, 110, 110))
            return c
        elif role == Qt.FontRole:
            if col in [0, 18, 20]:
                return QVariant(QFont("Cantarel", 10, QFont.Bold))

        return QVariant()
Exemplo n.º 22
0
 def getRA(self, arg):
     self.observer.date = ephem.Date(datetime.datetime.utcnow())
     self.sideral = self.observer.sidereal_time()
     beta = float(self.m.axis1.motorBeta) * self.m.axis1.minMotorStep
     ra = ephem.hours(self.sideral + beta).norm
     if ra == ephem.hours("24:00:00"):
         ra = ephem.hours("00:00:00")
     self.RA = ra
     return self.RA
Exemplo n.º 23
0
def fit_dec(data, start, end, debug=False):
    lst = np.load('data/report/3C144_03-28-2014_001926.npz')['lst'][start:end]
    data = data[(len(data)-len(lst))/2:-(len(data)-len(lst))/2]
    generate_plot(data, dft=True)

    source = ephem.FixedBody()
    obs = ephem.Observer()
    obs.lat = ephem.degrees(37.8732)
    obs.long = ephem.degrees(-122.2573)
    obs.date = ephem.date('2014/3/28 0:19:26')

    source._ra    = ephem.hours("5:34:31.95")
    source._dec   = ephem.degrees("22:00:51.1")
    source._epoch = ephem.J2000
    source.compute(obs)

    hs = np.array(ephem.hours(source.ra) - lst)

    # 'Brute force' least squares
    lmbda = 2.5 # Wavelength lambda in cm
    YBAR = []
    By = 1000
    cos_dec = np.linspace(0.01,1,500)
    A = []
    S_SQ = []

    # Iterate over baseline lengths in cm
    for dec in cos_dec:
        C = 2 * np.pi * By/lmbda * dec
        x1 = np.cos( C * np.sin(hs) )
        x2 = np.sin( C * np.sin(hs) )
        X = np.matrix([x1, x2])

        ybar, a, s_sq = least_squares(data, X)
        S_SQ.append(s_sq)
        ybar = np.array(ybar[:,0])
        YBAR.append(ybar)
        A.append(a)

    Dopt = np.argmin(S_SQ)
    if debug:
        plt.figure()
        plt.plot(cos_dec, S_SQ/max(S_SQ))
        plt.title('Normalized Residuals for Declination Fit')
        plt.savefig('img/crab/residual_dec.png')

        plt.figure()
        plt.plot(data)
        plt.plot(YBAR[Dopt])
        plt.title('Least Squares Fit for Declination')
        plt.legend(['Filtered', 'Fit'])
        plt.savefig('img/crab/fit_dec.png')
        print 'By = '+str(By)
        print 'delta (deg)= '+str(np.arccos(cos_dec[Dopt])*180/np.pi)
        print 'A = '+str(A[Dopt])
    return YBAR[Dopt], A[Dopt], np.arccos(cos_dec[Dopt])*180/np.pi
Exemplo n.º 24
0
	def __init__(self):
		port=servers['zmqEngineCmdPort']
		super(mainengine,self).__init__('mainengine',port)
		CMDs={ 
		chr(6):self.cmd_ack,  \
		":info": self.cmd_info,  \
  		":FirmWareDate": self.cmd_firware_date,  \
  		":GVF": self.cmd_firware_ver,  \
  		":V": self.cmd_firware_ver,  \
  		":GVD": self.cmd_firware_date,  \
  		":GC": self.cmd_getLocalDate,  \
  		":GL": self.cmd_getLocalTime,  \
  		":GS": self.cmd_getSideralTime,  \
  		":Sr": self.cmd_setTargetRA,  \
  		":Sd": self.cmd_setTargetDEC,  \
  		":MS": self.cmd_slew,  \
  		":Q":  self.cmd_stopSlew,  \
  		":Gr": self.cmd_getTargetRA,  \
  		":Gd": self.cmd_getTargetDEC,  \
  		":GR": self.cmd_getTelescopeRA,  \
  		":GD": self.cmd_getTelescopeDEC,  \
  		":RS": self.cmd_setMaxSlewRate,  \
  		":RM": self.cmd_slewRate,  \
  		":Me": self.cmd_pulseE,  \
  		":Mw": self.cmd_pulseW,  \
  		":Mn": self.cmd_pulseN,  \
  		":Ms": self.cmd_pulseS,  \
  		":CM": self.cmd_align2target,  \
  		"@getObserver": self.getObserver, \
  		"@getGear": self.getGear, \
  		"@getRA": self.getRA, \
  		"@getDEC": self.getDEC, \
  		"@setTrackSpeed": self.setTrackSpeed, \
  		"@values": self.values 
		}
		self.m=ramps.mount()
		self.valuesmsg ={}
		self.addCMDs(CMDs)
		self.observerInit()
		self.targetRA=ephem.hours(0)
		self.targetDEC=ephem.degrees(0)
		ra=ephem.hours(self.observer.sidereal_time())
		dec=ephem.degrees(0)
		star = ephem.FixedBody(ra,dec,observer=self.observer,epoch='2016.4')
		star.compute(self.observer)
		self.RA=star.ra
		self.DEC=star.dec
		self.alt=star.alt
		self.az=star.az

		self.pulseStep=ephem.degrees('00:00:01')
		a=ephem.degrees('00:20:00')

		vRA=-ephem.hours("00:00:01")
		vDEC=ephem.degrees("00:00:00")
		self.m.trackSpeed(vRA,vDEC)
Exemplo n.º 25
0
def equation_of_time(date):  # used in twilighttab (section 3)
    # returns equation of time, the sun's transit time,
    # the moon's transit-, antitransit-time, age and percent illumination.
    # (Equation of Time = Mean solar time - Apparent solar time)

    py_date = date.tuple()
    py_obsdate = datetime.date(py_date[0], py_date[1], py_date[2])
    d = ephem.date(date - 30 * ephem.second)
    obs = ephem.Observer()
    obs.date = d
    ephem_sun.compute(d)
    ephem_moon.compute(d)
    transs = '--:--'
    antim = '--:--'
    transm = '--:--'

    next_s_tr = obs.next_transit(ephem_sun, start=d)
    if next_s_tr - obs.date < 1:
        transs = hhmm(next_s_tr)

    next_m_atr = obs.next_antitransit(ephem_moon, start=d)
    if next_m_atr - obs.date < 1:
        antim = hhmm(next_m_atr)

    next_m_tr = obs.next_transit(ephem_moon, start=d)
    if next_m_tr - obs.date < 1:
        transm = hhmm(next_m_tr)

#-----------------------------
    obs = ephem.Observer()
    obs.date = date

    ephem_moon.compute(date + 0.5)
    pct = int(round(ephem_moon.phase))  # percent of moon surface illuminated
    age = int(round((date + 0.5) - ephem.previous_new_moon(date + 0.5)))
    phase = ephem_moon.elong.norm + 0.0  # moon phase as float (0:new to π:full to 2π:new)

    ephem_sun.compute(date - 0.1)
    obs.date = date - 0.1

    # round to the second; convert back to days
    x = round(
        (obs.next_antitransit(ephem_sun) - date) * 86400) * 2 * math.pi / 86400
    eqt00 = ephem.hours(x)
    eqt00 = str(eqt00)[-8:-3]
    if x >= 0:
        eqt00 = r"\colorbox{{lightgray!80}}{{{}}}".format(eqt00)

    y = round((obs.next_transit(ephem_sun) -
               (date + 0.5)) * 86400) * 2 * math.pi / 86400
    eqt12 = ephem.hours(y)
    eqt12 = str(eqt12)[-8:-3]
    if y >= 0:
        eqt12 = r"\colorbox{{lightgray!80}}{{{}}}".format(eqt12)

    return eqt00, eqt12, transs, transm, antim, age, pct
Exemplo n.º 26
0
def fit_dec(data, start, end, debug=False):
    lst = np.load("data/report/3C144_03-28-2014_001926.npz")["lst"][start:end]
    data = data[(len(data) - len(lst)) / 2 : -(len(data) - len(lst)) / 2]
    generate_plot(data, dft=True)

    source = ephem.FixedBody()
    obs = ephem.Observer()
    obs.lat = ephem.degrees(37.8732)
    obs.long = ephem.degrees(-122.2573)
    obs.date = ephem.date("2014/3/28 0:19:26")

    source._ra = ephem.hours("5:34:31.95")
    source._dec = ephem.degrees("22:00:51.1")
    source._epoch = ephem.J2000
    source.compute(obs)

    hs = np.array(ephem.hours(source.ra) - lst)

    # 'Brute force' least squares
    lmbda = 2.5  # Wavelength lambda in cm
    YBAR = []
    By = 1000
    cos_dec = np.linspace(0.01, 1, 500)
    A = []
    S_SQ = []

    # Iterate over baseline lengths in cm
    for dec in cos_dec:
        C = 2 * np.pi * By / lmbda * dec
        x1 = np.cos(C * np.sin(hs))
        x2 = np.sin(C * np.sin(hs))
        X = np.matrix([x1, x2])

        ybar, a, s_sq = least_squares(data, X)
        S_SQ.append(s_sq)
        ybar = np.array(ybar[:, 0])
        YBAR.append(ybar)
        A.append(a)

    Dopt = np.argmin(S_SQ)
    if debug:
        plt.figure()
        plt.plot(cos_dec, S_SQ / max(S_SQ))
        plt.title("Normalized Residuals for Declination Fit")
        plt.savefig("img/crab/residual_dec.png")

        plt.figure()
        plt.plot(data)
        plt.plot(YBAR[Dopt])
        plt.title("Least Squares Fit for Declination")
        plt.legend(["Filtered", "Fit"])
        plt.savefig("img/crab/fit_dec.png")
        print "By = " + str(By)
        print "delta (deg)= " + str(np.arccos(cos_dec[Dopt]) * 180 / np.pi)
        print "A = " + str(A[Dopt])
    return YBAR[Dopt], A[Dopt], np.arccos(cos_dec[Dopt]) * 180 / np.pi
Exemplo n.º 27
0
def solartime(time, lon_loc_rad, sun=ephem.Sun()):
    """Return sine and cosine value of solar hour angle depending on longitude and time of TRT cell at t0"""
    obs = ephem.Observer()
    obs.date = time
    obs.lon = lon_loc_rad
    sun.compute(obs)
    ## sidereal time == ra (right ascension) is the highest point (noon)
    angle_rad = ephem.hours(obs.sidereal_time() - sun.ra +
                            ephem.hours('12:00')).norm
    return np.sin(angle_rad), np.cos(angle_rad)
Exemplo n.º 28
0
def test_track_map(fname="molonglo_fb_map.fits"):
    ra,dec = "07:16:35","-19:00:40"
    eq = e.Equatorial(ra,dec)
    ra = eq.ra
    dec = eq.dec
    lst = float(e.hours("03:56"))
    dlst = float(e.hours("00:00:20.0016"))*SEC_TO_SID
    data = read(fname)
    lsts = np.arange(data.shape[1])*dlst + lst
    return TrackedFanBeamTimeMap(data,ra,dec,lsts)
Exemplo n.º 29
0
def possibleExposures(orbit, year='Y4'):
    '''
    Returns a list of exposures near the target orbit in a given year. Assumes the object moves slowly enough that
    it won't wander more than 10 degrees from its location on 2014/01/01. Returns a  preliminary exposure 
    list from which we do a more careful search. 
    :param orbit: orbit from pyOrbfit
    :param year: DES observing year to search, e.g. 'Y4'
    :return: dataframe of exposures to be searched.
    '''
    pos_ref = orbit.predict_pos(ephem.date('2014/01/01'))
    ra_ref, dec_ref = pos_ref['ra'], pos_ref['dec']
    assert year in ['all', 'SV', 'Y1', 'Y2', 'Y3', 'Y4', 'Y5']
    if year == 'all':
        search_exps = all_exps
    elif year == 'SV':
        search_exps = all_exps.loc[
            all_exps.apply(lambda row: 20121102 < row['nite'] < 20130220 and row['band'] != 'Y', axis=1)]
    elif year == 'Y1':
        search_exps = all_exps.loc[
            all_exps.apply(lambda row: 20130810 < row['nite'] < 20140220 and row['band'] != 'Y', axis=1)]
    elif year == 'Y2':
        search_exps = all_exps.loc[
            all_exps.apply(lambda row: 20140810 < row['nite'] < 20150220 and row['band'] != 'Y', axis=1)]
    elif year == 'Y3':
        search_exps = all_exps.loc[
            all_exps.apply(lambda row: 20150810 < row['nite'] < 20160220 and row['band'] != 'Y', axis=1)]
    elif year == 'Y4':
        search_exps = all_exps.loc[
            all_exps.apply(lambda row: 20160810 < row['nite'] < 20170220 and row['band'] != 'Y', axis=1)]
    elif year == 'Y5':
        search_exps = all_exps.loc[
            all_exps.apply(lambda row: 20170810 < row['nite'] < 20180220 and row['band'] != 'Y', axis=1)]
    else:
        print 'Oops'
        search_exps = None
    try:
        near_exps = search_exps.loc[search_exps.apply(lambda row:
                                                      ephem.separation(
                                                          (ephem.hours(row['ra']), ephem.degrees(row['dec'])),
                                                          (ra_ref, dec_ref)) < ephem.degrees('10:00:00'), axis=1)]
    except:
        near_exps = None
    in_exposures = []
    in_ccd = []
    if near_exps is not None:
        for ind, row in near_exps.iterrows():
            pos = orbit.predict_pos(row['date'])
            ra, dec = ephem.hours(pos['ra']), ephem.degrees(pos['dec'])
            ccdname, ccdnum = compute_chip(ra, dec, row['ra'], row['dec'])
            if ccdnum > -99 and ccdnum not in [2, 31, 61]:
                in_exposures.append(row['expnum'])
                in_ccd.append(ccdnum)
        near_exps = near_exps.loc[near_exps['expnum'].isin(in_exposures)]
        near_exps['ccd'] = pd.Series(in_ccd, index=near_exps.index)
    return near_exps
Exemplo n.º 30
0
    def __init__(self, name, port, parent_host, parent_port):
        super(telescope, self).__init__(name, 'telescope', port, parent_host, parent_port)
        CMDs={
        chr(6):self.cmd_ack,  \
        ":info": self.cmd_info,  \
          ":FirmWareDate": self.cmd_firware_date,  \
          ":GVF": self.cmd_firware_ver,  \
          ":V": self.cmd_firware_ver,  \
          ":GVD": self.cmd_firware_date,  \
          ":GC": self.cmd_getLocalDate,  \
          ":GL": self.cmd_getLocalTime,  \
          ":GS": self.cmd_getSideralTime,  \
          ":Sr": self.cmd_setTargetRA,  \
          ":Sd": self.cmd_setTargetDEC,  \
          ":MS": self.cmd_slew,  \
          ":Q":  self.cmd_stopSlew,  \
          ":Gr": self.cmd_getTargetRA,  \
          ":Gd": self.cmd_getTargetDEC,  \
          ":GR": self.cmd_getTelescopeRA,  \
          ":GD": self.cmd_getTelescopeDEC,  \
          ":RS": self.cmd_setMaxSlewRate,  \
          ":RM": self.cmd_slewRate,  \
          ":Me": self.cmd_pulseE,  \
          ":Mw": self.cmd_pulseW,  \
          ":Mn": self.cmd_pulseN,  \
          ":Ms": self.cmd_pulseS,  \
          ":CM": self.cmd_align2target,  \
          "@getObserver": self.getObserver, \
          "@getGear": self.getGear, \
          "@getRA": self.getRA, \
          "@getDEC": self.getDEC, \
          "@setTrackSpeed": self.setTrackSpeed, \
          "@values": self.values
        }
        self.m = ramps.mount()
        self.valuesmsg = {}
        self.addCMDs(CMDs)
        self.observerInit()
        self.targetRA = ephem.hours(0)
        self.targetDEC = ephem.degrees(0)
        ra = ephem.hours(self.observer.sidereal_time())
        dec = ephem.degrees(0)
        star = ephem.FixedBody(ra, dec, observer=self.observer, epoch='2016.4')
        star.compute(self.observer)
        self.RA = star.ra
        self.DEC = star.dec
        self.alt = star.alt
        self.az = star.az

        self.pulseStep = ephem.degrees('00:00:01')
        a = ephem.degrees('00:20:00')

        vRA = -ephem.hours("00:00:01")
        vDEC = ephem.degrees("00:00:00")
        self.m.trackSpeed(vRA, vDEC)
    def loadStackData(self):

        self.d2r = np.pi/180.0
        self.r2d = 180.0/np.pi

        self.stackFile = tables.openFile(self.loadStackName, mode='r')

        self.header = self.stackFile.root.header.header
        self.headerTitles = self.header.colnames
        self.headerInfo = self.header[0]
    
        self.stackNode = self.stackFile.root.stack

        self.stackData = np.array(self.stackNode.stack.read())
        self.jdData = np.array(self.stackNode.time.read()[0])

        self.nRow = self.stackData.shape[0]
        self.nCol = self.stackData.shape[1]
        self.totalFrames = self.stackData.shape[2]

        # Load data out of display stack h5 file
        self.centroid_RA = self.headerInfo[self.headerTitles.index('RA')]
        self.centroid_DEC = self.headerInfo[self.headerTitles.index('Dec')]
        self.original_lst = self.headerInfo[self.headerTitles.index('lst')]

        self.exptime = self.headerInfo[self.headerTitles.index('exptime')]
        self.integrationTime = self.headerInfo[self.headerTitles.index('integrationTime')]
        self.deadPixelFilename = self.headerInfo[self.headerTitles.index('deadPixFileName')]
        self.HA_offset = self.headerInfo[self.headerTitles.index('HA_offset')]
        self.nRow = self.headerInfo[self.headerTitles.index('nRow')]
        self.nCol = self.headerInfo[self.headerTitles.index('nCol')]


        self.centroid_RA_radians = ephem.hours(self.centroid_RA).real
        #self.centroid_RA_arcsec = self.radians_to_arcsec(self.centroid_RA_radians)/15.0
        self.centroid_RA_arcsec = self.radians_to_arcsec(self.centroid_RA_radians)
    
        self.centroid_DEC_radians = ephem.degrees(self.centroid_DEC).real
        self.centroid_DEC_arcsec = self.radians_to_arcsec(self.centroid_DEC_radians)
    
        self.original_lst_radians = ephem.hours(self.original_lst).real
        self.original_lst_seconds = self.radians_to_arcsec(self.original_lst_radians)/15.0
        #self.original_lst_seconds = self.radians_to_arcsec(self.original_lst_radians)

        self.HA_offset_radians = self.HA_offset*self.d2r
        
        self.ui.maxLabel.setText('/ ' + str(self.totalFrames-1))
        self.centerPositions = np.zeros((self.totalFrames,2))
        self.apertureRadii = np.zeros(self.totalFrames)
        self.annulusRadii = np.zeros((self.totalFrames,2))
        for iFrame in range(self.totalFrames):
            self.centerPositions[iFrame] = [float(self.nCol)/2.0 - 0.5, float(self.nRow)/2.0 - 0.5]
            self.apertureRadii[iFrame] = 5.0
            self.annulusRadii[iFrame] = [10.0, 20.0]
        self.updateFrameInfo()
Exemplo n.º 32
0
def solartime(observer, sun=ephem.Sun()):
    """
    """
    # Astronomical math
    import ephem
    # Credit: J.F. Sebastian
    # http://stackoverflow.com/questions/13314626/local-solar-time-function-from-utc-and-longitude
    sun.compute(observer)
    # sidereal time == ra (right ascension) is the highest point (noon)
    hour_angle = observer.sidereal_time() - sun.ra
    return ephem.hours(hour_angle + ephem.hours('12:00')).norm  # norm for 24h
Exemplo n.º 33
0
 def source_pick(self, *args):
     """
     Right click- gets Info of the source
     Left click- selects source
     scroll- finds nearest source
     """
     self.logger.debug("source_pick: called with %s", args)
     event1 = args[0]
     # Merge dictinaries for whatever sources ticked in the GUI
     thisline = None
     thisline = event1.artist
     #        thisline.update
     #        if thisline is not None and not hasattr(event1, 'already_picked'):
     self.logger.debug("source_pick: this line: %s", thisline)
     #When Plotting in Az-El
     self.source_pick_az = thisline.get_xdata()[0]
     self.source_pick_alt = thisline.get_ydata()[0]
     self.logger.debug("source_pick: az/el = %s/%s", self.source_pick_az,
                       self.source_pick_alt)
     #n = 0
     #m = 0
     for key, value in list(self.source_dict.items()):
         self.logger.debug("source_pick: matching az %s",
                           self.source_pick_az)
         self.logger.debug("source_pick: ... az %s",
                           repr(ephem.hours(value[2]) * rad2deg))
         if round(numpy.float64(self.source_pick_az), 6) == \
            round(numpy.float64(repr(ephem.hours(value[2])*rad2deg)), 6):
             self.logger.debug("source_pick: match found for object %s",
                               key)
             self.source_name = key
             self.source_info_ra = value[0]
             self.source_info_dec = value[1]
             self.source_info_az = value[2]
             self.source_info_alt = value[3]
             self.source_info_flux = value[4]
             self.source_info_vsys = value[5]
         else:
             pass
         #n = n +1
     #m = m+1
     self.annotation = self.ui.skymap_axes.annotate(
         self.source_name,
         xy=((self.source_pick_az), (self.source_pick_alt)),
         xytext=(-20, 20),
         textcoords='offset points',
         ha='right',
         va='bottom',
         bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
         arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
     # by default, disable the annotation visibility
     self.annotation.set_visible(True)
     self.ui.skymap_canvas.draw()
     self.annotation.set_visible(False)
Exemplo n.º 34
0
def calib_numogate_ridge_observatory_total_power(data):

    me = ephem.Observer()

    #
    # PyEphem wants lat/long as strings, rather than floats--took me quite
    #  a long time to figure that out.  If they don't arrive as strings,
    #  the calculations for sidereal time are complete garbage
    #
    me.long = globals()["calib_long"]
    me.lat = globals()["calib_lat"]

    me.date = ephem.now()
    sidtime = me.sidereal_time()

    foo = time.localtime()
    if not "calib_prefix" in globals():
        pfx = "./"
    else:
        pfx = globals()["calib_prefix"]
    filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, foo.tm_mon,
                                           foo.tm_mday, foo.tm_hour)

    numogate_file = open(filenamestr + ".tpdat", "a")

    r = (data / 409.6)
    flt = "%6.3f" % r
    #r = calib_default_total_power(data)
    inter = globals()["calib_decln"]
    integ = globals()["calib_integ_setting"]
    fc = globals()["calib_freq_setting"]
    fc = fc / 1000000
    bw = globals()["calib_bw_setting"]
    bw = bw / 1000000
    ga = globals()["calib_gain_setting"]

    now = time.time()

    if not "calib_then_tpdat" in globals():
        globals()["calib_then_tpdat"] = now

    if (now - globals()["calib_then_tpdat"]) >= 20:
        globals()["calib_then_tpdat"] = now

        numogate_file.write(
            str(ephem.hours(sidtime)) + " " + flt + " Dn=" + str(inter) + ",")
        numogate_file.write("Ti=" + str(integ) + ",Fc=" + str(fc) + ",Bw=" +
                            str(bw))
        numogate_file.write(",Ga=" + str(ga) + "\n")
    else:
        numogate_file.write(str(ephem.hours(sidtime)) + " " + flt + "\n")

    numogate_file.close()
    return (r)
Exemplo n.º 35
0
	def getRA(self,arg):
		self.observer.date=ephem.Date(datetime.datetime.utcnow())
		self.sideral=self.observer.sidereal_time()
		beta=float(self.m.axis1.motorBeta)*self.m.axis1.minMotorStep
		#beta=self.m.axis1.beta
		#print self.m.axis1.beta-beta
		ra=ephem.hours(self.sideral+beta).norm
		if ra==ephem.hours("24:00:00"):
			ra=ephem.hours("00:00:00")
		self.RA=ra
		return self.RA
Exemplo n.º 36
0
def get_solartime(mjd, longitude):
    '''calculate solar time'''
    sun = ephem.Sun()
    observer = ephem.Observer()
    observer.date = mjd2datetime(mjd)
    observer.long = longitude * np.pi / 180.0
    sun.compute(observer)
    hour_angle = observer.sidereal_time() - sun.ra
    lst = str(ephem.hours(hour_angle + ephem.hours('12:00')).norm)
    return (float(lst.split(':')[0]) +
            float(lst.split(':')[1]) / 60.0 +
            float(lst.split(':')[2]) / 3600.0)
Exemplo n.º 37
0
    def _ephem_risetime_(self, ephem_target, lst=True):
        try:
            rise_time = self.observer.next_rising(ephem_target)
        except ephem.AlwaysUpError:
            return ephem.hours('0:0:01.0')
        except AttributeError:
            return ephem.hours('0:0:01.0')

        if not lst:
            return rise_time
        self.observer.date = rise_time
        return self.observer.sidereal_time()
Exemplo n.º 38
0
def calib_numogate_ridge_observatory_total_power(data):

    me = ephem.Observer()

    #
    # PyEphem wants lat/long as strings, rather than floats--took me quite
    #  a long time to figure that out.  If they don't arrive as strings,
    #  the calculations for sidereal time are complete garbage
    #
    me.long = globals()["calib_long"]
    me.lat = globals()["calib_lat"]

    me.date = ephem.now()
    sidtime = me.sidereal_time()

    foo = time.localtime()
    if not "calib_prefix" in globals():
        pfx = "./"
    else:
        pfx = globals()["calib_prefix"]
    filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
       foo.tm_mon, foo.tm_mday, foo.tm_hour)

    numogate_file = open (filenamestr+".tpdat","a")
  
    r = (data / 409.6)
    flt = "%6.3f" % r
    #r = calib_default_total_power(data)
    inter = globals()["calib_decln"]
    integ = globals()["calib_integ_setting"]
    fc = globals()["calib_freq_setting"]
    fc = fc / 1000000
    bw = globals()["calib_bw_setting"]
    bw = bw / 1000000
    ga = globals()["calib_gain_setting"]

    now = time.time()

    if not "calib_then_tpdat" in globals():
        globals()["calib_then_tpdat"] = now

    if (now - globals()["calib_then_tpdat"]) >= 20:
        globals()["calib_then_tpdat"] = now
    
        numogate_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
        numogate_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
        numogate_file.write(",Ga="+str(ga)+"\n")
    else:
        numogate_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")

    numogate_file.close()
    return(r)
Exemplo n.º 39
0
def read_ephemeris(ephemeris, date):
    # TODO: is the ephemeris file fixed in col positions?

    """

    :param ephemeris:
    :param date:
    :return:
    """
    in_data = False
    now = date
    month_ints = {
        'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
        'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
    found = False
    for line in ephemeris.split('\n'):
        if line.startswith('$$SOE'):
            in_data = True
            c1 = 0
        elif line.startswith('$$EOE') or line.startswith(' $$EOE'):
            if not found:
                ra = ephem.hours('00:00:00')
                dec = ephem.degrees('00:00:00')
                ephe = False
                return ra, dec, ephe
        elif in_data:
            datestr = line[1:6] + str(month_ints[line[6:9]]) + line[9:18]
            date = datetime.strptime(datestr, '%Y-%m-%d %H:%M')
            if now.datetime() > date:
                data = line
                found = False
                # noinspection PyUnboundLocalVariable
                c1 += 1
            else:
                # noinspection PyUnboundLocalVariable
                if c1 == 0:

                    ra = ephem.hours('00:00:00')
                    dec = ephem.degrees('00:00:00')
                    ephe = False
                    return ra, dec, ephe
                # noinspection PyUnboundLocalVariable
                ra_temp = data[23:36].strip()
                dec_temp = data[37:50].strip()
                if len(ra_temp.split()) > 3:
                    ra_temp = data[23:34].strip()
                    dec_temp = data[35:46].strip()
                ra = ephem.hours(ra_temp.replace(' ', ':'))
                dec = ephem.degrees(dec_temp.replace(' ', ':'))
                ephe = True
                print(ra, dec, ephe, now)
                return pd.np.degrees(ra), pd.np.degrees(dec), ephe
Exemplo n.º 40
0
 def dLocation(self):
     s = ephem.Sun()
     s.compute(epoch=ephem.now())
     print("R.A.: %s DEC.: %s" % (s.a_ra, s.a_dec))
     o = ephem.Observer()
     o.lon, o.lat = '17.03333', '51.100000'  # Współrzędne Wrocławia
     o.date = ephem.now()  # 00:22:07 EDT 06:22:07 UT+1
     s.compute(o)
     hour_angle = o.sidereal_time() - s.ra
     t = ephem.hours(hour_angle +
                     ephem.hours('12:00')).norm  # .norm for 0..24
     rad = str(ephem.hours(hour_angle + ephem.hours('12:00')).norm)
     print("HOUR ANGLE: %s SIDERAL TIME: %s" % (rad, o.sidereal_time()))
Exemplo n.º 41
0
    def _ephem_settime_(self, ephem_target, lst=True):
        try:
            rise_time = self.observer.next_rising(ephem_target)
            set_time = self.observer.next_setting(ephem_target,
                                                  start=rise_time)
        except ephem.AlwaysUpError:
            return ephem.hours('23:59:59.0')
        except AttributeError:
            return ephem.hours('23:59:59.0')

        if not lst:
            return set_time
        self.observer.date = set_time
        return self.observer.sidereal_time()
Exemplo n.º 42
0
def confirm_align(star):
    result = tkMessageBox.askyesno("Align Telescope", "Are you sure?")
    if result is True:
        # Check if encoders are available
        try:
            ra = enc.Enc('RAEncoder')
            dec = enc.Enc('DECEncoder')
        except:
            log_action('ALIGN', 'Scope', 'Encoder(s) not found')
        else:
            # Initialize encoders
            ra = enc.Enc('RAEncoder')
            success = ra.connect()
            if not success:
                log_action('Connect', 'Encoder',
                           'RAEncoder failed to initialize')
            dec = enc.Enc('DECEncoder')
            success = dec.connect()
            if not success:
                log_action('Connect', 'Encoder',
                           'DECEncoder failed to initialize')

            # Look up the star
            try:
                ephem.star(star)  # Check if 'name' is a named star
            except KeyError:
                obj = read_db(
                    star
                )  # If not, read 'name' from the custom objects database (Weird to do but w/e)
            else:
                obj = ephem.star(star)  # But if it was a star...
            obj.compute(rho)
            # Create Scope object
            scope = sc.Scope(obj, ra, dec)
            position = scope.where()  # Grab scope position to confirm align
            st = rho.sidereal_time()  # Grab RHO sidereal time
            ha = '%s' % ephem.hours(
                st - ephem.hours(position[0]))  # Calc HA of object from RHO
            s_ha.set(ha)
            s_dec.set(str(position[1]))
            s_tick_ha.set(scope.data['Ticks'][-1][0])
            s_tick_dec.set(scope.data['Ticks'][-1][1])
            log_action('Align Success', obj.name,
                       str('HA: ' + position[0] + ' | DEC: ' + position[1]))
            s_ready.set('Telescope Aligned')
            s_scope.config(fg='black')
    else:
        # Do nothing
        return
Exemplo n.º 43
0
def gcDAR():
    iraf.noao()
    obs = iraf.noao.observatory

    # Set up Keck observatory info
    obs(command="set", obsid="keck")
    keck = ephem.Observer()
    keck.long = math.radians(-obs.longitude)
    keck.lat = math.radians(obs.latitude)
    keck.elev = obs.altitude
    keck.pressure = 800.0
    keck.temp = 278.0
    
    # Date of Observations: 06maylgs1
    keck.date = '2006/05/03 %d:%d:%f' % (obs.timezone+3, 28, 46.33)

    # Set up the galactic center target
    sgra = ephem.FixedBody()
    sgra._ra = ephem.hours("17:45:40")
    sgra._dec = ephem.degrees("-29:00:10")
    sgra._epoch = 2000
    sgra.compute()

    pos2 = ephem.FixedBody()
    pos2._ra = ephem.hours("17:45:40")
    pos2._dec = ephem.degrees("-29:00:00")
    pos2._epoch = 2000
    pos2.compute()

    print 'Date of Obs: ', keck.date
    sgra.compute(keck)
    pos2.compute(keck)

    print 'Azimuth of Objects:  %s  vs.  %s' % (sgra.az, pos2.az)

    for ii in range(15):
	keck.lat = math.radians(obs.latitude - (ii*2))

	sgra.compute(keck)
	pos2.compute(keck)

	angAbs = ephem.separation((sgra.ra, sgra.dec), (pos2.ra, pos2.dec))
	angAbs *= 206265.0
	angRel = ephem.separation((sgra.az, sgra.alt), (pos2.az, pos2.alt))
	angRel *= 206265.0
	angDiff = angAbs - angRel

	print 'Sgr A*:  %s   vs.  %s  deltaR = %5d (muas)' % \
	    (sgra.alt, pos2.alt, angDiff*1e6)
Exemplo n.º 44
0
def gcDAR():
    iraf.noao()
    obs = iraf.noao.observatory

    # Set up Keck observatory info
    obs(command="set", obsid="keck")
    keck = ephem.Observer()
    keck.long = math.radians(-obs.longitude)
    keck.lat = math.radians(obs.latitude)
    keck.elev = obs.altitude
    keck.pressure = 800.0
    keck.temp = 278.0

    # Date of Observations: 06maylgs1
    keck.date = '2006/05/03 %d:%d:%f' % (obs.timezone + 3, 28, 46.33)

    # Set up the galactic center target
    sgra = ephem.FixedBody()
    sgra._ra = ephem.hours("17:45:40")
    sgra._dec = ephem.degrees("-29:00:10")
    sgra._epoch = 2000
    sgra.compute()

    pos2 = ephem.FixedBody()
    pos2._ra = ephem.hours("17:45:40")
    pos2._dec = ephem.degrees("-29:00:00")
    pos2._epoch = 2000
    pos2.compute()

    print 'Date of Obs: ', keck.date
    sgra.compute(keck)
    pos2.compute(keck)

    print 'Azimuth of Objects:  %s  vs.  %s' % (sgra.az, pos2.az)

    for ii in range(15):
        keck.lat = math.radians(obs.latitude - (ii * 2))

        sgra.compute(keck)
        pos2.compute(keck)

        angAbs = ephem.separation((sgra.ra, sgra.dec), (pos2.ra, pos2.dec))
        angAbs *= 206265.0
        angRel = ephem.separation((sgra.az, sgra.alt), (pos2.az, pos2.alt))
        angRel *= 206265.0
        angDiff = angAbs - angRel

        print 'Sgr A*:  %s   vs.  %s  deltaR = %5d (muas)' % \
            (sgra.alt, pos2.alt, angDiff*1e6)
Exemplo n.º 45
0
def solarTime(utc_dt, lat, lon):
    """Compute local solar time for given (lat, lon)
    """
    import ephem
    o = ephem.Observer()
    o.date = utc_dt
    o.lat = str(lat)
    o.lon = str(lon)
    sun = ephem.Sun()
    sun.compute(o)
    hour_angle = o.sidereal_time() - sun.ra
    rad = str(ephem.hours(hour_angle + ephem.hours('12:00')).norm)
    t = datetime.strptime(rad, '%H:%M:%S.%f')
    solar_dt = datetime.combine(utc_dt.date(), t.time())
    return solar_dt
Exemplo n.º 46
0
	def central_radec(self, blockID):
		junk, fieldIds = self.fields_in_block(blockID)
		ras = []
		decs = []
		for field in fieldIds:
			ras.append(ephem.hours(self.bk.field_ra(field)))   # str in hours of RA
			decs.append(ephem.degrees(self.bk.field_dec(field))) # str in deg of Dec

		# mean ra, mean dec: APPROXIMATING
		ra = ephem.hours((sum(ras)/len(ras)))
		dec = ephem.degrees((sum(decs)/len(decs)))

		retval = (str(ra), str(dec))
		
		return retval
Exemplo n.º 47
0
 def ephem_string(self):
     string = []
     string.append(self.name)
     try:
         string.append("f|" + sac_to_ephem_dict[self.body_type])
     except KeyError:
         string.append("f|T")
     string.append(str(ephem.hours(self.ra)))
     string.append(str(ephem.degrees(self.dec)))
     string.append(str(self.mag))
     string.append("2000")
     
     max_s = self.size_max
     if len(max_s) == 0:
         fp = 0
     elif max_s[-1] == 'm': #arcmin
         fp = float(max_s[:-1]) / 3437.74677078
     elif max_s[-1] == 's': #arcsec
         fp = float(max_s[:-1]) / 206264.806247
     elif max_s[-1] == 'd': #degree
         fp = float(max_s[:-1]) / 57.2957795131 
     else:
         raise ValueError("Unkwnown format for size_max: " + max_s)
     string.append(str(fp * 206264.806247))
     
     return ','.join(string)
Exemplo n.º 48
0
    def mpcOutput(self,data):
        #TODO adapt data prior to invoke.
        import ephem
        out=''
        for d in data:
            fecha=d['DATETIME'][0:10].replace('-',' ')
            hh=float(d['DATETIME'][11:13])
            mm=float(d['DATETIME'][14:16])
            ss=float(d['DATETIME'][17:19])
            #print d['KEY'],fecha,hh,mm,ss,ephem.hours(ephem.degrees(str(d['RA']))),ephem.degrees(str(d['DEC']))
            hhdec=round((hh*3600.+mm*60.+ss)/(24*3600)*100000,0)
            fecha=fecha+'.'+"%05.0f" % (hhdec)+" "
            id=d['KEY']

            ra_hh,ra_mm,ra_ss=("%11s" % ephem.hours(ephem.degrees(str(d['RA'])))).split(':')
            #print ra_hh,ra_mm,ra_ss
            ra="%02d %02d %04.1f" % (float(ra_hh),float(ra_mm),float(ra_ss))

            dec_dd,dec_mm,dec_ss=("%11s" % ephem.degrees(str(d['DEC']))).split(':')
            #print dec_dd,dec_mm,dec_ss
            dec="%+03d %02d %05.2f" % (float(dec_dd),float(dec_mm),float(dec_ss))
            #print ra,"/",dec
            #rastr="%11s" % (ephem.degrees(str(d['DEC'])))
            #decstr="%11s" % (ephem.degrees(str(d['DEC'])))
            #ra=rastr.replace(':',' ')
            #dec=decstr.replace(':',' ')
            #id=d['INT_NUMBER'][-7:]

            #[MPnumber,Provisional,Discovery,Note1,Note2,Date,RA,DEC,Mag,Band,Observatory]
            #     492A002  C2014 09 03.13366 03 57 53.26 +05 44 22.9          18.6 V      J75
            #     K07VF3N  C2014 09 14.83670  0 53 58.89   0 07 53.1          20.2 V      J75

            obs=('',id,'','','C',fecha,ra,dec,d['MAG'],'V','J75')
            out+='%5s%7s%1s%1s%1s%16s%-12s%-12s        %5.1f %1s      %3s\n' % obs
        return out
Exemplo n.º 49
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)
Exemplo n.º 50
0
def compare_sun_altaz(obs, pressure = 1010):
    """Compare homebrewed and PyEphem calculations of sun alt-az

    Prints out results of:
        my method using RA/dec values from Karto's method and PyEphem
        PyEphem's computation of alt/az

    It appears that the refraction correction gives the biggest discrepancy.
    Without refraction (pressure = 0), the computations agree to within
    10-20 arcsec or so.
    """
    eph_sun = ephem.Sun()
    obs.date = ephem.now()
    if pressure != 1010:
        obs.pressure = pressure
    eph_sun.compute(obs)
    if pressure != 1010:
        obs.pressure = 1010

    ral_sun = ral.sunPos()
    sun_ra = ephem.hours(hrs2rad( ral_sun[0] ))
    sun_dec = ephem.degrees(deg2rad( ral_sun[1] ))

    print 'Sun alt-az, my matrix + kartp\'s ra, dec: (%s, %s)' % \
            radec2altaz(obs, sun_ra, sun_dec)
    print 'Sun alt-az, my matrix + PyEphem ra, dec: (%s, %s)' % \
            radec2altaz(obs, eph_sun.ra, eph_sun.dec)
    print 'Sun alt-az, PyEphem  +  PyEphem alt, az: (%s, %s)' % \
            (eph_sun.alt, eph_sun.az)
Exemplo n.º 51
0
def build_ossos_footprint(ax, blocks, field_offset):
    # build the pointings that will be used for the discovery fields
    x = []
    y = []
    names = []
    coverage = []
    year = '2013'
    if year == 'astr':
      field_offset = field_offset*0.75

    for block in blocks.keys():
      sign = -1
      if 'f' in block:  # unsure what this was ever meant to do
        sign=1
      rac = ephem.hours(blocks[block]["RA"])+years[year]["ra_off"]
      decc = ephem.degrees(blocks[block]["DEC"])+sign*years[year]["dec_off"]
      width = field_offset/math.cos(decc)
      block_centre.from_radec(rac,decc)
      block_centre.set(block_centre.lon + xgrid[year][0]*width,block_centre.lat)
      field_centre.set(block_centre.lon, block_centre.lat)
      for dx in xgrid[year]:
        (rac, decc) = field_centre.to_radec()
        for dy in ygrid[year]:
          ddec = dy*field_offset
          dec = math.degrees(decc + ddec)
          ra = math.degrees(rac)
          names.append("%s%+d%+d" % ( block, dx, dy))
          y.append(dec)
          x.append(ra)
          xcen = ra
          ycen = dec

          dimen = camera_dimen
          coverage.append(Polygon.Polygon((
                (xcen-dimen/2.0,ycen-dimen/2.0),
                (xcen-dimen/2.0,ycen+dimen/2.0),
                (xcen+dimen/2.0,ycen+dimen/2.0),
                (xcen+dimen/2.0,ycen-dimen/2.0),
                (xcen-dimen/2.0,ycen-dimen/2.0))))

          ax.add_artist(Rectangle(xy=(ra-dimen/2.0,dec-dimen/2.0),
                                  height=camera_dimen,
                                  width=camera_dimen,
                                  edgecolor='b',
                                  lw=0.5, fill=True, alpha=0.3))

        rac += field_offset / math.cos(decc)
        for i in range(3):
          field_centre.from_radec(rac,decc)
          field_centre.set(field_centre.lon, block_centre.lat)
          (ttt, decc) = field_centre.to_radec()


    if year == "astr":
      sys.exit(0)

    ras = np.radians(x)
    decs = np.radians(y)

    return ras, decs, coverage, names, ax
Exemplo n.º 52
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)
Exemplo n.º 53
0
def clusterSample():
    clusters = [
        {"name": "M17", "distance": 2, "ra": "18:20:26", "dec": "-17:10:01"},
        {"name": "Wd2", "distance": 5, "ra": "10:23:58", "dec": "-57:45:49"},
        {"name": "Wd1", "distance": 5, "ra": "16:47:04", "dec": "-45:51:05"},
        {"name": "RSGC1", "distance": 6, "ra": "18:37:58", "dec": "-06:52:53"},
        {"name": "RSGC2", "distance": 6, "ra": "18:39:20", "dec": "-06:05:10"},
    ]

    py.close(1)
    py.figure(1, linewidth=2, figsize=(16, 10))
    py.subplots_adjust(left=0.05, right=0.97, bottom=0.1, top=0.95, wspace=0.2, hspace=0.25)

    for ii in range(len(clusters)):
        clust = clusters[ii]

        obj = ephem.FixedBody()
        obj._ra = ephem.hours(clust["ra"])
        obj._dec = ephem.degrees(clust["dec"])
        obj._epoch = 2000
        obj.compute()

        gal = ephem.Galactic(obj)

        longitude = math.degrees(float(gal.lon))
        print ""
        print "%-10s  %s %s  l = %.1f" % (clust["name"], clust["ra"], clust["dec"], longitude)

        py.subplot(2, 3, ii + 1)
        properMotions(longitude, clust["distance"], clust["name"])
Exemplo n.º 54
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
Exemplo n.º 55
0
 def __repr__(self):
     if self.radius is not None:
         radius = '%.2f' % (self.radius)
     else:
         radius = 'NA'
     return "<SNR %s RA=%s Dec=%s Radius=%s\">" % \
         (self.name, ephem.hours(np.deg2rad(self.ra)), ephem.degrees(np.deg2rad(self.dec)), radius)
Exemplo n.º 56
0
	def write_hits(self,sidtime):
		# Create localtime structure for producing filename
		foo = time.localtime()
		pfx = self.prefix
		filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
		   foo.tm_mon, foo.tm_mday, foo.tm_hour)
	
		# Open the data file, appending
		hits_file = open (filenamestr+".seti","a")

		# Write sidtime first
		hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")

		#
		# Then write the hits/hit intensities buffers with enough
		#	"syntax" to allow parsing by external (not yet written!)
		#	"stuff".
		#
		for i in range(0,self.nhitlines):
			hits_file.write(" ")
			for j in range(0,self.nhits):
				hits_file.write(str(self.hits_array[j,i])+":")
				hits_file.write(str(self.hit_intensities[j,i])+",")
		hits_file.write("\n")
		hits_file.close()
		return
Exemplo n.º 57
0
 def __init__(self, obsnum='     ', MPprovisional='       ', discovery=' ', note1=' ', 
              note2='C', obsdate=ephem.date('2000/01/01'), ra_obs_J2000=ephem.hours(0), dec_obs_J2000=ephem.degrees(0), 
              mag=99, band='r', observatoryCode='W84', newobject=True):
         self.spaces  = []
         a = ''
         one_space = ' '
         for i in range(20):
             self.spaces.append(a)
             a += one_space
 
         self.newobject = newobject 
         self.obsnum = self.setobsnum(obsnum)
         self.MPprovisional = self.setMPprovisional(MPprovisional)
         if discovery==' ' or discovery=='*':
             self.discovery = discovery
         else:
             print 'Error, unrecognized discovery flag, should be * or one blank space'
         if len(note1)==1:
             self.note1 = note1
         else:
             print 'Error, note1 must have length 1'
         if len(note2)==1:
             self.note2 = note2
         else:
             print 'Error, note2 must have length 1'
         self.obsdate = self.setObsdate(obsdate)                  # YYYY MM DD.dddddd, with precision normally given to 0.00001d (about 0.8s). For DES data should use 0.000001d
         self.ra_obs_J2000 = self.setRa(ra_obs_J2000)
         self.dec_obs_J2000 = self.setDec(dec_obs_J2000)
         self.mag_band = self.setMagBand(mag, band)
         self.observatoryCode = observatoryCode
         self.record = self.obsnum+self.MPprovisional+self.discovery+self.note1+self.note2+self.obsdate+self.ra_obs_J2000 \
                       +self.dec_obs_J2000+self.spaces[9]+self.mag_band+self.spaces[6]+self.observatoryCode
Exemplo n.º 58
0
def sexagesimal(ra, dec):
    '''
    Return the sexagesimal representation, as pyEphem
    objects, of the coordinates (ra, dec), which are
    taken to be in decimal degree format.
    '''
    return hours(float(ra) * np.pi/180), degrees(float(dec) * np.pi/180)
Exemplo n.º 59
0
def decimal(ra, dec):
    '''
    Return the decimal degree representation of the
    coordinates (ra, dec), which are taken to be in
    radians (or pyEphem objects stored that way).
    '''
    return hours(ra) * 180/np.pi, degrees(dec) * 180/np.pi
Exemplo n.º 60
0
def xy2radec(x, y):
    lon, lat = map(x, y, inverse=True)
    lon = (180 + kwds["ra"] - lon) % 360  # lon = (360 - lon) % 360
    lon *= a.img.deg2rad
    lat *= a.img.deg2rad
    ra, dec = ephem.hours(lon), ephem.degrees(lat)
    return ra, dec