def aia_promote(self): if self.full_map.processing_level == 1.4: self.full_map = aia.aiaprep(self.full_map) self.full_map.meta['lvl_num'] = 1.6 else: self.full_map = aia.aiaprep(self.full_map) self.full_map.meta['lvl_num'] = 1.5
def process_med_int(fle): """ Processes 1 image and extracts the median intensity on the disk normalized for exposure time. Args: fle (str): image file name Returns: median intensity of the solar disk normalized for exptime """ amap = Map(fle) amap = aiaprep(amap) data = amap.data date = amap.date hdr = getFitsHdr(fle) exp_time = hdr['exptime'] r_pix = hdr['rsun_obs'] / hdr['cdelt1'] # radius of the sun in pixels disk_mask = get_disk_mask(data.shape, r_pix) disk_data = np.ma.array(data, mask=disk_mask) med_int = np.ma.median(disk_data) # np.median doesn't support masking return med_int / exp_time
def get_image(t, x, y): """ This function gets an AIA EUV image from the SDO (AIA = Atmospheric Imaging Assembly, EUV = Extreme UltraViolent, SDO = SOlar Dynamics Observatory) at a given time t, and crops the image to given location x, y. Param: t datetime, the datetime of the flare x integer, the longitude position of the flare in arcsec y integer, the latitude position of the flare in arcsec Return: aia_sub sunpy Map, the cropped image """ # request the data for the given time result = Fido.search(a.Time(t - dt.timedelta(seconds=10), t), a.Instrument("aia"), a.Wavelength(94 * u.angstrom), a.vso.Sample(12 * u.second)) print('found result') #print(result) # download the data file_download = Fido.fetch(result[0, -1], site='ROB') print('downloaded data') #print(file_download) # load the data to a sun map aia1 = sunpy.map.Map(file_download) print('loaded to sun map') #print(aia1) # calibrate it aia = aiaprep(aia1) print('calibrated') # plot it aia.plot() plt.colorbar() #plt.show() # get the co-ordinates of the top right and bottom left of the crop box co_ords = get_box_coord(x, y, 100) tr = co_ords[1] bl = co_ords[2] # sub-map top_right = SkyCoord(tr[0] * u.arcsec, tr[1] * u.arcsec, frame=aia.coordinate_frame) bottom_left = SkyCoord(bl[0] * u.arcsec, bl[1] * u.arcsec, frame=aia.coordinate_frame) aia_sub = aia.submap(top_right, bottom_left) aia_sub.plot_settings['cmap'] = plt.get_cmap('Greys_r') ax = plt.subplot(projection=aia_sub) aia_sub.plot() #plt.show() print('made sub map') return aia_sub
def create_tempmap(date, n_params=1, data_dir=home + 'SDO_data/', maps_dir=home + 'temperature_maps/'): wlens = ['94', '131', '171', '193', '211', '335'] t0 = 5.6 images = [] #imdates = {} print 'Finding data for {}.'.format(date.date()) # Loop through wavelengths for wl, wlen in enumerate(wlens): #print 'Finding {}A data...'.format(wlen), fits_dir = data_dir + '{}/{:%Y/%m/%d}/'.format(wlen, date) filename = fits_dir + 'aia*{0}*{1:%Y?%m?%d}?{1:%H?%M}*lev1?fits'.format( wlen, date) temp_im = Map(filename) # Download data if not enough found client = vso.VSOClient() if temp_im == []: print 'File not found. Downloading from VSO...' # Wavelength value for query needs to be an astropy Quantity wquant = u.Quantity(value=int(wlen), unit='Angstrom') qr = client.query( vso.attrs.Time( date, # - dt.timedelta(seconds=6), date + dt.timedelta(seconds=12)), #6)), vso.attrs.Wave(wquant, wquant), vso.attrs.Instrument('aia'), vso.attrs.Provider('JSOC')) res = client.get(qr, path=fits_dir + '{file}', site='NSO').wait() temp_im = Map(res) if temp_im == []: print 'Downloading failed.' print res, len(qr), qr return np.zeros((512, 512)), None, None if isinstance(temp_im, list): temp_im = temp_im[0] # TODO: save out level 1.5 data so it can be loaded quickly. temp_im = aiaprep(temp_im) temp_im.data = temp_im.data / temp_im.exposure_time # Can probably increase speed a bit by making this * (1.0/exp_time) images.append(temp_im) #imdates[wlen] = temp_im.date normim = images[2].data.copy() # Normalise images to 171A print 'Normalising images' for i in range(len(wlens)): images[i].data = images[i].data / normim # Produce temperature map if n_params == 1: tempmap = find_temp(images, t0) #, force_temp_scan=True) else: #tempmap = find_temp_3params(images, t0) pass return tempmap
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
def create_tempmap(date, n_params=1, data_dir=home+'SDO_data/', maps_dir=home+'temperature_maps/'): wlens = ['94', '131', '171', '193', '211', '335'] t0 = 5.6 images = [] #imdates = {} print 'Finding data for {}.'.format(date.date()) # Loop through wavelengths for wl, wlen in enumerate(wlens): #print 'Finding {}A data...'.format(wlen), fits_dir = data_dir + '{}/{:%Y/%m/%d}/'.format(wlen, date) filename = fits_dir + 'aia*{0}*{1:%Y?%m?%d}?{1:%H?%M}*lev1?fits'.format(wlen, date) temp_im = Map(filename) # Download data if not enough found client = vso.VSOClient() if temp_im == []: print 'File not found. Downloading from VSO...' # Wavelength value for query needs to be an astropy Quantity wquant = u.Quantity(value=int(wlen), unit='Angstrom') qr = client.query(vso.attrs.Time(date,# - dt.timedelta(seconds=6), date + dt.timedelta(seconds=12)),#6)), vso.attrs.Wave(wquant, wquant), vso.attrs.Instrument('aia'), vso.attrs.Provider('JSOC')) res = client.get(qr, path=fits_dir+'{file}', site='NSO').wait() temp_im = Map(res) if temp_im == []: print 'Downloading failed.' print res, len(qr), qr return np.zeros((512, 512)), None, None if isinstance(temp_im, list): temp_im = temp_im[0] # TODO: save out level 1.5 data so it can be loaded quickly. temp_im = aiaprep(temp_im) temp_im.data = temp_im.data / temp_im.exposure_time # Can probably increase speed a bit by making this * (1.0/exp_time) images.append(temp_im) #imdates[wlen] = temp_im.date normim = images[2].data.copy() # Normalise images to 171A print 'Normalising images' for i in range(len(wlens)): images[i].data = images[i].data / normim # Produce temperature map if n_params == 1: tempmap = find_temp(images, t0)#, force_temp_scan=True) else: #tempmap = find_temp_3params(images, t0) pass return tempmap
def run_subpix(self, fits_hmi, index): map_hmi = aiaprep(Map(fits_hmi)) data = map_hmi.data[2048 - 140:2048 + 140, 2048 - 140:2048 + 140] if index == self.nb_stack // 2: data_shift = data else: meta = map_hmi.meta shift_index = index - float(self.nb_stack // 2) rsun = meta['r_sun'] angle = (shift_index * 360. * np.pi) / (self.solar_rot_period * 24. * 80. * 180.) shift = rsun * np.sin(angle) * -1. data_shift = interpolation.shift(data, (0.0, shift), order=1) return data_shift
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
from __future__ import absolute_import import tempfile import numpy as np import sunpy import sunpy.data.test as test from sunpy.instr.aia import aiaprep # Define the original and prepped images first so they're available to all functions original = sunpy.map.Map(test.aia_171_level1) prep_map = aiaprep(original) def test_aiaprep(): # Test that header info for the map has been correctly updated # Check all of these for Map attributes and .meta values? # Check crpix values assert prep_map.meta["crpix1"] == prep_map.data.shape[1] / 2.0 + 0.5 assert prep_map.meta["crpix2"] == prep_map.data.shape[0] / 2.0 + 0.5 # Check cdelt values assert prep_map.meta["cdelt1"] / 0.6 == int(prep_map.meta["cdelt1"] / 0.6) assert prep_map.meta["cdelt2"] / 0.6 == int(prep_map.meta["cdelt2"] / 0.6) # Check rotation value, I am assuming that the inaccuracy in # the CROTA -> PCi_j matrix is causing the inaccuracy here np.testing.assert_allclose(prep_map.rotation_matrix, np.identity(2), rtol=1e-5, atol=1e-8) # Check level number assert prep_map.meta["lvl_num"] == 1.5
from sunpy.instr.aia import aiaprep from sunpy.net import Fido, attrs as a from astropy.coordinates import SkyCoord from astropy import units as u from matplotlib import animation from IPython.display import HTML import warnings warnings.filterwarnings("ignore") download = 'C:\\Users\\Carleano Libretto\\downloads\\LIP2020M5(171(allimgs))' mapped_files = sunpy.map.Map(download) aia_seq = [] k=0 for img in mapped_files: aiaprep(mapped_files[k]) k+=1 top_right = SkyCoord(1400*u.arcsec, 500*u.arcsec, frame=img.coordinate_frame) bottom_left = SkyCoord(600 * u.arcsec, -250. * u.arcsec, frame=img.coordinate_frame) aia_seq.append(img.submap(top_right, bottom_left)) aia = sunpy.map.Map(aia_seq) fig, ax = plt.subplots() # image half down sequence to get better scaling plot_obj = aia[len(aia) // 2].plot() def animate(i): ax.set_title("AIA %s %s" % (aia[i].meta['wave_str'][:-5], aia[i].meta['t_obs'])) plot_obj.set_data(aia[i].data) return (plot_obj,)
from __future__ import absolute_import import tempfile import numpy as np import sunpy import sunpy.data.test as test from sunpy.instr.aia import aiaprep # Define the original and prepped images first so they're available to all functions original = sunpy.map.Map(test.aia_171_level1) prep_map = aiaprep(original) def test_aiaprep(): # Test that header info for the map has been correctly updated # Check all of these for Map attributes and .meta values? # Check crpix values assert prep_map.meta['crpix1'] == prep_map.data.shape[1] / 2.0 + 0.5 assert prep_map.meta['crpix2'] == prep_map.data.shape[0] / 2.0 + 0.5 # Check cdelt values assert prep_map.meta['cdelt1'] / 0.6 == int(prep_map.meta['cdelt1'] / 0.6) assert prep_map.meta['cdelt2'] / 0.6 == int(prep_map.meta['cdelt2'] / 0.6) # Check rotation value, I am assuming that the inaccuracy in # the CROTA -> PCi_j matrix is causing the inaccuracy here np.testing.assert_allclose(prep_map.rotation_matrix, np.identity(2), rtol=1e-5, atol=1e-8) # Check level number
def prep_map(original): with pytest.warns(SunpyDeprecationWarning): return aiaprep(original)
wlens = ["094", "131", "171", "193", "211", "335"] t0 = 5.6 thiswlen = None if rank == 0: if datfile: images = {} f = open(datfile) # Loop through wavelengths for line in f: if line[:3] in wlens: allwlenmaps = [] thiswlen = line[:3] print "Loading {} files".format(thiswlen) elif "fits" in line: thismap = aiaprep(Map(line[:-1])) thismap.data /= thismap.exposure_time allwlenmaps.append(thismap) elif line.strip() in ["", "\n"]: if thiswlen: wlenmap = allwlenmaps[-1] for thismap in allwlenmaps[:-1]: wlenmap.data += thismap.data wlenmap.data /= len(allwlenmaps) images[thiswlen] = wlenmap images = [images[w] for w in wlens] else: images = [] # imagefiles = [] for wl, wlen in enumerate(wlens):
def process_img(fits_file, fname=None, downscale=None, rescale_brightness=True, side_by_side=False, timestamp=True, single_channel=False, suppress_aia_prep=False, custom_f=lambda x: x): """Produces an AIA image of the Sun from a fits file Parameters ---------- fits_file: str (Eg 'dir/image482005.fits') name of fits file to process fname : str (Eg 'dir/out_img.jpg') file name to save image as If None: returns a PIL image instance instead of saving directly downscale: tuple of two ints (Eg: (8, 8)) downscales the data by (x, y) factor if filled rescale_brightness: bool determines if brightness correction is done side_by_side: bool make a side-by-side comparison of the scaled and not brightness scaled images timestamp: bool show timestamp or not single_channel: bool return image data in np array before applying the colormap suppress_aia_prep: bool not do aia prep if image below lvl 1 custom_f: function custom function applied to data array applied early on, just after aiaprep """ hdr = sun_intensity.getFitsHdr(fits_file) wavelength = str(hdr['wavelnth']) exptime = hdr['EXPTIME'] cmap = get_cmap('sdoaia' + wavelength) cmap.set_bad() imin, imax = MINMAX[wavelength] themap = Map(fits_file) if (hdr['lvl_num'] != 1.5) and (not suppress_aia_prep): # perform aiaprep if data not at level 1.5 themap = aiaprep(themap) data = themap.data data = np.flipud(data) data = custom_f(data) # apply custom function data data = data / exptime # normalize for exposure norm_scale = STANDARD_INT[wavelength] dim_factor = sun_intensity.get_dim_factor(themap.date, wavelength) data = data * norm_scale if downscale: data = downscale_local_mean(data, downscale) if rescale_brightness or side_by_side: imin = imin / dim_factor # brightness correction imax = imax / dim_factor data[0, 0] = imin # first pixel set to min data[0, 1] = imax # second pixel sit to max if SQRT_NORM[wavelength]: norm = colors.PowerNorm(1) data = np.sqrt(np.clip(data, imin, imax)) else: norm = colors.LogNorm(vmin=imin, vmax=imax, clip=True) if single_channel: return norm(data) pil_img = misc.toimage(cmap(norm(data))) width, height = pil_img.size if side_by_side: new_img = Image.new('RGB', (width * 2, height)) new_img.paste(pil_img, (0, 0)) second_image = process_img(fits_file, downscale=downscale, rescale_brightness=False, timestamp=False) new_img.paste(second_image, (width, 0)) pil_img = new_img if timestamp: draw = ImageDraw.Draw(pil_img) font_height = int(height / 64) font = ImageFont.truetype('/Library/Fonts/Arial.ttf', font_height) draw.text((font_height, height - (2 * font_height)), 'SDO/AIA- ' + wavelength + ' ' + themap.date.strftime('%Y-%m-%d %H:%M:%S'), font=font) if fname: pil_img.save(fname) else: return pil_img
def prep_map(original): return aiaprep(original)
# In[23]: file_download = Fido.fetch(result[0, 3], site='ROB') # Read downloaed file in Map form. # In[5]: aia1 = sunpy.map.Map(file_download[0]) # Prepare the Map (Correct for rotation and revolution if needed) # In[6]: aia = aiaprep(aia1) # Finaly Plot the data # In[19]: plt.rc('font', family='serif') plt.figure(figsize=[8, 10]) aia.plot() aia.draw_limb() plt.grid(False) #plt.colorbar() plt.show() # In[ ]:
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
## rebinning AIA data opdir = '/Users/mskirk/data/AIA/TempQuicklook/304/' import os import fnmatch import sunpy.map as map import sunpy.instr.aia as aia fls = fnmatch.filter(os.listdir(opdir), '*.fits') itr = 0 for file in fls: aia_map = aia.aiaprep(map.Map(opdir + file)) prep_map = aia_map.resample([1024, 1024]) prep_map.save(opdir + file, filetype='fits', clobber=True) itr = itr + 1 print itr
def download_AIA_data(rec_time, doCut=True, jsoc_serie='aia.lev1_euv_12s', wavelength=[94, 131, 171, 193, 211, 304, 335]): ''' Download the AIA data from a given time which is same to the HMI data in this project. Parameters: ---------------------------- rec_time: String (in JSOC time format) The HMI record time, locate the corresponding AIA data, notice that the record time maybe not exactly the same doCut: Bool (Default is True) Control if the AIA data is cropped jsoc_serie: String The jsoc series to get the AIA data, default is 'aia.lev1_euv_12s' wavelength: List The wavelengths for the AIA data, all avaiable are [94,131,171,193,211,304,335] Returns: ---------------------------- For now, the return is a dictionary, data part are image datas, keys are channels (wavelength). [Output HDF5 files in the future.] ''' c = drms.Client() # Query the HMI data, because can't directly get the record time from the # HMI fits files ds_HMI = '{}[{}]'.format('hmi.sharp_cea_720s[1-7256]', rec_time) keys_HMI, segments_HMI = c.query(ds_HMI, key=drms.const.all, seg='magnetogram') url_hmi_cea = 'http://jsoc.stanford.edu' + segments_HMI.magnetogram[0] hmi_image = fits.open(url_hmi_cea) ds = '{}[{}]'.format(jsoc_serie, rec_time) avaiable_wavelengths = [94, 131, 171, 193, 211, 304, 335] for wlength in wavelength: if wlength not in avaiable_wavelengths: raise RuntimeError('Wavelength not avaiable!') ds = ds + str(wavelength) keys_AIA, segments_AIA = c.query(ds, key=drms.const.all, seg='image') # The all aia urls urls_aia = 'http://jsoc.stanford.edu' + segments_AIA['image'] aia_data_dict = dict() for chnl in range(len(wavelength)): url = urls_aia[chnl] image_file = download_file(url, cache=False) aiamap = aiaprep(Map(image_file)) fullsize_aia_image_data = np.array(aiamap.data, dtype=np.int16) if doCut: aia_image_data = cut_AIA(keys_AIA.loc[chnl], keys_HMI, fullsize_aia_image_data, hmi_image) else: aia_image_data = fullsize_aia_image_data wavelnth = str(int(aiamap.wavelength.value)) aia_data_dict[wavelnth] = aia_image_data return aia_data_dict, keys_AIA, keys_HMI
a = 1. b = -2 * (r_1.to(u.cm) * np.cos(phi.to(u.radian))) c = r_1.to(u.cm)**2 - r_2.to(u.cm)**2 r = (-b + np.sqrt(b**2 - 4 * a * c)) / 2 / a # Choose only points above the surface i_r = np.where(r > r_1) r = r[i_r] phi = phi[i_r] hcc_frame = Heliocentric( observer=SkyCoord(lon=75 * u.deg, lat=25 * u.deg, radius=r_1, frame='heliographic_stonyhurst')) return (SkyCoord(y=r.to(u.cm) * np.sin(phi.to(u.radian)), x=u.Quantity(r.shape[0] * [0 * u.cm]), z=r.to(u.cm) * np.cos(phi.to(u.radian)), frame=hcc_frame).transform_to('heliographic_stonyhurst')) loop = semi_circular_loop(140 * u.Mm, theta0=5 * u.deg) aia = glob.glob('C:\\Users\\Carleano Libretto\\downloads\\LIP2020M5(171)') aia = sorted(aia) dummy_map = (sunpy.map.Map(aia)) dummy_map = aiaprep(dummy_map[0]) fig = plt.figure(figsize=(30, 35)) ax = fig.gca(projection=dummy_map) dummy_map.plot(title=False) ax.plot_coord(loop.transform_to(dummy_map.coordinate_frame), color='C3', lw=3) #ax.plot_coord(SkyCoord(1400*u.arcsec, 500*u.arcsec, frame=dummy_map.coordinate_frame)) #ax.plot_coord(SkyCoord(600*u.arcsec, -250*u.arcsec, frame=dummy_map.coordinate_frame))