예제 #1
0
import numpy as np
import spiceypy
from spiceypy.utils import support_types as spiceytypes
import astropy.time as time
import astropy.units as u
import astropy.coordinates as astrocoords

import sunpy
import sunpy.coordinates as suncoords
import sunpy.sun.constants

# Mapping from SPICE frame name to (frame, frame kwargs)
spice_astropy_frame_mapping = {
    'IAU_SUN': (suncoords.HeliographicCarrington, {
        'observer':
        suncoords.HeliographicStonyhurst(0 * u.deg, 0 * u.deg,
                                         sunpy.sun.constants.radius)
    }),
}


def furnish(kernel):
    """
    Furnish SPICE with a kernel.

    Parameters
    ----------
    fname : `SPKKernel` or list of `SPKKernel`
        SPICE kernel(s) to load.

    See also
    --------
예제 #2
0
def overplot_aia_coords(aiaimg, pch_obj):

    plt.rcParams.update({'font.size': 16})
    aia = Map(aiaimg)

    if aia.fits_header['lvl_num'] == 1:
        aia2 = update_pointing(aia)
        aia = register(aia2)

    aia_north = pch_obj['AIA171'][0]
    #aia_north = pch_obj['AIA171'][0].resample('0.5D').median()

    n_lat = aia_north[np.abs(
        pd.to_datetime(aia_north.index).date - aia.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].N_lower_lat.values * u.rad
    n_lon = aia_north[np.abs(
        pd.to_datetime(aia_north.index).date - aia.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].N_mean_lon.values * u.rad
    times = aia_north[np.abs(
        pd.to_datetime(aia_north.index).date -
        aia.date.to_datetime().date()) <= datetime.timedelta(days=8.25)].index
    n_pts = coordinates.HeliographicStonyhurst(n_lon, n_lat, obstime=times)
    n_pts_hpc = n_pts.transform_to(aia.coordinate_frame)

    #fov = 800 * u.arcsec
    #mid_pt = n_pts_hpc[int(np.floor((len(n_pts_hpc)-1)/2))]
    #bottom_left = SkyCoord(mid_pt.Tx - fov/2, mid_pt.Ty - fov/2, frame=aia.coordinate_frame)
    #smap = aia.submap(bottom_left, width=fov, height=fov)

    #ax = plt.subplot(projection=smap)
    #smap.plot()
    #smap.draw_limb()
    #ax.grid(False)
    #ax.plot_coord(n_pts_hpc, 'x', color='deepskyblue', label='North PCH')
    #plt.legend()
    #plt.show()

    #------------------------------------

    #aia_south = pch_obj['AIA171'][1].resample('0.5D').median()
    aia_south = pch_obj['AIA171'][1]
    s_lat = aia_south[np.abs(
        pd.to_datetime(aia_south.index).date - aia.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].S_lower_lat.values * u.rad
    s_lon = aia_south[np.abs(
        pd.to_datetime(aia_south.index).date - aia.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].S_mean_lon.values * u.rad
    times = aia_south[np.abs(
        pd.to_datetime(aia_south.index).date -
        aia.date.to_datetime().date()) <= datetime.timedelta(days=8.25)].index
    s_pts = coordinates.HeliographicStonyhurst(s_lon, s_lat, obstime=times)
    s_pts_hpc = s_pts.transform_to(aia.coordinate_frame)

    # fov = 800 * u.arcsec
    # mid_pt = s_pts_hpc[int(np.floor((len(s_pts_hpc)-1)/2))]
    # bottom_left = SkyCoord(mid_pt.Tx - fov/2, mid_pt.Ty - fov/2, frame=aia.coordinate_frame)
    # smap = aia.submap(bottom_left, width=fov, height=fov)
    smap = aia

    n_zoom_coords = SkyCoord(Tx=(-200, 200) * u.arcsec,
                             Ty=(850, 1050) * u.arcsec,
                             frame=smap.coordinate_frame)
    s_zoom_coords = SkyCoord(Tx=(-500, 500) * u.arcsec,
                             Ty=(-1050, -850) * u.arcsec,
                             frame=smap.coordinate_frame)

    n_zoom = smap.submap(n_zoom_coords)
    n_zoom.data[0, 0] = smap.min()
    n_zoom.data[-1, -1] = smap.max()
    s_zoom = smap.submap(s_zoom_coords)
    s_zoom.data[0, 0] = smap.min()
    s_zoom.data[-1, -1] = smap.max()

    fig = plt.figure(figsize=(10, 10))
    ax = plt.subplot(projection=smap)
    smap.plot()
    ax.grid(False)
    ax.plot_coord(n_pts_hpc, 'x', color='cornflowerblue', label='North PCH')
    ax.plot_coord(s_pts_hpc, 'x', color='rebeccapurple', label='South PCH')
    smap.draw_quadrangle(n_zoom_coords,
                         edgecolor="white",
                         linestyle="-",
                         linewidth=2)
    smap.draw_quadrangle(s_zoom_coords,
                         edgecolor="white",
                         linestyle="-",
                         linewidth=2)
    plt.legend()
    plt.savefig('/Users/mskirk/Desktop/SWAP Paper Plots/PCH_AIA171_' +
                str(aia.date.to_datetime().date()) + '.png')

    fig2 = plt.figure(figsize=(4, 2), frameon=False)
    ax2 = plt.subplot(projection=n_zoom)
    n_zoom.plot()
    ax2.grid(False)
    ax2.set_axis_off()
    ax2.set_title('')
    ax2.plot_coord(n_pts_hpc, 'x', color='cornflowerblue', label='North PCH')
    plt.savefig('/Users/mskirk/Desktop/SWAP Paper Plots/PCH_AIA171N_' +
                str(aia.date.to_datetime().date()) + '.png')

    fig3 = plt.figure(figsize=(10, 2), frameon=False)
    ax2 = plt.subplot(projection=s_zoom)
    s_zoom.plot()
    ax2.grid(False)
    ax2.set_axis_off()
    ax2.set_title('')
    ax2.plot_coord(s_pts_hpc, 'x', color='rebeccapurple', label='South PCH')
    plt.savefig('/Users/mskirk/Desktop/SWAP Paper Plots/PCH_AIA171S_' +
                str(aia.date.to_datetime().date()) + '.png')
예제 #3
0
def overplot_swap_coords(swapimg, pch_obj):

    plt.rcParams.update({'font.size': 16})
    swap = Map(swapimg)

    swap_north = pch_obj['SWAP174'][0]
    #swap_north = pch_obj['SWAP174'][0].resample('0.5D').median()

    n_lat = swap_north[np.abs(
        pd.to_datetime(swap_north.index).date - swap.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].N_lower_lat.values * u.rad
    n_lon = swap_north[np.abs(
        pd.to_datetime(swap_north.index).date - swap.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].N_mean_lon.values * u.rad
    times = swap_north[np.abs(
        pd.to_datetime(swap_north.index).date -
        swap.date.to_datetime().date()) <= datetime.timedelta(days=8.25)].index
    n_pts = coordinates.HeliographicStonyhurst(n_lon, n_lat, obstime=times)
    n_pts_hpc = n_pts.transform_to(swap.coordinate_frame)

    #fov = 800 * u.arcsec
    #mid_pt = n_pts_hpc[int(np.floor((len(n_pts_hpc)-1)/2))]
    #bottom_left = SkyCoord(mid_pt.Tx - fov/2, mid_pt.Ty - fov/2, frame=swap.coordinate_frame)
    #smap = swap.submap(bottom_left, width=fov, height=fov)

    #ax = plt.subplot(projection=smap)
    #smap.plot()
    #smap.draw_limb()
    #ax.grid(False)
    #ax.plot_coord(n_pts_hpc, 'x', color='deepskyblue', label='North PCH')
    #plt.legend()
    #plt.show()

    #------------------------------------

    #swap_south = pch_obj['SWAP174'][1].resample('0.5D').median()
    swap_south = pch_obj['SWAP174'][1]
    s_lat = swap_south[np.abs(
        pd.to_datetime(swap_south.index).date - swap.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].S_lower_lat.values * u.rad
    s_lon = swap_south[np.abs(
        pd.to_datetime(swap_south.index).date - swap.date.to_datetime().date()
    ) <= datetime.timedelta(days=8.25)].S_mean_lon.values * u.rad
    times = swap_south[np.abs(
        pd.to_datetime(swap_south.index).date -
        swap.date.to_datetime().date()) <= datetime.timedelta(days=8.25)].index
    s_pts = coordinates.HeliographicStonyhurst(s_lon, s_lat, obstime=times)
    s_pts_hpc = s_pts.transform_to(swap.coordinate_frame)

    fov = 2454 * u.arcsec
    mid_pt = s_pts_hpc[int(np.floor((len(s_pts_hpc) - 1) / 2))]
    #bottom_left = SkyCoord(mid_pt.Tx - fov/2, mid_pt.Ty - fov/2, frame=swap.coordinate_frame)
    bottom_left = SkyCoord(-fov / 2, -fov / 2, frame=swap.coordinate_frame)
    smap = swap.submap(bottom_left, width=fov, height=fov)

    n_zoom_coords = SkyCoord(Tx=(-200, 200) * u.arcsec,
                             Ty=(850, 1050) * u.arcsec,
                             frame=smap.coordinate_frame)
    s_zoom_coords = SkyCoord(Tx=(-500, 500) * u.arcsec,
                             Ty=(-1050, -850) * u.arcsec,
                             frame=smap.coordinate_frame)

    #Contrast Adjustment
    p2, p99 = np.percentile(smap.data, (2, 99))
    img_rescale = exposure.rescale_intensity(smap.data, in_range=(p2, p99))
    smap.data[:] = img_rescale

    n_zoom = smap.submap(n_zoom_coords)
    n_zoom.data[0, 0] = smap.min()
    n_zoom.data[-1, -1] = smap.max()
    s_zoom = smap.submap(s_zoom_coords)
    s_zoom.data[0, 0] = smap.min()
    s_zoom.data[-1, -1] = smap.max()

    fig = plt.figure(figsize=(10, 10))
    ax = plt.subplot(projection=smap)
    smap.plot()
    ax.grid(False)
    ax.plot_coord(n_pts_hpc, 'x', color='cornflowerblue', label='North PCH')
    ax.plot_coord(s_pts_hpc, 'x', color='rebeccapurple', label='South PCH')
    smap.draw_quadrangle(n_zoom_coords,
                         edgecolor="white",
                         linestyle="-",
                         linewidth=2)
    smap.draw_quadrangle(s_zoom_coords,
                         edgecolor="white",
                         linestyle="-",
                         linewidth=2)
    plt.legend()
    plt.savefig('/Users/mskirk/Desktop/SWAP Paper Plots/PCH_SWAP174_' +
                str(swap.date.to_datetime().date()) + '.png')

    fig2 = plt.figure(figsize=(4, 2), frameon=False)
    ax2 = plt.subplot(projection=n_zoom)
    n_zoom.plot()
    ax2.grid(False)
    ax2.set_axis_off()
    ax2.set_title('')
    ax2.plot_coord(n_pts_hpc, 'x', color='cornflowerblue', label='North PCH')
    plt.savefig('/Users/mskirk/Desktop/SWAP Paper Plots/PCH_SWAP174N_' +
                str(swap.date.to_datetime().date()) + '.png')

    fig3 = plt.figure(figsize=(10, 2), frameon=False)
    ax2 = plt.subplot(projection=s_zoom)
    s_zoom.plot()
    ax2.grid(False)
    ax2.set_axis_off()
    ax2.set_title('')
    ax2.plot_coord(s_pts_hpc, 'x', color='rebeccapurple', label='South PCH')
    plt.savefig('/Users/mskirk/Desktop/SWAP Paper Plots/PCH_SWAP174S_' +
                str(swap.date.to_datetime().date()) + '.png')
예제 #4
0
def find_carr_coords(cme_root, craft, c1cme, eucme):
    """ Function to calculate carrington longitude and latitude of events in
    eucme and add these to the dataframe. These are used to create plots of
    each event.
    """
    # Find the euvi fits files
    if craft == 'A':
        fn_tag = '*eua.fts'
    elif craft == 'B':
        fn_tag = '*eub.fts'

    # Calculate Carrington Longitudes and Latitudes of source locations
    eucme['carrington_longitude'] = pd.Series(np.zeros(len(eucme)) * np.NaN,
                                              index=eucme.index)
    eucme['carrington_latitude'] = pd.Series(np.zeros(len(eucme)) * np.NaN,
                                             index=eucme.index)
    for i in range(len(eucme)):
        print i
        cme_root_new = r'/home/sq112614/SS/Images/EUVI/ST' + craft
        cme_root2 = cme_root_new + '/cme_' + '{0:02d}'.format(i + 1)
        euvi_files = find_files(cme_root2, fn_tag)
        print len(euvi_files)
        if len(euvi_files) > 0:
            print '**********'
            print cme_root2
            print euvi_files
            # Files exist, load in the subpy map to work out carrington coordinates
            euvi = smap.Map(euvi_files[0])
            # Convert the 256x256 coordinates into correctly scaled coordinates
            xn = eucme['l'][i] + eucme['w'][i] / 2
            yn = eucme['b'][i] + eucme['h'][i] / 2
            xn = (xn / 256) * euvi.dimensions[0]
            yn = euvi.dimensions[1] - (yn / 256) * euvi.dimensions[1]

            # Get HPC and HPR coords
            lon, lat = HPC_LONLAT(euvi)
            el, pa = HPC_to_HPR(lon.to('deg').value, lat.to('deg').value)
            # Get Carrington coords:
            cf = euvi.coordinate_frame
            hpc = spc.Helioprojective(Tx=lon,
                                      Ty=lat,
                                      D0=cf.D0,
                                      B0=cf.B0,
                                      L0=cf.L0,
                                      representation=cf.representation)
            hcc = spc.Heliocentric(D0=cf.D0, B0=cf.B0, L0=cf.L0)
            hcc = spc.hpc_to_hcc(hpc, hcc)
            hgs = spc.HeliographicStonyhurst(dateobs=cf.dateobs)
            hgc = spc.HeliographicCarrington(dateobs=cf.dateobs)
            hgs = spc.hcc_to_hgs(hcc, hgs)
            hgc = spc.hgs_to_hgc(hgs, hgc)

            # Try looking up carrington coordinates
            idy = np.int(np.round(yn.value))
            idx = np.int(np.round(xn.value))
            hgc_lon = hgc.lon[idy, idx]
            hgc_lat = hgc.lat[idy, idx]
            # If returned NaNs extrapolate to limb
            if np.logical_or(np.isnan(hgc_lon), np.isnan(hgc_lat)):
                print('Limb Extrapolation')
                # Get elongation of Limb
                el_limb = np.arctan(0.99 * euvi.rsun_meters /
                                    euvi.dsun).to('deg')
                # Get position angle of point
                ppa = pa[idy, idx]
                # Find pixel best matching this elongation and pa
                pa_diff = np.abs(pa - ppa)
                el_diff = np.abs(el - el_limb)
                diff = np.sqrt(pa_diff**2 + el_diff**2)
                idy, idx = np.unravel_index(np.argmin(diff), diff.shape)
                hgc_lon = hgc.lon[idy, idx]
                hgc_lat = hgc.lat[idy, idx]

            # Make sure hgc lon runs between 0 and 360, rather than -180, 180
            if hgc_lon.value < 0:
                hgc_lon = 360 * u.deg + hgc_lon

            euvi.peek()
            plt.contour(pa.value, levels=[c1cme['pa'][i]], colors=['r'])
            plt.plot(xn.value, yn.value, 'yo', markersize=12)
            plt.plot(idx, idy, 'y*', markersize=12)
            plt.contour(hgc.lon.value, colors=['white'])
            plt.contour(hgc.lat.value, colors=['m'])
            plt.draw()
            name = cme_root2 + r'\euvi_eruption_id.png'
            plt.savefig(name)
            plt.close('all')
            # Mark out the coords for chucking in the array
            eucme.loc[eucme.index == i, 'carrington_longitude'] = hgc_lon.value
            eucme.loc[eucme.index == i, 'carrington_latitude'] = hgc_lat.value
    return eucme