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)) # Show the figure plt.savefig(img_filepath + '_wave_progress_map.{:s}'.format(image_file_type))
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,
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()
c_map = Map(sun_image, fp_map, best_long_score_map, composite=True) # 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 fit map\n{:s}".format(observation) image_file_type = 'png' 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(color='c') c_map.draw_grid(color='c') # Add a small circle to indicate the estimated epicenter of the wave ip = SkyCoord(transform_hpc2hg_parameters['epi_lon'], transform_hpc2hg_parameters['epi_lat'], frame='heliographic_stonyhurst').transform_to(sun_image.coordinate_frame) ccc = Circle((ip.Tx.value, ip.Ty.value), radius=50, edgecolor='w', fill=True, facecolor='c', zorder=1000) axes.add_patch(ccc) # 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)
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