Example #1
0
def submap(mc, range_a, range_b, **kwargs):
    """
    Parameters
    ----------
    mc : sunpy.map.MapCube
       A sunpy mapcube object

    range_a : list


    range_b : list

    Returns
    -------
    sunpy.map.MapCube
       A mapcube containing maps that have had the map submap
       method applied to each layer.
    """
    nmc = len(mc)
    if (len(range_a) == nmc) and (len(range_b) == nmc):
        ra = range_a
        rb = range_b
    elif (len(range_a) == 1) and (len(range_b) == 1):
        ra = [range_a for i in range(0, nmc)]
        rb = [range_b for i in range(0, nmc)]
    else:
        raise ValueError('Both input ranges must be either of size 1 or size '
                         'equal to the number of maps in the mapcube')

    # Storage for the returned maps
    maps = []
    for im, m in enumerate(mc):
        maps.append(Map.submap(m, ra[im], rb[im], **kwargs))
    # Create the new mapcube and return
    return Map(maps, cube=True)
Example #2
0
def plot_aia_channels(aia,
                      time: u.s,
                      root_dir,
                      corners=None,
                      figsize=None,
                      norm=None,
                      fontsize=14,
                      **kwargs):
    """
    Plot maps of the EUV channels of AIA for a given timestep

    Parameters
    ----------
    aia : `synthesizAR.instruments.InstrumentSDOAIA`
    time : `astropy.Quantity`
    root_dir : `str`
    figsize : `tuple`, optional
    """
    if figsize is None:
        figsize = (15, 10)
    if norm is None:
        norm = matplotlib.colors.SymLogNorm(1e-6, vmin=1, vmax=5e3)
    with h5py.File(aia.counts_file, 'r') as hf:
        reference_time = u.Quantity(hf['time'], hf['time'].attrs['unit'])
    i_time = np.where(reference_time == time)[0][0]
    fig_format = os.path.join(root_dir, f'{aia.name}', '{}',
                              f'map_t{i_time:06d}.fits')
    fig = plt.figure(figsize=figsize)
    plt.subplots_adjust(wspace=0., hspace=0., top=0.95)
    ims = {}
    for i, channel in enumerate(aia.channels):
        tmp = Map(fig_format.format(channel['name']))
        if corners is not None:
            blc = SkyCoord(*corners[0], frame=tmp.coordinate_frame)
            trc = SkyCoord(*corners[1], frame=tmp.coordinate_frame)
            tmp = tmp.submap(blc, trc)
        ax = fig.add_subplot(2, 3, i + 1, projection=tmp)
        ims[channel['name']] = tmp.plot(annotate=False, title=False, norm=norm)
        lon, lat = ax.coords
        lon.grid(alpha=0)
        lat.grid(alpha=0)
        if i % 3 == 0:
            lat.set_axislabel(r'solar-y [arcsec]', fontsize=fontsize)
        else:
            lat.set_ticks_visible(False)
            lat.set_ticklabel_visible(False)
        if i > 2:
            lon.set_axislabel(r'solar-x [arcsec]', fontsize=fontsize)
        else:
            lon.set_ticks_visible(False)
            lon.set_ticklabel_visible(False)
        ax.text(0.1 * tmp.dimensions.x.value,
                0.9 * tmp.dimensions.y.value,
                r'${}$ $\mathrm{{\mathring{{A}}}}$'.format(channel['name']),
                color='w',
                fontsize=fontsize)
    fig.suptitle(r'$t={:.0f}$ {}'.format(time.value, time.unit.to_string()),
                 fontsize=fontsize)
    if kwargs.get('use_with_animation', False):
        return fig, ims
Example #3
0
def submap(mc, range_a, range_b, **kwargs):
    """
    Parameters
    ----------
    mc : sunpy.map.MapCube
       A sunpy mapcube object

    range_a : list


    range_b : list

    Returns
    -------
    sunpy.map.MapCube
       A mapcube containing maps that have had the map submap
       method applied to each layer.
    """
    nmc = len(mc)
    if (len(range_a) == nmc) and (len(range_b) == nmc):
        ra = range_a
        rb = range_b
    elif (len(range_a) == 1) and (len(range_b) == 1):
        ra = [range_a for i in range(0, nmc)]
        rb = [range_b for i in range(0, nmc)]
    else:
        raise ValueError('Both input ranges must be either of size 1 or size '
                         'equal to the number of maps in the mapcube')

    # Storage for the returned maps
    maps = []
    for im, m in enumerate(mc):
        maps.append(Map.submap(m, ra[im], rb[im], **kwargs))
    # Create the new mapcube and return
    return Map(maps, cube=True)
Example #4
0
    def calculate_em(self, wlen='171', dz=100, model=False):
        """
        Calculate an approximation of the coronal EmissionMeasure using a given
        TemperatureMap object and a particular AIA channel.
    
        Parameters
        ----------
        tmap : CoronaTemps.temperature.TemperatureMap
            A TemperatureMap instance containing coronal temperature data
        wlen : {'94' | '131' | '171' | '193' | '211' | '335'}
            AIA wavelength used to approximate the emission measure. '171', '193'
            and '211' are most likely to provide reliable results. Use of other
            channels is not recommended.
        """
        # Load the appropriate temperature response function
        tresp = read('/imaps/holly/home/ajl7/CoronaTemps/aia_tresp')
        resp = tresp['resp{}'.format(wlen)]
    
        # Get some information from the TemperatureMap and set up filenames, etc
        tempdata = self.data.copy()
        tempdata[np.isnan(tempdata)] = 0.0
        date = sunpy.time.parse_time(self.date)
        if not model:
            data_dir = self.data_dir
            fits_dir = path.join(data_dir, '{:%Y/%m/%d}/{}'.format(date, wlen))
            filename = path.join(fits_dir,
                                 '*{0:%Y?%m?%d}?{0:%H?%M}*fits'.format(date))
            if wlen == '94': filename = filename.replace('94', '094')
    
            # Load and appropriately process AIA data
            filelist = glob.glob(filename)
            if filelist == []:
                print 'AIA data not found :('
                return
            aiamap = Map(filename)
            aiamap.data /= aiamap.exposure_time
            aiamap = aiaprep(aiamap)
            aiamap = aiamap.submap(self.xrange, self.yrange)
        else:
            fname = '/imaps/holly/home/ajl7/CoronaTemps/data/synthetic/{}/model.fits'.format(wlen)
            if wlen == '94': fname = fname.replace('94', '094')
            aiamap = Map(fname)

        # Create new Map and put EM values in it
        emmap = Map(self.data.copy(), self.meta.copy())
        indices = np.round((tempdata - 4.0) / 0.05).astype(int)
        indices[indices < 0] = 0
        indices[indices > 100] = 100
        #print emmap.shape, indices.shape, tempdata.shape, aiamap.shape, resp.shape
        emmap.data = np.log10(aiamap.data / resp[indices])
        #emmap.data = aiamap.data / resp[indices]

        emmapcubehelix = _cm.cubehelix(s=2.8, r=-0.7, h=1.4, gamma=1.0)
        cm.register_cmap(name='emhelix', data=emmapcubehelix)
        emmap.cmap = cm.get_cmap('emhelix')
    
        return emmap
Example #5
0
    def compare(self, display_wlen='171', context_wlen=None, extra_maps=[]):
        #        temp_args=None, temp_kwargs=None,
        #        wlen_args=None, wlen_kwargs=None,
        #        ctxt_args=None, ctxt_kwargs=None,
        #        extr_args=None, extr_kwargs=None):
        valid_wlens = ['94', '131', '171', '195', '211', '335', '304', 'hmi']
        if display_wlen.lower() not in valid_wlens:
            print "Display wavelength provided invalid or None."
            output = self.plot()  #*temp_args, **temp_kwargs)
            return output
        save_output = True
        data_dir = self.data_dir
        maps_dir = self.maps_dir

        date = self.date
        nmaps = 2 + len(extra_maps)
        if context_wlen:
            nrows = 2
        else:
            nrows = 1

        fig = plt.figure(figsize=(24, 14))

        fig.add_subplot(nrows, nmaps, nmaps, axisbg='k')
        self.plot()  #*temp_args, **temp_kwargs)
        plt.colorbar(orientation='horizontal')

        displaymap = Map(data_dir+'{0}/{1:%Y/%m/%d}/aia*{0}*t{1:%H?%M}*lev1?fits'\
            .format(display_wlen, date))
        if isinstance(displaymap, list):
            displaymap = displaymap[0]
        displaymap = aiaprep(displaymap)
        displaymap /= displaymap.exposure_time

        fig.add_subplot(nrows, nmaps, 1, axisbg='k')
        displaymap.plot()  #*wlen_args, **wlen_kwargs)
        plt.colorbar(orientation='horizontal')

        if context_wlen and self.region != None:
            context_plot = fig.add_subplot(nrows, 1, nrows)
            contextmap = Map(data_dir +
                             '{0}/{1:%Y/%m/%d}/aia*{0}*t{1:%H?%M}*lev1?fits'.
                             format(context_wlen, date))
            if isinstance(contextmap, list):
                contextmap = contextmap[0]
            x, y = self.region_coordinate['x'], self.region_coordinate['y']
            contextmap = contextmap.submap([-1000, 1000], [y - 300, y + 300])
            # Need to figure out how to get 'subimsize' from self. Use the default 150'' for now
            #rect = patches.Rectangle([x-subdx, y-subdx], subimsize[0], subimsize[1], color='white', fill=False)
            rect = patches.Rectangle([x - 150, y - 150],
                                     300,
                                     300,
                                     color='white',
                                     fill=False)
            contextmap.plot()  #*ctxt_args, **ctxt_kwargs)
            context_plot.add_artist(rect)

        for m, thismap in extra_maps:
            fig.add_subplot(nrows, nmaps, 3 + m)
            thismap.plot()  #*extr_args, **extr_kwargs)

        if save_output:
            error = sys('touch ' + maps_dir +
                        'maps/{:%Y/%m/%d/} > shelloutput.txt'.format(date))
            if error != 0:
                sys('{0}{1:%Y}; {0}{1:%Y/%m}; {0}{1:%Y/%m/%d} > shelloutput.txt'\
                        .format('mkdir '+maps_dir+'maps/', date))
            filename = maps_dir+'maps/{:%Y/%m/%d/%Y-%m-%dT%H:%M:%S}_with{}'.\
                    format(date, display_wlen)
            plt.savefig(filename)
            if self.region != None:
                reg_dir = maps_dir + 'maps/region_maps'
                reg_dir = reg_dir + '/{}/'.format(self.region)
                error = sys('touch ' + reg_dir + ' > shelloutput.txt')
                if error != 0:
                    sys('mkdir ' + reg_dir + ' > shelloutput.txt')
                plt.savefig(reg_dir + '{:%Y-%m-%dT%H:%M:%S}'.format(date))
            plt.close()
        else:
            plt.show()

        return
Example #6
0
    def compare(self, display_wlen='171', context_wlen=None, extra_maps=[]):
        #        temp_args=None, temp_kwargs=None,
        #        wlen_args=None, wlen_kwargs=None,
        #        ctxt_args=None, ctxt_kwargs=None,
        #        extr_args=None, extr_kwargs=None):
        valid_wlens = ['94', '131', '171', '195', '211', '335', '304', 'hmi']
        if display_wlen.lower() not in valid_wlens:
            print "Display wavelength provided invalid or None."
            output = self.plot()#*temp_args, **temp_kwargs)
            return output
        save_output = True
        data_dir = self.data_dir
        maps_dir = self.maps_dir
        
        date = self.date
        nmaps = 2 + len(extra_maps)
        if context_wlen:
            nrows = 2
        else:
            nrows = 1
        
        fig = plt.figure(figsize=(24, 14))
        
        fig.add_subplot(nrows, nmaps, nmaps, axisbg='k')
        self.plot()#*temp_args, **temp_kwargs)
        plt.colorbar(orientation='horizontal')
        
        displaymap = Map(data_dir+'{0}/{1:%Y/%m/%d}/aia*{0}*t{1:%H?%M}*lev1?fits'\
            .format(display_wlen, date))
        if isinstance(displaymap, list):
            displaymap = displaymap[0]
        displaymap = aiaprep(displaymap)
        displaymap /= displaymap.exposure_time
        
        fig.add_subplot(nrows, nmaps, 1, axisbg='k')
        displaymap.plot()#*wlen_args, **wlen_kwargs)
        plt.colorbar(orientation='horizontal')
        
        if context_wlen and self.region != None:
            context_plot = fig.add_subplot(nrows, 1, nrows)
            contextmap = Map(data_dir+'{0}/{1:%Y/%m/%d}/aia*{0}*t{1:%H?%M}*lev1?fits'.format(context_wlen, date))
            if isinstance(contextmap, list):
                contextmap = contextmap[0]
            x, y = self.region_coordinate['x'], self.region_coordinate['y']
            contextmap = contextmap.submap([-1000, 1000], [y-300, y+300])
            # Need to figure out how to get 'subimsize' from self. Use the default 150'' for now
            #rect = patches.Rectangle([x-subdx, y-subdx], subimsize[0], subimsize[1], color='white', fill=False)
            rect = patches.Rectangle([x-150, y-150], 300, 300, color='white',
                                     fill=False)
            contextmap.plot()#*ctxt_args, **ctxt_kwargs)
            context_plot.add_artist(rect)
        
        for m, thismap in extra_maps:
            fig.add_subplot(nrows, nmaps, 3+m)
            thismap.plot()#*extr_args, **extr_kwargs)
        
        if save_output:
            error = sys('touch '+maps_dir+'maps/{:%Y/%m/%d/} > shelloutput.txt'.format(date))
            if error != 0:
                sys('{0}{1:%Y}; {0}{1:%Y/%m}; {0}{1:%Y/%m/%d} > shelloutput.txt'\
                        .format('mkdir '+maps_dir+'maps/', date))
            filename = maps_dir+'maps/{:%Y/%m/%d/%Y-%m-%dT%H:%M:%S}_with{}'.\
                    format(date, display_wlen)
            plt.savefig(filename)
            if self.region != None:
                reg_dir = maps_dir + 'maps/region_maps'
                reg_dir = reg_dir + '/{}/'. format(self.region)
                error = sys('touch ' + reg_dir + ' > shelloutput.txt')
                if error != 0:
                    sys('mkdir ' + reg_dir + ' > shelloutput.txt')
                plt.savefig(reg_dir+'{:%Y-%m-%dT%H:%M:%S}'.format(date))
            plt.close()
        else:
            plt.show()

        return
Example #7
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')
Example #8
0
aia = Map(s.AIA_171_IMAGE)

fig, axs = plt.subplots(1, 1)
aia.plot(axes=axs[0])
aia.draw_grid()

pixel_size = 3.4
number_of_pixels = 160

center = np.array([461, 303])
smap = aia.submap(
    Quantity([
        center[0] - pixel_size * number_of_pixels / 2.,
        center[0] + pixel_size * number_of_pixels / 2.
    ], 'arcsec'),
    Quantity([
        center[1] - pixel_size * number_of_pixels / 2.,
        center[1] + pixel_size * number_of_pixels / 2.
    ], 'arcsec'))
smap.plot()

#plate scale for this image is 1.3 arcsec
#plate scale for AIA image is 1.4 arcsec which is very close
psf = np.fromfile('onaxis_psf.dat', dtype=np.float32).reshape(53, 53)
psf /= psf.sum()

r = scipy.signal.convolve2d(smap.data, psf, mode='same')

smap.data = r
smap.plot()
Example #9
0
import sunpy.data.sample as s
import numpy as np
from astropy.units import Quantity
import scipy.signal

aia = Map(s.AIA_171_IMAGE)

fig, axs = plt.subplots(1,1)
aia.plot(axes=axs[0])
aia.draw_grid()

pixel_size = 3.4
number_of_pixels = 160

center = np.array([461, 303])
smap = aia.submap(Quantity([center[0] - pixel_size * number_of_pixels/2., center[0] + pixel_size * number_of_pixels/2.], 'arcsec'),
                  Quantity([center[1] - pixel_size * number_of_pixels/2., center[1] + pixel_size * number_of_pixels/2.], 'arcsec'))
smap.plot()

#plate scale for this image is 1.3 arcsec
#plate scale for AIA image is 1.4 arcsec which is very close
psf = np.fromfile('onaxis_psf.dat', dtype=np.float32).reshape(53,53)
psf /= psf.sum()

r = scipy.signal.convolve2d(smap.data, psf, mode='same')

smap.data = r
smap.plot()

new_dim = int(smap.dimensions.x.value * smap.scale.x.value / pixel_size)

rmap = smap.resample(Quantity([new_dim, new_dim], 'pix'), method='spline')
Example #10
0
def prepData(files, base_dir, prefix, custom_keywords={}, plot=False):
    diffs = {'center_x': [], 'center_y': [], 'radius': [], 'scale': []}
    os.makedirs(os.path.join(base_dir, 'level1'), exist_ok=True)
    os.makedirs(os.path.join(base_dir, 'level1_5'), exist_ok=True)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        for file in tqdm(files):
            try:
                # load existing file
                hdul = fits.open(file)
                hdu = hdul[0]
                hdu.verify('fix')
                d, h = hdu.data, hdu.header

                # set custom keywords
                h.update(custom_keywords)

                # evaluate center and radius
                imsave("demo.jpg", d)
                myCmd = os.popen(
                    '/home/rja/PythonProjects/SpringProject/spring/limbcenter/sunlimb demo.jpg'
                ).read()
                center_x, center_y, radius, d_radius = map(
                    float, myCmd.splitlines())

                if "EXPTIME" in h:
                    h['EXP_TIME'] = h['EXPTIME']
                    del h['EXPTIME']
                if 'TIME-OBS' in h:
                    obs_date = datetime.strptime(
                        h['DATE-OBS'] + 'T' + h['TIME-OBS'],
                        "%m/%d/1%yT%H:%M:%S")
                    h['DATE-OBS'] = obs_date.isoformat()
                    del h["TIME-OBS"]
                if 'TIME' in h:
                    obs_date = datetime.strptime(
                        h['DATE-OBS'] + 'T' + h['TIME'], "%d/%m/%YT%H:%M:%S")
                    h['DATE-OBS'] = obs_date.isoformat()
                    del h["TIME"]

                obs_time = parse(h["DATE-OBS"])
                rsun = angular_radius(obs_time)
                b0_angle = sun.B0(obs_time)
                l0 = sun.L0(obs_time)
                p_angle = sun.P(obs_time)
                filename = "%s_%s_fi_%s.fits" % (
                    prefix, h["OBS_TYPE"].lower(),
                    obs_time.strftime("%Y%m%d_%H%M%S"))

                # prepare existing header information
                if "ANGLE" not in h:
                    h["ANGLE"] = p_angle.value

                scale = rsun / (radius * u.pix)
                coord = SkyCoord(0 * u.arcsec,
                                 0 * u.arcsec,
                                 obstime=obs_time,
                                 observer='earth',
                                 frame=frames.Helioprojective)

                # create WCS header info
                header = header_helper.make_fitswcs_header(
                    d,
                    coord,
                    rotation_angle=h["ANGLE"] * u.deg,
                    reference_pixel=u.Quantity([center_x, center_y] * u.pixel),
                    scale=u.Quantity([scale, scale]),
                    instrument=h["INSTRUME"],
                    telescope=h["TELESCOP"],
                    observatory=h["OBSVTRY"],
                    exposure=h["EXP_TIME"] * u.ms,
                    wavelength=h["WAVELNTH"] * u.angstrom)

                header["KEYCOMMENTS"] = {
                    "EXPTIME": "[s] exposure time in seconds",
                    "DATE": "file creation date (YYYY-MM-DDThh:mm:ss UT)",
                    "DATE-OBS": "date of observation",
                    "WAVELNTH": "[Angstrom] wavelength",
                    "BANDPASS": "******",
                    "WAVEMIN": "[Angstrom] minimum wavelength",
                    "WAVEMAX": "[Angstrom] maximum wavelength",
                    "BZERO": "offset data range to that of unsigned short",
                    "CDELT1": "[arcsec/pix]",
                    "CDELT2": "[arcsec/pix]",
                    "SOLAR_R": "[pix]",
                    "DSUN_OBS": "[m]",
                    "RSUN_REF": "[m]",
                    "RSUN_ARC": "[%s]" % rsun.unit,
                    "ANGLE": "[deg]",
                    "SOLAR_P": "[%s]" % p_angle.unit,
                    "SOLAR_L0": "[%s]" % l0.unit,
                    "SOLAR_B0": "[%s]" % b0_angle.unit,
                    'SIMPLE': 'file does conform to FITS standard',
                    'BITPIX': 'number of bits per data pixel',
                    'CUNIT1': '[arcsec]',
                    'CUNIT2': '[arcsec]',
                    'CRVAL1': 'coordinate system value at reference pixel',
                    'CRVAL2': 'coordinate system value at reference pixel',
                    'CTYPE1': 'name of the coordinate axis',
                    'CTYPE2': 'name of the coordinate axis',
                    'INSTRUME': 'name of instrument',
                    'TELESCOP': 'name of telescope',
                    'OBSVTRY': 'name of observatory',
                }

                # set constants and default values
                header["FILENAME"] = filename
                header["DATE"] = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

                header["SOLAR_R"] = radius
                header["RSUN_ARC"] = rsun.value
                header["SOLAR_P"] = p_angle.value
                header["SOLAR_L0"] = l0.value
                header["SOLAR_B0"] = b0_angle.value

                header["DATAMIN"] = np.min(d)
                header["DATAMEAN"] = np.mean(d)
                header["DATAMAX"] = np.max(d)

                # copy existing keys
                for key, value in h.items():
                    if key not in header:
                        header[key] = value

                # copy comments
                for key, value in zip(list(h.keys()), list(h.comments)):
                    if key not in header["KEYCOMMENTS"]:
                        header["KEYCOMMENTS"][key] = value

                # LEVEL 1
                s_map = Map(d.astype(np.float32), header)
                level1_path = os.path.join(base_dir, 'level1', filename)

                h.add_history("unified FITS header")
                s_map.meta["HISTORY"] = h["HISTORY"]
                s_map.meta["LVL_NUM"] = "1.0"
                s_map = Map(s_map.data.astype(np.float32), s_map.meta)
                s_map.save(level1_path, overwrite=True)

                # LEVEL 1.5
                scale = s_map.scale[0].value
                s_map = padScale(s_map)

                s_map = s_map.rotate(
                    recenter=True,
                    scale=scale,
                    missing=s_map.min(),
                )
                center = np.floor(s_map.meta['crpix1'])
                range_side = (center + np.array([-1, 1]) * 2048 / 2) * u.pix
                s_map = s_map.submap(
                    u.Quantity([range_side[0], range_side[0]]),
                    u.Quantity([range_side[1], range_side[1]]))
                level1_5_path = os.path.join(base_dir, 'level1_5', filename)

                h.add_history("recentered and derotated")
                s_map.meta["HISTORY"] = h["HISTORY"]
                s_map.meta["LVL_NUM"] = "1.5"
                s_map = Map(s_map.data.astype(np.float32), s_map.meta)
                s_map.save(level1_5_path, overwrite=True)

                if plot:
                    s_map.plot()
                    s_map.draw_grid()
                    plt.savefig(level1_5_path.replace(".fits", ".jpg"))
                    plt.close()

                # check header
                hdul = fits.open(level1_5_path)
                hdu = hdul[0]
                hdu.verify('exception')

                # evaluate difference
                if 'center_x' in h and not isinstance(h["center_x"], str):
                    diffs['center_x'].append(
                        np.abs(h['center_x'] - header['crpix1']))
                if 'center_y' in h and not isinstance(h["center_y"], str):
                    diffs['center_y'].append(
                        np.abs(h['center_y'] - header['crpix2']))
                if 'SOLAR_R' in h and not isinstance(h["SOLAR_R"], str):
                    diffs['radius'].append(
                        np.abs(h['SOLAR_R'] - header['SOLAR_R']))
                if 'cdelt1' in h and not isinstance(h["cdelt1"], str):
                    diffs['scale'].append(
                        np.abs(h['cdelt1'] - header['cdelt1']))
            except Exception as ex:
                print("INVALID FILE", file)
                print("ERROR:", ex)
        return diffs
Example #11
0
c3 = SkyCoord((x1 - diffLon) * u.arcsec,
              y1 * u.arcsec,
              frame=frames.Helioprojective)
c4 = SkyCoord((x2 + diffLon) * u.arcsec,
              y2 * u.arcsec,
              frame=frames.Helioprojective)

# get middle frame subregion & time to anchor derotation
midmap = Map(flist[mid_file]).submap(c3, c4)
dt0 = midmap.date
mapShape = midmap.data.shape

# calculate pixels to trim based off of what actual derotation trims
# *for some reason this result is different than method above
diffMapI = diffrot_map(mapI.submap(c3, c4), time=dt0)
diffMapF = diffrot_map(mapF.submap(c3, c4), time=dt0)

xminindI = np.argmin(np.fliplr(diffMapI.data), axis=1)[diffLatPix:-diffLatPix]
xminindF = np.argmin(diffMapF.data, axis=1)[diffLatPix:-diffLatPix]

xminI = mapShape[1] - np.min(xminindI)
xminF = mapShape[1] - np.min(xminindF)

del new_mapcube1, mc_shifts, diffMapI, diffMapF

# specify which chunks should be handled by each processor
subcube = np.array_split(flist, size)[rank]

start = timer()