Example #1
0
def test2():
    aia = Map(sunpy.AIA_171_IMAGE)
    fig = plt.figure()
    ax = plt.subplot(111)
    aia.plot()
    plt.colorbar()
    aia.draw_limb()
    plt.show()
Example #2
0
    def plot_observations(self, obsdate: str, mdi_map: Map = None):
        """
        Plots the Active Regions for a given observation on the
        MDI map corresponding to that observation.

        Parameters
        ----------
        obsdate : str
            The observation time and date.
        mdi_map : Map, optional
            The MDI map corresponding to the given observation,
            If None, the Map will be downloaded first.
            By default None.

        Examples
        --------
        >>> from pythia.seo import Sunspotter
        >>> sunspotter = Sunspotter()
        >>> obsdate = '2000-01-01 12:47:02'
        >>> sunspotter.plot_observations(obsdate)
        """
        obsdate = self.get_nearest_observation(obsdate)

        if mdi_map is None:
            mdi_map = self.get_mdi_fulldisk_map(obsdate)

        hek_result = self.get_observations_from_hek(obsdate)

        bottom_left_x = hek_result['boundbox_c1ll']
        bottom_left_y = hek_result['boundbox_c2ll']
        top_right_x = hek_result['boundbox_c1ur']
        top_right_y = hek_result['boundbox_c2ur']

        number_of_observations = len(hek_result)

        bottom_left_coords = SkyCoord(
            [(bottom_left_x[i], bottom_left_y[i]) * u.arcsec
             for i in range(number_of_observations)],
            frame=mdi_map.coordinate_frame)

        top_right_coords = SkyCoord(
            [(top_right_x[i], top_right_y[i]) * u.arcsec
             for i in range(number_of_observations)],
            frame=mdi_map.coordinate_frame)

        fig = plt.figure(figsize=(12, 10), dpi=100)
        mdi_map.plot()

        for i in range(number_of_observations):
            mdi_map.draw_rectangle(bottom_left_coords[i],
                                   top_right=top_right_coords[i],
                                   color='b',
                                   label="Active Regions")

        hek_legend, = plt.plot([], color='b', label="Active Regions")

        plt.legend(handles=[hek_legend])
        plt.show()
Example #3
0
def create_figure(unix, wavelen=131):
    utc_start = stix_datetime.unix2datetime(unix).strftime('%Y-%m-%dT%H:%M:%S')
    utc_end = stix_datetime.unix2datetime(unix +
                                          60).strftime('%Y-%m-%dT%H:%M:%S')
    #print(utc_start, utc_end)
    sdo_query = Fido.search(a.Time(utc_start, utc_end), a.Instrument('AIA'),
                            a.Wavelength(wavelen * u.angstrom))
    sdo_res = Fido.fetch(sdo_query[0], progress=False, path='/tmp/')
    sdo = Map(sdo_res[0])
    fig = plt.figure(figsize=(6, 6), dpi=100)
    ax = fig.add_subplot(projection=sdo)
    sdo.plot(clip_interval=[1, 100] * u.percent, axes=ax)
    return fig
Example #4
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 #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
    mc[i].plot_settings['norm'] = norm3
    im = mc[i].plot()
    mc[i].draw_grid(grid_spacing=5*u.deg)
    mc[i].draw_limb()
    cbar = fig.colorbar(im, cmap=cmap3, ticks=temps, norm=norm3,
                        orientation='vertical', spacing='proportional',
                        boundaries=boundaries)
    cbar.ax.set_yticklabels(['0.5', '1.0', '2.0', '4.0', '6.0', '9.0', '14.0'])
    cbar.ax.set_ylabel('MK')
    #plt.colorbar(label='temperature (MK)')
    plt.title('maximum temperature\n{:s}'.format(mc[i].date.strftime(date_format)))
    filepath = os.path.join(output_directory, '{:s}_jet_dem_temp_{:n}.png'.format(jet_number_string, i))
    plt.savefig(filepath)


def myplot(fig, ax, sunpy_map):
    p = sunpy_map.draw_limb()
    p = sunpy_map.draw_grid(grid_spacing=5*u.deg)
    ax.set_title('maximum temperature\n{:s}'.format(sunpy_map.date.strftime(date_format)))
    #fig.colorbar(sunpy_map.plot())
    return p

ani = mc.plot(plot_function=myplot)
Writer = animation.writers['avconv']
writer = Writer(fps=20, metadata=dict(artist='SunPy'), bitrate=18000)
fname = os.path.join(output_directory, '{:s}_maximum_temperature.mp4'.format(jet_number_string))
ani.save(fname, writer=writer)



Example #7
0
detector = a.Detector("C2")
result = Fido.search(time_range, instrument)

downloaded_files = Fido.fetch(result[0])
data, header = read_file(downloaded_files[0])[0]

# Add the missing meta information to the header
header["CUNIT1"] = "arcsec"
header["CUNIT2"] = "arcsec"

###############################################################################
# With this fix we can load it into a map and plot the results.

lasco_map = Map(data, header)
fig1 = plt.figure()
lasco_map.plot()

###############################################################################
# Now we will call the `astroscrappy.detect_cosmics <https://astroscrappy.readthedocs.io/en/latest/api/astroscrappy.detect_cosmics.html>`__
# to remove the cosmic ray hits.
# This algorithm can perform well with both high and low noise levels in the original data.
# The function takes a `~numpy.ndarray` as input so we only pass the map data.
# This particular image has lots of high intensity cosmic ray hits which
# cannot be effectively removed by using the default set of parameters.
# So we reduce ``sigclip``, the Laplacian to noise ratio from 4.5 to 2 to mark more hits.
# We also reduce ``objlim``, the contrast between the Laplacian image and the fine structured image
# to clean the high intensity bright cosmic ray hits.
# We also modify the ``readnoise`` parameter to obtain better results.

mask, clean_data = astroscrappy.detect_cosmics(lasco_map.data,
                                               sigclip=2,
Example #8
0
from scipy.interpolate import RegularGridInterpolator as rgi
from itertools import product

emmapcubehelix = _cm.cubehelix(s=2.8, r=-0.7, h=1.4, gamma=1.0)
cm.register_cmap(name='emhelix', data=emmapcubehelix)
emcm = cm.get_cmap('emhelix')

# Load a temperature map and get the EM data out of it
tmap = TMap('2011-02-15',
            maps_dir=expanduser('~/coronal-backprojection/'),
            n_params=3)
EMmap = Map(10.0**tmap.emission_measure, tmap.meta.copy())
EMlog = Map(tmap.emission_measure, tmap.meta.copy())
print np.nanmin(EMlog.data), np.nanmax(EMlog.data)
fig = plt.figure(figsize=(32, 24))
EMlog.plot(cmap=emcm)
plt.colorbar()
plt.savefig('input-em')
plt.close()

# Define ranges of reconstruction space
rsun = EMmap.rsun_arcseconds
xrange = (EMmap.xrange[0] / rsun, EMmap.xrange[1] / rsun)
yrange = (EMmap.yrange[0] / rsun, EMmap.yrange[1] / rsun)
zrange = [min([xrange[0], yrange[0]]), max([xrange[1], yrange[1]])]
print xrange, yrange, zrange

side = 1024

try:
    # Attempt to load distribution and coordinates files
Example #9
0
# create GCS mesh
date = dt.datetime(2020, 4, 15, 6, 54)
half_angle = 25
height = 8.79
kappa = 0.26
lat = np.radians(-1)
lon = np.radians(354)
tilt = np.radians(5)

mesh = gcs_mesh_sunpy(date, half_angle, height, 20, 20, 20, kappa, lat, lon,
                      tilt)

# download STEREO-A COR2 image
hv = helioviewer.HelioviewerClient()
f = hv.download_jp2(date,
                    observatory='STEREO_A',
                    instrument='SECCHI',
                    detector='COR2')
map = Map(f)

# plot image
fig = plt.figure()
ax = plt.subplot(projection=map)

map.plot(cmap='Greys_r')

# plot GCS mesh
ax.plot_coord(mesh, '.', ms=3)

plt.show()
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
import matplotlib.pyplot as plt
from sunpy.map import Map
import sunpy.data.sample as s
import numpy as np
aia = Map(s.AIA_171_IMAGE)

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

r = [11.52, 10.42, 6.14, 3.64, 2.75]
e = [10, 20, 30, 40, 50]

pixel_size = 3.4
number_of_pixels = 160

center = np.array([461, 303])

line_color = 'w'

rect = plt.Rectangle(center - pixel_size * number_of_pixels / 2.,
                     pixel_size * number_of_pixels,
                     pixel_size * number_of_pixels,
                     fill=False,
                     color=line_color)
ax[0].add_artist(rect)

rect = plt.Rectangle(center - pixel_size / 2.,
                     pixel_size,
                     pixel_size,
                     fill=False,
Example #12
0
c_map_cm.set_under('k', alpha=0.001)
c_map.set_colors(1, c_map_cm)
c_map.set_alpha(1, 0.8)

# Create the figure
plt.close('all')
figure = plt.figure()
axes = figure.add_subplot(111)
if for_paper:
    observation = r"AIA {:s}".format(mc[0].measurement._repr_latex_())
    title = "wave progress map\n{:s}".format(observation)
    image_file_type = 'eps'
else:
    title = "{:s} ({:s})".format(observation_date, wave_name)
    image_file_type = 'png'
ret = c_map.plot(axes=axes, title=title)
c_map.draw_limb()
c_map.draw_grid()

# Set up the color bar
nticks = 6
timestamps_index = np.linspace(1, len(timestamps)-1, nticks, dtype=np.int).tolist()
cbar_tick_labels = []
for index in timestamps_index:
    wpm_time = timestamps[index].strftime("%H:%M:%S")
    cbar_tick_labels.append(wpm_time)
cbar = figure.colorbar(ret[1], ticks=timestamps_index)
cbar.ax.set_yticklabels(cbar_tick_labels)
cbar.set_label('time (UT) ({:s})'.format(observation_date))
cbar.set_clim(vmin=1, vmax=len(timestamps))
Example #13
0
     emiss.meta['cdelt2'] = temps[1] - temps[0]
     #emiss.meta['crval1'] = widths[0]
     emiss.meta['crval1'] = heights[0] #np.log10(heights[0])
     emiss.meta['crval2'] = temps[0]
     emiss.meta['crpix1'] = 0.5
     emiss.meta['crpix2'] = 0.5
     if wlength == '94': wlength = '094'
     fits_dir = path.join(CThome, 'data', 'synthetic', wlength)
     if not path.exists(fits_dir): makedirs(fits_dir)
     emiss.save(path.join(fits_dir, 'model.fits'), clobber=True)
     #print '----', emission[2, :, :, :].min(), emission[2, :, :, :].max()
     #print '------', emission[2, :, w, :].min(), emission[2, :, w, :].max()
     emiss.data /= emission[2, :, w, :]
     #print '--------', emiss.min(), emiss.max()
     ax = fig.add_subplot(1, 6, wl+1)
     emiss.plot(aspect='auto', vmin=emiss.min(), vmax=emiss.max())
     plt.title('{}'.format(wlength))
     plt.xlabel('Input EM')
     plt.ylabel('Input log(T)')
     plt.colorbar()
     #fig.gca().add_artist(rect)
     plt.axvline(20.0, color='white')
     plt.axvline(35.0, color='white')
     plt.axhline(5.6, color='white')
     plt.axhline(7.0, color='white')
 #plt.savefig(path.join(outdir, 'model_emission_h={}'.format(np.log10(wid)).replace('.', '_')))
 plt.savefig(path.join(outdir, 'model_emission_w={}'.format(wid).replace('.', '_')))
 plt.close()
 
 #images = [Map(emission[i, :, :, w], mapmeta) for i in range(6)]
 images = [Map(emission[i, :, w, :], mapmeta) for i in range(6)]
from astropy import units as u
from scipy.interpolate import RegularGridInterpolator as rgi
from itertools import product

emmapcubehelix = _cm.cubehelix(s=2.8, r=-0.7, h=1.4, gamma=1.0)
cm.register_cmap(name='emhelix', data=emmapcubehelix)
emcm = cm.get_cmap('emhelix')

# Load a temperature map and get the EM data out of it
tmap = TMap('2011-02-15', maps_dir=expanduser('~/coronal-backprojection/'),
            n_params=3)
EMmap = Map(10.0**tmap.emission_measure, tmap.meta.copy())
EMlog = Map(tmap.emission_measure, tmap.meta.copy())
print np.nanmin(EMlog.data), np.nanmax(EMlog.data)
fig = plt.figure(figsize=(32, 24))
EMlog.plot(cmap=emcm)
plt.colorbar()
plt.savefig('input-em')
plt.close()

# Define ranges of reconstruction space
rsun = EMmap.rsun_arcseconds
xrange = (EMmap.xrange[0] / rsun, EMmap.xrange[1] / rsun)
yrange = (EMmap.yrange[0] / rsun, EMmap.yrange[1] / rsun)
zrange = [min([xrange[0], yrange[0]]), max([xrange[1], yrange[1]])]
print xrange, yrange, zrange

side = 1024

try:
  # Attempt to load distribution and coordinates files
Example #15
0
import matplotlib.pyplot as plt
from sunpy.map import Map
import sunpy.data.sample as s
import numpy as np
aia = Map(s.AIA_171_IMAGE)

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

r = [11.52, 10.42, 6.14, 3.64, 2.75]
e = [10, 20, 30, 40, 50]

pixel_size = 3.4
number_of_pixels = 160

center = np.array([461, 303])

line_color = 'w'

rect = plt.Rectangle(center - pixel_size * number_of_pixels/2., pixel_size * number_of_pixels, pixel_size * number_of_pixels, fill=False, color=line_color)
ax[0].add_artist(rect)

rect = plt.Rectangle(center - pixel_size/2., pixel_size, pixel_size, fill=False, color=line_color)
ax[0].add_artist(rect)

for radius, energy in zip(r,e):
    circle = plt.Circle(center, radius=radius*60, fill=False, label=str(energy), color=line_color)
    ax[0].add_artist(circle)
plt.colorbar()
plt.legend()
Example #16
0
                        norm=norm3,
                        orientation='vertical',
                        spacing='proportional',
                        boundaries=boundaries)
    cbar.ax.set_yticklabels(['0.5', '1.0', '2.0', '4.0', '6.0', '9.0', '14.0'])
    cbar.ax.set_ylabel('MK')
    #plt.colorbar(label='temperature (MK)')
    plt.title('maximum temperature\n{:s}'.format(
        mc[i].date.strftime(date_format)))
    filepath = os.path.join(
        output_directory,
        '{:s}_jet_dem_temp_{:n}.png'.format(jet_number_string, i))
    plt.savefig(filepath)


def myplot(fig, ax, sunpy_map):
    p = sunpy_map.draw_limb()
    p = sunpy_map.draw_grid(grid_spacing=5 * u.deg)
    ax.set_title('maximum temperature\n{:s}'.format(
        sunpy_map.date.strftime(date_format)))
    #fig.colorbar(sunpy_map.plot())
    return p


ani = mc.plot(plot_function=myplot)
Writer = animation.writers['avconv']
writer = Writer(fps=20, metadata=dict(artist='SunPy'), bitrate=18000)
fname = os.path.join(output_directory,
                     '{:s}_maximum_temperature.mp4'.format(jet_number_string))
ani.save(fname, writer=writer)
Example #17
0
from pyfoxsi.psf import convolve
from sunpy.map import Map
import matplotlib.pyplot as plt

f = '/Users/schriste/Google Drive/Work/FOXSI SMEX/Data/hsi_image_20050513_164526to164626_pixon_3arcsecx64_25to50kev_d1to9.fits'
hsi = Map(f)

foxsi_map = convolve(hsi)

plt.figure()
plt.subplot(1, 2, 1)
hsi.plot()
plt.subplot(1, 2, 2)
foxsi_map.plot()
plt.show()
Example #18
0
mid_file = nf // 2

global full_map
full_map = Map(flist[mid_file])
fm_shape = full_map.data.shape

fig = plt.figure(figsize=(10, 6))
plt.subplots_adjust(bottom=0.23)
plt.suptitle('Select a subregion: draw a box or enter coordinates')

ax = plt.subplot2grid((1, 33), (0, 0),
                      colspan=14,
                      rowspan=1,
                      projection=full_map)
im = full_map.plot()
ax.set_autoscale_on(False)

xlim_default = ax.get_xlim()
ylim_default = ax.get_ylim()

toggle_selector.RS = RectangleSelector(ax,
                                       onselect,
                                       drawtype='box',
                                       useblit=True,
                                       interactive=True)
plt.connect('key_press_event', toggle_selector)

global x1, y1, x2, y2

x_y1 = full_map.pixel_to_world(0 * u.pixel, 0 * u.pixel)
Example #19
0
Three dimensional plots
=======================
sunpy can interface with the `pyvista` package to produce interactive 3D plots.
"""
###############################################################################
# Start by importing the required modules
import astropy.constants as const
import astropy.units as u
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
from sunpy.data.sample import AIA_335_IMAGE
from sunpy.map import Map
from quadrangle import Draw

m = Map(AIA_335_IMAGE)
m.plot()
plotter = PyVistaPlotter()
map_mesh = plotter.plot_map(m)
line_mesh = plotter.plot_solar_axis()
quad_mesh = plotter.plot_quadrangle(m)
# combined_mesh = map_mesh + quad_mesh

# blocks = pv.MultiBlock([line_mesh])
# merged = blocks.combine()
# # merged
# pv.save_meshio('/home/jeffrey/jupy/tmp.vtk', merged)
# plotter = pv.Plotter()
# plotter.add_mesh(merged)
plotter.show()
# plotter.show(cpos=(-100,0,0), screenshot="quad.png")
Example #20
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