<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 TESS 2015 - Introduction to Solar Data Analysis in Python
<img src="https
Step1:  SunPy version (stable) 0.5
Let's study a flare!
Searching for events in the HEK
Step2:  We can find out when this event occured
Step3:  and where it occurred
Step4:  Lightcurves!
Let's look at the GOES curve for this event.
First some time manipulation!
Step5:  The data is stored in a standard place
Step6:  This is a pandas dataframe! Provides lots of additional functionality. For example
Step7:  Compares well to the official max from the HEK
Step8:  Meta data is also stored in a standard place
Step9:  This is a dictionary like the hek results so...
Step10:  Solar Images in SunPy
SunPy has a Map type that supports 2D images, it makes it simple to read data in from any filetype supported in sunpy.io which is currently FITS, JPEG2000 and ANA files. You can also create maps from any (data, metadata) pair.
Let's download an AIA image of this flare from the vso
Step11:  Then do a search.
Step12:  It works, now lets see how many results we have!
Step13:  That's way too many!
So that is every image that SDO/AIA had on that day. Let us reduce that amount.
To do this, we will limit the time search for a specify a wavelength.
Step14:  Let's also grab another wavelength for later.
Step15:  Let's download this data!
Step16:  For SunPy the top level name-space is kept clean. Importing SunPy does not give you access to much. You need to import specific names. SciPy is the same. 
So, the place to start here is with the core SunPy data object. It is called Map.
Step17:  Maps contain both the image data and the metadata associated with the image, this metadata currently does not deviate much from the standard FITS WCS keywords, but presented in a instrument-independent manner.
Step18:  SunPy Maps!
Maps are the same for each file, regardless of source. It does not matter if the source is SDO or SOHO, for example.
The most used attributes are as follows (some of them will look similar to NumPy's Array)
Step19:  The data (stored in a numpy array)
Step20:  Because it is just a numpy array you have access to all of those function
The standard deviation
Step21:  The original metadata (stored in a dictionary)
Step22:  We also provide quick access to some key metadata values as object variables (these are shortcuts)
Step23:  Maps also provide some nice map specific functions such as submaps. Let's zoom in on the flare location which was given to us by the HEK.
Step24:  The default image scale is definitely not right. Let's fix that so we can see the flare region better.
Step25:  Composite Maps
Let's plot the two channels we downloaded from AIA together! Composite map is the way to do this. Let's check out the other map we got.
Step26:  Some other topics...
Solar Constants
Step27:  Not all constants have a short-cut assigned to them (as above). The rest of the constants are stored in a dictionary. The following code grabs the dictionary and gets all of the keys.
Step28:  These are astropy constants which are a subclass of Quantities (numbers with units) which are a great idea.
<ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
matplotlib.rc('savefig', dpi=120)
import warnings
warnings.simplefilter("ignore", Warning)
from matplotlib import dates
import sunpy
sunpy.system_info()
Explanation: TESS 2015 - Introduction to Solar Data Analysis in Python
<img src="https://raw.github.com/sunpy/sunpy-logo/master/generated/sunpy_logo_compact_192x239.png">
SunPy!
Author: Steven Christe
Email: steven.christe@nasa.gov
Through tutorials and presentations we will demonstrate how free and open-source Python and SunPy library can be used to analyze solar data. Depending on interest, dinner may be ordered after the main presentation (roughly an hour) and a hands-on help session will take place for the remainder of the evening.  Installing the following software is recommended but not required: Anaconda Python and SunPy.
Schedule: 19:00 to 22:00
+ 18:00-18:15 pm: Organization (chatroom, organize dinner)?
+ 18:15-19:00 pm: Intro to SunPy (presentation)
+ 19:00-19:15 pm: Break
+ 19:15-20:15: Dinner & Installation Workshop
+ 20:15-22:00: SunPy Workshop
What is SunPy?
A community-developed, free and open-source solar data analysis environment for Python.
website: http://www.sunpy.org<br>
documentation: http://docs.sunpy.org<br>
code (version control!): https://github.com/sunpy/sunpy
Mailing list: https://groups.google.com/forum/#!forum/sunpy**
IRC: #sunpy on freenode.net web client
SunPy is built upon foundational libraries which enable scientific computing in Python which includes
NumPy
SciPy
matplotlib
AstroPy
<p>Supported observations
      <ul>Images
          <li>SDO AIA and HMI</li>
          <li>SOHO EIT, LASCO, MDI</li>
          <li>STEREO EUVI and COR</li>
          <li>TRACE</li>
          <li>Yohkoh SXT</li>
          <li>RHESSI mapcubes (beta)</li>
          <li>PROBA2 SWAP</li>
          <li>IRIS Slit-Jaw (beta)</li>
        </ul>
    <ul>Time Series
            <li>GOES XRS</li>
          <li>PROBA2 LYRA</li>
          <li>Fermi GBM</li>
          <li>SDO EVE</li>
        <li>RHESSI Summary Lightcurves</li>
          <li>Nobeyama Radioheliograph LightCurve</li>
        <li>NOAA Solar Cycle monthly indices</li>
        <li>NOAA Solar Cycle Prediction</li>
    </ul>
    <ul>Spectra
        <li>Callisto</li>
        <li>STEREO SWAVES</li>
    </ul>
<p>Supported data retrieval services 
    <ul>
        <li>Virtual Solar Observatory (VSO)</li>
        <li>JSOC</li>
        <li>Heliophysics Events Knowledgebase (HEK)</li>
        <li>Helio</li>
        <li>Helioviewer</li>
    </ul>
</p>
<p>Supported file formats include
<ul>
    <li>FITS (read/write)</li>
    <li>Comma-separated files, text files (read/write)</li>
    <li>ANA (read/write)</li>
    <li>JPG2 (read/write)</li>
</ul>
</p>
# What is this webby notebooky magic?!
## ipython notebook (now known as jupyter)
similar to matlab, mathematica, maple
Some setup...
End of explanation
from sunpy.net import hek
client = hek.HEKClient()
tstart, tend = '2014/01/01 00:00:00', '2014/01/02 00:00:00'
result = client.query(hek.attrs.Time(tstart, tend), 
                      hek.attrs.EventType('FL'), 
                      hek.attrs.FRM.Name=='SSW Latest Events')
len(result)
result[0]
for res in result:
    print(res.get('fl_goescls'))
result = client.query(hek.attrs.Time(tstart, tend), 
                      hek.attrs.EventType('FL'), 
                      hek.attrs.FRM.Name=='SSW Latest Events', 
                      hek.attrs.FL.GOESCls>'M')
len(result)
result
Explanation: SunPy version (stable) 0.5
Let's study a flare!
Searching for events in the HEK
End of explanation
result[0].get('event_peaktime')
Explanation: We can find out when this event occured
End of explanation
result[0].get('hpc_coord')
Explanation: and where it occurred
End of explanation
from sunpy.time import TimeRange, parse_time
from datetime import timedelta
tmax = parse_time(result[0].get('event_peaktime'))
tmax
tr = TimeRange(tmax - timedelta(minutes=30), tmax + timedelta(minutes=30))
tr
from sunpy.lightcurve import GOESLightCurve
goes = GOESLightCurve.create(tr)
goes.peek()
Explanation: Lightcurves!
Let's look at the GOES curve for this event.
First some time manipulation!
End of explanation
goes.data
Explanation: The data is stored in a standard place
End of explanation
print('The max flux is {flux:2.5f} at {time}'.format(flux=goes.data['xrsb'].max(), time=goes.data['xrsb'].idxmax()))
Explanation: This is a pandas dataframe! Provides lots of additional functionality. For example
End of explanation
str(tmax)
goes.peek()
plt.axhline(goes.data['xrsb'].max())
plt.axvline(goes.data['xrsb'].idxmax())
Explanation: Compares well to the official max from the HEK
End of explanation
goes.meta
Explanation: Meta data is also stored in a standard place
End of explanation
goes.meta.get('COMMENT')
goes.data.resample('10s', how='mean')
Explanation: This is a dictionary like the hek results so...
End of explanation
from sunpy.net import vso
client=vso.VSOClient()
Explanation: Solar Images in SunPy
SunPy has a Map type that supports 2D images, it makes it simple to read data in from any filetype supported in sunpy.io which is currently FITS, JPEG2000 and ANA files. You can also create maps from any (data, metadata) pair.
Let's download an AIA image of this flare from the vso
End of explanation
recs = client.query(vso.attrs.Time(tr), vso.attrs.Instrument('AIA'))
Explanation: Then do a search.
End of explanation
recs.num_records()
Explanation: It works, now lets see how many results we have!
End of explanation
recs = client.query(vso.attrs.Time('2014/01/01 18:52:08', '2014/01/01 18:52:15'), 
                    vso.attrs.Instrument('AIA'),
                    vso.attrs.Wave(171,171))
recs.num_records()
recs.show()
Explanation: That's way too many!
So that is every image that SDO/AIA had on that day. Let us reduce that amount.
To do this, we will limit the time search for a specify a wavelength.
End of explanation
recs = client.query(vso.attrs.Time('2014/01/01 18:52:08', '2014/01/01 18:52:15'), 
                    vso.attrs.Instrument('AIA'),
                    vso.attrs.Wave(94,171))
recs.num_records()
Explanation: Let's also grab another wavelength for later.
End of explanation
f = client.get(recs, methods = ('URL-FILE_Rice')).wait()
f
Explanation: Let's download this data!
End of explanation
from sunpy.map import Map
aia = Map(f[1])
aia
Explanation: For SunPy the top level name-space is kept clean. Importing SunPy does not give you access to much. You need to import specific names. SciPy is the same. 
So, the place to start here is with the core SunPy data object. It is called Map.
End of explanation
aia.peek()
Explanation: Maps contain both the image data and the metadata associated with the image, this metadata currently does not deviate much from the standard FITS WCS keywords, but presented in a instrument-independent manner.
End of explanation
aia.data
Explanation: SunPy Maps!
Maps are the same for each file, regardless of source. It does not matter if the source is SDO or SOHO, for example.
The most used attributes are as follows (some of them will look similar to NumPy's Array):
End of explanation
type(aia.data)
aia.mean(),aia.max(),aia.min()
Explanation: The data (stored in a numpy array)
End of explanation
aia.data.std()
aia.data.shape
Explanation: Because it is just a numpy array you have access to all of those function
The standard deviation
End of explanation
aia.meta
aia.meta.keys()
aia.meta.get('rsun_obs')
Explanation: The original metadata (stored in a dictionary)
End of explanation
print(aia.date, aia.coordinate_system, aia.detector, aia.dsun)
Explanation: We also provide quick access to some key metadata values as object variables (these are shortcuts)
End of explanation
result[0].get('hpc_coord')
point = [665.04, -233.4096]
dx = 50
dy = 50
xrange = [point[0] - dx, point[0] + dx]
yrange = [point[1] - dy, point[1] + dy]
aia.submap(xrange,yrange).peek()
plt.plot(point[0], point[1], '+')
plt.xlim(xrange)
plt.ylim(yrange)
Explanation: Maps also provide some nice map specific functions such as submaps. Let's zoom in on the flare location which was given to us by the HEK.
End of explanation
smap = aia.submap(xrange,yrange)
import matplotlib.colors as colors
norm = colors.Normalize(0, 3000)
smap.plot(norm=norm)
plt.plot(point[0], point[1], '+')
smap.draw_grid(grid_spacing=1)
plt.colorbar()
Explanation: The default image scale is definitely not right. Let's fix that so we can see the flare region better.
End of explanation
aia131 = Map(f[0])
aia131
smap131 = aia131.submap(xrange, yrange)
smap131.peek()
norm = colors.Normalize(0, 4000)
smap131.plot(norm=norm)
plt.colorbar()
smap171 = smap
compmap = Map(smap171, smap131, composite=True)
levels = np.arange(0,100,5)
print(levels)
compmap.set_levels(1, levels, percent=True)
compmap.set_mpl_color_normalizer(0, norm)
compmap.set_colors(1, plt.cm.Reds)
compmap.plot(norm=norm)
plt.show()
Explanation: Composite Maps
Let's plot the two channels we downloaded from AIA together! Composite map is the way to do this. Let's check out the other map we got.
End of explanation
from sunpy.sun import constants as solar_constants
solar_constants.mass
print(solar_constants.mass)
(solar_constants.mass/solar_constants.volume).cgs
solar_constants.volume + solar_constants.density
Explanation: Some other topics...
Solar Constants
End of explanation
solar_constants.physical_constants.keys()
type(solar_constants.mass)
Explanation: Not all constants have a short-cut assigned to them (as above). The rest of the constants are stored in a dictionary. The following code grabs the dictionary and gets all of the keys.:
End of explanation
from astropy import units as u
u.keV
u.keV.decompose()
Explanation: These are astropy constants which are a subclass of Quantities (numbers with units) which are a great idea.
End of explanation
<END_TASK>