示例#1
0
    def galactic(self, timestamp=None, antenna=None):
        """Calculate target's galactic (l, b) coordinates as seen from antenna at time(s).

        This calculates the galactic coordinates of the target, based on the
        J2000 *astrometric* equatorial coordinates. This is its position relative
        to the Galactic reference frame for the epoch of J2000.

        Parameters
        ----------
        timestamp : :class:`Timestamp` object or equivalent, or sequence, optional
            Timestamp(s) in UTC seconds since Unix epoch (defaults to now)
        antenna : :class:`Antenna` object, optional
            Antenna which points at target (defaults to default antenna)

        Returns
        -------
        l : :class:`ephem.Angle` object, or array of same shape as *timestamp*
            Galactic longitude, in radians
        b : :class:`ephem.Angle` object, or array of same shape as *timestamp*
            Galactic latitude, in radians

        Raises
        ------
        ValueError
            If no antenna is specified, and no default antenna was set either

        """
        if self.body_type == 'gal':
            l, b = ephem.Galactic(
                ephem.Equatorial(self.body._ra, self.body._dec)).get()
            if is_iterable(timestamp):
                return np.tile(l, len(timestamp)), np.tile(b, len(timestamp))
            else:
                return l, b
        ra, dec = self.astrometric_radec(timestamp, antenna)
        if is_iterable(ra):
            lb = np.array([
                ephem.Galactic(ephem.Equatorial(ra[n], dec[n])).get()
                for n in xrange(len(ra))
            ])
            return lb[:, 0], lb[:, 1]
        else:
            return ephem.Galactic(ephem.Equatorial(ra, dec)).get()
示例#2
0
 def azel2radec(self):
     """
     Compute the ra,dec (J2000) from Az,El location and time
     """
     if ephemOK:
         location = ephem.Observer()
         location.lon = str(self.tellon)
         location.lat = str(self.tellat)
         location.elevation = self.telelev
     strnow = self.utc.isoformat()
     # convert Time string format into value for Observer
     dates = strnow.split('T')
     datestr = dates[0] + ' ' + dates[1]
     if ephemOK:
         location.date = datestr
         # compute Local Sidereal Time
         lst = location.sidereal_time()
         aparts = angles.phmsdms(str(lst))
         self.lst = angles.sexa2deci(aparts['sign'],
                                     *aparts['vals'],
                                     todeg=True)
         ## Must set the date before calculating ra, dec!!!
         # compute apparent RA,DEC for date of observations
         ra_a, dec_a = location.radec_of(str(self.telaz), str(self.telel))
         radec = ephem.Equatorial(ra_a, dec_a, epoch=datestr)
         radec2000 = ephem.Equatorial(radec, epoch=ephem.J2000)
         # Hours
         aparts = angles.phmsdms(str(radec2000.ra))
         self.ra = angles.sexa2deci(aparts['sign'],
                                    *aparts['vals'],
                                    todeg=True)
         # to convert to dec degrees need to replace on : with d
         aparts = angles.phmsdms(str(radec2000.dec))
         self.dec = angles.sexa2deci(aparts['sign'], *aparts['vals'])
     self.epoch = "2000"
     # now update galactic coordinates
     if ephemOK:
         self.radec2gal()
         sun = ephem.Sun(location)
         aparts = angles.phmsdms(str(sun.az))
         self.az_sun = angles.sexa2deci(aparts['sign'], *aparts['vals'])
         aparts = angles.phmsdms(str(sun.alt))
         self.altsun = angles.sexa2deci(aparts['sign'], *aparts['vals'])
示例#3
0
文件: mk_difimg.py 项目: nkern/capo
def to_fits(ftag,i,src,cnt):
    filename = fname(ftag,cnt)
    print 'Saving data to', filename
    while len(i.shape) < 4: i.shape = i.shape + (1,)
    cen = ephem.Equatorial(src.ra, src.dec, epoch=aa.epoch)
    # We precess the coordinates of the center of the image here to
    # J2000, just to have a well-defined epoch for them.  For image coords to
    # be accurately reconstructed, precession needs to be applied per pixel
    # and not just per phase-center because ra/dec axes aren't necessarily
    # aligned between epochs.  When reading these images, to be 100% accurate,
    # one should precess the ra/dec coordinates back to the date of the
    # observation, infer the coordinates of all the pixels, and then
    # precess the coordinates for each pixel independently.
    cen = ephem.Equatorial(cen, epoch=ephem.J2000)
    a.img.to_fits(filename, i, clobber=True,
        object=src.src_name, obs_date=str(aa.date),
        ra=cen.ra*a.img.rad2deg, dec=cen.dec*a.img.rad2deg, epoch=2000.,
        d_ra=L[-1,-1]*a.img.rad2deg, d_dec=M[1,1]*a.img.rad2deg,
        freq=n.average(aa[0].beam.afreqs))
示例#4
0
 def test_swift_grb_v2_fk5(self):
     with open(datapaths.swift_bat_grb_pos_v2) as f:
         swift_grb_v2 = voeventparse.load(f)
     known_swift_grb_posn = ephem.Equatorial(74.741200 / DEG_PER_RADIAN,
                                             25.313700 / DEG_PER_RADIAN,
                                             epoch=ephem.J2000)
     voe_coords = voeventparse.pull_astro_coords(swift_grb_v2)
     extracted_posn = convert_voe_coords_to_eqposn(voe_coords)
     self.assertEqual(extracted_posn.ra, known_swift_grb_posn.ra)
     self.assertEqual(extracted_posn.dec, known_swift_grb_posn.dec)
示例#5
0
def ecliptic(ra, dec):
    """ecliptic.

    Args:
        ra:
        dec:
    """
    np = ephem.Equatorial(math.radians(ra), math.radians(dec), epoch='2000')
    e = ephem.Ecliptic(np)
    return (math.degrees(e.lon), math.degrees(e.lat))
示例#6
0
def transform_celestial(coords, systems):
    lons, lats = np.radians(coords['lon']), np.radians(coords['lat'])

    out = Table()
    out['lon'] = np.zeros(len(coords), dtype='float64')
    out['lat'] = np.zeros(len(coords), dtype='float64')

    for ii, (lon, lat) in enumerate(zip(lons, lats)):
        # Create coordinate in input system
        if systems['in'] == 'fk5':
            coord = ephem.Equatorial(lon, lat)
        elif systems['in'] == 'fk4':
            coord = ephem.Equatorial(lon, lat, epoch=ephem.B1950)
        elif systems['in'] == 'galactic':
            coord = ephem.Galactic(lon, lat)
        elif systems['in'] == 'ecliptic':
            coord = ephem.Ecliptic(lon, lat)
        else:
            raise ValueError()

        # Convert to appropriate output system
        # Retrieving output system coordinates is system specific
        # because the attribute names depend on the system
        if systems['out'] == 'fk5':
            coord = ephem.Equatorial(coord, epoch=ephem.J2000)
            lon, lat = coord.ra, coord.dec
        elif systems['out'] == 'fk4':
            coord = ephem.Equatorial(coord, epoch=ephem.B1950)
            lon, lat = coord.ra, coord.dec
        elif systems['out'] == 'galactic':
            coord = ephem.Galactic(coord)
            lon, lat = coord.lon, coord.lat
        elif systems['out'] == 'ecliptic':
            coord = ephem.Ecliptic(coord)
            lon, lat = coord.lon, coord.lat
        else:
            raise ValueError()

        out[ii]['lon'] = np.degrees(lon)
        out[ii]['lat'] = np.degrees(lat)

    return out
示例#7
0
def ecliptic_to_J2000(elong, elat, mjd):
    """
  convert from ephem.Ecliptic coordinates to RA and dec
  """
    t = Time(mjd, format='mjd')
    # t is probably needed for convert from current to J2000
    eq = Ecliptic(str(elong), str(elat), epoch=2000)
    ra, dec = ephem.Equatorial(eq).to_radec()
    #print "Astronomy:",type(ra),type(dec)
    #print "Astronomy:", type(ra.real), type(dec.real)
    return ra.real, dec.real
示例#8
0
def ecliptic_lon(now_time: datetime.datetime) -> float:
    """
    根据日期计算黄经
    now_time -- 日期
    Return arguments:
    float -- 黄经
    """
    s = ephem.Sun(now_time)
    equ = ephem.Equatorial(s.ra, s.dec, epoch=now_time)
    e = ephem.Ecliptic(equ)
    return e.lon
    def precess(self, epoch=Epoch.NOW):
        if str(epoch).lower() == str(Epoch.J2000).lower():
            epoch = ephem.J2000
        elif str(epoch).lower() == str(Epoch.B1950).lower():
            epoch = ephem.B1950
        elif str(epoch).lower() == str(Epoch.NOW).lower():
            epoch = ephem.now()

        j2000 = self.toEphem()
        now = ephem.Equatorial(j2000, epoch=epoch)
        return Position.fromRaDec(Coord.fromR(now.ra), Coord.fromR(now.dec), epoch=Epoch.NOW)
示例#10
0
def plot_ecliptic_plane(handles, labels):
    ep = [ephem.Ecliptic(str(lon), str(0)) for lon in range(0, 360)
          ]  # this line is fine: need Ecliptic(long, lat) format in creation
    ecPlane = [ephem.Equatorial(coord)
               for coord in ep]  # so this must be where the issue is.
    ra_ecPlane = [math.degrees(coord.ra) for coord in ecPlane]
    dec_ecPlane = [math.degrees(coord.dec) for coord in ecPlane]
    handles.append(plt.plot(ra_ecPlane, dec_ecPlane, '#E47833'))
    labels.append('ecliptic')
    # plt.plot([rr+360 for rr in ra_ecPlane], dec_ecPlane, '#E47833')  # echo

    return handles, labels
示例#11
0
 def __init__(self, source_name):
     # Check if the source is in the catalogue.
     if not source_name in catalogue.keys():
         raise ValueError("Source not in catalogue see "
                          "(`source.catalogue`).")
     self.source_name = source_name
     cat_info = catalogue[source_name]
     # Convert souce location to degrees.
     Loc = ephem.Equatorial(cat_info['RA'], cat_info['DEC'])
     RA, DEC = Loc.get()
     self.RA = RA * 180 / np.pi
     self.DEC = DEC * 180 / np.pi
示例#12
0
def parse_patch_center_and_width(args, parts):
    """ Parse center-and-width patch definition
    """
    corners = []
    print('Center-and-width format ', end='')
    try:
        # Assume coordinates in degrees
        lon = float(parts[2]) * degree
        lat = float(parts[3]) * degree
    except:
        # Failed simple interpreration, assume pyEphem strings
        lon = parts[2]
        lat = parts[3]
    width = float(parts[4]) * degree
    if args.patch_coord == 'C':
        center = ephem.Equatorial(lon, lat, epoch='2000')
    elif args.patch_coord == 'E':
        center = ephem.Ecliptic(lon, lat, epoch='2000')
    elif args.patch_coord == 'G':
        center = ephem.Galactic(lon, lat, epoch='2000')
    else:
        raise RuntimeError('Unknown coordinate system: {}'.format(
            args.patch_coord))
    center = ephem.Equatorial(center)
    # Synthesize 8 corners around the center
    phi = center.ra
    theta = center.dec
    r = width / 2
    ncorner = 8
    angstep = 2 * np.pi / ncorner
    for icorner in range(ncorner):
        ang = angstep * icorner
        delta_theta = np.cos(ang) * r
        delta_phi = np.sin(ang) * r / np.cos(theta + delta_theta)
        patch_corner = ephem.FixedBody()
        patch_corner._ra = phi + delta_phi
        patch_corner._dec = theta + delta_theta
        corners.append(patch_corner)

    return corners
示例#13
0
    def createEclipticPath(self):

        eline = []
        for i in range(361):
            l = str(0 + i)
            b = ephem.Ecliptic(l, "0", epoch="2016")
            c = ephem.Equatorial(b)
            r = c.ra
            d = c.dec
            rr = float(r) / (2.0 * math.pi) * 24
            dd = float(d) * 180. / math.pi
            eline.append([rr, dd])
        return eline
示例#14
0
 def testprecession(self):
     """Test coordinate precessions for accuracy"""
     crdpairs = [[('0:00', '0:00'), ('00:02:33.77', '00:16:42.1')],
                 [('6:00', '0:00'), ('06:02:33.75', '-00:00:05.6')],
                 [('0:00', '89:00'), ('00:03:03.75', '+89:16:41.7')]]
     for b1950, j2000 in crdpairs:
         c1 = a.coord.convert(b1950,
                              'eq',
                              'eq',
                              iepoch=e.B1950,
                              oepoch=e.J2000)
         c2 = a.coord.convert(j2000,
                              'eq',
                              'eq',
                              iepoch=e.J2000,
                              oepoch=e.B1950)
         c1_ck = e.Equatorial(j2000[0], j2000[1], epoch=e.J2000).get()
         c2_ck = e.Equatorial(b1950[0], b1950[1], epoch=e.B1950).get()
         self.assertAlmostEqual(c1[0], c1_ck[0], 4)
         self.assertAlmostEqual(c1[1], c1_ck[1], 4)
         self.assertAlmostEqual(c2[0], c2_ck[0], 4)
         self.assertAlmostEqual(c2[1], c2_ck[1], 4)
示例#15
0
 def radec2gal(self):
     """
     Compute the ra,dec (J2000) from Az,El location and time
     """
     rads = np.pi / 180.
     radec2000 = ephem.Equatorial( rads*self.ra, rads*self.dec, epoch=ephem.J2000)
     # to convert to dec degrees need to replace on : with d
     self.epoch = "2000"
     gal = ephem.Galactic(radec2000)
     aparts = angles.phmsdms(str(gal.lon))
     self.gallon = angles.sexa2deci(aparts['sign'], *aparts['vals'])
     aparts = angles.phmsdms(str(gal.lat))
     self.gallat = angles.sexa2deci(aparts['sign'], *aparts['vals'])
示例#16
0
    def __init__(self, parfile, timfile):

        # initialize libstempo object
        t2psr = t2.tempopulsar(
            parfile,
            timfile,
            maxobs=30000,
        )

        # get attributes
        self.name = t2psr.name
        self.residuals = np.double(t2psr.residuals())
        self.toas = np.double(t2psr.toas() * 86400)
        self.toaerrs = np.double(t2psr.toaerrs * 1e-6)
        self.flags = t2psr.flagvals('f')
        Mmat = np.double(t2psr.designmatrix())

        # sort
        self.isort, self.iisort = utils.argsortTOAs(self.toas,
                                                    self.flags,
                                                    which='jitterext',
                                                    dt=1.0)

        self.toas = self.toas[self.isort]
        self.toaerrs = self.toaerrs[self.isort]
        self.residuals = self.residuals[self.isort]
        self.flags = self.flags[self.isort]
        Mmat = Mmat[self.isort, :]

        u, s, v = np.linalg.svd(Mmat, full_matrices=False)
        self.Musvd = u
        self.Mssvd = s

        # get sky location
        pars = t2psr.pars()
        if 'RAJ' not in pars and 'DECJ' not in pars:
            elong, elat = t2psr['ELONG'].val, t2psr['ELAT'].val
            ec = ephem.Ecliptic(elong, elat)

            # check for B name
            if 'B' in t2psr.name:
                epoch = '1950'
            else:
                epoch = '2000'
            eq = ephem.Equatorial(ec, epoch=epoch)
            self.phi = np.double([eq.ra])
            self.theta = np.pi / 2 - np.double([eq.dec])

        else:
            self.phi = np.double(t2psr['RAJ'].val)
            self.theta = np.pi / 2 - np.double(t2psr['DECJ'].val)
示例#17
0
def calcazel(ra, dec, longitude=-79.8397, latitude=38.4331, elevation=800.):
    """
    Compute the ra,dec (J2000) from Az,El location and time
    """
    location = ephem.Observer()
    location.lon = angles.d2r(longitude)
    location.lat = angles.d2r(latitude)
    location.elevation = elevation
    now = datetime.datetime.utcnow()
    strnow = now.isoformat()
    dates = strnow.split('T')
    datestr = dates[0] + ' ' + dates[1]
    location.date = datestr
    lst = location.sidereal_time()
    fmt = 'Date   = %s,  LST = %s'
    print fmt % (datestr, lst)
    # first put ra,dec in ephemeris format
    radec2000 = ephem.Equatorial( ra, dec, epoch=ephem.J2000)
    # now compute ra, dec of date
    radec = ephem.Equatorial(radec2000.ra, radec2000.dec, epoch=datestr)
    print 'Ra,Dec = %s, %s (J2000)' % (radec2000.ra, radec2000.dec)
    gal = ephem.Galactic(radec2000)
    print 'Lon,Lat= %s, %s (Galactic)' % (gal.lon, gal.lat)
    object = ephem.FixedBody()
    object._ra = radec.ra
    object._dec = radec.dec
    object.compute(location)
    # need to turn dd:mm:ss into float
    aparts = angles.phmsdms(str(object.az))
    az = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=False)
    aparts = angles.phmsdms(str(object.alt))
    el = angles.sexa2deci(aparts['sign'], *aparts['vals'], todeg=False)
#    print "Az: %s -> %f" % (str(object.az), az)
#    print "El: %s -> %f" % (str(object.alt), el)
    fmt = 'Az, El = %.2f, %.2f (degrees)' 
    print fmt % (az, el)
    
    return az, el
示例#18
0
    def ecliptic_lat_span(self, blockID):
        junk, fieldIds = self.fields_in_block(blockID)
        ecs = []
        for field in fieldIds:
            rr = ephem.Equatorial(ephem.hours(self.bk.field_ra(field)),
                                  ephem.degrees(self.bk.field_dec(field)))
            ec = ephem.Ecliptic(rr)
            ecs.append(ec)
        ecs.sort(key=lambda x: x.__getattribute__('lat'))

        retval = (degrees(ecs[0].lat), degrees(ecs[-1].lat)
                  )  # eclat is float (deg), min-max

        return retval
示例#19
0
def plot_galactic_plane(handles, labels):
    gp = [ephem.Galactic(str(lon), str(0)) for lon in range(0, 360)]
    galPlane = [ephem.Equatorial(coord) for coord in gp]
    # rewrap the ra to start at zero: that otherwise causes a problem in the plotting!
    temp = [(math.degrees(coord.ra), math.degrees(coord.dec))
            for coord in galPlane]
    temp.sort(key=lambda x: x[0])
    ra_galPlane = [t[0] for t in temp]
    dec_galPlane = [tt[1] for tt in temp]
    handles.append(plt.plot(ra_galPlane, dec_galPlane, 'b'))
    labels.append('galactic plane')
    # plt.plot([r+360 for r in ra_galPlane], dec_galPlane, 'b')  # echo

    return handles, labels
示例#20
0
def convertMapToJ2000(map):
    """
    Given a map in Equatorial coodinates in the B1950 epoch, convert it to
    the J2000 epoch.
    """

    hasMask = False
    if getattr(map, 'mask', None) is not None:
        hasMask = True

    map2 = map * 0.0
    nSides = hp.pixelfunc.npix2nside(map.size)
    for i in xrange(map.size):
        theta, phi = hp.pixelfunc.pix2ang(nSides, i)
        eq = ephem.Equatorial(phi, np.pi / 2 - theta, epoch=ephem.B1950)
        eq = ephem.Equatorial(eq, epoch=ephem.J2000)
        j = hp.pixelfunc.ang2pix(nSides, np.pi / 2 - eq.dec, eq.ra)
        map2[j] += map[i]

        if hasMask:
            map2.mask[j] = map.mask[i]

    return map2
示例#21
0
def gal_index(ra, dec):
    p = ephem.Equatorial(str(ra), str(dec))
    galactic = ephem.Galactic(p)
    glong = math.degrees(galactic.lon)
    glat = math.degrees(galactic.lat)

    glndx = int(glong) + 180
    glndx %= 360
    glndx /= args.increment
    glndx -= 1

    gladx = int(glat) + 90
    gladx /= args.increment
    gladx -= 1
    return ((glndx, gladx))
示例#22
0
def radec_decimal(ra, dec):
    a = ephem.Equatorial(0.0, 0.0)
    if (hasattr(ra, "__len__") == False):
        a.from_radec(ra, dec)
        temp = np.degrees(a.to_radec())
        return [temp[0], temp[1]]
    else:
        rao = np.zeros(len(ra), dtype='float64')
        deco = np.zeros(len(ra), dtype='float64')
        for i in range(len(ra)):
            a.from_radec(ra[i], dec[i])
            temp = np.degrees(a.to_radec())
            rao[i] = temp[0]
            deco[i] = temp[1]
        return rao, deco
示例#23
0
def parse_patch_explicit(args, parts):
    """ Parse an explicit patch definition line
    """
    corners = []
    print('Explicit-corners format ', end='')
    while i < len(parts):
        print(' ({}, {})'.format(parts[2], parts[3]), end='')
        try:
            # Assume coordinates in degrees
            lon = float(parts[2]) * degree
            lat = float(parts[3]) * degree
        except:
            # Failed simple interpreration, assume pyEphem strings
            lon = parts[2]
            lat = parts[3]
        i += 2
        if args.patch_coord == 'C':
            corner = ephem.Equatorial(lon, lat, epoch='2000')
        elif args.patch_coord == 'E':
            corner = ephem.Ecliptic(lon, lat, epoch='2000')
        elif args.patch_coord == 'G':
            corner = ephem.Galactic(lon, lat, epoch='2000')
        else:
            raise RuntimeError('Unknown coordinate system: {}'.format(
                args.patch_coord))
        corner = ephem.Equatorial(corner)
        if corner.dec > 80 * degree or corner.dec < -80 * degree:
            raise RuntimeError(
                '{} has at least one circumpolar corner. '
                'Circumpolar targeting not yet implemented'.format(name))
        patch_corner = ephem.FixedBody()
        patch_corner._ra = corner.ra
        patch_corner._dec = corner.dec
        corners.append(patch_corner)

    return corners
示例#24
0
 def _run(self, simData):
     for i in np.arange(simData.size):
         coord = ephem.Equatorial(simData[self.raCol][i],
                                  simData[self.decCol][i],
                                  epoch=2000)
         ecl = ephem.Ecliptic(coord)
         simData['eclipLat'][i] = ecl.lat
         if self.subtractSunLon:
             djd = mjd2djd(simData[self.mjdCol][i])
             sun = ephem.Sun(djd)
             sunEcl = ephem.Ecliptic(sun)
             lon = wrapRA(ecl.lon - sunEcl.lon)
             simData['eclipLon'][i] = lon
         else:
             simData['eclipLon'][i] = ecl.lon
     return simData
示例#25
0
    def shift_to_vlsr_frame(self):
        # From http://web.mit.edu/8.13/www/nsrt_software/documentation/vlsr.pdf
        ep_target = ephem.Equatorial(self.target)
        # Sun velocity apex is at 18 hr, 30 deg; convert to x, y, z
        # geocentric celestial for dot product with source, multiply by speed
        x0 = 20.0 * math.cos(18.0 * np.pi / 12.0) * math.cos(
            30.0 * np.pi / 180.0)
        y0 = 20.0 * math.sin(18.0 * np.pi / 12.0) * math.cos(
            30.0 * np.pi / 180.0)
        z0 = 20.0 * math.sin(30.0 * np.pi / 180.0)

        # Make sure we have target angles in radians
        tg_ra_rad = float(ep_target.ra)
        tg_dec_rad = float(ep_target.dec)

        # Calculate sinces, cosines for dot product
        ctra = math.cos(tg_ra_rad)
        stra = math.sin(tg_ra_rad)
        ctdc = math.cos(tg_dec_rad)
        stdc = math.sin(tg_dec_rad)

        # Calculate correction due to movement of Sun with respect to LSR
        # dot product of target & apex vectors
        vsun = x0 * ctra * ctdc + y0 * stra * ctdc + z0 * stdc

        # get target in geocentric ecliptic system
        ecl = ephem.Ecliptic(ep_target)
        tlon = ecl.lon
        tlat = ecl.lat

        # Get sun ecliptic coordinates, in radians
        sun = ephem.Sun()
        sun.compute(self.site)
        se = ephem.Ecliptic(sun)
        slong = float(se.lon)

        # Calculate correction due to earth movement relative to the Sun
        vorb = 30.0 * math.cos(tlat) * math.sin(slong - tlon)

        # Combine both effects
        vlsr_kmps = vsun + vorb  # in km/s

        vlsr_corr = 1e3 * vlsr_kmps  # in m/s

        self.vlsr_corr = vlsr_corr  # store for this spectrum
        # Convert and store shift also for frequency
        self.freq_vlsr_corr = -1 * self.rest_freq * self.vlsr_corr / c
示例#26
0
def gc2azalt(gl,gb,ct3):
    global convert
    body_gl=gl*convert
    body_gb=gb*convert
    galactic_coord = ephem.Galactic(body_gl, body_gb)
    eq = ephem.Equatorial(galactic_coord)
   
    getlocal = ephem.Observer()
    getlocal.long, getlocal.lat = '116.97345','40.55666' # at Miyun
    getlocal.date = ct3 # UT
   
    body = ephem.FixedBody()
    body._ra = eq.ra
    body._dec = eq.dec
    body._epoch = ephem.J2000
    body.compute(getlocal)
    return float(body.az)*180/np.pi,float(body.alt)*180/np.pi
示例#27
0
    def compute_libration(self):
        """
        Compute topocentric libration angles and the position angle of the moon's rotational axis.
        
        :return: -
        """

        # Astrometric libration angles and the selenographic co-longitude of the sun are provided
        # by PyEphem.
        self.astrometric_lib_lat = self.moon.libration_lat
        self.astrometric_lib_long = self.moon.libration_long
        self.colong = self.moon.colong

        # Compute topocentric libration values. For algorithmic details, refer to the user's guide.
        j2000 = ephem.Date(datetime.datetime(2000, 1, 1, 12, 0))
        t = (ephem.Date(self.location_time.date) - j2000) / 36525.
        epsilon = radians(23.439281 - 0.013002575 * t)
        ma = ephem.Equatorial(self.ra,
                              self.de,
                              epoch=ephem.Date(self.location_time.date))
        me = ephem.Ecliptic(ma)
        cap_i = radians(1.54266)
        omega = radians(125.044555 - 1934.13626194 * t)
        lm = radians(218.31664563 + 481267.88119575 * t - 0.00146638 * t**2)
        i = acos(
            cos(cap_i) * cos(epsilon) + sin(cap_i) * sin(epsilon) * cos(omega))
        omega_prime = atan2(-sin(cap_i) * sin(omega) / sin(i),
                            (cos(cap_i) * sin(epsilon) -
                             sin(cap_i) * cos(epsilon) * cos(omega)) / sin(i))

        self.pos_rot_north = atan2(
            -sin(i) * cos(omega_prime - self.ra),
            cos(self.de) * cos(i) -
            sin(self.de) * sin(i) * sin(omega_prime - self.ra))
        self.topocentric_lib_lat = asin(-sin(cap_i) * cos(me.lat) *
                                        sin(me.lon - omega) -
                                        cos(cap_i) * sin(me.lat))
        self.topocentric_lib_long = (atan2(
            cos(cap_i) * cos(me.lat) * sin(me.lon - omega) -
            sin(cap_i) * sin(me.lat),
            cos(me.lat) * cos(me.lon - omega)) - lm + omega) % (2. * pi)
        if self.topocentric_lib_long > 1.:
            self.topocentric_lib_long -= 2. * pi
        elif self.topocentric_lib_long < -1.:
            self.topocentric_lib_long += 2. * pi
示例#28
0
def add_fields():
    fields_to_plot = ascii.read("fields_to_plot.txt")

    for i in range(len(fields_to_plot["RA"])):
        eq = ephem.Equatorial(fields_to_plot["RA"][i] / degrad,
                              fields_to_plot["Dec"][i] / degrad,
                              epoch=2000)
        ec = ephem.Ecliptic(eq, epoch=2000)

        if abs(float(ec.lat) * degrad) >= 54:
            pltcolor = 'g'
        else:
            pltcolor = 'r'

        add_point(fields_to_plot["RA"][i] / degrad,
                  fields_to_plot["Dec"][i] / degrad,
                  color=pltcolor,
                  txtlabel=fields_to_plot["Field"][i])
示例#29
0
def block_table_pprint():
    """

    :return:
    """
    with open('block_table.tex', 'w') as outfile:
        for name, coords in parameters.BLOCKS.items():
            print name, coords
            ra = ephem.hours(coords['RA'])
            dec = ephem.degrees(coords['DEC'])
            eq = ephem.Equatorial(ra, dec)
            ec = ephem.Ecliptic(eq)
            outfile.write(
                "{} & {:2.1f} & {:2.1f} & {:2.1f} & {:2.1f} {} \n".format(
                    name[2:], math.degrees(ephem.degrees(ra)),
                    math.degrees(dec), math.degrees(ec.lat),
                    math.degrees(ec.lon), r"\\"))
    return
示例#30
0
 def p(self, lon, lat):
     if 0 == 1:
         g = ephem.Galactic(ephem.Equatorial(lon * pi / 180.,
                                             lat * pi / 180.,
                                             epoch=ephem.J2000),
                            epoch=ephem.J2000)
         lon = g.long * 180 / pi
         lat = g.lat * 180 / pi
     #print lon,lat
     try:
         x, y = pyproj.transform(self.prj_ra_dec, self.prj, lon, lat)
     except:
         return (-999999, -999999)
     x = -x * self.paperwidth / self.xfactor + self.paperwidth / 2
     y = y * self.paperheight / self.yfactor + self.paperheight / 2
     #		x=x*self.paperwidth/self.scale+self.paperwidth/2
     #		y=y*self.paperwidth/self.scale+self.paperheight/2
     return x, y