def get_all_sdo_images(self, time_in, save_path=''):
        """
        Download a complete set of the SDO images in AIA and HMI for a given time

        :param time_in: string time for JP2 image download
        :param save_path: save path for downloaded images
        :return: full file path of example AIA image downloaded (335 channel)
        """

        hv = helioviewer.HelioviewerClient()

        wavelnths = [
            '1600', '1700', '094', '131', '171', '211', '304', '335', '193'
        ]
        measurement = ['continuum', 'magnetogram']

        for wav in wavelnths:
            aia_filepath = hv.download_jp2(time_in,
                                           observatory='SDO',
                                           instrument='AIA',
                                           detector='AIA',
                                           measurement=wav,
                                           directory=save_path,
                                           overwrite=True)

        for measure in measurement:
            hmi_filepath = hv.download_jp2(time_in,
                                           observatory='SDO',
                                           instrument='HMI',
                                           detector='HMI',
                                           measurement=measure,
                                           directory=save_path,
                                           overwrite=True)

        return aia_filepath
Exemple #2
0
def acquire_jp2(directory,
                time_range,
                observatory='SDO',
                instrument='AIA',
                detector='AIA',
                measurement='211',
                verbose=True):
    """Acquire Helioviewer JPEG2000 files between the two specified times"""

    # Create a Helioviewer Client
    hv = helioviewer.HelioviewerClient()

    # Start the search
    jp2_list = []
    this_time = time_range.t1
    while this_time <= time_range.t2:
        # update the directory dictionary with the latest contents
        directory_dict = get_jp2_dict(directory)

        # find what the closest image to the requested time is
        response = hv.get_closest_image(this_time,
                                        observatory=observatory,
                                        instrument=instrument,
                                        detector=detector,
                                        measurement=measurement)

        # if this date is not already present, download it
        if not (response["date"] in directory_dict):
            if verbose:
                print('Downloading new file:')
            jp2 = hv.download_jp2(this_time,
                                  observatory=observatory,
                                  instrument=instrument,
                                  detector=detector,
                                  measurement=measurement,
                                  directory=directory,
                                  overwrite=True)
        else:
            # Otherwise, get its location
            jp2 = directory_dict[response["date"]]
        # Only one instance of this file should exist
        if not (jp2 in jp2_list):
            jp2_list.append(jp2)
            if verbose:
                print('Found file ' + jp2 + '. Total found: ' +
                      str(len(jp2_list)))

        # advance the time
        this_time = this_time + timedelta(seconds=6)
    return jp2_list
Exemple #3
0
"""
import matplotlib.pyplot as plt
from astroquery.vizier import Vizier

import astropy.units as u
from astropy.coordinates import SkyCoord

import sunpy.map
from sunpy.coordinates import frames, get_body_heliographic_stonyhurst
from sunpy.net import helioviewer

###############################################################################
# Let's download a STEREO-A SECCHI COR2 image from Helioviewer which provide
# pre-processed images and load it into a Map.

hv = helioviewer.HelioviewerClient()
f = hv.download_jp2('2014/05/15 07:54', observatory='STEREO_A',
                    instrument='SECCHI', detector='COR2')
cor2 = sunpy.map.Map(f)

###############################################################################
# To efficiently search the star field we need to know what stars are near the
# Sun as observed by STEREO. We need the vector that points from STEREO to the Sun.
# By converting to HCRS we get the vector from the Sun to STEREO

sun_to_stereo = cor2.observer_coordinate.transform_to('hcrs')

###############################################################################
# We next reflect the vector to get our search vector which points from STEREO
# to the Sun
def test_coords (
time='2015/01/17 07:30:00'
,wavelength='171'
,outdir='~/Desktop/'
,delete=True):
    
    """Test coordinate function for use prior to the get_png() function.
    Use by specifying the start time of your desired observation time window
    and any wavelength you can identify your target in. Before running the script,
    it may be necessary to type '%matplotlib qt' without quotes to get the window
    to pop up. A matplotlib plot should show your coordinates where your cursor is.
    Use these coordinates when calling the get_png() function as your xcenter and ycenter
    coordinates at the same starting time. If you change your starting time you will
    need to adjust the coordiates.
    
    Args:
        time (str): Start time string for test image to be pulled from, expected format YYYY/mm/dd HH:MM:SS
        
        wavelength (str): String or int wavelength that you intend to observe, preferably one where you can see your target
        
        outdir (str): Directory of where to (temporarily) download the file to, probably safe to leave this default
        
        delete (bool): Unless you specifically want to keep the test file, then leave this to True, will remove the test image after viewing
    """
    
    #A note to anyone reading this in the future - If the image the get_png method downloads is not in the same spot
    #as what you selected from this test function, then it is probable that sunpy or helioviewer changed its methods and
    #the math that is required to convert from px to arcsec offset.
    
    #Imports
    from sunpy.net import helioviewer
    from datetime import datetime
    import os
    import matplotlib.pyplot as plt
    
    #Datetime object
    timedt = datetime.strptime(time,'%Y/%m/%d %H:%M:%S')
    
    #Check for bad directory format
    if not outdir[-1] == '/':
        outdir = outdir + '/'    
    
    #Create the directory if it is not there
    if not os.path.isdir(outdir):
        os.makedirs(outdir)
    
    #Confirm wavelength variable type
    wavelength = str(wavelength)
    
    #Creates an instance of the helioviewer client
    hv = helioviewer.HelioviewerClient()
    
    #The parameters required to show a full disk image of the sun
    height=4096
    width=4096
    x0=0
    y0=0
    
    
    #Downloads and opens test image
    filename= hv.download_png(timedt, 0.6, "[SDO,AIA,AIA,"+wavelength+",1,100]", x0=x0, y0=y0, width=width, height=height, directory=outdir, watermark=False,overwrite=True)
    im = plt.imread(filename)
    fig,ax=plt.subplots()
    ax.imshow(im)
    #Deletes the test image unless otherwise specified
    if(delete):
        os.remove(filename)
def get_png (
start='2015/01/17 07:00:00'
,end='2015/01/17 08:30:00'
,wavelength=[94,131,171,193,211,304,335,1600,'hmi']
,basedir='/data/reu/wwainwri/Data/solar/'
,xcenter=941.39
,ycenter=746.31
,width=650
,height=400
,skipdays=0
,skiphours=0):
    
    """Sunpy-Helioviewer client based method to get png files cropped to a 
    region of interest over a given timeframe for any AIA/HMI wavelengths.
    All arguments are by keyword. Script functions in sunpy 0.9.9, it has
    been tested in 1.0.0+, but is potentially slower, buggier, and spams 
    the console. It should still work though. Skipdays and skiphours are 
    intended for use when a large download has ceased in the middle of a 
    time range for a single wavelength and you do not wish to start from
    the beginning. The time skip accounts for the rotation of the sun
    to make sure an object at xcenter and ycenter at start time will be
    in view at the skipped to time.

    Args:
        start (str): Start time string for the download, expected format YYYY/mm/dd HH:MM:SS
        
        end (str): End time string for the download, expected format YYYY/mm/dd HH:MM:SS
        
        wavelength (list): List object of wavelengths, for example [171,304,hmi] <---hmi is str object, wavelengths may be string or int objects
        
        basedir (str): Directory where the data will be downloaded to, subdirectory will be made based on date, expects full /path/to/dir/ format
        
        xcenter (float): Float or int for the center x coordinate of the image, expects pixel coordinates as determined by the test_coords() function
        
        ycenter (float): Float or int for the center y coordinate of the image, expects pixel coordinates as determined by the test_coords() function
        
        width (int): Integer value for the width of the image in pixels
        
        height (int): Integer value for the height of the image in pixels
        
        skipdays (float): Number of days to skip from the start date, intended for use in large downloads where a crash has occurred before the end
        
        skiphours (float): Number of hours to skip from the start date, intended for use in large downloads where a crash has occurred before the end
    """
    
    #Imports
    from sunpy.net import helioviewer
    from datetime import datetime,timedelta
    from dateutil.rrule import rrule, SECONDLY
    import os
    import numpy as np
    import astropy.units as u
    from astropy.coordinates import SkyCoord
    from sunpy.coordinates import frames
    
    #Convert xcenter and ycenter pixel coordinates to arcsec offput from solar center coordinates (sunpy makes this unnecessarily complicated)
    arcperpx=np.float128(0.600714)
    xcenter=(xcenter-600)*arcperpx*4096/1200
    ycenter=(ycenter-600)*arcperpx*4096/1200
    
    xcenterinit=float(xcenter)
    
    #Datetime objects
    startdt=datetime.strptime(start,'%Y/%m/%d %H:%M:%S')
    enddt=datetime.strptime(end,'%Y/%m/%d %H:%M:%S')
    endstr=datetime.strftime(enddt,'%Y_%m_%d_%H_%M_%S_')
    
    #Check for bad directory format
    if not basedir[-1] == '/':
        basedir = basedir + '/'  
    
    
    #Sub directory path from date input
    subdir=start.split(' ')[0]+'/'
    
    #Open helioviewer client instance
    hv = helioviewer.HelioviewerClient()


    #akm=np.arctan(1/3600)*1.496e8 <-- The way it SHOULD be done, but it works better the other way
    akm=1.496e8/1230.262271999999939
    c1 = SkyCoord(akm*xcenter*u.km,akm*ycenter*u.km,6.9e5*u.km,obstime=startdt,frame=frames.Heliocentric)
    lat=c1.transform_to('heliographic_stonyhurst').lat.value
    
    #Differential rotation in deg per day based on solar latitude
    A=14.713
    B=-2.396
    C=-1.787
    xoffsetdegperday=A+B*np.sin(lat/60)**2+C*np.sin(lat/60)**4
    
    rotdays=180/xoffsetdegperday
    xoffset=2460/rotdays/2/3600 #Arcsec per 12 sec

    
    for wv in wavelength:
        #Create directory for each wavelength if not already there
        path=basedir+subdir+str(wv)+'/'
        if not os.path.isdir(path):
            os.makedirs(path)
        
        xcenter = float(xcenterinit)
        
        
        #Skips wavelengths that have already been downloaded to save time
        if os.path.isfile(f"{basedir}{subdir}{wv}/{endstr}AIA_{wv}.png") or os.path.isfile(f"{basedir}{subdir}{wv}/{endstr}HMI_Mag.png"):
            continue
        
        #If the program crashed in the middle of downloading, you can skip the the nearest hour and day that needs to be downloaded
        #This math applies the rotation offset needed to keep your object in frame where it was before the program failed
        startdttemp = startdt + timedelta(days=skipdays,hours=skiphours)
        xcenter = xcenter + (skipdays*24+skiphours)*300*xoffset
        
        skipdays=0
        skiphours=0
        
        #Download png files     
        for t in rrule(SECONDLY, dtstart=startdttemp, until=enddt):
            if t.second%12 == 0:
                xcenter = xcenter + xoffset
                if wv == 'hmi':
                    hv.download_png(t, 0.6, "[SDO,HMI,HMI,magnetogram,1,100]", x0=xcenter, y0=ycenter, width=width, height=height,directory=path,watermark=False,overwrite=True)
                else:
                    hv.download_png(t, 0.6, "[SDO,AIA,AIA,"+str(wv)+",1,100]", x0=xcenter, y0=ycenter, width=width, height=height,directory=path,watermark=False,overwrite=True)