def plotTECmap(x, y, z, title='', cmap='viridis', clim=[0, 15], figsize=(10, 6), latlim=[0, 70], lonlim=[-150, -60], projection='stereo', background_color='gray', grid_color='w', border_color='#006600', meridians=[-180, -150, -120, -90, -60, -40, -20], parallels=[0, 20, 30, 40, 50, 60, 70, 80], colorbar=True, cbar_label='TEC [TECu]', tight=False, savefn=False, DPI=100, nightshade=False, ns_dt=None, ns_alpha=0.1): # Make map fig = gm.plotCartoMap(figsize=figsize, projection=projection, latlim=latlim, lonlim=lonlim, parallels=parallels, meridians=meridians, title=title, background_color=background_color, grid_color=grid_color, grid_linewidth=1, border_color=border_color, figure=True, nightshade=nightshade, ns_dt=ns_dt, ns_alpha=ns_alpha) plt.pcolormesh(x, y, z.T, cmap=cmap, transform=ccrs.PlateCarree()) plt.clim(clim) if colorbar: cbar = plt.colorbar() cbar.set_label(cbar_label) if tight: plt.tight_layout() # Save if savefn is not None and isinstance(savefn, str): try: plt.savefig(savefn, dpi=DPI) plt.close(fig) except Exception as e: raise (e) else: plt.show() return fig
def overlay2d(img: xarray.DataArray, ofn: Path=None, mlp: Dict[str, Any]={}, lattick: Union[float, int, list]=None, lontick: Union[float, int, list]=None, scalefn: Path=None, verbose: bool=False) -> dict: """plot NEXRAD reflectivity on map coordinates""" if figure is None: logging.error('skipping overlay plot') return {} title = img.filename.stem[6:-3] def _savemap(ofn, fg): ofn=str(ofn) print('\n Saving Nexrad map:', ofn) plt.savefig(ofn, dpi=DPI) plt.close(fig) fig = cm.plotCartoMap(latlim=LATLIM,lonlim=LONLIM,figsize=FIGSIZE, title=title,projection=PROJECTION, parallels=PARALLELS,meridians=MERIDIANS, grid_linewidth=grid_linewidth, grid_color=grid_color) plt.imshow(img, origin='upper', extent=[img.lon[0], img.lon[-1], img.lat[0], img.lat[-1]], transform=ccrs.PlateCarree()) plt.tight_layout() if scalefn and scalefn.is_file(): scale = np.rot90(imageio.imread(scalefn), 2) ax = fig.add_axes([0.9, 0.15, 0.055, 0.3]) ax.imshow(scale) ax.axis('off') # turn off all ticks, etc. if ofn is not None: _savemap(ofn, fig) else: plt.show() return mlp
def plotIMmap(x, y, z, title='', save=False, lon0=None, lat0=None, alt=None, clim=[0, 3000], cmap='Greens', norm_gamma=None, figure=False): # Figure limits maplatlim = [58, 72] maplonlim = [-162, -132] meridians = [-165, -155, -145, -135, -125] parallels = [55, 60, 65, 70, 75] # Plot ax = ggm.plotCartoMap(latlim=maplatlim, lonlim=maplonlim, meridians=meridians, parallels=parallels, projection='merc', title=title) if lon0 is not None and lat0 is not None: plt.plot(lon0, lat0, 'xr', ms=10, transform=ccrs.PlateCarree()) if alt is not None: plt.text(np.mean(maplonlim) + 0.2 * np.diff(maplonlim)[0], maplatlim[1], '{}km'.format(alt), fontsize=12, fontweight='bold', color='blue', transform=ccrs.PlateCarree()) gca = plt.pcolormesh(x, y, z, cmap=cmap, transform=ccrs.PlateCarree()) if norm_gamma is not None: gca.set_norm(colors.PowerNorm(gamma=norm_gamma)) plt.clim(clim) plt.colorbar() if figure: pass # return fig plt.show()
im_levels = streammap.get('image_nlevels') levels = linspace(clim[0],clim[1], im_levels) # Image processing fillpixeriter = 3 # Image overlays: Scatter locations marker_locations = streammap.get('marker_location') marker = streammap.get('marker') marker_color = streammap.get('marker_color') marker_size = streammap.get('marker_size') marker_width = streammap.get('marker_width') # --------------------------------------------------------------------------- # # Make a map: ALWAYS # --------------------------------------------------------------------------- # fig = cm.plotCartoMap(projection=projection, latlim=latlim,lonlim=lonlim,parallels=parallels, meridians=meridians,figsize=figure_size, background_color=background_color,border_color=border_color, grid_color=grid_color,grid_linestyle=grid_linestyle, grid_linewidth=grid_linewidth, terrain=terrain,figure=True) # --------------------------------------------------------------------------- # # Plot the TEC image # --------------------------------------------------------------------------- # if DTEC: # Get data datafn = 'single233_02_130_60.h5' # datafn = 'single232_02_130_60.h5' # datafn = 'single233_02_cut.h5' # datafn = 'single234_02.h5' fn = folder + datafn #i = 2273 # 18:57 # i = 2243 # 18:42 i = 2235 # 18:38
idt_tec = abs(tectime - it).argmin() tecim = D['tecim'][idt_tec - 2:idt_tec + 1] tecim = np.nanmean(tecim, 0) fig, ax = cm.plotCartoMap( latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, grid_linewidth=1, states=False, title='{} -- {}'.format(os.path.split(dmspfn)[1][:3].upper(), it), background_color='grey', # nightshade=True, ns_dt=it, apex=True, mlat_levels=[-80, -60, -40, -20, 0, 20, 40, 60, 80, 90], mlat_colors='m', mgrid_width=1, mgrid_style='--', mlon_levels=np.arange(0, 361, 40), mlat_labels=False, mlon_colors='m', mlon_labels=False, # igrf=True, date=it, # decl_levels=[0], decl_colors='w') ) im = plt.pcolormesh( xgrid, ygrid,
def main(date='', root=None, scintfn=None, clim=None, tlim=None, trange=2.5, odir=None, SAVE=1, resolution=5): if tlim is None: tlim = [parser.parse(date), parser.parse(date) + timedelta(days=1)] if isinstance(tlim[0], str): tlim = [parser.parse(tlim[0]), parser.parse(tlim[1])] assert isinstance(tlim[0], datetime) and isinstance(tlim[1], datetime) obstimes = [] t = tlim[0] while t <= tlim[1]: obstimes.append(t) t += timedelta(minutes=resolution) latlim=[-10, 75] lonlim=[-160, -50] DPI = 100 if clim is None: tecclim = [0, 20] else: tecclim = clim if root is None: if platform.system() == 'Windows': root = os.getcwd() else: root = '/home/smrak/Documents/scintillation/' if odir is None: if platform.system() == 'Windows': odir = root + '\\maps\\{}\\{}\\bw-{}-{}\\'.format(tlim[0].year, parser.parse(date).strftime("%Y%m%d"), tecclim[0], tecclim[1]) TECFN = root + '\\maps\\{}\\{}\\conv_{}T0000-{}T0000.h5'.format(tlim[0].year, parser.parse(date).strftime("%Y%m%d"), tlim[0].strftime("%m%d"), tlim[1].strftime("%m%d")) else: odir = root + '/maps/{}/bw-{}-{}/'.format(parser.parse(date).strftime("%Y%m%d"), tecclim[0], tecclim[1]) TECFN = '/media/smrak/figures/gpstec/{}/{}/conv_{}T0000-{}T0000.h5'.format(parser.parse(date).year, parser.parse(date).strftime("%m%d"), tlim[0].strftime("%Y%m%d"), tlim[1].strftime("%Y%m%d")) if platform.system() == 'Windows': TECFN = root + '\\maps\\{}\\{}\\conv_{}T0000-{}T0000.h5'.format(tlim[0].year, parser.parse(date).strftime("%Y%m%d"), tlim[0].strftime("%m%d"), (tlim[0]+timedelta(days=1)).strftime("%m%d")) else: TECFN = '/media/smrak/figures/gpstec/{}/{}/conv_{}T0000-{}T0000.h5'.format(parser.parse(date).year, parser.parse(date).strftime("%m%d"), tlim[0].strftime("%Y%m%d"), (tlim[0]+timedelta(days=1)).strftime("%Y%m%d")) assert os.path.isfile(TECFN), TECFN if scintfn is None: if platform.system() == 'Windows': scint_root = root + '\\hdf\\{}\\'.format(tlim[0].year) else: scint_root = root + '/hdf/' scint_fn_list = sorted(glob.glob(scint_root + "ix_{}_{}T*.h5".format(tlim[0].year, tlim[0].strftime("%m%d")))) assert len(scint_fn_list) > 0 scintfn = scint_fn_list[0] assert os.path.isfile(scintfn) # --------------------------------------------------------------------------- # for ii, it in enumerate(obstimes): # TEC data D = gpstec.readFromHDF(TECFN) tectime = D['time'] xgrid = D['xgrid'] ygrid = D['ygrid'] idt_tec = abs(tectime - it).argmin() tecim = D['tecim'][idt_tec] # Scintillation data scintdata = h5py.File(scintfn, 'r') scint_time = scintdata['data/time'][:] scint_dt = np.array([datetime.utcfromtimestamp(t) for t in scint_time]) # Filter out time range of interest scint_idt = np.zeros(scint_dt.size, dtype=bool) time_range = np.where( (scint_dt >= it-timedelta(minutes=trange)) & (scint_dt <= it+timedelta(minutes=trange)) )[0] scint_idt[time_range[0]:time_range[-1]+1] = True # scint_idt[time_range[0]] = True # Read in data ipp_lat = scintdata['data/ipp'][scint_idt, :, :, 0] ipp_lon = scintdata['data/ipp'][scint_idt, :, :, 1] sigma_tec = scintdata['data/sigma_tec'][scint_idt, :, :] snr4 = scintdata['data/snr4'][scint_idt, :, :] # Plot fig = plt.figure(figsize=[12,6]) ax0 = plt.subplot(121, projection=ccrs.Stereographic(central_longitude=(sum(lonlim)/2))) ax1 = plt.subplot(122, projection=ccrs.Stereographic(central_longitude=(sum(lonlim)/2))) ax0 = cm.plotCartoMap(latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, ax=ax0, grid_linewidth=1, states = False, title=it, background_color='grey', apex=True, mlat_levels=[-20,0,20,40,60,80,90], mlat_colors='w', mgrid_width=1, mgrid_style='--', mlon_levels=np.arange(0,361,40), mlat_labels=False, mlon_colors='w', mlon_labels=False) ax1 = cm.plotCartoMap(latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, ax=ax1, grid_linewidth=1, states = False, title=it, background_color='grey', apex=True, mlat_levels=[-20,0,20,40,60,80,90], mlat_colors='w', mgrid_width=1, mgrid_style='--', mlon_levels=np.arange(0,361,40), mlat_labels=False, mlon_colors='w', mlon_labels=False) # ------------------------------------------------------------------------- - # im0 = ax0.pcolormesh(xgrid, ygrid, tecim.T, cmap='gray', vmin = tecclim[0], vmax = tecclim[1], transform=ccrs.PlateCarree()) im1 = ax1.pcolormesh(xgrid, ygrid, tecim.T, cmap='gray', #'nipy_spectral' vmin = tecclim[0], vmax = tecclim[1], transform=ccrs.PlateCarree()) # Scint with amplitude if np.sum(np.isfinite(sigma_tec)) > 0: ax0.scatter(ipp_lon, ipp_lat, c = 'r', s = (sigma_tec)**2 * 1000000, marker = '+', alpha=0.2, # facecolors = 'none', transform = ccrs.PlateCarree()) if np.sum(np.isfinite(snr4)) > 0: ax0.scatter(ipp_lon, ipp_lat, c = 'b', s = np.square(snr4) * 1000, linewidth = 0.8, marker = 'x', alpha = 1, # facecolors = 'none', transform = ccrs.PlateCarree()) # Scint locations if np.sum(np.isfinite(sigma_tec)) > 0: maskst = np.isfinite(sigma_tec) ax1.scatter(ipp_lon[maskst], ipp_lat[maskst], c = 'r', s = 2, marker = '.', alpha=0.5, transform = ccrs.PlateCarree()) if np.sum(np.isfinite(snr4)) > 0: masks4 = np.isfinite(snr4) ax1.scatter(ipp_lon[masks4], ipp_lat[masks4], c = 'b', s = 10, lw = 0.2, marker = 'x', alpha = 0.5, transform = ccrs.PlateCarree()) posn = ax1.get_position() cax = fig.add_axes([posn.x0+posn.width+0.01, posn.y0, 0.02, posn.height]) fig.colorbar(im1, cax=cax, label='TEC [TECu]') if SAVE: if not os.path.exists(odir): import subprocess if platform.system() == 'Linux': subprocess.call('mkdir -p "{}"'.format(odir), shell=True, timeout=2) elif platform.system() == 'Windows': subprocess.call('mkdir "{}"'.format(odir), shell=True, timeout=2) print ("Plotting {}/{} - {}".format(ii+1, len(obstimes), it)) fig.savefig(odir+'{}.png'.format(it.strftime('%m%d_%H%M')), dpi=DPI) plt.close(fig) del fig del sigma_tec del snr4
skip = 3 average = 5 it = datetime(2017, 5, 28, 3, 0) D = gpstec.merge_time(TECFN) tectime = D['time'] xgrid = D['xgrid'] ygrid = D['ygrid'] idx = (xgrid >= -125) & (xgrid <= -58) idy = (ygrid >= 25) & (ygrid <= 50) idt_tec = abs(tectime - it).argmin() tecim = np.nanmean(D['tecim'][idt_tec-average : idt_tec+1], axis=0) tecim[~idx, :] = np.nan tecim[:, ~idy] = np.nan fig, ax = gm.plotCartoMap(latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, grid_linewidth=1, states = False, title=it, background_color='grey', apex=True, mlat_levels=[-20,0,20,40,60,80,90], mlat_colors='w', mgrid_width=1, mgrid_style='--', mlon_levels=np.arange(0,361,40), mlat_labels=False, mlon_colors='w', mlon_labels=False) im = ax.pcolormesh(xgrid, ygrid, tecim.T, cmap=cmap, vmin=clim[0], vmax=clim[1], transform=ccrs.PlateCarree()) lap = laplace(tecim) lap[lap<0] = np.nan ax.contour(xgrid, ygrid, lap.T, cmap='jet', transform=ccrs.PlateCarree())
import numpy as np from cartomap import geogmap as gm import matplotlib.pyplot as plt import cartopy.crs as ccrs import igrf12 latlim = [30, 85] lonlim = [-160, -60] date = datetime(2017, 8, 21, 11) fig = gm.plotCartoMap( projection='stereo', title='Magnetic declination angle. Ground (solid), 150 km (dashed)', latlim=latlim, lonlim=lonlim, parallels=[20, 40, 60, 80, 90], meridians=[-220, -180, -160, -140, -120, -100, -80, -60, -40, 0], grid_linewidth=1, figure=True, states=False) glon = np.arange(0, 360, 1) glat = np.arange(-90, 90.1, 1) longrid, latgrid = np.meshgrid(glon, glat) mag0 = igrf12.gridigrf12(t=date, glat=latgrid, glon=longrid, alt_km=0.0) mag150 = igrf12.gridigrf12(t=date, glat=latgrid, glon=longrid, alt_km=150.0) # Declination #ai = plt.contour(longrid, latgrid, mag0.decl.values, levels=np.arange(-30,30.1,1), # cmap='bwr', transform=ccrs.PlateCarree())
j += 1 # Get a map fig, ax = gm.plotCartoMap( figsize=figure_size, projection=projection, #title=dt[i], terrain=terrain, states=states, border_color=border_color, background_color=background_color, lonlim=lonlim, latlim=latlim, title="{}, alt = {} km".format(dt[i], altkm), meridians=meridians, parallels=parallels, grid_linewidth=grid_linewidth, grid_color=grid_color, apex=apex, mlon_cs=mlon_cs, date=dt[i], mlon_levels=mag_meridians, mlat_levels=mag_parallels, mlon_labels=False, mlat_labels=False, mgrid_style='--', mlon_colors='w', mlat_colors='w', terminator=terminator, terminator_altkm=terminator_altkm, ) # dTEC/TEC ? if fntec is not None:
def plot(fnhdf: str = None, odir: str = None, cfg: str = None, clim: list = None, mode: str = None, average: int = None, cmap=None, projection=None, lonlim=None, latlim=None, terminator=None): C0 = clim fnhdf = os.path.expanduser(fnhdf.strip()) assert fnhdf is not None assert os.path.splitext(fnhdf)[1] in ['.h5', '.hdf5'] # Converted file D = gpstec.readFromHDF(fnhdf) if cfg is None: folder = os.path.expanduser(os.path.join(os.getcwd(), 'map')) mcfg = sorted(glob(os.path.join(folder, '*.yaml')))[0] else: assert os.path.splitext(cfg)[1] in ['.yaml', 'yml'] mcfg = cfg # Map mst = yaml.load(open(mcfg, 'r')) if projection is None: projection = mst.get('projection') if cmap is None: cmap = mst.get('cmap') if lonlim is None: lonlim = mst.get('lonlim') if latlim is None: latlim = mst.get('latlim') try: nightshade = mst.get('nightshade') except: pass try: paralim = mst.get('parallels') meridilim = mst.get('meridians') parallels = np.arange(paralim[0], paralim[1], paralim[2]) meridians = np.arange(meridilim[0], meridilim[1], meridilim[2]) except: parallels = [] meridians = [] try: apex = True mlatlim = mst.get('mlat') mltlim = mst.get('mlt') mlat_levels = np.arange(mlatlim[0], mlatlim[1] + .1, mlatlim[2]) mlon_levels = np.arange(mltlim[0], mltlim[1] + .1, mltlim[2]) except: apex = False mlat_levels = None mlon_levels = None if mode is None: mode = 'lin' if isinstance(mode, str): mode = [mode] colorbar = mst.get('colorbar') cbar_label = mst.get('cbar_label') if mst.get( 'cbar_label') is not None else 'TEC [TECu]' if clim is None: clim = mst.get('clim') if clim is None: vmax = 3 * _round(np.nanmedian(D['tecim']), base=5) vmin = 0 clim = [vmin, vmax] else: vmax = float(clim[1]) vmin = float(clim[0]) clim = [vmin, vmax] figsize = mst.get('figsize') if mst.get('figsize') is not None else [12, 8] background_color = mst.get('background_color') if mst.get( 'background_color') is not None else 'grey' grid_color = mst.get('grid_color') if mst.get( 'grid_color') is not None else 'white' grid_linewidth = mst.get('grid_linewidth') if mst.get( 'grid_linewidth') is not None else 1 grid_linestyle = mst.get('grid_linestyle') if mst.get( 'grid_linestyle') is not None else '--' dpi = int(mst.get('DPI')) if mst.get('DPI') is not None else 50 # Plot for mode in mode: if mode == 'log': clim[1] = np.log10(vmax) else: clim[1] = vmax iterate = np.arange(0, D['time'].size, average) for i in iterate: #range(D['time'].shape[0]): t0 = D['time'][i] z = np.log10(np.nanmean(D['tecim'][i:i + average], axis=0)) if mode == 'log' else np.nanmean( D['tecim'][i:i + average], axis=0) fig, ax = gm.plotCartoMap( latlim=latlim, lonlim=lonlim, projection='merc', #lon0 = -90,#glons[idmidnight], title=t0, #lat0 = 40, meridians=None, parallels=None, figsize=figsize, background_color='gray', border_color='k', states=0, apex=True, mlat_labels=0, mlon_labels=0, mlat_levels=mlat_levels, mlon_levels=mlon_levels, date=t0, mlon_colors='w', mlat_colors='w', mlon_cs='mlt', terminator=True, ter_color='r', terminator_altkm=350) print("Plotting {}".format(D['time'][i])) im = plt.pcolormesh(D['xgrid'], D['ygrid'], z.T, cmap=cmap, transform=ccrs.PlateCarree()) plt.clim(clim) if colorbar: posn = ax.get_position() cax = fig.add_axes( [posn.x0 + posn.width + 0.01, posn.y0, 0.02, posn.height]) fig.colorbar(im, cax=cax, label='TEC [TECu]') if odir is None: odir = os.path.join( os.path.split(fnhdf)[0], D['time'][i].strftime("%Y%m%d")) svdir = projection + '_' + mode + '_' + str(int( clim[0])) + '-' + str(int(clim[1])) figdir = os.path.expanduser(os.path.join(odir, svdir)) if not os.path.exists(figdir): print('Creating a new directory: ', figdir) if platform.system == 'Linux': subprocess.call('mkdir -p {}'.format(figdir), shell=True, timeout=5) else: subprocess.call('mkdir "{}"'.format(figdir), shell=True, timeout=5) fn = D['time'][i].strftime('%m%d_%H%M') figname = fn + str('.png') plt.savefig(os.path.join(figdir, figname), dpi=dpi) plt.close(fig=fig)
date = '20170821' wl = 193 galt = 150 root = root = "\\".join(os.getcwd().split('\\')[:-1]) EOFF = glob.glob( root + "\\data\\{}\\SDO193ephem_test\\{}A_{}*km*.nc".format(date, wl, galt)) odir = root + "\\data\\{}\\EOF\\{}_{}\\".format(date, wl, galt) for f in EOFF: EOF = xarray.open_dataset(f) t = np.datetime64(EOF.time.values, 's').astype(datetime) fig, ax = gm.plotCartoMap(projection='plate', lon0=0, figsize=[8, 5], lonlim=[-180, 180], latlim=[-90, 90], title='{}, Alt = {} km'.format( t, EOF.alt_km.values), meridians=np.arange(-180, 180.1, 40), parallels=np.arange(-80, 81, 20), background_color='grey') # lap = abs(ndimage.laplace(EOF.of.values)) # lap[lap<0.001] = np.nan # LAP = ax.contourf(EOF.glon.values, EOF.glat.values, lap.T, cmap='terrain', # levels = np.linspace(0.008, 0.1, 40),# vmin=0.001, vmax=0.08, # transform=ccrs.PlateCarree()) OF = ax.pcolormesh(EOF.glon.values, EOF.glat.values, EOF.of.values, cmap='terrain', vmin=0, vmax=1,
def plotDMSPtrack(glon, glat, galt, dt=None, latlim=[-70, 70], lonlim=[-150, -50], meridians=None, parallels=None, mlon_levels=np.arange(0, 361, 40), mlat_levels=np.arange(-90, 91, 30), original=True, northb=False, conjugated=False, conjugated_altkm=None, conjugated_linestyle='--', lw=3, color='m', nticks=None, tick_labels=False, mlon_labels=True, mlat_labels=True): fig, ax = gm.plotCartoMap(latlim=[-70, 70], lonlim=[-150, -50], projection='stereo', background_color='w', grid_linewidth=1, states=False, meridians=meridians, parallels=parallels, apex=True, mlon_cs='mlon', mlon_levels=mlon_levels, mlon_colors='b', mgrid_style='-', mgrid_width=1, mlat_levels=mlat_levels, mlat_colors='b', mlon_labels=mlon_labels, mlat_labels=mlat_labels) if conjugated_altkm is None: conjugated_altkm = galt if original: if np.nanmax(abs(glon)) > 180: glon = np.unwrap(glon, 180) plt.plot(glon, glat, c=color, lw=lw, transform=ccrs.PlateCarree()) if conjugated: #1: To mag A = Apex() mlat, mlon = A.convert(lon=np.unwrap(glon, 180), lat=glat, source='geo', dest='apex', height=conjugated_altkm) #2: Conjugated --> back to geog Cglat, Cglon = A.convert(lat=-mlat, lon=mlon, source='apex', dest='geo', height=conjugated_altkm) #3 Plot conjugaed track plt.plot(Cglon, Cglat, conjugated_linestyle, c=color, lw=lw, transform=ccrs.PlateCarree()) if northb: glon = np.unwrap(glon, 180) #1: To mag A = Apex() mlat, mlon = A.convert(lon=glon, lat=glat, source='geo', dest='apex', height=conjugated_altkm) #2: Conjugated --> back to geog Cglat, Cglon = A.convert(lat=-mlat, lon=mlon, source='apex', dest='geo', height=conjugated_altkm) # m1 = mlat >= 0 m2 = mlat <= 0 glon[m2] = Cglon[m2] glat[m2] = Cglat[m2] plt.plot(glon, glat, c=color, lw=lw, transform=ccrs.PlateCarree()) # plt.plot(Cglon[m2], Cglat[m2], c=color, lw=lw, transform=ccrs.PlateCarree()) if nticks is not None: ixticks = np.linspace(0, glon.size - 1, nticks).astype(np.int16) if original or northb: plt.scatter(np.unwrap(glon, 180)[ixticks], glat[ixticks], marker=1, c=color, s=50, transform=ccrs.PlateCarree()) if conjugated: plt.scatter(np.unwrap(Cglon, 180)[ixticks], Cglat[ixticks], marker=1, c=color, s=50, transform=ccrs.PlateCarree()) if tick_labels: if dt is None: print( 'Ther is trajectory time information. Set-up the "dt" argument if you want tick labels.' ) else: if not isinstance(dt[0], datetime.datetime): dt = dt.astype(datetime.datetime) assert isinstance(dt[0], datetime.datetime) fmt = np.array([t.strftime("%H:%M") for t in dt[ixticks]]) if original or northb: fx = np.unwrap(glon, 180)[ixticks] + 2.5 fy = glat[ixticks] - 1 for i, txt in enumerate(fmt): if (fx[i] > lonlim[0]) and (fx[i] < lonlim[1]) and ( fy[i] > latlim[0]) and (fy[i] < latlim[1]): plt.text(fx[i], fy[i], txt, color=color, transform=ccrs.PlateCarree()) if conjugated: fx = np.unwrap(Cglon, 180)[ixticks] + 2.5 fy = Cglat[ixticks] - 1 for i, txt in enumerate(fmt): if (fx[i] > lonlim[0]) and (fx[i] < lonlim[1]) and ( fy[i] > latlim[0]) and (fy[i] < latlim[1]): plt.text(fx[i], fy[i], txt, color=color, transform=ccrs.PlateCarree()) return fig, ax
def main(idir=None, wl=None, alt_km=None, odir=None, tlim=None, laplace=0, auroral_oval=0, clabel=0, lat0=None, lon0=None, save=1): cmax = 10 if clabel else 25 clw = 1 if clabel else 0.5 if auroral_oval: apx = 1 else: apx = 0 if odir is None: if laplace: odir = os.path.join(idir, "{}_{}_lap\\".format(wl, alt_km)) else: odir = os.path.join(idir, "{}_{}\\".format(wl, alt_km)) if not os.path.exists(odir): subprocess.call('mkdir "{}"'.format(odir), timeout=2, shell=True) assert os.path.exists(odir) EOFF = np.array( sorted(glob.glob(idir + "*_{}km_{}*.nc".format(alt_km, wl)))) f_times = [] for f in EOFF: try: f_times.append(parser.parse(os.path.split(f)[1][:14])) except: pass f_times = np.array(f_times) assert (f_times.size > 0) if tlim is None: idt = np.ones(f_times.size, dtype=bool) else: tlim = [parser.parse(tlim[0]), parser.parse(tlim[1])] assert len(tlim) == 2 idt = (f_times >= tlim[0]) & (f_times <= tlim[1]) # F = EOFF[idt] # for i, f in enumerate(F): t = f_times[idt][i] save_fn = odir + "{}_{}_{}.png".format(t.strftime("%Y%m%d_%H%M%S"), alt_km, wl) EOF = xarray.open_dataset(f) fig, ax = gm.plotCartoMap(projection=projection, lon0=lon0, lat0=lat0, figsize=[8, 5], lonlim=[-180, 180], latlim=[-90, 90], title='{}, Alt = {} km'.format( t, EOF.alt_km.values), meridians=np.arange(-180, 180.1, 40), parallels=np.arange(-80, 81, 20), background_color='grey', apex=apx, mlat_levels=mlat_levels, mlat_colors='b', mlat_labels=0) sza = EOF.sza.values night = np.copy(sza) inight = (sza > 90) if laplace: lap = abs(ndimage.laplace(EOF.of.values)) lap[lap < 0.001] = np.nan lapm = 0.1 lap[lap > lapm] = lapm night[inight] = 0 night[~inight] = 1 OF = ax.pcolormesh(EOF.glon.values, EOF.glat.values, EOF.of.values, cmap='gray', vmin=0, vmax=1, transform=ccrs.PlateCarree()) try: ax.contour(EOF.glon.values, EOF.glat.values, lap, cmap='nipy_spectral', levels=np.linspace(0.005, lapm, 20), transform=ccrs.PlateCarree()) except: pass if clabel: try: OFC = ax.contour(EOF.glon.values, EOF.glat.values, EOF.of.values, cmap='jet', linewidths=clw, levels=np.linspace(0.0, 1.0, cmax), transform=ccrs.PlateCarree()) if clabel: ax.clabel(OFC, OFC.levels, inline=True) except: pass else: OF = ax.pcolormesh(EOF.glon.values, EOF.glat.values, EOF.of.values, cmap='gray', vmin=0, vmax=1, transform=ccrs.PlateCarree()) try: Zcont = EOF.of.values Zcont[inight] = np.nan OFC = ax.contour(EOF.glon.values, EOF.glat.values, Zcont, colors='r', linewidths=clw, levels=np.linspace(np.nanmin(Zcont), 1.0, cmax), transform=ccrs.PlateCarree()) if clabel: ax.clabel(OFC, OFC.levels, inline=True, fmt='%.2f') except: pass posn0 = ax.get_position() cax = fig.add_axes( [posn0.x0 + posn0.width + 0.01, posn0.y0, 0.02, posn0.height]) fig.colorbar(OF, cax=cax, label='EOF', format='%.2f') EOF.close() if save: fig.savefig(save_fn) plt.close(fig) else: break
from cartomap import geogmap as gm from datetime import datetime import matplotlib.pyplot as plt import cartopy.crs as ccrs import apexpy as ap latlim = [-0, 60] lonlim = [-140, 0] date = datetime(2017, 8, 21, 6) fig = gm.plotCartoMap( projection='plate', title='Geomagnetic coordinates: MLAT/MLT', latlim=latlim, lonlim=lonlim, parallels=[0, 10, 20, 40, 60, 80, 90], meridians=[-220, -180, -160, -140, -120, -100, -80, -60, -40, 0], grid_linewidth=1, figure=True, states=False) A = ap.Apex(date=date) #glon = np.arange(lonlim[0]-40, lonlim[1] + 40.1, 1) #glat = np.arange(latlim[0], latlim[1] + 0.1, 1) #longrid, latgrid = np.meshgrid(glon, glat) mlat_levels = np.arange(-90, 90.1, 10) #mlat_levels = np.array([40,50,60,70]) # mlon #mlat, mlon = A.convert(latgrid, longrid, 'geo', 'apex')
fig = plt.figure(figsize=[12, 7]) ax0 = plt.subplot( 121, projection=ccrs.Stereographic(central_longitude=(sum(lonlim) / 2))) ax1 = plt.subplot( 122, projection=ccrs.Stereographic(central_longitude=(sum(lonlim) / 2))) ax0 = cm.plotCartoMap( latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, ax=ax0, grid_linewidth=1, states=False, title='TEC: {} -- \n {}'.format(tectime[idt_tec - tecrange], tectime[idt_tec + tecrange - 1]), background_color='grey', apex=True, mlat_levels=[-80, -60, -40, -20, 0, 20, 40, 60, 80, 90], mlat_colors='w', mgrid_width=0.5, mgrid_style='--', mlon_levels=np.arange(0, 361, 40), mlat_labels=False, mlon_colors='w', mlon_labels=False, ) ax1 = cm.plotCartoMap( latlim=latlim1, lonlim=lonlim1, projection='stereo', meridians=None,
def main(date='', root=None, scintfn=None, clim=None, tlim=None, trange=None, odir=None, latlim=None, lonlim=None, terminator=False, nightshade=False, cmap='gray', SAVE=1, resolution=5): DPI = 150 datedt = [parser.parse(date), parser.parse(date) + timedelta(days=1)] if trange is None: trange = resolution / 2 if latlim is None: latlim = [-10, 75] if lonlim is None: lonlim = [-160, -50] if clim is None: tecclim = [0, 20] else: tecclim = clim if root is None: if platform.system() == 'Windows': root = 'G:\\My Drive\\scintillation_data\\' else: root = '/home/smrak/Documents/scintillation/' if odir is None: if platform.system() == 'Windows': odir = root + '{}\\{}-{}-{}\\'.format( parser.parse(date).strftime("%Y%m%d"), cmap, tecclim[0], tecclim[1]) else: odir = root + '/maps/{}/{}-{}-{}/'.format( parser.parse(date).strftime("%Y%m%d"), cmap, tecclim[0], tecclim[1]) if platform.system() == 'Windows': TECFN = root + 'tid\\{}\\conv_{}T0000-{}T0000.h5'.format( parser.parse(date).strftime("%Y%m%d"), datedt[0].strftime("%Y%m%d"), datedt[1].strftime("%Y%m%d")) else: TECFN = '/media/smrak/figures/gpstec/{}/{}/conv_{}T0000-{}T0000.h5'.format( parser.parse(date).year, parser.parse(date).strftime("%m%d"), datedt[0].strftime("%Y%m%d"), datedt[1].strftime("%Y%m%d")) assert os.path.isfile(TECFN), TECFN if scintfn is None: if platform.system() == 'Windows': scint_root = root + '\\hdf\\{}\\'.format(datedt[0].year) else: scint_root = root + '/hdf/' scint_fn_list = sorted( glob.glob(scint_root + "ix_{}_{}T*.h5".format( datedt[0].year, datedt[0].strftime("%m%d")))) assert len(scint_fn_list) > 0 scintfn = scint_fn_list[0] assert os.path.isfile(scintfn) #TEC TEC = gpstec.readFromHDF(TECFN) tectime = TEC['time'] xgrid = TEC['xgrid'] ygrid = TEC['ygrid'] #SCINT DATA scintdata = h5py.File(scintfn, 'r') scint_time = scintdata['data/time'][:] scint_dt = np.array([datetime.utcfromtimestamp(t) for t in scint_time]) if tlim is None: tlim = [parser.parse(date), parser.parse(date) + timedelta(days=1)] if isinstance(tlim[0], str): dirnametime = scint_dt[0].strftime('%Y%m%d') if dirnametime != parser.parse(P.tlim[0]).strftime('%Y%m%d'): t0 = parser.parse(dirnametime + 'T' + P.tlim[0]) t1 = parser.parse(dirnametime + 'T' + P.tlim[1]) else: t0 = parser.parse(P.tlim[0]) t1 = parser.parse(P.tlim[0]) tlim = [t0, t1] assert isinstance(tlim[0], datetime) and isinstance(tlim[1], datetime) obstimes = [] t = tlim[0] while t <= tlim[1]: obstimes.append(t) t += timedelta(minutes=resolution) # --------------------------------------------------------------------------- # for ii, it in enumerate(obstimes): # TEC data idt_tec = abs(tectime - it).argmin() if idt_tec < tectime.size - 2: tecim = np.nanmean(TEC['tecim'][idt_tec:idt_tec + 2], axis=0) else: tecim = TEC['tecim'][idt_tec] # Scintillation data # Filter out time range of interest scint_idt = np.zeros(scint_dt.size, dtype=bool) time_range = np.where((scint_dt >= it - timedelta(minutes=trange)) & (scint_dt <= it + timedelta(minutes=trange)))[0] scint_idt[time_range[0]:time_range[-1] + 1] = True # scint_idt[time_range[0]] = True # Read in data ipp_lat = scintdata['data/ipp'][scint_idt, :, :, 0] ipp_lon = scintdata['data/ipp'][scint_idt, :, :, 1] sigma_tec = scintdata['data/sigma_tec'][scint_idt, :, :] snr4 = scintdata['data/snr4'][scint_idt, :, :] roti = scintdata['data/roti'][scint_idt, :, :] # Plot fig = plt.figure(figsize=[15, 6]) ax0 = plt.subplot( 121, projection=ccrs.Stereographic(central_longitude=(sum(lonlim) / 2))) ax1 = plt.subplot( 122, projection=ccrs.Stereographic(central_longitude=(sum(lonlim) / 2))) ax0 = cm.plotCartoMap(latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, ax=ax0, grid_linewidth=1, states=False, title=it, background_color='grey', apex=True, mlat_levels=[-40, -20, 0, 20, 40, 60, 80, 90], mlat_colors='w', mgrid_width=1, mgrid_style='--', nightshade=nightshade, terminator=terminator, terminator_altkm=350, ter_color='r', ter_style='-', ter_width=2, mlon_cs='mlt', date=it, mlon_levels=np.arange(0, 24.1, 4), mlat_labels=False, mlon_colors='w', mlon_labels=False) ax1 = cm.plotCartoMap(latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, ax=ax1, grid_linewidth=1, states=False, title=it, background_color='grey', apex=True, mlat_levels=[-40, -20, 0, 20, 40, 60, 80, 90], nightshade=nightshade, terminator=terminator, terminator_altkm=350, ter_color='r', ter_style='-', ter_width=2, mlon_cs='mlt', date=it, mlat_colors='w', mgrid_width=1, mgrid_style='--', mlon_levels=np.arange(0, 24.1, 4), mlat_labels=False, mlon_colors='w', mlon_labels=False) glon_ter, glat_ter = ter.get_terminator(it, alt_km=350) idlon = (glon_ter > -160) & (glon_ter < 0) mlat_ter, mlon_ter = A.convert(glat_ter[idlon], glon_ter[idlon], 'geo', 'apex', height=350) mlat_south = (mlat_ter < 0) glat_ter_conj, glon_ter_conj = A.convert(-mlat_ter[mlat_south], mlon_ter[mlat_south], 'apex', 'geo', height=350) ax0.plot(np.unwrap(glon_ter_conj, 180), glat_ter_conj, '--r', lw=2, transform=ccrs.PlateCarree()) # ------------------------------------------------------------------------- - # ax0.pcolormesh(xgrid, ygrid, tecim.T, cmap=cmap, vmin=tecclim[0], vmax=tecclim[1], transform=ccrs.PlateCarree()) im1 = ax1.pcolormesh( xgrid, ygrid, tecim.T, cmap=cmap, #'nipy_spectral' vmin=tecclim[0], vmax=tecclim[1], transform=ccrs.PlateCarree()) # Scint with amplitude # if np.sum(np.isfinite(sigma_tec)) > 0: if trange >= 1: idf0 = np.isfinite(sigma_tec) if np.sum(np.isfinite(idf0)) == 0: idf0[0] = True imst = ax0.scatter( ipp_lon[idf0], ipp_lat[idf0], c=sigma_tec[idf0], s=30, #(sigma_tec)**2 * 1000000, marker='o', cmap='Reds', alpha=0.8, vmin=0, vmax=0.05, # facecolors = 'none', transform=ccrs.PlateCarree()) idf0 = np.isfinite(snr4) if np.sum(np.isfinite(idf0)) == 0: idf0[0] = True # if np.sum(np.isfinite(snr4)) > 0: imsnr4 = ax0.scatter( ipp_lon[idf0], ipp_lat[idf0], c=snr4[idf0], s=30, #np.square(snr4) * 1000, # linewidth = 0.8, marker='o', alpha=0.8, cmap='Blues', vmin=0, vmax=1.2, # facecolors = 'none', transform=ccrs.PlateCarree()) # Scint locations if np.sum(np.isfinite(roti)) > 0: idf0 = np.isfinite(roti) imroti = ax1.scatter(ipp_lon[idf0], ipp_lat[idf0], c=roti[idf0], s=15, marker='o', alpha=0.8, vmin=0, vmax=0.02, cmap='jet', transform=ccrs.PlateCarree()) posn0 = ax0.get_position() cax = fig.add_axes([posn0.x0, posn0.y0 - 0.03, posn0.width, 0.02]) fig.colorbar(imsnr4, cax=cax, label='$SNR_4$', orientation='horizontal') posn1 = ax1.get_position() cax = fig.add_axes([posn1.x0, posn1.y0 - 0.03, posn1.width, 0.02]) fig.colorbar(imroti, cax=cax, label='ROTI [TECu]', orientation='horizontal') cax = fig.add_axes( [posn1.x0 + posn1.width + 0.01, posn1.y0, 0.02, posn1.height]) fig.colorbar(im1, cax=cax, label='TEC [TECu]') posn0 = ax0.get_position() cax = fig.add_axes( [posn0.x0 + posn0.width + 0.01, posn0.y0, 0.02, posn0.height]) fig.colorbar(imst, cax=cax, label='$\sigma_{TEC}$ [TECu]') else: posn0 = ax0.get_position() cax = fig.add_axes( [posn0.x0 + posn0.width + 0.01, posn0.y0, 0.02, posn0.height]) fig.colorbar(im1, cax=cax, label='$\sigma_{TEC}$ [TECu]') if SAVE: # plt.tight_layout() if not os.path.exists(odir): import subprocess if platform.system() == 'Linux': subprocess.call('mkdir -p "{}"'.format(odir), shell=True, timeout=2) elif platform.system() == 'Windows': subprocess.call('mkdir "{}"'.format(odir), shell=True, timeout=2) print("Plotting {}/{} - {}".format(ii + 1, len(obstimes), it)) fig.savefig(odir + '{}.png'.format(it.strftime('%m%d_%H%M')), dpi=DPI) plt.close(fig) del fig del sigma_tec del snr4
def plot(fnhdf: str = None, show: bool = False, odir: str = None, cfg: str = None, clim: list = None, mode: str = None): C0 = clim fnhdf = os.path.expanduser(fnhdf.strip()) assert fnhdf is not None assert os.path.splitext(fnhdf)[1] in ['.h5', '.hdf5'] # Converted file D = gpstec.readFromHDF(fnhdf) if cfg is None: folder = os.path.expanduser(os.path.join(os.getcwd(), 'map')) mcfg = sorted(glob(os.path.join(folder, '*.yaml')))[0] else: assert os.path.splitext(cfg)[1] in ['.yaml', 'yml'] mcfg = cfg # Map mst = yaml.load(open(mcfg, 'r')) projection = mst.get('projection') cmap = mst.get('cmap') nightshade = mst.get('nightshade') latlim = mst.get('latlim') lonlim = mst.get('lonlim') paralim = mst.get('parallels') meridilim = mst.get('meridians') parallels = np.arange(paralim[0], paralim[1], paralim[2]) meridians = np.arange(meridilim[0], meridilim[1], meridilim[2]) if mode is None: mode = mst.get('mode') if mst.get('mode') is not None else 'lin' if isinstance(mode, str): mode = [mode] colorbar = mst.get('colorbar') cbar_label = mst.get('cbar_label') if mst.get( 'cbar_label') is not None else 'TEC [TECu]' if clim is None: clim = mst.get('clim') if clim is None: vmax = 3 * _round(np.nanmedian(D['tecim']), base=5) vmin = 0 clim = [vmin, vmax] else: vmax = float(clim[1]) vmin = float(clim[0]) clim = [vmin, vmax] figsize = mst.get('figsize') if mst.get('figsize') is not None else [12, 8] background_color = mst.get('background_color') if mst.get( 'background_color') is not None else 'grey' grid_color = mst.get('grid_color') if mst.get( 'grid_color') is not None else 'white' grid_linewidth = mst.get('grid_linewidth') if mst.get( 'grid_linewidth') is not None else 1 grid_linestyle = mst.get('grid_linestyle') if mst.get( 'grid_linestyle') is not None else '--' dpi = mst.get('dpi') if mst.get('dpi') is not None else 50 # Plot for mode in mode: if mode == 'log': clim[1] = np.log10(vmax) else: clim[1] = vmax for i in range(D['time'].shape[0]): z = np.log10(D['tecim'][i]) if mode == 'log' else D['tecim'][i] fig, ax = gm.plotCartoMap(figsize=figsize, projection=projection, title=D['time'][i], latlim=latlim, lonlim=lonlim, meridians=meridians, parallels=parallels, background_color=background_color, grid_color=grid_color, grid_linewidth=grid_linewidth, grid_linestyle=grid_linestyle, figure=True, nightshade=nightshade, ns_dt=D['time'][i]) im = plt.pcolormesh(D['xgrid'], D['ygrid'], z.T, cmap=cmap, transform=ccrs.PlateCarree()) plt.clim(clim) if colorbar: cax = fig.add_axes([0, 0, 0.1, 0.1]) plt.colorbar(im, cax=cax, label=cbar_label) axp = fig.gca() posn = ax.get_position() axp.set_position( [posn.x0 + posn.width + 0.01, posn.y0, 0.02, posn.height]) fig.canvas.draw() if show: plt.show() else: if odir is None: odir = os.path.split(fnhdf)[0] assert os.path.isdir(odir) if C0 is not None: svdir = mode + str(int(clim[0])) + '-' + str(int(clim[1])) else: svdir = mode figdir = os.path.expanduser(os.path.join(odir, svdir)) if not os.path.exists(figdir): print('Creating a new directory: ', figdir) subprocess.call('mkdir -p {}'.format(figdir), shell=True, timeout=5) fn = D['time'][i].strftime('%m%d_%H%M') figname = fn + str('.png') plt.savefig(os.path.join(figdir, figname), dpi=dpi) plt.close(fig=fig)
projection=ccrs.Stereographic(central_longitude=(sum(lonlim) / 2))) ax0 = cm.plotCartoMap(latlim=latlim, lonlim=lonlim, projection='stereo', meridians=None, parallels=None, ax=ax0, grid_linewidth=1, states=False, title=it, background_color='grey', apex=True, mlat_levels=[-40, -20, 0, 20, 40, 60, 80, 90], mlat_colors='w', mgrid_width=1, mgrid_style='--', nightshade=nightshade, terminator=terminator, terminator_altkm=350, ter_color='r', ter_style='-', ter_width=2, mlon_cs='mlt', date=it, mlon_levels=np.arange(0, 24.1, 4), mlat_labels=False, mlon_colors='w', mlon_labels=False) ax1 = cm.plotCartoMap(latlim=latlim,
glon, glat = np.meshgrid(np.arange(-180, 180.1, 1), np.arange(-90, 90.1, 1)) sza = get_terminator(time=date, alt_km=alt_km, glon=glon, glat=glat, return_sza=True) terminator = np.squeeze(np.array(measure.find_contours(sza, 0))) x, y = get_terminator(time=date, alt_km=alt_km, glon=glon, glat=glat) if isinstance(x, list): plt.figure() im = plt.pcolormesh(glon, glat, sza, cmap='bwr', vmin=-80, vmax=80) for i in range(len(x)): plt.plot(x[i], y[i], '--g', lw=4) plt.colorbar(im) else: plt.figure() im = plt.pcolormesh(glon, glat, sza, cmap='bwr', vmin=-80, vmax=80) plt.plot(x, y, '--g', lw=4) plt.colorbar(im) fig, ax = gm.plotCartoMap(projection='plate', lon0=-50, title="{}, Terminators H=[0,150] km".format(date), lonlim=[-140, 0], latlim=[-90, 90], meridians=np.arange(-180, 180.1, 40), parallels=np.arange(-80, 80.1, 20), date=date, terminator=True, terminator_altkm=[0, 150])