Example #1
0
    def skycoord(self):
        '''
        Manage and fix sky coordinates
        '''
        head = self.head.copy()

        # time
        if self.obstime not in head:
            head['JD'] = Time.now().jd

        # earthlocation
        location = EarthLocation(lon=self.lon, lat=self.lat, height=self.alt)

        timekey = head[self.obstime]
        # log.warning(timekey)
        if 'MJD' in self.obstime:
            obstime = Time(timekey, format='mjd')
        elif self.obstime == 'JD':
            obstime = Time(timekey, format='jd')
        # elif isinstance(self.obstime, list):
        #     obstime = Time(Time(timekey[0]).unix+timekey[1])
        elif 'DATE' in self.obstime:
            obstime = Time(timekey)
        else:
            obstime = Time(timekey)

        obstime.location = location

        # skycoord
        if self.ra in head and self.dec in head:
            coord = SkyCoord(
                ra=head[self.ra],
                dec=head[self.dec],
                location=location,
                obstime=obstime,
                equinox=obstime.jyear_str[:-2],
                # frame='icrs',
                frame='fk5',
                unit=self.unit)

        elif self.obj in head:
            coord = SkyCoord.from_name(
                head[self.obj],
                #location=location,
                #obstime=obstime,
                # frame='icrs',
                #equinox=obstime.jyear_str[:-2]
                frame='fk5')

        else:
            log.error("No (RA DEC) and no OBJECT in header")
            return

        coord = coord.transform_to(FK5(equinox='J2000'))

        # Meteo
        if self.temperature and self.temperature in head:
            coord.temperature = head[self.temperature] * u.deg_C
        if self.pressure and self.pressure in head:
            coord.pressure = head[self.pressure] * u.hPa
        if self.humidity and self.humidity in head:
            coord.relative_humidity = head[self.humidity] / 100

        # coord.obstime=obstime

        self.coord = coord
        return coord
Example #2
0
def test_asdf_url_mapper():
    """Make sure specutils asdf extension url_mapping doesn't interfere with astropy schemas"""
    frame = FK5()
    af = asdf.AsdfFile()
    af.tree = {'frame': frame}
Example #3
0
@pytest.fixture(params=[None] + LSRD_EQUIV)
def observer(request):
    return request.param


# Target located in direction of motion of LSRD with no velocities
LSRD_DIR_STATIONARY = Galactic(u=9 * u.km,
                               v=12 * u.km,
                               w=7 * u.km,
                               representation_type='cartesian')

LSRD_DIR_STATIONARY_EQUIV = [
    LSRD_DIR_STATIONARY,
    SkyCoord(LSRD_DIR_STATIONARY),  # as a SkyCoord
    LSRD_DIR_STATIONARY.transform_to(FK5()),  # different frame
    LSRD_DIR_STATIONARY.transform_to(ICRS()).transform_to(
        Galactic())  # different representation
]


@pytest.fixture(params=[None] + LSRD_DIR_STATIONARY_EQUIV)
def target(request):
    return request.param


def test_create_spectral_coord_observer_target(observer, target):

    with nullcontext() if target is None else pytest.warns(
            AstropyUserWarning, match='No velocity defined on frame'):
        coord = SpectralCoord([100, 200, 300] * u.nm,
Example #4
0
def main(targ_file,
         survey='2r',
         radec=None,
         deci=None,
         fpath=None,
         EPOCH=0.,
         DSS=None,
         BW=False,
         imsize=5.,
         show_spec=False):
    '''
    Parameters:
    ---------
    targ_file: string or List of string
       ASCII file for targets (Name, RA, DEC)
       or a List 
       Colon separated RA, DEC expected
    radec: integer (0)
       Flag indicating type of input
       0 = ASCII file
       1 = List or ['Name', 'RA', 'DEC']  
    BW: bool (False)
       B&W image?
    show_spec: bool (False)
       Try to grab and show an SDSS spectrum 
    '''
    import radec as x_r
    reload(x_r)
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    # Init
    if fpath is None:
        fpath = './'
    cradius = imsize / 50.

    # Read in the Target list
    ra_tab = get_coord(targ_file, radec=radec)

    # Grab ra, dec in decimal degrees
    if deci != None:
        return
    # Convert to decimal degress

    x_r.stod(ra_tab)  #ra_tab['RA'][q], ra_tab['DEC'][q], TABL)

    # Precess (as necessary)
    if EPOCH > 1000.:
        from astropy import units as u
        from astropy.coordinates import FK5
        from astropy.time import Time
        # Precess to 2000.
        tEPOCH = Time(EPOCH, format='jyear', scale='utc')
        # Load into astropy
        fk5c = FK5(ra=ra_tab['RAD'],
                   dec=ra_tab['DECD'],
                   equinox=tEPOCH,
                   unit=(u.degree, u.degree))
        # Precess
        newEPOCH = Time(2000., format='jyear', scale='utc')
        newfk5 = fk5c.precess_to(newEPOCH)
        # Save
        ra_tab['RAD'] = newfk5.ra.degree
        ra_tab['DECD'] = newfk5.dec.degree
        # Strings too?
        ra_tab['RA'] = str(newfk5.ra.to_string(unit=u.hour, sep=':'))
        ra_tab['DEC'] = str(newfk5.dec.to_string(unit=u.hour, sep=':'))

    ##
    # Main Loop
    nobj = len(ra_tab)
    for qq in range(nobj):

        # Outfil
        outfil = fpath + ra_tab['Name'][qq] + '.pdf'
        print(outfil)

        # Grab the Image
        from xastropy.obs import x_getsdssimg as xgs
        reload(xgs)
        img, oBW = xgs.getimg(ra_tab['RAD'][qq],
                              ra_tab['DECD'][qq],
                              imsize,
                              BW=BW,
                              DSS=DSS)

        # Generate the plot
        plt.clf()
        fig = plt.figure(dpi=1200)
        fig.set_size_inches(8.0, 10.5)

        # Font
        plt.rcParams['font.family'] = 'times new roman'
        ticks_font = matplotlib.font_manager.FontProperties(
            family='times new roman',
            style='normal',
            size=16,
            weight='normal',
            stretch='normal')
        ax = plt.gca()
        for label in ax.get_yticklabels():
            label.set_fontproperties(ticks_font)
        for label in ax.get_xticklabels():
            label.set_fontproperties(ticks_font)

        # Image
        if oBW == 1:
            cmm = cm.Greys_r
        else:
            cmm = None
        plt.imshow(img,
                   cmap=cmm,
                   aspect='equal',
                   extent=(-imsize / 2., imsize / 2, -imsize / 2., imsize / 2))

        # Axes
        plt.xlim(-imsize / 2., imsize / 2.)
        plt.ylim(-imsize / 2., imsize / 2.)

        # Label
        plt.xlabel('Relative ArcMin', fontsize=20)
        xpos = 0.12 * imsize
        ypos = 0.02 * imsize
        plt.text(-imsize / 2. - xpos, 0., 'EAST', rotation=90., fontsize=20)
        plt.text(0.,
                 imsize / 2. + ypos,
                 'NORTH',
                 fontsize=20,
                 horizontalalignment='center')

        # Title
        plt.text(0.5,
                 1.24,
                 str(ra_tab['Name'][qq]),
                 fontsize=32,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        plt.text(0.5,
                 1.16,
                 'RA (J2000) = ' + str(ra_tab['RA'][qq]),
                 fontsize=28,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        plt.text(0.5,
                 1.10,
                 'DEC (J2000) = ' + str(ra_tab['DEC'][qq]),
                 fontsize=28,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        #import pdb; pdb.set_trace()

        # Circle
        circle = plt.Circle((0, 0), cradius, color='y', fill=False)
        plt.gca().add_artist(circle)

        # Spectrum??
        if show_spec:
            spec_img = xgs.get_spec_img(ra_tab['RAD'][qq], ra_tab['DECD'][qq])
            plt.imshow(spec_img,
                       extent=(-imsize / 2.1, imsize * (-0.1), -imsize / 2.1,
                               imsize * (-0.2)))

        # Write
        if show_spec:
            plt.savefig(outfil, dpi=300)
        else:
            plt.savefig(outfil)
        print 'finder: Wrote ' + outfil
        #xdb.set_trace()

    print 'finder: All done.'
    return
Example #5
0
def compute_paral_angles(header,
                         latitude,
                         ra_key,
                         dec_key,
                         lst_key,
                         acqtime_key,
                         date_key='DATE-OBS'):
    """Calculates the parallactic angle for a frame, taking coordinates and
    local sidereal time from fits-headers (frames taken in an alt-az telescope 
    with the image rotator off).
    
    The coordinates in the header are assumed to be J2000 FK5 coordinates.
    The spherical trigonometry formula for calculating the parallactic angle
    is taken from Astronomical Algorithms (Meeus, 1998).
    
    Parameters
    ----------
    header : dictionary
        Header of current frame.
    latitude : float
        Latitude of the observatory in degrees. The dictionaries in 
        vip/conf/param.py can be used like: latitude=LBT['latitude'].
    ra_key, dec_key, lst_key, acqtime_key, date_key : strings
        Keywords where the values are stored in the header.
        
    Returns
    -------
    pa.value : float
        Parallactic angle in degrees for current header (frame).
    """
    obs_epoch = Time(header[date_key], format='iso', scale='utc')

    # equatorial coordinates in J2000
    ra = header[ra_key]
    dec = header[dec_key]
    coor = SkyCoord(ra=ra,
                    dec=dec,
                    unit=(hourangle, degree),
                    frame=FK5,
                    equinox='J2000.0')
    # recalculate for DATE-OBS (precession)
    coor_curr = coor.transform_to(FK5(equinox=obs_epoch))

    # new ra and dec in radians
    ra_curr = coor_curr.ra
    dec_curr = coor_curr.dec

    lst_split = header[lst_key].split(':')
    lst = float(lst_split[0]) + old_div(float(lst_split[1]), 60) + old_div(
        float(lst_split[2]), 3600)
    exp_delay = old_div((header[acqtime_key] * 0.5), 3600)
    # solar to sidereal time
    exp_delay = exp_delay * 1.0027

    # hour angle in degrees
    hour_angle = (lst + exp_delay) * 15 - ra_curr.deg
    hour_angle = np.deg2rad(hour_angle)
    latitude = np.deg2rad(latitude)

    # PA formula from Astronomical Algorithms
    pa = -np.rad2deg(np.arctan2(-np.sin(hour_angle), np.cos(dec_curr) * \
                 np.tan(latitude) - np.sin(dec_curr) * np.cos(hour_angle)))

    #if dec_curr.value > latitude:  pa = (pa.value + 360) % 360

    return pa.value
Example #6
0
from astropy import coordinates
import numpy as np
from astropy.coordinates import FK5
from astropy.time import Time


df = pd.read_csv("gaume1995_format.tab", header=0, delim_whitespace=True)
# df = pd.read_csv('gaume1995.csv')

header = fits.open('../data/abcd_006_lpf_new.fits')[0].header
mywcs = wcs.WCS(header).celestial
df['G95_X'] = np.ones_like(df['G95_RA'])
df['G95_Y'] = np.ones_like(df['G95_DEC'])
df['G95_A'] = df['G95_A']/0.05
df['G95_B'] = df['G95_B']/0.05
for i in range(df.shape[0]):
    cen_coor = coordinates.SkyCoord(str(df['G95_RA'][i]),
                                    str(df['G95_DEC'][i]),
                                    unit=(u.h, u.deg),
                                    frame='fk4',
                                    equinox='B1950')
    cen_coor = cen_coor.transform_to(FK5(equinox='J2000'))
    # print(cen_coor)
    (df['G95_X'][i], df['G95_Y'][i]) =  mywcs.wcs_world2pix([[cen_coor.ra.deg,
                                                             cen_coor.dec.deg]], 0)[0].astype(int)
    # print('%s %s' % (df['G95_RA'][i], df['G95_DEC'][i])
    print('%.0f %.0f' % (df['G95_X'][i], df['G95_Y'][i]))


df.to_csv('gaume1995.csv', index=False)
Example #7
0
    def calc_vobs(self, ra_2000, dec_2000):

        x_2000 = []
        x = []
        x_solar = []
        v_earth = []
        v_solar = []
        solar_tmp = []

        #1.85m at nobeyama
        #glongitude = 138.472153
        #nanten2 at atacama (nanten2wiki)
        glongitude = -67.70308139
        #1.85m at nobeyama
        #glatitude = 35.940874
        #nanten2 at atacama (nanten2wiki)
        glatitude = -22.96995611
        #1.85m at nobeyama
        #gheight = 1386
        #nanten2 at atacama
        gheight = 4863.85

        #init
        a = math.cos(dec_2000)
        x_2000 = [
            a * math.cos(ra_2000), a * math.sin(ra_2000),
            math.sin(dec_2000)
        ]

        tu = (self.t.jd - 2451545.) / 36525.
        #correction(precession, nutation)
        sc_fk5 = SkyCoord(ra=ra_2000 * u.radian,
                          dec=dec_2000 * u.radian,
                          frame="fk5")
        trans = sc_fk5.transform_to(
            FK5(equinox="J{}".format(2000. + tu * 100.)))
        ranow = trans.ra.radian
        delnow = trans.dec.radian

        x = self.nutation(ranow, delnow)

        #Earth velocity to object
        earthloc = EarthLocation(lon=glongitude * u.deg,
                                 lat=glatitude * u.deg,
                                 height=gheight * u.m)
        earthloc_gcrs = earthloc.get_gcrs(self.t)
        sc_earth = SkyCoord(earthloc_gcrs).fk5

        v_earth = sc_earth.velocity.d_xyz.value

        vobs = -(v_earth[0] * x_2000[0] + v_earth[1] * x_2000[1] +
                 v_earth[2] * x_2000[2])

        #solar
        sc_fk4_sol = SkyCoord(ra=18 * 15 * u.deg, dec=30 * u.deg, frame="fk4")
        trans_sol = sc_fk4_sol.transform_to(
            FK5(equinox="J{}".format(2000. + tu * 100.)))
        rasol = trans_sol.ra.radian
        delsol = trans_sol.dec.radian

        solar_tmp = self.nutation(rasol, delsol)
        v_solar = [solar_tmp[0] * 20, solar_tmp[1] * 20, solar_tmp[2] * 20]

        vobs = -(vobs -
                 (v_solar[0] * x[0] + v_solar[1] * x[1] + v_solar[2] * x[2]))

        return vobs
Example #8
0
def test_fk5_time(tmpdir):

    tree = {'coord': FK5(equinox="2011-01-01T00:00:00")}

    assert_roundtrip_tree(tree, tmpdir)
Example #9
0
def stack_npixels(
    npixels,
    level_neighbours=5,
    params=None,
    max_data=1000,
    calc_flux=True,
    use_flagged_pixels=False,
    skip_detections=False,
    custom_bkg=False,
    moc_masked_sources=None,
    order=16,
    with_plots=False,
    plotfile=None,
    scale=None,
):
    ecf_pn = {
        "6": ECF.ecf_det_eband("PN", "6"),
        "7": ECF.ecf_det_eband("PN", "7"),
        "8": ECF.ecf_det_eband("PN", "8"),
    }

    num_neighbours = sum([8 * k for k in range(level_neighbours + 1)]) + 1

    ebands = ["6", "7", "8"]
    src_stack = np.zeros((max_data, num_neighbours, len(ebands)))
    bkg_stack = np.zeros((max_data, num_neighbours, len(ebands)))
    exp_stack = np.zeros((max_data, num_neighbours, len(ebands)))
    eef_stack = np.ones((max_data, num_neighbours, len(ebands)))
    ac_stack = np.zeros((max_data, num_neighbours, len(ebands)))
    npixels_bkg_stack = np.ones((max_data, num_neighbours, len(ebands)))
    ecf_stack = np.zeros((max_data, len(ebands)))

    if calc_flux:
        src_flux_center = np.full((max_data, len(ebands)), np.nan)
        bkg_flux_center = np.full((max_data, len(ebands)), np.nan)
        src_flux_err_center = np.full((max_data, len(ebands)), np.nan)
        bkg_flux_err_center = np.full((max_data, len(ebands)), np.nan)

    if params:
        params_stack = np.zeros((max_data, len(params.colnames)))

    hp = HEALPix(nside=2**order, order="nested", frame=FK5())

    n, nsrc = 0, 0
    for j, npixel in enumerate(tqdm(npixels)):
        sorted_neighbours = get_neighbours(npixel, hp, level=level_neighbours)
        data = rapidxmm.query_npixels(sorted_neighbours["npixel"],
                                      obstype="pointed",
                                      instrum="PN")

        if len(data) == 0:
            continue

        nsrc += 1
        data = data.group_by(["obsid", "instrum"])

        for group in data.groups:
            data_obs_order = join(sorted_neighbours,
                                  group,
                                  keys=["npixel"],
                                  join_type="left")
            data_obs_order.sort("order")

            if skip_detections:
                if np.any(data_obs_order["band8_flags"] >= 8):
                    continue

            if custom_bkg:
                bkg_data = get_bkg_data(npixel, group["obsid"][0], hp)

                if bkg_data is None:
                    # We couldn't find a good background region for this npixel,
                    # so it's rejected from the stack
                    continue

            for i, eband in enumerate(ebands):
                if use_flagged_pixels:
                    mask = [True] * len(sorted_neighbours)
                else:
                    mask = data_obs_order[f"band{eband}_flags"] == 0

                src_stack[n, mask,
                          i] = data_obs_order[f"band{eband}_src_counts"][mask]
                exp_stack[n, mask,
                          i] = data_obs_order[f"band{eband}_exposure"][mask]
                eef_stack[n, mask, i] = data_obs_order["eef"][mask]
                ac_stack[n, mask, i] = data_obs_order["area_ratio"][mask]

                if custom_bkg:
                    mask_bkg = bkg_data[f"band{eband}_flags"] == 0

                    # The same average bkg value is assigned to all npixels in the detection
                    bkg_counts = bkg_data[f"band{eband}_bck_counts"][mask_bkg]
                    bkg_stack[n, mask, i] = np.mean(bkg_counts)
                    npixels_bkg_stack[n, mask, i] = len(bkg_counts)
                else:
                    bkg_stack[
                        n, mask,
                        i] = data_obs_order[f"band{eband}_bck_counts"][mask]

                if calc_flux and np.any(mask):
                    ecf_stack[n, i] = ecf_pn[eband][group["filt"][0]].get_ecf(
                        params["NHGAL"][j], 1.9)
                    exp = np.mean(exp_stack[n, mask, i])
                    ngood = len(exp_stack[n, mask, i])

                    src_flux_center[n,
                                    i] = (np.sum(src_stack[n, mask, i]) / exp /
                                          ecf_stack[n, i] / 1e11 / ngood)
                    src_flux_err_center[n, i] = (
                        np.sqrt(np.sum(src_stack[n, mask, i])) / exp /
                        ecf_stack[n, i] / 1e11 / ngood)

                    if custom_bkg:
                        exp_bkg = np.mean(
                            bkg_data[f"band{eband}_exposure"][mask_bkg])
                        ngood_bkg = len(
                            bkg_data[f"band{eband}_exposure"][mask_bkg])

                        bkg_flux_center[n, i] = (np.sum(bkg_counts) / exp_bkg /
                                                 ecf_stack[n, i] / 1e11 /
                                                 ngood_bkg)
                        bkg_flux_err_center[n,
                                            i] = (np.sqrt(np.sum(bkg_counts)) /
                                                  exp_bkg / ecf_stack[n, i] /
                                                  1e11 / ngood_bkg)
                    else:
                        bkg_flux_center[n,
                                        i] = (np.sum(bkg_stack[n, mask, i]) /
                                              exp / ecf_stack[n, i] / 1e11 /
                                              ngood)
                        bkg_flux_err_center[n, i] = (
                            np.sqrt(np.sum(bkg_stack[n, mask, i])) / exp /
                            ecf_stack[n, i] / 1e11 / ngood)

            if params:
                for i, col in enumerate(params.colnames):
                    params_stack[n, i] = params[col][j]

            n += 1

    src_stack = src_stack[:n, :, :]
    bkg_stack = bkg_stack[:n, :, :]
    exp_stack = exp_stack[:n, :, :]
    ecf_stack = ecf_stack[:n, :]

    if custom_bkg:
        # No need to take into account the area correction when using custom
        # backgrounds, since counts are extracted in regions with the same size
        ac_stack = None
        npixels_bkg_stack = npixels_bkg_stack[:n, :]
    else:
        ac_stack = ac_stack[:n, :]
        npixels_bkg_stack = None

    if n < 2:
        return None, None, None, None, None, None, None

    cr, cr_mad, snr, snr_mad, ecf, texp = stats_bootstrap(src_stack,
                                                          bkg_stack,
                                                          exp_stack,
                                                          eef_stack,
                                                          ecf_stack,
                                                          ac_stack,
                                                          npixels_bkg_stack,
                                                          nsim=1000)

    flux, flux_mad = None, None
    flux2, flux2_mad = None, None
    if calc_flux:
        src_flux_center = src_flux_center[:n, :]
        src_flux_err_center = src_flux_err_center[:n, :]
        bkg_flux_center = bkg_flux_center[:n, :]
        bkg_flux_err_center = bkg_flux_err_center[:n, :]

        flux, flux_mad = flux_bootstrap(src_flux_center,
                                        src_flux_err_center,
                                        bkg_flux_center,
                                        bkg_flux_err_center,
                                        nsim=1000)

        flux2 = np.mean(cr, axis=0) / ecf / 1e11
        flux2_mad = np.sqrt(np.mean(cr_mad**2, axis=0)) / ecf / 1e11

    if with_plots:
        scale = plot_stack(sorted_neighbours["npixel"], hp, cr, snr, plotfile,
                           scale)

        plot_radial(sorted_neighbours["npixel"], level_neighbours, hp, cr,
                    cr_mad, snr, snr_mad, plotfile)

    print_stats(cr, cr_mad, snr, snr_mad, texp, flux, flux_mad)

    if params:
        average_params = print_params(params.colnames, params_stack[:n, :])
    else:
        average_params = None

    return flux, flux_mad, flux2, flux2_mad, average_params, scale, n, nsrc
    def setcelest(self, celestin, ra_unit=u.hourangle, dec_unit=u.deg):
        """Sets the celestial coords.  Input can be a SkyCoord instance, a list or tuple of (ra,dec) or
           (ra,dec,equinox), or a character string.  If it's a character string it has to be e.g.
                 18:22:22.3  -0:18:33 
                 18:22:22.3  -0:18:33 2015
                 18 22 22.3  -0 18 33 
                 18 22 22.3  -0 18 33 2015
           specifying "ra_unit = u.deg" will accept ras.
        """

        if isinstance(celestin, SkyCoord):  # if it's a SkyCoord, just copy it.
            self.celest = celestin
        elif isinstance(celestin, tuple) or isinstance(celestin, list):  #
            if len(celestin) == 2:
                self.celest = SkyCoord(celestin[0],
                                       celestin[1],
                                       unit=(ra_unit,
                                             dec_unit))  # parse a tuple
            elif len(celestin) == 3:
                # print("celestin[2] = ",celestin[2])
                eq = float(celestin[2])
                if eq == 2000.:
                    self.celest = SkyCoord(celestin[0],
                                           celestin[1],
                                           unit=(ra_unit, dec_unit))
                else:
                    eq = "J%7.2f" % (eq)
                    self.celest = SkyCoord(celestin[0],
                                           celestin[1],
                                           unit=(ra_unit, dec_unit),
                                           frame=FK5(equinox=eq))
        elif isinstance(celestin, str):  # str includes unicode in python3.
            pieces = celest.splitin()
            if len(pieces
                   ) >= 6:  # space-separated fields - glue back together.
                rastr = pieces[0] + ":" + pieces[1] + ":" + pieces[2]
                decstr = pieces[3] + ":" + pieces[4] + ":" + pieces[5]
                if len(pieces) == 7:  # if there's an equinox ...
                    eqstr = pieces[6]
                else:
                    eqstr = '2000.'
            else:  # e.g. 21:29:36.2   so split gets ra and dec separately
                rastr = pieces[0]
                decstr = pieces[1]
                if len(pieces) > 2:
                    eqstr = pieces[2]  # if there's an equinox ...
                else:
                    eqstr = '2000.'
            # print "rastr decstr eqstr",rastr,decstr,eqstr
            if float(eqstr) == 2000.:  # default to ICRS if 2000.
                self.celest = SkyCoord(rastr, decstr, unit=(ra_unit, dec_unit))
            else:  # or set in FK5 frame of date if not 2000.
                eq = "J" + eqstr
                self.celest = SkyCoord(rastr,
                                       decstr,
                                       unit=(ra_unit, dec_unit),
                                       frame=FK5(equinox=eq))

#        print(" ************ IN SETCELEST ************ ")
#        print( "self.celest:",self.celest)
#        print( "frame.name:",self.celest.frame.name)

        if self.celest.frame.name == 'icrs' or self.celest.frame.name == 'gcrs':
            self.cel_J2000 = self.celest
        elif self.celest.frame.name == 'precessedgeocentric':
            self.cel_J2000 = self.celest.transform_to('gcrs')
        else:
            self.cel_J2000 = self.celest.transform_to('icrs')
Example #11
0
def main():

    args = parse_args()

    np.warnings.filterwarnings('ignore')

    # Find calibrator position
    calib = SkyCoord.from_name(args.calibname)

    # Put all the output from drift_scan_auto_corr.ipynb in a unique folder per source, per set of drift scans.
    datafiles = glob(args.root + '*exported_data.csv')
    datafiles.sort()
    posfiles = glob(args.root + '*hadec.csv')
    posfiles.sort()

    # Put calibrator into apparent coordinates (because that is what the telescope observes it in.)
    test = calib.transform_to('fk5')
    calibnow = test.transform_to(FK5(equinox='J{}'.format(taskid2equinox(args.taskid))))

    corr_im = []
    diff_im = []
    for beam in range(40):
        print(beam, end=' ')
        # Create the vectors which contain all data from all scans for a given beam which has been specified above.
        x, y, z_xx, z_yy = [], [], [], []
        for file, pos in zip(datafiles, posfiles):
            data = Table.read(file, format='csv')
            hadec = Table.read(pos, format='csv')
            hadec_start = SkyCoord(ra=hadec['ha'], dec=hadec['dec'], unit=(u.rad, u.rad))  # From ALTA (same as above)

            time_mjd = Time(data['time'] / (3600 * 24), format='mjd')
            lst = time_mjd.sidereal_time('apparent', westerbork().lon)

            HAcal = lst - calibnow.ra  # in sky coords
            dHAsky = HAcal - hadec_start[beam].ra + (24 * u.hourangle)  # in sky coords in hours
            dHAsky.wrap_at('180d', inplace=True)
            dHAphys = dHAsky * np.cos(hadec_start[beam].dec.deg * u.deg)  # physical offset in hours

            x = np.append(x, dHAphys.deg)
            y = np.append(y, np.full(len(dHAphys.deg), hadec_start[beam].dec.deg))
            z_xx = np.append(z_xx, data['auto_corr_beam_' + str(beam) + '_xx'] - np.median(
                data['auto_corr_beam_' + str(beam) + '_xx']))
            z_yy = np.append(z_yy, data['auto_corr_beam_' + str(beam) + '_yy'] - np.median(
                data['auto_corr_beam_' + str(beam) + '_yy']))

        # # Add a fake drift that goes to zero power at 1 deg above last scan
        # x=np.append(x,dHAphys.deg)
        # y=np.append(y,np.full(len(dHAphys.deg),max(y)+1.0))
        # z_xx=np.append(z_xx,np.full(len(dHAphys.deg),1))
        # z_yy=np.append(z_yy,np.full(len(dHAphys.deg),1))

        # # Add a fake drift that goes to zero power at 1 deg below first scan
        # x=np.append(x,dHAphys.deg)
        # y=np.append(y,np.full(len(dHAphys.deg),min(y)-1.0))
        # z_xx=np.append(z_xx,np.full(len(dHAphys.deg),1))
        # z_yy=np.append(z_yy,np.full(len(dHAphys.deg),1))

        # Create the 2D grid and do a cubic interpolation
        cell_size = 105. / 3600.
        tx = np.arange(min(x), max(x), cell_size)
        ty = np.arange(min(y), max(y), cell_size)
        XI, YI = np.meshgrid(tx, ty)
        gridcubx = interpolate.griddata((x, y), z_xx, (XI, YI), method='cubic')  # median already subtracted
        gridcuby = interpolate.griddata((x, y), z_yy, (XI, YI), method='cubic')

        # Find the reference pixel at the apparent coordinates of the calibrator
        ref_pixy = (calibnow.dec.deg - min(y)) / cell_size
        ref_pixx = (-min(x)) / cell_size

        # Find the peak of the primary beam to normalize
        norm_xx = np.max(gridcubx[int(ref_pixy)-3:int(ref_pixy)+4, int(ref_pixx)-3:int(ref_pixx)+4])
        norm_yy = np.max(gridcuby[int(ref_pixy) - 3:int(ref_pixy) + 4, int(ref_pixx) - 3:int(ref_pixx) + 4])
        if beam == 0:
            norm0_xx = np.max(gridcubx[int(ref_pixy) - 3:int(ref_pixy) + 4, int(ref_pixx) - 3:int(ref_pixx) + 4])
            norm0_yy = np.max(gridcuby[int(ref_pixy) - 3:int(ref_pixy) + 4, int(ref_pixx) - 3:int(ref_pixx) + 4])

        # Convert to decibels
        db_xx = np.log10(gridcubx/norm_xx) * 10.
        db_yy = np.log10(gridcuby/norm_yy) * 10.
        # db0_xx = np.log10(gridcubx/norm0_xx) * 10.
        # db0_yy = np.log10(gridcuby/norm0_yy) * 10.

        wcs = WCS(naxis=2)
        wcs.wcs.cdelt = np.array([-cell_size, cell_size])
        wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
        wcs.wcs.crval = [calib.ra.to_value(u.deg), calib.dec.to_value(u.deg)]
        wcs.wcs.crpix = [ref_pixx, ref_pixy]
        header = wcs.to_header()

        hdux_db = fits.PrimaryHDU(db_xx, header=header)
        hduy_db = fits.PrimaryHDU(db_yy, header=header)
        hdux = fits.PrimaryHDU(gridcubx/norm_xx, header=header)
        hduy = fits.PrimaryHDU(gridcuby/norm_yy, header=header)
        # hdulx = fits.HDUList([hdux])
        # hduly = fits.HDUList([hduy])

        # Save the FITS files
        hdux_db.writeto(args.root + '{}_{}_{:02}xx_db.fits'.format(args.calibname.replace(" ", ""), args.taskid[:-3],
                                                                   beam), overwrite=True)
        hduy_db.writeto(args.root + '{}_{}_{:02}yy_db.fits'.format(args.calibname.replace(" ", ""), args.taskid[:-3],
                                                                   beam), overwrite=True)
        hdux.writeto(args.root + '{}_{}_{:02}xx.fits'.format(args.calibname.replace(" ", ""), args.taskid[:-3],
                                                             beam), overwrite=True)
        hduy.writeto(args.root + '{}_{}_{:02}yy.fits'.format(args.calibname.replace(" ", ""), args.taskid[:-3],
                                                             beam), overwrite=True)

        fig1 = plt.figure(figsize=(6, 9))
        ax1 = fig1.add_subplot(2, 1, 1, projection=wcs.celestial)
        ax1.grid(lw=1, color='white')
        ax1.set_title("Beam {:02} - XX Correlation - Cubic".format(beam))
        ax1.set_ylabel("Declination [J2000]")
        ax1.set_xlabel("Right Ascension [J2000]")
        im1 = ax1.imshow(gridcubx/norm0_xx, vmax=0.10, vmin=-0.03, cmap='magma', animated=True)
        ax2 = fig1.add_subplot(2, 1, 2, projection=wcs.celestial)
        ax2.grid(lw=1, color='white')
        ax2.set_title("Beam {:02} - YY Correlation - Cubic".format(beam))
        ax2.set_ylabel("Declination [J2000]")
        ax2.set_xlabel("Right Ascension [J2000]")
        im2 = ax2.imshow(gridcuby/norm0_yy, vmax=0.10, vmin=-0.03, cmap='magma', animated=True)
        corr_im.append([im1, im2])
        plt.savefig(args.root + '{}_{}_{:02}db0_reconstructed.png'.format(args.calibname.replace(" ", ""),
                                                                          args.taskid, beam))
        plt.close('all')

        # Plot the difference between XX and YY for every beam
        diffcub = gridcubx/norm_xx - gridcuby/norm_yy

        fig2 = plt.figure(figsize=(10, 9))
        ax1 = fig2.add_subplot(1, 1, 1, projection=wcs.celestial)
        ax1.grid(lw=1, color='white')
        ax1.set_title("Beam {:02} - Difference (XX$-$YY)".format(beam))
        ax1.set_ylabel("Declination [J2000]")
        ax1.set_xlabel("Right Ascension [J2000]")
        ax1.scatter(ref_pixx, ref_pixy, marker='x', color='black')
        im3 = ax1.imshow(diffcub, vmin=-0.1, vmax=0.1)
        plt.colorbar(im3)
        diff_im.append([im3])
        plt.savefig(args.root + '{}_{}_{:02}_difference.png'.format(args.calibname.replace(" ", ""),
                                                                    args.taskid, beam))
        plt.close('all')

    if args.make_gifs:
        make_gifs(args.root)
Example #12
0
    def __init__(self, **kwargs):

        '''
        Possible arguments:
        - lon: Longitude (in degrees otherwise specify lon_unit as an astropy unit)
        - lat: Latitude (in degrees otherwise specify lat_unit as an astropy unit)
        - height: Altitude (in meters otherwise specify height_unit as an astropy unit)
        - time: time of the observation in unix format and in seconds or as an astropy.time.core.Time object
        - ra: Right ascension (in degrees otherwise specify coord1_unit as an astropy unit)
        - dec: Declination (in degrees otherwise specify coord2_unit as an astropy unit)
        - az: Azimuth (in degrees otherwise specify coord1_unit as an astropy unit)
        - alt: Elevation (in degrees otherwise specify coord2_unit as an astropy unit)
        - radec_frame: Frame of the Equatorial system, ICRS, current or J2000. Default is current if
                       a time is defined, otherwise is J2000
        '''

        ra = kwargs.get('ra')
        dec = kwargs.get('dec')
        if ra is not None and dec is not None:
            self.system = 'celestial'
            coord1 = ra
            coord2 = dec

        az = kwargs.get('az')
        alt = kwargs.get('alt')
        if az is not None and alt is not None:
            self.system = 'horizontal'
            coord1 = az
            coord2 = alt

        coord1_unit = kwargs.get('coord1_unit', u.degree)
        if isinstance(coord1, u.quantity.Quantity):
            self.coord1 = coord1
        else:
            self.coord1 = coord1*coord1_unit

        coord2_unit = kwargs.get('coord2_unit', u.degree)
        if isinstance(coord2, u.quantity.Quantity):
            self.coord2 = coord2
        else:
            self.coord2 = coord2*coord2_unit

        lon = kwargs.get('lon')
        lon_unit = kwargs.get('lon_unit', u.degree)
        if isinstance(lon, u.quantity.Quantity):
            self.lon = lon
        else:
            self.lon = lon*lon_unit

        lat = kwargs.get('lat')
        lat_unit = kwargs.get('lat_unit', u.degree)
        if isinstance(lat, u.quantity.Quantity):
            self.lat = lat
        else:
            self.lat = lat*lat_unit

        height = kwargs.get('height', 0.)
        height_unit = kwargs.get('height_unit', u.meter)
        if isinstance(height, u.quantity.Quantity):
            self.height = height
        else:
            self.height = height*height_unit

        time = kwargs.get('time')
        if isinstance(time, core.Time):
            self.time = Time
        else:
            if time is not None:
                self.time = Time(time*u.s, format='unix', scale='utc')
            else:
                self.time = Time('J2000')

        if time is not None:
            radec_frame = kwargs.get('radec_frame', 'current')
        else:
            radec_frame = 'j2000'

        if radec_frame.lower() == 'icrs':
            self.radec_frame = ICRS()
        elif radec_frame.lower() == 'j2000':
            self.radec_frame = FK5(equinox='j2000')
        elif radec_frame.lower() == 'current':
            time_epoch = np.mean(self.time.unix)
            self.radec_frame = FK5(equinox=Time(time_epoch, format='unix', scale='utc'))
        else:
            self.radec_frame = radec_frame

        self.location = EarthLocation(lon=self.lon, lat=self.lat, height=self.height)

        self.altaz_frame = AltAz(obstime = self.time, location = self.location)

        self.coordinates = []

        if self.system == 'celestial':
            self.coordinates = SkyCoord(self.coord1, self.coord2, frame=self.radec_frame)
        elif self.system == 'horizontal':
            self.coordinates = SkyCoord(self.coord1, self.coord2, frame=self.altaz_frame)
Example #13
0
spm_dec = '+15:20:10.84'  # penso il centro del campo, pixel 516
# Scala in gradi: 0.000138 gradi per pixel.
# Il target si trova ai pixel 430, 385
# Differenza in pixel: -82,-131 → -0.0114,0.0182 gradi

spm_jd = 2458829.827152778
spm_equinox = 'J2019.9'

spm = SkyCoord(ra=spm_ra,
               dec=spm_dec,
               obstime=Time(spm_jd, format="jd"),
               frame="fk5",
               equinox=spm_equinox,
               unit=(u.hourangle, u.deg) )

spm_2000 = spm.transform_to(FK5(equinox="J2000"))

# SIMBAD
gj = SkyCoord.from_name("GJ3470").fk5

##########################################
# Generic2
##########################################

# INIT
pattern = "gj3470/*/*/*.fit*"
filenames = glob.glob(pattern, recursive=True)
db = minidb(filenames)


keys = ["CCDXBIN"]
Example #14
0
        a = source.split(',')
        from_info = [int(a[2]), int(a[4]), int(a[5])]
        if from_file == from_info:
            ra = float(a[0])
            dec = float(a[1])
            trigger = 1
            break

    f1.close()

    if trigger == 1:  #ie if a match is detected

        ## Get Pixel Coordinates
        header = fits.getheader('./fits/' + name[:-1])
        a = WCS(header)
        c = FK5(float(ra), float(dec), unit='deg')
        output = astropy.wcs.utils.skycoord_to_pixel(c, a)  #

        pix1 = np.floor(output[0])
        pix2 = np.floor(output[1])

        # Check if the peak coincides with centre and shift if it does not.

        temp = fits.getdata('./fits/' + name[:-1])
        temp = temp[pix2 - 5:pix2 + 6, pix1 - 5:pix1 + 6]
        new_pix = np.argmax(temp)
        new_pix = np.unravel_index(new_pix, (11, 11))
        pix2 = pix2 + (new_pix[0] - 5)
        pix1 = pix1 + (new_pix[1] - 5)

        # Now with given peak value, form an image cutout
Example #15
0
def radec_to_altaz(radec: SkyCoord,
                   time: Time,
                   observer: EarthLocation = nenufar_position,
                   fast_compute: bool = True) -> SkyCoord:
    r""" Converts a celestial object equatorial coordinates
        to horizontal coordinates.

        If ``fast_compute=True`` is selected, the computation is
        accelerated using Local Sidereal Time approximation
        (see :func:`~nenupy.astro.astro_tools.local_sidereal_time`).
        The altitude :math:`\theta` and azimuth :math:`\varphi` are computed
        as follows:

        .. math::
            \cases{
                \sin(\theta) = \sin(\delta) \sin(l) + \cos(\delta) \cos(l) \cos(h)\\
                \cos(\varphi) = \frac{\sin(\delta) - \sin(l) \sin(\theta)}{\cos(l)\cos(\varphi)}
            }

        with :math:`\delta` the object's declination, :math:`l`
        the ``observer``'s latitude and :math:`h` the Local Hour Angle
        (see :func:`~nenupy.astro.astro_tools.hour_angle`).
        If :math:`\sin(h) \geq 0`, then :math:`\varphi = 2 \pi - \varphi`.
        Otherwise, :meth:`~astropy.coordinates.SkyCoord.transform_to`
        is used.

        :param radec:
            Celestial object equatorial coordinates.
        :type radec:
            :class:`~astropy.coordinates.SkyCoord`
        :param time:
            Coordinated universal time.
        :type time:
            :class:`~astropy.time.Time`
        :param observer:
            Earth location where the observer is at.
            Default is NenuFAR's position.
        :type observer:
            :class:`~astropy.coordinates.EarthLocation`
        :param fast_compute:
            If set to ``True``, it enables faster computation time for the
            conversion, mainly relying on an approximation of the
            local sidereal time. All other values would lead to
            accurate coordinates computation. Differences in
            coordinates values are of the order of :math:`10^{-2}`
            degrees or less.
        :type fast_compute:
            `bool`

        :returns:
            Celestial object's horizontal coordinates.
            If either ``radec`` or ``time`` are 1D arrays, the
            resulting object will be of shape ``(time, positions)``.
        :rtype:
            :class:`~astropy.coordinates.SkyCoord`

        :Example:
            .. code-block:: python

                from nenupy.astro import radec_to_altaz
                from astropy.time import Time
                from astropy.coordinates import SkyCoord

                altaz = radec_to_altaz(
                    radec=SkyCoord([300, 200], [45, 45], unit="deg"),
                    time=Time("2022-01-01T12:00:00"),
                    fast_compute=True
                )

    """
    if not time.isscalar:
        time = time.reshape((time.size, 1))
        radec = radec.reshape((1, radec.size))

    if fast_compute:
        radec = radec.transform_to(FK5(equinox=time))

        ha = hour_angle(radec=radec,
                        time=time,
                        observer=observer,
                        fast_compute=fast_compute)

        two_pi = Angle(360.0, unit='deg')

        ha = hour_angle(radec=radec,
                        time=time,
                        observer=observer,
                        fast_compute=fast_compute)

        sin_dec = np.sin(radec.dec.rad)
        cos_dec = np.cos(radec.dec.rad)
        sin_lat = np.sin(observer.lat.rad)
        cos_lat = np.cos(observer.lat.rad)

        # Compute elevation
        sin_elevation = sin_dec * sin_lat + cos_dec * cos_lat * np.cos(ha.rad)
        elevation = Latitude(np.arcsin(sin_elevation), unit="rad")

        # Compute azimuth
        cos_azimuth = (sin_dec - np.sin(elevation.rad)*sin_lat)/\
            (np.cos(elevation.rad)*cos_lat)
        azimuth = Longitude(np.arccos(cos_azimuth), unit="rad")

        if azimuth.isscalar:
            if np.sin(ha.rad) > 0:
                azimuth *= -1
                azimuth += two_pi
        else:
            posMask = np.sin(ha.rad) > 0
            azimuth[posMask] *= -1
            azimuth[posMask] += two_pi

        return SkyCoord(azimuth,
                        elevation,
                        frame=AltAz(obstime=time, location=observer))
    else:
        return radec.transform_to(AltAz(obstime=time, location=observer))
Example #16
0
def main():

    args = parse_args()

    np.warnings.filterwarnings('ignore')

    # Find calibrator position
    calib = SkyCoord.from_name(args.calibname)

    cell_size = 100. / 3600.
    freqchunks = 10

    # Put all the output from drift_scan_auto_corr.ipynb in a unique folder per source, per set of drift scans.
    datafiles = glob(args.root + '*_exported_data_frequency_split.csv')
    datafiles.sort()
    posfiles = glob(args.root + '*hadec.csv')
    posfiles.sort()

    # Put calibrator into apparent coordinates (because that is what the telescope observes it in.)
    test = calib.transform_to('fk5')
    calibnow = test.transform_to(
        FK5(equinox='J{}'.format(taskid2equinox(args.taskid))))

    # Read data once and be smart about how we search it.
    data_tab, hadec_tab = [], []
    print("\nReading in all the data...")
    for file, pos in zip(datafiles, posfiles):
        data_tab.append(Table.read(file, format='csv'))  # list of tables
        hadec_tab.append(Table.read(pos, format='csv'))  # list of tables

    print("Making beam maps: ", end=' ')
    for beam in range(0, 40):
        print(beam, end=' ')

        for f in range(freqchunks):
            x, y, z_xx, z_yy = [], [], [], []

            for data, hadec in zip(data_tab, hadec_tab):
                hadec_start = SkyCoord(ra=hadec['ha'],
                                       dec=hadec['dec'],
                                       unit=(u.rad, u.rad))
                time_mjd = Time(data['time'] / (3600 * 24), format='mjd')
                lst = time_mjd.sidereal_time('apparent', westerbork().lon)

                HAcal = lst - calibnow.ra  # in sky coords
                dHAsky = HAcal - hadec_start[beam].ra + (
                    24 * u.hourangle)  # in sky coords in hours
                dHAsky.wrap_at('180d', inplace=True)
                dHAphys = dHAsky * np.cos(hadec_start[beam].dec.deg *
                                          u.deg)  # physical offset in hours

                x = np.append(x, dHAphys.deg)
                y = np.append(
                    y, np.full(len(dHAphys.deg), hadec_start[beam].dec.deg))
                z_xx = np.append(
                    z_xx,
                    data['auto_corr_beam_{}_freq_{}_xx'.format(beam, f)] -
                    np.median(data['auto_corr_beam_{}_freq_{}_xx'.format(
                        beam, f)]))
                z_yy = np.append(
                    z_yy,
                    data['auto_corr_beam_{}_freq_{}_yy'.format(beam, f)] -
                    np.median(data['auto_corr_beam_{}_freq_{}_yy'.format(
                        beam, f)]))

            # Create the 2D plane, do a cubic interpolation, and append it to the cube.
            tx = np.arange(min(x), max(x), cell_size)
            ty = np.arange(min(y), max(y), cell_size)
            XI, YI = np.meshgrid(tx, ty)
            gridcubx = interpolate.griddata(
                (x, y), z_xx, (XI, YI),
                method='cubic')  # median already subtracted
            gridcuby = interpolate.griddata((x, y),
                                            z_yy, (XI, YI),
                                            method='cubic')

            # Find the reference pixel at the apparent coordinates of the calibrator
            ref_pixy = (calibnow.dec.deg -
                        min(y)) / cell_size + 1  # FITS indexed from 1
            ref_pixx = (-min(x)) / cell_size + 1  # FITS indexed from 1
            ref_pixz = 1  # FITS indexed from 1

            # Find the peak of the primary beam to normalize
            norm_xx = np.max(gridcubx[int(ref_pixy) - 3:int(ref_pixy) + 4,
                                      int(ref_pixx) - 3:int(ref_pixx) + 4])
            norm_yy = np.max(gridcuby[int(ref_pixy) - 3:int(ref_pixy) + 4,
                                      int(ref_pixx) - 3:int(ref_pixx) + 4])
            # if beam == 0:
            #     norm0_xx = np.max(gridcubx[int(ref_pixy) - 3:int(ref_pixy) + 4, int(ref_pixx) - 3:int(ref_pixx) + 4])
            #     norm0_yy = np.max(gridcuby[int(ref_pixy) - 3:int(ref_pixy) + 4, int(ref_pixx) - 3:int(ref_pixx) + 4])

            # Create 3D array with proper size for given scan set to save data as a cube
            if f == 0:
                cube_xx = np.zeros(
                    (freqchunks, gridcubx.shape[0], gridcubx.shape[1]))
                cube_yy = np.zeros(
                    (freqchunks, gridcuby.shape[0], gridcuby.shape[1]))
                db_xx = np.zeros(
                    (freqchunks, gridcubx.shape[0], gridcubx.shape[1]))
                db_yy = np.zeros(
                    (freqchunks, gridcuby.shape[0], gridcuby.shape[1]))

            cube_xx[f, :, :] = gridcubx / norm_xx
            cube_yy[f, :, :] = gridcuby / norm_yy

            # Convert to decibels
            db_xx[f, :, :] = np.log10(gridcubx / norm_xx) * 10.
            db_yy[f, :, :] = np.log10(gridcuby / norm_yy) * 10.

        stokesI = np.sqrt(0.5 * cube_yy**2 + 0.5 * cube_xx**2)
        squint = cube_xx - cube_yy

        wcs = WCS(naxis=3)
        wcs.wcs.cdelt = np.array([-cell_size, cell_size, 12.207e3 * 1500])
        wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'FREQ']
        wcs.wcs.crval = [
            calib.ra.to_value(u.deg),
            calib.dec.to_value(u.deg),
            1219.609e6 + (12.207e3 * (500 + 1500 / 2))
        ]
        wcs.wcs.crpix = [ref_pixx, ref_pixy, ref_pixz]
        wcs.wcs.specsys = 'TOPOCENT'
        wcs.wcs.restfrq = 1.420405752e+9
        header = wcs.to_header()

        # hdux_db = fits.PrimaryHDU(db_xx, header=header)
        # hduy_db = fits.PrimaryHDU(db_yy, header=header)
        hdux = fits.PrimaryHDU(cube_xx, header=header)
        hduy = fits.PrimaryHDU(cube_yy, header=header)
        hduI = fits.PrimaryHDU(stokesI, header=header)
        hdusq = fits.PrimaryHDU(squint, header=header)

        # Save the FITS files
        # hdux_db.writeto(args.root + '{}_{}_{:02}xx_db_cube.fits'.format(args.calibname.replace(" ", ""),
        #                                                                 args.taskid[:-3],
        #                                                                 beam), overwrite=True)
        # hduy_db.writeto(args.root + '{}_{}_{:02}yy_db_cube.fits'.format(args.calibname.replace(" ", ""),
        #                                                                 args.taskid[:-3],
        #                                                                 beam), overwrite=True)
        hdux.writeto(args.root + '{}_{}_{:02}xx.fits'.format(
            args.calibname.replace(" ", ""), args.taskid[:-3], beam),
                     overwrite=True)
        hduy.writeto(args.root + '{}_{}_{:02}yy.fits'.format(
            args.calibname.replace(" ", ""), args.taskid[:-3], beam),
                     overwrite=True)
        hduI.writeto(args.root + '{}_{}_{:02}_I.fits'.format(
            args.calibname.replace(" ", ""), args.taskid[:-3], beam),
                     overwrite=True)
        hdusq.writeto(args.root + '{}_{}_{:02}_diff.fits'.format(
            args.calibname.replace(" ", ""), args.taskid[:-3], beam),
                      overwrite=True)
Example #17
0
import numpy as np
from astropy.coordinates import (SkyCoord, FK5, Latitude, Angle, ICRS,
                                 concatenate, UnitSphericalRepresentation,
                                 CartesianRepresentation,
                                 match_coordinates_sky)
from astropy import units as u
from astropy.time import Time


def time_latitude():
    Latitude(3.2, u.degree)


ANGLES = Angle(np.ones(10000), u.deg)
J2010 = Time('J2010')
fk5_J2010 = FK5(equinox=J2010)
rnd = np.random.RandomState(seed=42)


def time_angle_array_repr():
    # Prior to Astropy 3.0, this was very inefficient
    repr(ANGLES)


def time_angle_array_str():
    # Prior to Astropy 3.0, this was very inefficient
    str(ANGLES)


def time_angle_array_repr_latex():
    # Prior to Astropy 3.0, this was very inefficient
Example #18
0
    mwatime = Time(dt)
    logger.info('Computing for %s=%10.0f' % (mwatime.iso, mwatime.gps))

    source = SkyCoord(ra=RA,
                      dec=Dec,
                      frame='icrs',
                      unit=(astropy.units.deg, astropy.units.deg))
    source.location = config.MWAPOS
    source.obstime = mwatime

    source_altaz = source.transform_to('altaz')
    Alt, Az = source_altaz.alt.deg, source_altaz.az.deg  # Transform to Topocentric Alt/Az at the current epoch

    if precess:
        source_now = source.transform_to(
            FK5(equinox=mwatime
                ))  # Transform to FK5 coordinates at the current epoch
        RAnow, Decnow = source_now.ra.deg, source_now.dec.deg
    else:
        RAnow, Decnow = RA, Dec

    # print "DEBUG = %s" % (Az) # different than what it was in the original version
    # print "DEBUG = %s" % (Alt)

    # go from altitude to zenith angle
    theta = (90 - Alt) * math.pi / 180
    phi = Az * math.pi / 180

    logger.info('Time (get beam): %s' % datetime.datetime.now().time())

    # BUGFIX by MS 2016-04-20 - described in details in odt document. The essence is that python reads images transposed with respect to cross-diagonal
    #  however later Tim calculates map of ra,dec then az,alt using WCS parameters which results in having coordinates for non-transposed image.
Example #19
0
 def time_init_nodata(self):
     FK5()
Example #20
0
                                (row['time_2'] - row['time_1']).to(u.h).value,
                                axis=1)
data['timespan'] = data.apply(lambda row: row['time_1'] + np.linspace(
    0, row['obs_length'], 100) * u.hour,
                              axis=1)

data['altazframe'] = data.apply(
    lambda row: AltAz(location=WSRT, obstime=row['timespan']), axis=1)
data['my_obj'] = data.apply(lambda row: SkyCoord(
    ra=row['ra'], dec=row['dec'], unit=(u.hourangle, u.deg)),
                            axis=1)
data['my_obj_altaz'] = data.apply(
    lambda row: row['my_obj'].transform_to(row['altazframe']), axis=1)

data['my_obj_fk5'] = data.apply(
    lambda row: row['my_obj'].transform_to(FK5(equinox=row['timespan'])),
    axis=1)
data['my_obj_HA'] = data.apply(lambda row: row['my_obj_fk5'].ra - row[
    'timespan'].sidereal_time('apparent', longitude=WSRT.lon),
                               axis=1)
data['LST'] = data.apply(
    lambda row: row['timespan'].sidereal_time('apparent', longitude=WSRT.lon),
    axis=1)
data['my_obj_LHA'] = data.apply(lambda row: row['timespan'].sidereal_time(
    'apparent', longitude=WSRT.lon) - row['my_obj_fk5'].ra,
                                axis=1)
data['my_obj_LHA_2'] = data.apply(lambda row: add_12(row['my_obj_LHA'].value),
                                  axis=1)

#--------------------------------------------------
# make elevation plot
Example #21
0
 def time_init_scalar(self):
     FK5(self.scalar_ra, self.scalar_dec)
Example #22
0
def get_sunset_and_sunrise(tnow, loc, refalt_set, refalt_rise):
    # Get time
    nmjd = 64
    mjd0 = np.floor(tnow.mjd)
    mnow = tnow.mjd - mjd0
    mjd = np.linspace(mjd0 - 1.0, mjd0 + 3.0, nmjd)
    t = Time(mjd, format='mjd', scale='utc')

    # Get sun position
    psun = get_sun(t)

    # Correct for precession by converting to FK5
    pos = SkyCoord(ra=psun.ra.degree,
                   dec=psun.dec.degree,
                   frame='icrs',
                   unit='deg').transform_to(FK5(equinox=t))

    # Compute altitude extrema
    de = np.mean(pos.dec)
    minalt = np.arcsin(
        np.sin(loc.lat) * np.sin(de) - np.cos(loc.lat) * np.cos(de))
    maxalt = np.arcsin(
        np.sin(loc.lat) * np.sin(de) + np.cos(loc.lat) * np.cos(de))

    # Never sets, never rises?
    if minalt > min(refalt_set, refalt_rise):
        return "sun never sets", t[0], t[0]
    elif maxalt < max(refalt_set, refalt_rise):
        return "sun never rises", t[0], t[0]

    # Prevent discontinuities in right ascension
    dra = pos[-1].ra - pos[0].ra
    ra = pos.ra.degree
    if dra < 0.0:
        c = pos.ra.degree < 180.0
        ra[c] = pos[c].ra.degree + 360.0

    # Set up interpolating function
    fra = interpolate.interp1d(t.mjd, ra)
    fde = interpolate.interp1d(t.mjd, pos.dec.degree)

    # Get GMST
    gmst0 = Time(mjd0, format='mjd',
                 scale='utc').sidereal_time('mean', 'greenwich')

    # Get transit time
    mtransit = np.mod(
        (fra(mjd0) * u.degree - loc.lon - gmst0) / (360.0 * u.degree), 1.0)
    while True:
        gmst = gmst0 + 360.985647 * u.deg * mtransit
        ra = fra(mjd0 + mtransit) * u.deg
        ha = gmst + loc.lon - ra
        mtransit -= ha / (360.0 * u.deg)
        if np.abs(ha.degree) < 1e-9:
            break

    # Hour angle offset
    ha0 = np.arccos(
        (np.sin(refalt_set) - np.sin(loc.lat) * np.sin(np.mean(pos.dec))) /
        (np.cos(loc.lat) * np.cos(np.mean(pos.dec))))

    # Get set time
    mset = mtransit + ha0 / (360.0 * u.deg)
    while True:
        gmst = gmst0 + 360.985647 * u.deg * mset
        ra = fra(mjd0 + mset) * u.deg
        de = fde(mjd0 + mset) * u.deg
        ha = gmst + loc.lon - ra
        alt = np.arcsin(
            np.sin(loc.lat) * np.sin(de) +
            np.cos(loc.lat) * np.cos(de) * np.cos(ha))
        dm = (alt - refalt_set) / (360.0 * u.deg * np.cos(de) *
                                   np.cos(loc.lat) * np.sin(ha))
        mset += dm

        # Break loop or find sunset on next day
        if np.abs(dm) < 1e-9:
            if mset >= mnow:
                break
            else:
                mset += 1.0

    # Set set time
    tset = Time(mjd0 + mset.value, format='mjd', scale='utc')

    # Get rise time
    mrise = mtransit - ha0 / (360.0 * u.deg)
    while True:
        gmst = gmst0 + 360.985647 * u.deg * mrise
        ra = fra(mjd0 + mrise) * u.deg
        de = fde(mjd0 + mrise) * u.deg
        ha = gmst + loc.lon - ra
        alt = np.arcsin(
            np.sin(loc.lat) * np.sin(de) +
            np.cos(loc.lat) * np.cos(de) * np.cos(ha))
        dm = (alt - refalt_rise) / (360.0 * u.deg * np.cos(de) *
                                    np.cos(loc.lat) * np.sin(ha))
        mrise += dm

        # Break loop or find sunrise on next day
        if np.abs(dm) < 1e-9:
            if mrise >= mnow:
                break
            else:
                mrise += 1.0

    # Set rise time
    trise = Time(mjd0 + mrise.value, format='mjd', scale='utc')

    return "sun rises and sets", tset, trise
Example #23
0
 def time_init_array(self):
     FK5(self.array_ra, self.array_dec)
    def test_overlay_coords(self, ignore_matplotlibrc, tmpdir):
        wcs = WCS(self.msx_header)

        fig = plt.figure(figsize=(4, 4))
        canvas = fig.canvas

        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs)
        fig.add_axes(ax)

        # On some systems, fig.canvas.draw is not enough to force a draw, so we
        # save to a temporary file.
        fig.savefig(tmpdir.join('test1.png').strpath)

        # Testing default displayed world coordinates
        string_world = ax._display_world_coords(0.523412, 0.518311)
        assert string_world == '0\xb029\'45" -0\xb029\'20" (world)'

        # Test pixel coordinates
        event1 = KeyEvent('test_pixel_coords', canvas, 'w')
        fig.canvas.key_press_event(event1.key, guiEvent=event1)
        string_pixel = ax._display_world_coords(0.523412, 0.523412)
        assert string_pixel == "0.523412 0.523412 (pixel)"

        event3 = KeyEvent('test_pixel_coords', canvas, 'w')
        fig.canvas.key_press_event(event3.key, guiEvent=event3)
        # Test that it still displays world coords when there are no overlay coords
        string_world2 = ax._display_world_coords(0.523412, 0.518311)
        assert string_world2 == '0\xb029\'45" -0\xb029\'20" (world)'

        overlay = ax.get_coords_overlay('fk5')

        # Regression test for bug that caused format to always be taken from
        # main world coordinates.
        overlay[0].set_major_formatter('d.ddd')

        # On some systems, fig.canvas.draw is not enough to force a draw, so we
        # save to a temporary file.
        fig.savefig(tmpdir.join('test2.png').strpath)

        event4 = KeyEvent('test_pixel_coords', canvas, 'w')
        fig.canvas.key_press_event(event4.key, guiEvent=event4)
        # Test that it displays the overlay world coordinates
        string_world3 = ax._display_world_coords(0.523412, 0.518311)

        assert string_world3 == '267.176\xb0 -28\xb045\'56" (world, overlay 1)'

        overlay = ax.get_coords_overlay(FK5())

        # Regression test for bug that caused format to always be taken from
        # main world coordinates.
        overlay[0].set_major_formatter('d.ddd')

        # On some systems, fig.canvas.draw is not enough to force a draw, so we
        # save to a temporary file.
        fig.savefig(tmpdir.join('test3.png').strpath)

        event5 = KeyEvent('test_pixel_coords', canvas, 'w')
        fig.canvas.key_press_event(event4.key, guiEvent=event4)
        # Test that it displays the overlay world coordinates
        string_world4 = ax._display_world_coords(0.523412, 0.518311)

        assert string_world4 == '267.176\xb0 -28\xb045\'56" (world, overlay 2)'

        overlay = ax.get_coords_overlay(FK5(equinox=Time("J2030")))

        # Regression test for bug that caused format to always be taken from
        # main world coordinates.
        overlay[0].set_major_formatter('d.ddd')

        # On some systems, fig.canvas.draw is not enough to force a draw, so we
        # save to a temporary file.
        fig.savefig(tmpdir.join('test4.png').strpath)

        event6 = KeyEvent('test_pixel_coords', canvas, 'w')
        fig.canvas.key_press_event(event5.key, guiEvent=event6)
        # Test that it displays the overlay world coordinates
        string_world5 = ax._display_world_coords(0.523412, 0.518311)

        assert string_world5 == '267.652\xb0 -28\xb046\'23" (world, overlay 3)'
Example #25
0
 def time_init_scalar_diff(self):
     FK5(self.scalar_ra,
         self.scalar_dec,
         pm_ra_cosdec=self.scalar_pmra,
         pm_dec=self.scalar_pmdec)
Example #26
0
    when = time.Time.now() + time.TimeDelta(60 * args.offset, format='sec')
    print('\nUT  =', when)

    # Get location
    info = SITES[args.telescope]
    site = coord.EarthLocation.from_geodetic(info['long'], info['lat'],
                                             info['height'])
    print('Lat = {:0.2f} degrees'.format(site.lat.value))
    print('Lon = {:0.2f} degrees'.format(site.lon.value))

    # Get position
    position = SkyCoord(args.position, unit=(u.hourangle, u.deg))

    lst = when.sidereal_time(kind='apparent', longitude=site.lon)
    print('LST =', lst)
    FK5_when = FK5(equinox=when)
    position_when = position.transform_to(FK5_when)
    ha = lst - position_when.ra.to(u.hourangle)
    print('HA  =', ha)

    # now convert to alt/az
    altazframe = AltAz(obstime=when, location=site)
    altaz = position_when.transform_to(altazframe)

    print('Az  = {:0.2f} degrees'.format(altaz.az.value))
    print('Alt = {:0.2f} degrees'.format(altaz.alt.value))

    # Compute latitude, alt, az, dec and ha, all in radians
    lat = math.radians(site.lat.value)
    alt = math.radians(altaz.alt.value)
    az = math.radians(altaz.az.value)
Example #27
0
def main(inp,
         survey='2r',
         radec=None,
         deci=None,
         fpath=None,
         show_circ=True,
         EPOCH=0.,
         DSS=None,
         BW=False,
         imsize=5. * astrou.arcmin,
         show_spec=False,
         OUT_TYPE='PDF'):
    '''
    Parameters:
    ---------
    inp: Input
       string or List of strings or List of several items
       'ra_dec_list.txt' -- ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
        ['NAME_OF_TARG', '10:31:38.87', '+25:59:02.3']
        ['NAME_OF_TARG', 124.24*u.deg, -23.244*u.deg]
        ['NAME_OF_TARG', SkyCoord]
    radec: integer (0) [DEPRECATED!]
       Flag indicating type of input
       0 = ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
       1 = List of string ['Name', 'RA', 'DEC']  
       2 = ['Name', ra_deg, dec_deg]
    BW: bool (False)
       B&W image?
    show_circ: bool (True)
       Show a yellow circle on the target
    show_spec: bool (False)
       Try to grab and show an SDSS spectrum 
    imsize: Quantity, optional
       Image size 
    OUT_TYPE: str, optional  
       File type -- 'PDF', 'PNG'
    '''
    reload(x_r)
    reload(xgs)
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    # Init
    if fpath is None:
        fpath = './'
    try:
        imsize = imsize.to('arcmin').value
    except AttributeError:
        raise AttributeError('finder: Input imsize needs to be an Angle')
    cradius = imsize / 50.

    # Read in the Target list
    if isinstance(inp, basestring):
        ra_tab = get_coord(targ_file, radec=radec)
    else:
        ira_tab = {}
        ira_tab['Name'] = inp[0]
        if isinstance(inp[1], basestring):
            ra, dec = x_r.stod1((inp[1], inp[2]))
            ira_tab['RA'] = ra
            ira_tab['DEC'] = dec
        elif isinstance(inp[1], float):
            ira_tab['RA'] = inp[1] * astrou.deg
            ira_tab['DEC'] = inp[2] * astrou.deg
        elif isinstance(inp[1], SkyCoord):
            ira_tab['RA'] = inp[1].ra.deg
            ira_tab['DEC'] = inp[1].dec.deg
        else:  # Should check it is a Quantity
            ira_tab['RA'] = inp[1]
            ira_tab['DEC'] = inp[2]
        # Strings
        ras, decs = x_r.dtos1((ira_tab['RA'], ira_tab['DEC']))
        ira_tab['RAS'] = ras
        ira_tab['DECS'] = decs
        # Make a list
        ra_tab = [ira_tab]

    # Grab ra, dec in decimal degrees
    if deci is not None:
        return

    #xdb.set_trace()
    #x_r.stod(ra_tab) #ra_tab['RA'][q], ra_tab['DEC'][q], TABL)

    # Precess (as necessary)
    if EPOCH > 1000.:
        from astropy import units as u
        from astropy.coordinates import FK5
        from astropy.time import Time
        # Precess to 2000.
        tEPOCH = Time(EPOCH, format='jyear', scale='utc')
        # Load into astropy
        fk5c = FK5(ra=ra_tab['RA'],
                   dec=ra_tab['DEC'],
                   equinox=tEPOCH,
                   unit=(u.degree, u.degree))
        # Precess
        newEPOCH = Time(2000., format='jyear', scale='utc')
        newfk5 = fk5c.precess_to(newEPOCH)
        # Save
        ra_tab['RA'] = newfk5.ra.degree
        ra_tab['DEC'] = newfk5.dec.degree
        # Strings too?
        ra_tab['RAS'] = str(newfk5.ra.to_string(unit=u.hour, sep=':'))
        ra_tab['DECS'] = str(newfk5.dec.to_string(unit=u.hour, sep=':'))

    ##
    # Main Loop
    for obj in ra_tab:

        # Outfil
        nm = "".join(obj['Name'].split())
        if OUT_TYPE == 'PNG':
            outfil = fpath + nm + '.png'
        else:
            outfil = fpath + nm + '.pdf'
        print(outfil)

        # Grab the Image
        reload(xgs)
        img, oBW = xgs.getimg(obj['RA'], obj['DEC'], imsize, BW=BW, DSS=DSS)

        # Generate the plot
        plt.clf()
        fig = plt.figure(dpi=1200)
        fig.set_size_inches(8.0, 10.5)

        # Font
        plt.rcParams['font.family'] = 'times new roman'
        ticks_font = matplotlib.font_manager.FontProperties(
            family='times new roman',
            style='normal',
            size=16,
            weight='normal',
            stretch='normal')
        ax = plt.gca()
        for label in ax.get_yticklabels():
            label.set_fontproperties(ticks_font)
        for label in ax.get_xticklabels():
            label.set_fontproperties(ticks_font)

        # Image
        if oBW == 1:
            cmm = cm.Greys_r
        else:
            cmm = None
        plt.imshow(img,
                   cmap=cmm,
                   aspect='equal',
                   extent=(-imsize / 2., imsize / 2, -imsize / 2., imsize / 2))

        # Axes
        plt.xlim(-imsize / 2., imsize / 2.)
        plt.ylim(-imsize / 2., imsize / 2.)

        # Label
        plt.xlabel('Relative ArcMin', fontsize=20)
        xpos = 0.12 * imsize
        ypos = 0.02 * imsize
        plt.text(-imsize / 2. - xpos, 0., 'EAST', rotation=90., fontsize=20)
        plt.text(0.,
                 imsize / 2. + ypos,
                 'NORTH',
                 fontsize=20,
                 horizontalalignment='center')

        # Title
        plt.text(0.5,
                 1.24,
                 str(nm),
                 fontsize=32,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        plt.text(0.5,
                 1.16,
                 'RA (J2000) = ' + str(obj['RAS']),
                 fontsize=28,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        plt.text(0.5,
                 1.10,
                 'DEC (J2000) = ' + str(obj['DECS']),
                 fontsize=28,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        #import pdb; pdb.set_trace()

        # Circle
        if show_circ:
            circle = plt.Circle((0, 0), cradius, color='y', fill=False)
            plt.gca().add_artist(circle)

        # Spectrum??
        if show_spec:
            spec_img = xgs.get_spec_img(obj['RA'], obj['DEC'])
            plt.imshow(spec_img,
                       extent=(-imsize / 2.1, imsize * (-0.1), -imsize / 2.1,
                               imsize * (-0.2)))

        # Write
        if show_spec:
            plt.savefig(outfil, dpi=300)
        else:
            plt.savefig(outfil)
        print 'finder: Wrote ' + outfil
        plt.close()
        #xdb.set_trace()

    print 'finder: All done.'
    return oBW