Пример #1
0
    def test_as_cartopy_crs(self):
        latitude_of_projection_origin = -90.0
        longitude_of_projection_origin = -45.0
        false_easting = 100.0
        false_northing = 200.0
        ellipsoid = GeogCS(6377563.396, 6356256.909)

        st = Stereographic(central_lat=latitude_of_projection_origin,
                           central_lon=longitude_of_projection_origin,
                           false_easting=false_easting,
                           false_northing=false_northing,
                           ellipsoid=ellipsoid)
        expected = ccrs.Stereographic(
            central_latitude=latitude_of_projection_origin,
            central_longitude=longitude_of_projection_origin,
            false_easting=false_easting,
            false_northing=false_northing,
            globe=ccrs.Globe(semimajor_axis=6377563.396,
                             semiminor_axis=6356256.909,
                             ellipse=None))

        res = st.as_cartopy_crs()
        self.assertEqual(res, expected)
def PlotPoVCompositesDiffENSO(var1, var2, var3, lat, lon, title, filename):
	vars = [var1, var2, var3]
	tit = ['All', 'El Ninio', 'La Ninia']
	proj = ccrs.Stereographic(central_longitude=-60, central_latitude=-90)
	fig = plt.figure(1, (10, 6.7), 300)
	center, radius = [0.5, 0.5], 0.5
	theta = np.linspace(0, 2 * np.pi, 100)
	verts = np.vstack([np.sin(theta), np.cos(theta)]).T
	circle = mpath.Path(verts * radius + center)
	for i in range(3):
		ax = plt.subplot(3, 1, i + 1, projection=proj)
		clevs = np.arange(-60, 70, 10)
		barra = plt.cm.RdBu_r
		ax.set_extent([0, 359, -90, -20], crs=ccrs.PlateCarree())
		ax.set_boundary(circle, transform=ax.transAxes)
		im = ax.contourf(lon, lat, vars[i], clevs, transform=ccrs.PlateCarree(),
				cmap=barra, extend='both', vmin=-60, vmax=60)
		barra.set_under(barra(0))
		barra.set_over(barra(barra.N-1))
		ax.coastlines()
		#ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)
		#ax.gridlines(crs=proj, linewidth=0.3, linestyle='-')
		#lon_formatter = LongitudeFormatter(zero_direction_label=True)
		#lat_formatter = LatitudeFormatter()
		#ax.xaxis.set_major_formatter(lon_formatter)
		#ax.yaxis.set_major_formatter(lat_formatter)
		plt.title(tit[i])
	plt.suptitle(title, fontsize=12, x=0.47, y=0.9)
	fig.subplots_adjust(right=0.8)
	fig.subplots_adjust(bottom=0.17, top=0.82, hspace=0.2, wspace=0.05)
	cbar_ax = fig.add_axes([0.33, 0.1, 0.25, 0.05])
	fig.colorbar(im, cax=cbar_ax, orientation='horizontal')
	plt.savefig(filename, dpi=300, bbox_inches='tight', orientation='landscape',
		    papertype='A4')
	plt.clf()
	plt.cla()
	plt.close()
Пример #3
0
    def __init__(
        self,
        ecc=0.081816153,
        a=6378.273e3,
        lat_0=90.,
        lon_0=-45.,
        lat_ts=60.,
    ):
        '''
        Default is the projection used by neXtSIM

        Parameters:
        -----------
        ecc : float
            eccentricity of ellipsoid for globe
        a : float
            semi-major axis of ellipsoid for globe (radius at equator)
        lat_0 : float
            central latitude
        lon_0 : float
            central longitude
        lat_ts : float
            true scale latitude
        '''
        b = a * np.sqrt(1 - ecc**2)
        self.pyproj = pyproj.Proj(proj='stere',
                                  a=a,
                                  b=b,
                                  lon_0=lon_0,
                                  lat_0=lat_0,
                                  lat_ts=lat_ts)

        globe = ccrs.Globe(semimajor_axis=a, semiminor_axis=b)
        self.crs = ccrs.Stereographic(central_latitude=lat_0,
                                      central_longitude=lon_0,
                                      true_scale_latitude=lat_ts,
                                      globe=globe)
Пример #4
0
    def dessiner_fond_carte(self, lon_0, lat_0, lonn, latn, lonx, latx):

        proj = ccrs.Stereographic(central_longitude=lon_0,
                                  central_latitude=lat_0)

        ax = plt.axes(projection=proj)

        pays = cfeature.NaturalEarthFeature(category='cultural',
                                            name='admin_0_countries',
                                            scale='10m',
                                            facecolor='none')
        ax.add_feature(pays, edgecolor='black', linewidth=(0.7))

        fleuves = cfeature.NaturalEarthFeature(category='physical',
                                               name='rivers_lake_centerlines',
                                               scale='10m',
                                               facecolor='none')
        ax.add_feature(fleuves, edgecolor='blue', linewidth=(0.3))
        rivieres = cfeature.NaturalEarthFeature(category='physical',
                                                name='rivers_europe',
                                                scale='10m',
                                                facecolor='none')
        ax.add_feature(rivieres, edgecolor='blue', linewidth=(0.3))

        ax.plot([4.875, 4.8148, 5.7242], [45.775, 45.1896, 45.1721],
                'bo',
                color="red",
                markersize=0.5,
                transform=ccrs.PlateCarree())

        if self.zoom == 1:
            ax.set_extent([lonn, lonx, latn, latx])
        else:
            ax.set_extent([lonn, lonx, latn + 0.5, latx])

        return ax
Пример #5
0
def PlotEnsoCompositesPoV(var1, var2, var3, var4, var5, var6, var7, lat, lon, title, filename):
	vars = [var1, var2, var3, var4, var5, var6]
	tit = ['Ninio (All PoV)', 'Ninia (All PoV)',
		'Ninio (Weak PoV)', 'Ninia (Weak PoV)',
		'Ninio (Strong PoV)', 'Ninia (Strong PoV)']
	proj = ccrs.Stereographic(central_longitude=-60, central_latitude=-90)
	fig = plt.figure(1, (6, 10), 300)
	for i in range(6):
		ax = plt.subplot(3, 2, i + 1, projection=proj)
		clevs = np.arange(-60, 70, 10)
		barra = plt.cm.RdBu_r
		ax.set_extent([0, 359, -90, -30], crs=ccrs.PlateCarree())
		theta = np.linspace(0, 2 * np.pi, 100)
		center, radius = [0.5, 0.5], 0.5
		verts = np.vstack([np.sin(theta), np.cos(theta)]).T
		circle = mpath.Path(verts * radius + center)
		ax.set_boundary(circle, transform=ax.transAxes)
#		ax.contour(lon, lat, var7, np.arange(-200, 250, 50),
#			    transform=ccrs.PlateCarree(), colors='black')
		im = ax.contourf(lon, lat, vars[i], clevs, transform=ccrs.PlateCarree(),
				cmap=barra, extend='both', vmin=-60, vmax=60)
		barra.set_under(barra(0))
		barra.set_over(barra(barra.N-1))
		ax.coastlines()
		ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)
		plt.title(tit[i])
	plt.suptitle(title, fontsize=12, x=0.47, y=0.9)
	fig.subplots_adjust(right=0.8)
	fig.subplots_adjust(bottom=0.17, top=0.85, hspace=0.2, wspace=0.05)
	cbar_ax = fig.add_axes([0.22, 0.1, 0.5, 0.05])
	fig.colorbar(im, cax=cbar_ax, orientation='horizontal')
	plt.savefig(filename, dpi=300, bbox_inches='tight', orientation='landscape',
		    papertype='A4')
	plt.clf()
	plt.cla()
	plt.close()
Пример #6
0
def test_multiple_projections():

    projections = [ccrs.PlateCarree(),
                   ccrs.Robinson(),
                   ccrs.RotatedPole(pole_latitude=45, pole_longitude=180),
                   ccrs.OSGB(),
                   ccrs.TransverseMercator(),
                   ccrs.Mercator(
                       globe=ccrs.Globe(semimajor_axis=math.degrees(1)),
                       min_latitude=-85., max_latitude=85.),
                   ccrs.LambertCylindrical(),
                   ccrs.Miller(),
                   ccrs.Gnomonic(),
                   ccrs.Stereographic(),
                   ccrs.NorthPolarStereo(),
                   ccrs.SouthPolarStereo(),
                   ccrs.Orthographic(),
                   ccrs.Mollweide(),
                   ccrs.InterruptedGoodeHomolosine(),
                   ]

    fig = plt.figure(figsize=(10, 10))
    for i, prj in enumerate(projections, 1):
        ax = fig.add_subplot(5, 5, i, projection=prj)

        ax.set_global()

        ax.coastlines()

        plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree())

        plt.plot([-0.08, 132], [51.53, 43.17], color='red',
                 transform=ccrs.PlateCarree())

        plt.plot([-0.08, 132], [51.53, 43.17], color='blue',
                 transform=ccrs.Geodetic())
Пример #7
0
def main(myfiles,
         fieldname,
         idm=None,
         jdm=None,
         clim=None,
         filetype="archive",
         window=None,
         cmap="jet",
         datetime1=None,
         datetime2=None,
         vector="",
         tokml=False,
         masklim=None,
         filename2='',
         dpi=180):

    cmap = matplotlib.pyplot.get_cmap("jet")
    if tokml:
        ab = abf.ABFileGrid("regional.grid", "r")
        plon = ab.read_field("plon")
        plat = ab.read_field("plat")
        ab.close()

    ab = abf.ABFileGrid("regional.grid", "r")
    plon = ab.read_field("plon")
    plat = ab.read_field("plat")
    scpx = ab.read_field("scpx")
    scpy = ab.read_field("scpy")
    target_lonlats = [plon, plat]
    abdpth = abf.ABFileBathy('regional.depth', "r", idm=ab.idm, jdm=ab.jdm)
    mdpth = abdpth.read_field('depth')
    maskd = mdpth.data
    maskd[maskd > 1e29] = np.nan
    #Region_mask=True
    Region_mask = False
    if Region_mask:
        maskd[plat > 80] = np.nan
        maskd[plat < 50] = np.nan
        maskd[plon > 60] = np.nan
        maskd[plon < -50] = np.nan

    Nordic_mask = maskd

    proj = ccrs.Stereographic(central_latitude=90.0, central_longitude=-40.0)
    pxy = proj.transform_points(ccrs.PlateCarree(), plon, plat)
    px = pxy[:, :, 0]
    py = pxy[:, :, 1]
    x, y = np.meshgrid(np.arange(plon.shape[1]), np.arange(plon.shape[0]))

    if vector:
        logger.info("Vector component 1:%s" % fieldname)
        logger.info("Vector component 2:%s" % vector)

    #---------------
    fieldlevel = 0
    Err_map = 1
    #freezp=-2.5
    freezp = -1.8
    Point_tid = True
    Point_tid = False
    if Point_tid:
        ix = 1394
        jy = 267
    sum_fld1 = maskd
    sum_fld1[~np.isnan(sum_fld1)] = 0.0
    Clim_arr = np.zeros((plon.shape[0], plon.shape[1], 12))
    #---------------
    # compute for TP6 files
    figure = matplotlib.pyplot.figure(figsize=(8, 8))
    ax = figure.add_subplot(111)
    counter = 0
    file_count = 0
    sum_fld1 = maskd
    sum_fld1[~np.isnan(sum_fld1)] = 0.0

    #-----------------------------------------
    figure = matplotlib.pyplot.figure(figsize=(8, 8))
    ax = figure.add_subplot(111)
    onemm = 9.806
    counter = 0
    file_count = 0
    sum_fld1 = maskd
    sum_fld1[~np.isnan(sum_fld1)] = 0.0
    dt_cnl = np.zeros(len(myfiles))
    diff_dt_cnl = np.zeros(len(myfiles))
    rmse_dt_cnl = np.zeros(len(myfiles))
    Labl1 = myfiles[0][:28]
    #Labl1="CNTL: New prsbas=0"
    yyyy1 = myfiles[0][-14:-10]
    print("myfiles[0]=", myfiles[0])
    print("yyy1=", yyyy1)
    base = datetime.datetime(int(yyyy1), 1, 15)
    tid = np.array(
        [base + relativedelta(months=i) for i in range(len(myfiles))])
    counter = 0
    file_count = 0
    sum_fld1 = maskd
    sum_fld1[~np.isnan(sum_fld1)] = 0.0
    logger.info(
        ">>>>>--------------------------Processing the first files=  myfiles")
    if "salin" in fieldname:
        fieldname = "salin01"
    for ncfile0 in myfiles:
        logger.info("Now processing  %s" % ncfile0)
        fh = Dataset(ncfile0, mode='r')
        fld_arr = fh.variables[fieldname][:]
        if "srfhgt" in fieldname:
            #convert to "m"
            fld_arr = fld_arr / 9.806
        print("fld_arr.shpe", fld_arr.shape)
        tot = fld_arr.shape[0]
        fh.close()
        for ii in range(tot):
            fld = fld_arr[ii, :, :]
            print('mn,mx=', fld.min(), fld.max(), 'count=', counter)
            dt_cnl[counter] = np.nanmean(fld)
            if Point_tid:
                dt_cnl[counter] = fld[jy, ix]
            print("fld.shape", fld.shape)
            print("Nordic_mask.shape", Nordic_mask.shape)
            counter = counter + 1
            sum_fld1 = sum_fld1 + fld
            del fld
        # End i_intloop
    print('Computing the avearge of file_counter= ', file_count, 'counter=',
          counter)
    #next experminet
    if filename2:
        dt_2 = np.zeros(len(filename2))
        diff_dt_2 = np.zeros(len(filename2))
        rmse_dt_2 = np.zeros(len(filename2))
        yyyy2 = filename2[0][-14:-10]
        print("filename2[0]=", filename2[0])
        print("yyy1=", yyyy2)
        tid_2 = np.array([
            datetime.datetime(int(yyyy2), 1, 15) + relativedelta(months=i)
            for i in range(len(filename2))
        ])
        Labl2 = filename2[0][:28]
        counter = 0
        file_count = 0
        sum_fld1 = maskd
        sum_fld1[~np.isnan(sum_fld1)] = 0.0
        logger.info(
            ">>>>>--------------------------Processing the first files=  myfiles"
        )
        for ncfil in filename2:
            logger.info("Now processing  %s" % ncfil)
            fh = Dataset(ncfil, mode='r')
            fld_arr = fh.variables[fieldname][:]
            if "srfhgt" in fieldname:
                fld_arr = fld_arr / 9.806
            print("fld_arr.shpe", fld_arr.shape)
            tot = fld_arr.shape[0]
            fh.close()
            for ii in range(tot):
                fld = fld_arr[ii, :, :]
                #fld=np.ma.masked_where(fld<freezp,fld)
                print('mn,mx=', fld.min(), fld.max(), 'count=', counter)
                dt_2[counter] = np.nanmean(fld)
                if Point_tid:
                    dt_2[counter] = fld[jy, ix]
                counter = counter + 1
                sum_fld1 = sum_fld1 + fld
                del fld

    #---------------------------------------
    figure, ax = plt.subplots()
    years = YearLocator()  # every year
    months = MonthLocator()  # every month
    yearsFmt = DateFormatter('%Y')
    #ax=figure.add_subplot(111)
    nplts = 1
    ax.plot_date(tid, dt_cnl, '-o', color='g', ms=3, label=Labl1)
    if filename2:
        ax.plot_date(tid_2, dt_2, '-v', color='blue', ms=3, label=Labl2)
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)
    ax.autoscale_view()

    # format the coords message box
    def price(x):
        return '$%1.2f' % x

    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.fmt_ydata = price
    ax.grid(True)
    figure.autofmt_xdate()
    legend = plt.legend(loc='upper right', fontsize=8)
    if Point_tid:
        plt.title("Point:(lon,lat)=(" + str(plon[jy, ix]) + ',' +
                  str(plat[jy, ix]) + "): %s(%d)" % (fieldname, fieldlevel))
    else:
        plt.title("Area-averaged: %s(%d)" % (fieldname, fieldlevel))
    #plt.xlabel('dayes')
    if "srfhgt" in fieldname:
        plt.ylabel("%s[m]" % (fieldname))
    else:
        plt.ylabel("%s(%d)" % (fieldname, fieldlevel))
    #plt.title('Pakistan India Population till 2007')
    ts_fil = "Time_series_cntl%s_%02d_%02d" % (fieldname, fieldlevel,
                                               len(myfiles))
    if Region_mask:
        ts_fil = 'Region_' + ts_fil
    if Point_tid:
        ts_fil = 'Point_ix' + str(ix) + 'jy' + str(jy) + ts_fil
    figure.canvas.print_figure(ts_fil, bbox_inches='tight', dpi=dpi)
    logger.info("Successfull printing:  %s" % ts_fil)
Пример #8
0
def plotCartoMap(latlim=None, lonlim=None, parallels=None, meridians=None,
                 pole_center_lon=0, figsize=(12, 8), terrain=False, ax=False,
                 projection='stereo', title='', resolution='110m',
                 states=True, grid_linewidth=0.5, grid_color='black',
                 grid_linestyle='--', background_color=None, border_color='k',
                 figure=False, nightshade=False, ns_dt=None, ns_alpha=0.1,
                 apex=False, igrf=False, date=None,
                 mlat_levels=None, mlon_levels=None, alt_km=0.0,
                 mlon_colors='blue', mlat_colors='red', mgrid_width=1,
                 mgrid_labels=True, mgrid_fontsize=12, mlon_cs='mlon',
                 incl_levels=None, decl_levels=None, igrf_param='incl',
                 mlon_labels=True, mlat_labels=True, mgrid_style='--',
                 label_colors='k',
                 decl_colors='k', incl_colors='k'):

    if lonlim is None:
        if projection in ['southpole', 'northpole']:
            lonlim = [-180, 180]
        else:
            lonlim = [-40, 40]
    if latlim is None:
        if projection is'southpole':
            latlim = [-90, 0]
        elif projection is 'northpole':
            latlim = [90, 0]
        else:
            latlim = [0, 75]

    STATES = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')

    if not ax:
        if figsize is None:
            fig = plt.figure()
        else:
            fig = plt.figure(figsize=figsize)

        if projection == 'stereo':
            ax = plt.axes(projection=ccrs.Stereographic(central_longitude=(sum(lonlim) / 2)))
        elif projection == 'merc':
            ax = plt.axes(projection=ccrs.Mercator())
        elif projection == 'plate':
            ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=(sum(lonlim) / 2)))
        elif projection == 'lambert':
            ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=(sum(lonlim) / 2),
                                                           central_latitude=(sum(latlim) / 2)))
        elif projection == 'mollweide':
            ax = plt.axes(projection=ccrs.Mollweide(central_longitude=(sum(lonlim) / 2)))
        elif projection == 'northpole':
            ax = plt.axes(projection=ccrs.NorthPolarStereo())
            ax.set_boundary(circle, transform=ax.transAxes)
            # polarLim(ax, projection)
        elif projection == 'southpole':
            ax = plt.axes(projection=ccrs.SouthPolarStereo())
            ax.set_boundary(circle, transform=ax.transAxes)
            # polarLim(ax, projection)
    if background_color is not None:
        ax.background_patch.set_facecolor(background_color)
    ax.set_title(title)
    ax.coastlines(color=border_color, resolution=resolution)  # 110m, 50m or 10m
    if states:
        ax.add_feature(STATES, edgecolor=border_color)
    ax.add_feature(cfeature.BORDERS, edgecolor=border_color)
    if terrain:
        ax.stock_img()
    if nightshade:
        assert ns_dt is not None
        assert ns_alpha is not None
        ax.add_feature(Nightshade(ns_dt, ns_alpha))
    # Draw Parallels
    if projection == 'merc' or projection == 'plate':
        if isinstance(meridians, np.ndarray):
            meridians = list(meridians)
        if isinstance(parallels, np.ndarray):
            parallels = list(parallels)

        gl = ax.gridlines(crs=ccrs.PlateCarree(), color=grid_color, draw_labels=False,
                          linestyle=grid_linestyle, linewidth=grid_linewidth)
        if meridians is None:
            gl.xlines = False
        else:
            if len(meridians) > 0:
                gl.xlocator = mticker.FixedLocator(meridians)
                gl.xlabels_bottom = True
            else:
                gl.ylines = False

        if parallels is None:
            gl.ylines = False
        else:
            if len(parallels) > 0:
                gl.ylocator = mticker.FixedLocator(parallels)
                #                ax.yaxis.set_major_formatter(LONGITUDE_FORMATTER)
                gl.ylabels_left = True
            else:
                gl.ylines = False
    else:
        gl = ax.gridlines(crs=ccrs.PlateCarree(), color=grid_color, draw_labels=False,
                          linestyle=grid_linestyle, linewidth=grid_linewidth)
        if meridians is None:
            gl.xlines = False
        else:
            #            if isinstance(meridians, np.ndarray):
            #                meridians = list(meridians)
            #            ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER)
            #            ax.yaxis.set_major_formatter(LATITUDE_FORMATTER)
            #            if isinstance(meridians, np.ndarray):
            #                meridians = list(meridians)
            gl.xlocator = mticker.FixedLocator(meridians)
        #        else:
        #            gl.xlines = False
        if parallels is not None:
            if isinstance(parallels, np.ndarray):
                parallels = list(parallels)
            gl.ylocator = mticker.FixedLocator(parallels)
        else:
            gl.ylines = False

    # Geomagnetic coordinates @ Apex
    if apex:
        if date is None:
            date = datetime(2017, 12, 31, 0, 0, 0)
        assert isinstance(date, datetime)

        A = ap.Apex(date=date)
        # Define levels and ranges for conversion
        if mlon_cs == 'mlt':
            if mlon_levels is None:
                mlon_levels = np.array([])
                mlon_range = np.arange(0, 24.1, 0.1)
            elif isinstance(mlon_levels, bool):
                if mlon_levels == False:
                    mlon_levels = np.array([])
                    mlon_range = np.arange(0, 24.1, 0.1)
            else:
                mlon_range = np.arange(mlon_levels[0], mlon_levels[-1] + 0.1, 0.1)
        else:
            if mlon_levels is None:
                mlon_levels = np.array([])
                mlon_range = np.arange(-180, 180, 0.5)
            elif isinstance(mlon_levels, bool):
                if mlon_levels == False:
                    mlon_levels = np.array([])
                    mlon_range = np.arange(-180, 181, 0.1)
            else:
                mlon_range = np.arange(mlon_levels[0], mlon_levels[0] + 362, 0.1)
        if mlat_levels is None:
            mlat_levels = np.arange(-90, 90.1, 5)
        mlat_range = np.arange(mlat_levels[0], mlat_levels[-1] + 0.1, 0.1)
        # Do meridans
        for mlon in mlon_levels:
            MLON = mlon * np.ones(mlat_range.size)
            if mlon_cs == 'mlt':
                y, x = A.convert(mlat_range, MLON, 'mlt', 'geo', datetime=date)
            else:
                y, x = A.convert(mlat_range, MLON, 'apex', 'geo')
            # Plot meridian
            inmap = np.logical_and(x >= lonlim[0], x <= lonlim[1])
            if np.sum(inmap) > 10:
                ax.plot(np.unwrap(x, 180), np.unwrap(y, 90), c=mlon_colors,
                        lw=mgrid_width, linestyle=mgrid_style,
                        transform=ccrs.PlateCarree())

            # Labels
            if mlon_labels:
                ix = np.argmin(abs(y - np.mean(latlim)))
                mx = x[ix] - 1 if mlon >= 10 else x[ix] - 0.5
                my = np.mean(latlim)
                if np.logical_and(mx >= lonlim[0], mx <= lonlim[1]):
                    if mlon_cs == 'mlt' and mlon != 0:
                        ax.text(mx, my, str(int(mlon)), color=label_colors,
                                fontsize=14, backgroundcolor='white',
                                transform=ccrs.PlateCarree())
                    elif mlon_cs != 'mlt' and mlon != 360:
                        ax.text(mx, my, str(int(mlon)), color=label_colors,
                                fontsize=14, backgroundcolor='white',
                                transform=ccrs.PlateCarree())
        # Do parallels
        for mlat in mlat_levels:
            MLAT = mlat * np.ones(mlon_range.size)
            if mlon_cs == 'mlt':
                gy, gx = A.convert(MLAT, mlon_range, 'mlt', 'geo', datetime=date)
            else:

                gy, gx = A.convert(MLAT, mlon_range, 'apex', 'geo', datetime=date)
            inmap = np.logical_and(gy >= latlim[0], gy <= latlim[1])
            if np.sum(inmap) > 2:
                ax.plot(np.unwrap(gx, 180), np.unwrap(gy, 90), c=mlat_colors,
                        lw=mgrid_width, linestyle=mgrid_style,
                        transform=ccrs.PlateCarree())

            # Labels
            if mlat_labels:
                ix = np.argmin(abs(gx - np.mean(lonlim)))
                mx = np.mean(lonlim)
                my = gy[ix] - 0.5
                if np.logical_and(mx >= lonlim[0], mx <= lonlim[1]) and \
                        np.logical_and(my >= latlim[0], my <= latlim[1]):
                    ax.text(mx, my, str(int(mlat)), color=label_colors,
                            fontsize=14, backgroundcolor='white',
                            transform=ccrs.PlateCarree())

    if igrf:
        glon = np.arange(lonlim[0] - 40, lonlim[1] + 40.1, 0.5)
        glat = np.arange(-90, 90 + 0.1, 0.5)
        longrid, latgrid = np.meshgrid(glon, glat)
        mag = igrf12.gridigrf12(t=date, glat=latgrid, glon=longrid, alt_km=alt_km)
        if decl_levels is not None:
            z = mag.decl.values
            for declination in decl_levels:
                ax.contour(longrid, latgrid, z, levels=declination,
                           colors=decl_colors, transform=ccrs.PlateCarree())
        if incl_levels is not None:
            z = mag.incl.values
            for inclination in incl_levels:
                ax.contour(longrid, latgrid, z, levels=declination,
                           colors=incl_colors, transform=ccrs.PlateCarree())
    # Set Extent

    ax.set_extent([lonlim[0], lonlim[1], latlim[0], latlim[1]], crs=ccrs.PlateCarree())

    if 'fig' in locals():
        return fig, ax
    else:
        return ax
Пример #9
0
def make_stereo(attrs_dict, globe):
    """Handle generic stereographic projection."""
    attr_mapping = [('scale_factor', 'scale_factor_at_projection_origin')]
    kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)

    return ccrs.Stereographic(globe=globe, **kwargs)
tit = 'Composites S4 Z* 200hPa '
filename = FIG_PATH + 'z200_composites_ENSO_SPoV.eps'

#plots.PlotEnsoCompositesPoV(var_WPV_all - var_normal, var_SPV_all - var_normal,
#				
#				    var_ninio_all - var_normal, var_ninia_all - var_normal,
#				    var_ninio_WPV - var_normal, var_ninia_WPV - var_normal,
#				    var_ninio_SPV - var_normal, var_ninia_SPV - var_normal,
#				    var_normal, hgt.latitude, hgt.longitude, tit, filename)
titulos = ['Weak SPoV (All ENSO)', 'Strong SPoV (All ENSO)', 'Ninio (All SPoV)',
	   'Ninia (All SPoV)', 'Ninio & Weak SPoV', 'Ninia & Strong SPoV',
	   'Ninio & Strong SPoV)', 'Ninia & Weak SPoV']
lon = hgt.longitude.values
lat = hgt.latitude.values
proj = ccrs.Stereographic(central_longitude=-60, central_latitude=-90)
clevs = np.arange(-60, 70, 10)
clevs2 = np.arange(-50, 70, 20)
barra = plt.cm.RdBu_r
theta = np.linspace(0, 2 * np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
fig, ax = plt.subplots(nrows=8, ncols=6, figsize=(12, 20), subplot_kw={'projection': proj})
for i in range(6):
	#ax = plt.subplot(8, 6, i + 1, projection=proj)
	ax[0, i].set_extent([0, 359, -90, -30], crs=ccrs.PlateCarree())
	ax[0, i].set_boundary(circle, transform=ax[0, i].transAxes)
	ax[0, i].coastlines()
	variable = var_WPV_all[i + 1, :, :] - var_normal[i + 1, :, :]
	variable_std = variable / np.sqrt(SS_WPV_all[i + 1, :, :] + SS_normal[i + 1, :, :])
Пример #11
0
    def plot(self,
             variable=None,
             vmin=None,
             vmax=None,
             filename=None,
             title=None,
             buffer=1,
             lscale='auto'):
        """Plot geographical coverage of reader."""

        import matplotlib.pyplot as plt
        from matplotlib.patches import Polygon
        import cartopy.crs as ccrs
        import cartopy.feature as cfeature
        from opendrift_landmask_data import Landmask
        fig = plt.figure()

        corners = self.xy2lonlat([self.xmin, self.xmin, self.xmax, self.xmax],
                                 [self.ymax, self.ymin, self.ymax, self.ymin])
        lonmin = np.min(corners[0]) - buffer * 2
        lonmax = np.max(corners[0]) + buffer * 2
        latmin = np.min(corners[1]) - buffer
        latmax = np.max(corners[1]) + buffer
        latspan = latmax - latmin

        # Initialise map
        if latspan < 90:
            # Stereographic projection centred on domain, if small domain
            x0 = (self.xmin + self.xmax) / 2
            y0 = (self.ymin + self.ymax) / 2
            lon0, lat0 = self.xy2lonlat(x0, y0)
            sp = ccrs.Stereographic(central_longitude=lon0,
                                    central_latitude=lat0)
            ax = fig.add_subplot(1, 1, 1, projection=sp)
            corners_stere = sp.transform_points(ccrs.PlateCarree(),
                                                np.array(corners[0]),
                                                np.array(corners[1]))
        else:
            # Global map if reader domain is large
            sp = ccrs.Mercator()
            ax = fig.add_subplot(1, 1, 1, projection=sp)

        # GSHHS coastlines
        f = cfeature.GSHHSFeature(scale=lscale,
                                  levels=[1],
                                  facecolor=cfeature.COLORS['land'])
        ax.add_geometries(f.intersecting_geometries(
            [lonmin, lonmax, latmin, latmax]),
                          ccrs.PlateCarree(),
                          facecolor=cfeature.COLORS['land'],
                          edgecolor='black')

        gl = ax.gridlines(ccrs.PlateCarree())
        gl.top_labels = False

        # Get boundary
        npoints = 10  # points per side
        x = np.array([])
        y = np.array([])
        x = np.concatenate((x, np.linspace(self.xmin, self.xmax, npoints)))
        y = np.concatenate((y, [self.ymin] * npoints))
        x = np.concatenate((x, [self.xmax] * npoints))
        y = np.concatenate((y, np.linspace(self.ymin, self.ymax, npoints)))
        x = np.concatenate((x, np.linspace(self.xmax, self.xmin, npoints)))
        y = np.concatenate((y, [self.ymax] * npoints))
        x = np.concatenate((x, [self.xmin] * npoints))
        y = np.concatenate((y, np.linspace(self.ymax, self.ymin, npoints)))
        # from x/y vectors create a Patch to be added to map
        lon, lat = self.xy2lonlat(x, y)
        lat[lat > 89] = 89.
        lat[lat < -89] = -89.
        p = sp.transform_points(ccrs.PlateCarree(), lon, lat)
        xsp = p[:, 0]
        ysp = p[:, 1]

        if variable is None:
            boundary = Polygon(list(zip(xsp, ysp)),
                               alpha=0.5,
                               ec='k',
                               fc='b',
                               zorder=100)
            ax.add_patch(boundary)
            buf = (xsp.max() -
                   xsp.min()) * .1  # Some whitespace around polygon
            buf = 0
            try:
                ax.set_extent([
                    xsp.min() - buf,
                    xsp.max() + buf,
                    ysp.min() - buf,
                    ysp.max() + buf
                ],
                              crs=sp)
            except:
                pass
        if title is None:
            plt.title(self.name)
        else:
            plt.title(title)
        plt.xlabel('Time coverage: %s to %s' %
                   (self.start_time, self.end_time))

        if variable is not None:
            rx = np.array([self.xmin, self.xmax])
            ry = np.array([self.ymin, self.ymax])
            data = self.get_variables(variable, self.start_time, rx, ry)
            rx, ry = np.meshgrid(data['x'], data['y'])
            rx = np.float32(rx)
            ry = np.float32(ry)
            rlon, rlat = self.xy2lonlat(rx, ry)
            data[variable] = np.ma.masked_invalid(data[variable])
            if self.convolve is not None:
                from scipy import ndimage
                N = self.convolve
                if isinstance(N, (int, np.integer)):
                    kernel = np.ones((N, N))
                    kernel = kernel / kernel.sum()
                else:
                    kernel = N
                logger.debug('Convolving variables with kernel: %s' % kernel)
                data[variable] = ndimage.convolve(data[variable],
                                                  kernel,
                                                  mode='nearest')
            if data[variable].ndim > 2:
                logger.warning('Ensemble data, plotting only first member')
                data[variable] = data[variable][0, :, :]
            mappable = ax.pcolormesh(rlon,
                                     rlat,
                                     data[variable],
                                     vmin=vmin,
                                     vmax=vmax,
                                     transform=ccrs.PlateCarree())
            cbar = fig.colorbar(mappable,
                                orientation='horizontal',
                                pad=.05,
                                aspect=30,
                                shrink=.4)
            cbar.set_label(variable)

        try:  # Activate figure zooming
            mng = plt.get_current_fig_manager()
            mng.toolbar.zoom()
        except:
            pass

        if filename is not None:
            plt.savefig(filename)
            plt.close()
        else:
            plt.show()
Пример #12
0
path = "/Users/ainajoh/Data/ISLAS/flexpart/test/"
times = ["20190320_00"]
for t in times:
    filein = path + "lsl" + t
print(filein)
trajs = Tra()
trajs.load_ascii(filein)

print(trajs)
wcb_trajs = trajs

#wcb_trajs = Tra()
#wcb_trajs.set_array(trajs[wcb_index[0], :])

crs = ccrs.Stereographic(central_longitude=10,
                         central_latitude=90,
                         true_scale_latitude=90)

fig = plt.figure()
ax = plt.axes(projection=crs)
#ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
ax.set_extent([-90, 40, 50, 90])  # [lon0,lon1, lat0, lat1]
cax = plot_trajs(ax, wcb_trajs, "Q")  # color with Q
# cax = plot_trajs( ax, upt_idx, "Q" ) #color with Q
# an = plt.annotate(trajs["time"])
# for i in range(len(x)):
#    plt.annotate(labls[i], xy=(x[i,2], y[i,2]), rotation=rotn[i,2])
cbar = fig.colorbar(cax)

plt.show()
Пример #13
0
import themisasi.io as tio
import numpy as np
import matplotlib.pyplot as plt
import pymap3d.aer as pm
import themisasi as ta
import themisasi.io as tio
import os
from os import path
import argparse
from datetime import date
from datetime import time
from datetime import datetime, timedelta
from typing import List

PC = ccrs.PlateCarree()
ST = ccrs.Stereographic()
MR = ccrs.Mercator()
def datetimerange(start: datetime, stop: datetime, step: timedelta) -> List[datetime]:
    """
    generates range of datetime start,stop,step just like range() for datetime
    """
    return [start + i*step for i in range((stop-start) // step)]
def themisasi(dat, ax): #function used to save plots 
        
    imgs = dat['imgs'].squeeze()
    #gets rid of the negative values and replaces them with nans
    el = dat['el'].values
    el.setflags(write=True)
    bad = el < 15 
    el[bad] = np.nan
    az = dat.az.values
Пример #14
0
    def create(pfile, field=None, lonRange=None, latRange=None, coast=True, land=False, projection=False, polar=False, wedge=False, times='flat', particle_subsample=1, title="", fps=24, colormap=None, size=None, cbar=True, cbextend='neither', units=None, s=0.01, **kwargs):
        """
        Create particle animations
        """
        
        # Load arrays from file
        lon = np.ma.filled(pfile.variables['lon'][::particle_subsample], np.nan)
        lat = np.ma.filled(pfile.variables['lat'][::particle_subsample], np.nan)
        time = np.ma.filled(pfile.variables['time'][::particle_subsample], np.nan)
        mesh = pfile.attrs['parcels_mesh'] if 'parcels_mesh' in pfile.attrs else 'spherical'
        
        # Range
        if lonRange:
            minLon, maxLon = lonRange
        else: 
            minlon = np.amin(pfile.variables['lon']) - margin
            maxlon = np.amax(pfile.variables['lon']) + margin
        if latRange:
            minLat, maxLat = latRange
        else:
            minlat = np.amin(pfile.variables['lat']) - margin
            maxlat = np.amax(pfile.variables['lat']) + margin
        
        # Set projection
        if projection:
            map_crs = projection
        else:
            if polar:
                map_crs = ccrs.NorthPolarStereo(central_longitude=0.0, globe=None)
            elif wedge: 
                map_crs = ccrs.Stereographic(central_latitude = minLat+(maxLat-minLat)/2, central_longitude=minLon+(maxLon-minLon)/2)
            else:
                map_crs = ccrs.PlateCarree()
        
        if size:
            fig     = plt.figure(figsize=size)
        else:
            fig     = plt.figure()
        ax      = plt.axes(projection=map_crs)
        ax.set_extent((minLon,maxLon,minLat,maxLat), crs=ccrs.PlateCarree())
        
        # Set masks
        if coast:
            ax.coastlines()
        if land:
            ax.add_feature(cart.feature.LAND, zorder=5, edgecolor='k')
        
            # Add gridlines
        if projection or polar or wedge:
            gl = ax.gridlines(linestyle='--', alpha=0.8, linewidth=1.25)
            gl.n_steps = 90
        else: 
            gl = ax.gridlines(crs=map_crs, linestyle='--', alpha=0.75, linewidth=0.5, draw_labels = True)
            gl.xlabels_top   = False
            gl.ylabels_right = False
            gl.xformatter    = LONGITUDE_FORMATTER
            gl.yformatter    = LATITUDE_FORMATTER

        # Circular clipping
        if polar:
            circle_clip = set_circular_boundary(ax)
        if wedge:
            wedge_clip = set_wedge_boundary(ax, minLon, maxLon, minLat, maxLat)
            
        if field:
            fieldName = field.name
            field.fieldset.computeTimeChunk(field.grid.time[0], 1)
            if not colormap:
                colormap = 'viridis'
            ax.pcolormesh(field.lon, field.lat, field.data[0,:,:], transform=map_crs, cmap=colormap, zorder=1)
        else:
            fieldName = 'noField'

        # Determine plotting time indices
        if times == 'flat':
            firstFullTrajectoryIdx = np.searchsorted(~np.isnat(time[:, -1]), True)
            plottimes = time[firstFullTrajectoryIdx,:]
        else:
            plottimes = np.unique(time)
            if isinstance(plottimes[0], (np.datetime64, np.timedelta64)):
                plottimes = plottimes[~np.isnat(plottimes)]
            else:
                try:
                    plottimes = plottimes[~np.isnan(plottimes)]
                except:
                    pass
    
        # Create initial scatter plot of particles
        if times == 'flat':
            scat   = ax.scatter(lon[:,0], lat[:,0], c=lat[:,0], s=s, transform=ccrs.Geodetic(), zorder=10)
        else:
            currtime = time == plottimes[0]
            scat   = ax.scatter(lon[currtime], lat[currtime], c=lat[currtime], s=s, transform=ccrs.Geodetic(), zorder=10)
        
        # Colorbar
        if cbar:
            divider = make_axes_locatable(ax)
            if wedge:
                ax_cb = divider.new_vertical(size="5%", pad=0.1, axes_class=plt.Axes, pack_start=True)
                fig.add_axes(ax_cb)
                cbar = plt.colorbar(scat, cax=ax_cb, orientation='horizontal', extend=cbextend)
            else:
                ax_cb = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
                fig.add_axes(ax_cb)
                cbar = plt.colorbar(scat, cax=ax_cb, extend=cbextend)

            # Set units
            if units:
                if wedge:
                    cbar.ax.set_xlabel(f"{str(units)}")
                else:
                    cbar.ax.set_ylabel(f"{str(units)}")
        
        head = fig.suptitle('Particles at time ' + str(plottimes[0])[:13])
        frames = np.arange(0, len(plottimes))
        
        # Animation
        def animate(t):
            if times == 'flat':
                scat.set_offsets(np.vstack((lon[:, t], lat[:, t])).transpose())
            else:
                currtime = time == plottimes[t]
                scat.set_offsets(np.vstack((lon[currtime], lat[currtime])).transpose())
            scat.set_color
            head.set_text('Particles at time ' + str(plottimes[t])[:13])
            return scat,
        
        anim = animation.FuncAnimation(fig, 
                                       animate, 
                                       frames=len(plottimes),
                                       blit=True)
        if not os.path.exists('animations'):
            os.makedirs('animations')
        anim.save(f'animations/particle_evolution_{fieldName}_{title}.mp4', fps=fps, metadata={'artist':'Daan', 'title':f'Particles on {fieldName} - {title}'}, extra_args=['-vcodec', 'libx264'])
        plt.show()
        plt.close()
Пример #15
0
def field_from_dataset(lons, lats, data, latRange=(-90, 90), lonRange=(-180, 180), \
                    coast=True, land=False, projection=False, polar=False, wedge=False, export=None, \
                    units=None, t_end=None, title="", colormap=None, size=None, cbar=True, cbextend='neither', **kwargs):
    # Extract Options
    minLat, maxLat = latRange
    minLon, maxLon = lonRange
    
    if projection:
        map_crs = projection
    else:
        if polar:
            map_crs = ccrs.NorthPolarStereo(central_longitude=0.0, globe=None)
        elif wedge: 
            map_crs = ccrs.Stereographic(central_latitude = minLat+(maxLat-minLat)/2, central_longitude=minLon+(maxLon-minLon)/2)

        else:
            map_crs = ccrs.PlateCarree()
    
    # Build axes
    if size:
        fig     = plt.figure(figsize=size)
    else:
        fig     = plt.figure()
    ax      = plt.axes(projection=map_crs)

    ax.set_extent((minLon,maxLon,minLat,maxLat), crs=ccrs.PlateCarree())
    
    # Set masks
    if coast:
        ax.coastlines()
    if land:
        ax.add_feature(cart.feature.LAND, zorder=5, edgecolor='k')
    
    # Add gridlines
    if projection or polar or wedge:
        gl = ax.gridlines(linestyle='--', alpha=0.8, linewidth=1.25)
        gl.n_steps = 90
    else: 
        gl = ax.gridlines(crs=map_crs, linestyle='--', alpha=0.75, linewidth=0.5, draw_labels = True)
        gl.xlabels_top   = False
        gl.ylabels_right = False
        gl.xformatter    = LONGITUDE_FORMATTER
        gl.yformatter    = LATITUDE_FORMATTER
        
    # Circular clipping
    if polar:
        circle_clip = set_circular_boundary(ax)
    if wedge:
        wedge_clip = set_wedge_boundary(ax, minLon, maxLon, minLat, maxLat)
    
    if not colormap:
        colormap = 'viridis'
    # Plot field
    if polar: 
        plotfield = ax.pcolormesh(lons, lats, data, transform=ccrs.PlateCarree(), clip_path=(circle_clip, ax.transAxes), cmap=colormap, **kwargs)
    else:
        plotfield = ax.pcolormesh(lons, lats, data, transform=ccrs.PlateCarree(), cmap=colormap, **kwargs)
    
    # Colorbar
    if cbar:
        divider = make_axes_locatable(ax)
        if wedge:
            ax_cb = divider.new_vertical(size="5%", pad=0.1, axes_class=plt.Axes, pack_start=True)
            fig.add_axes(ax_cb)
            cbar = plt.colorbar(plotfield, cax=ax_cb, orientation='horizontal', extend=cbextend)
        else:
            ax_cb = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
            fig.add_axes(ax_cb)
            cbar = plt.colorbar(plotfield, cax=ax_cb, extend=cbextend)
        
        # Set units
        if units:
            if wedge:
                cbar.ax.set_xlabel(f"{str(units)}")
            else:
                cbar.ax.set_ylabel(f"{str(units)}")
    
    ax.set_title(title)
    # Export as figure
    if export:
        if not os.path.exists('figures'):
            os.makedirs('figures')
        if export[-4] == '.':
            plt.savefig(f'figures/{export}', dpi=300, bbox_inches='tight')
        else:
            plt.savefig(f'figures/{export}.png', dpi=300, bbox_inches='tight')
    return fig, ax
Пример #16
0
    cols = 304
    rows = 448
    img = np.fromfile(file, dtype='byte').reshape(rows, cols)
    return img

# Define image projection and parameters
src_proj = {'pixel_width': 25000,
            'pixel_height': 25000,
            'ccrs': {'central_latitude': 90.0,
                     'central_longitude': -45.0,
                     'false_easting': 0.0,
                     'false_northing': 0.0,
                     'true_scale_latitude': 70 },
            'bounds': [-3850000.000, 3750000., -5350000., 5850000.000]}
src_globe = ccrs.Globe(datum=None, semimajor_axis=6378273., semiminor_axis=6356889.449)
src_crs = ccrs.Stereographic(**src_proj['ccrs'], globe=src_globe)


#Define output projection and parameters
dst_proj = {'pixel_width': 50135.05,
            'pixel_height': 50135.05,
            'ccrs': {'central_latitude': 90.,
                     'central_longitude': 0.,
                     'false_easting': 0.0,
                     'false_northing': 0.0},
            'bounds': [-8999241.475, 8999241.475, -8999241.475, 8999241.475]}
dst_globe = ccrs.Globe(datum=None, semimajor_axis=6371228, semiminor_axis=6371228)
dst_crs = ccrs.LambertAzimuthalEqualArea(**dst_proj['ccrs'], globe=dst_globe)

# Get mask
mask = read_seaice_mask()
Пример #17
0
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import sys

grbs = pygrib.open('../sampledata/cl00010000_ecoclimap_rot.grib1')
grb = grbs.message(7)
lats, lons = grb.latlons()
data = grb.values
sys.stdout.write(repr(grb.projparams) + '\n')

globe = ccrs.Globe(ellipse='sphere',
                   semimajor_axis=grb.projparams['a'],
                   semiminor_axis=grb.projparams['b'])
pj = ccrs.Stereographic(globe=globe, central_longitude=10, central_latitude=55)


@pytest.mark.mpl_image_compare(tolerance=20, remove_text=True)
def test_rotated_ll():
    fig = plt.figure()
    ax = plt.axes(projection=pj)
    coords = pj.transform_points(ccrs.PlateCarree(), np.asarray([-14.75, 72]),
                                 np.asarray([29.5, 65.6]))
    ax.set_extent([coords[0, 0], coords[1, 0], coords[0, 1], coords[1, 1]],
                  crs=pj)
    ax.scatter(lons[::5, ::5].flat,
               lats[::5, ::5].flat,
               1,
               marker='o',
               color='k',
Пример #18
0
    def projection(self):
        if self.proj is None:
            return ccrs.PlateCarree()

        proj_dict = ast.literal_eval(self.proj)
        user_proj = proj_dict.pop("proj")
        if user_proj == 'PlateCarree':
            self.xylim_supported = True
            return ccrs.PlateCarree(**proj_dict)
        elif user_proj == 'AlbersEqualArea':
            return ccrs.AlbersEqualArea(**proj_dict)
        elif user_proj == 'AzimuthalEquidistant':
            return ccrs.AzimuthalEquidistant(**proj_dict)
        elif user_proj == 'EquidistantConic':
            return ccrs.EquidistantConic(**proj_dict)
        elif user_proj == 'LambertConformal':
            return ccrs.LambertConformal(**proj_dict)
        elif user_proj == 'LambertCylindrical':
            return ccrs.LambertCylindrical(**proj_dict)
        elif user_proj == 'Mercator':
            return ccrs.Mercator(**proj_dict)
        elif user_proj == 'Miller':
            return ccrs.Miller(**proj_dict)
        elif user_proj == 'Mollweide':
            return ccrs.Mollweide(**proj_dict)
        elif user_proj == 'Orthographic':
            return ccrs.Orthographic(**proj_dict)
        elif user_proj == 'Robinson':
            return ccrs.Robinson(**proj_dict)
        elif user_proj == 'Sinusoidal':
            return ccrs.Sinusoidal(**proj_dict)
        elif user_proj == 'Stereographic':
            return ccrs.Stereographic(**proj_dict)
        elif user_proj == 'TransverseMercator':
            return ccrs.TransverseMercator(**proj_dict)
        elif user_proj == 'UTM':
            return ccrs.UTM(**proj_dict)
        elif user_proj == 'InterruptedGoodeHomolosine':
            return ccrs.InterruptedGoodeHomolosine(**proj_dict)
        elif user_proj == 'RotatedPole':
            return ccrs.RotatedPole(**proj_dict)
        elif user_proj == 'OSGB':
            self.xylim_supported = False
            return ccrs.OSGB(**proj_dict)
        elif user_proj == 'EuroPP':
            self.xylim_supported = False
            return ccrs.EuroPP(**proj_dict)
        elif user_proj == 'Geostationary':
            return ccrs.Geostationary(**proj_dict)
        elif user_proj == 'NearsidePerspective':
            return ccrs.NearsidePerspective(**proj_dict)
        elif user_proj == 'EckertI':
            return ccrs.EckertI(**proj_dict)
        elif user_proj == 'EckertII':
            return ccrs.EckertII(**proj_dict)
        elif user_proj == 'EckertIII':
            return ccrs.EckertIII(**proj_dict)
        elif user_proj == 'EckertIV':
            return ccrs.EckertIV(**proj_dict)
        elif user_proj == 'EckertV':
            return ccrs.EckertV(**proj_dict)
        elif user_proj == 'EckertVI':
            return ccrs.EckertVI(**proj_dict)
        elif user_proj == 'EqualEarth':
            return ccrs.EqualEarth(**proj_dict)
        elif user_proj == 'Gnomonic':
            return ccrs.Gnomonic(**proj_dict)
        elif user_proj == 'LambertAzimuthalEqualArea':
            return ccrs.LambertAzimuthalEqualArea(**proj_dict)
        elif user_proj == 'NorthPolarStereo':
            return ccrs.NorthPolarStereo(**proj_dict)
        elif user_proj == 'OSNI':
            return ccrs.OSNI(**proj_dict)
        elif user_proj == 'SouthPolarStereo':
            return ccrs.SouthPolarStereo(**proj_dict)
Пример #19
0
def get_map_projection(
        proj_name,
        central_longitude=0.0,
        central_latitude=0.0,
        false_easting=0.0,
        false_northing=0.0,
        globe=None,
        standard_parallels=(20.0, 50.0),
        scale_factor=None,
        min_latitude=-80.0,
        max_latitude=84.0,
        true_scale_latitude=None,
        latitude_true_scale=None,  ### BOTH
        secant_latitudes=None,
        pole_longitude=0.0,
        pole_latitude=90.0,
        central_rotated_longitude=0.0,
        sweep_axis='y',
        satellite_height=35785831,
        cutoff=-30,
        approx=None,
        southern_hemisphere=False,
        zone=15):  #### numeric UTM zone

    proj_name = proj_name.lower()

    if (proj_name == 'albersequalarea'):
        proj = ccrs.AlbersEqualArea(central_longitude=central_longitude,
                                    central_latitude=central_latitude,
                                    false_easting=false_easting,
                                    false_northing=false_northing,
                                    globe=globe,
                                    standard_parallels=standard_parallels)
    elif (proj_name == 'azimuthalequidistant'):
        proj = ccrs.AzimuthalEquidistant(central_longitude=central_longitude,
                                         central_latitude=central_latitude,
                                         false_easting=false_easting,
                                         false_northing=false_northing,
                                         globe=globe)
    elif (proj_name == 'equidistantconic'):
        proj = ccrs.EquidistantConic(central_longitude=central_longitude,
                                     central_latitude=central_latitude,
                                     false_easting=false_easting,
                                     false_northing=false_northing,
                                     globe=globe,
                                     standard_parallels=standard_parallels)
    elif (proj_name == 'lambertconformal'):
        proj = ccrs.LambertConformal(
            central_longitude=-96.0,  ##########
            central_latitude=39.0,  ##########
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            secant_latitudes=None,
            standard_parallels=None,  ## default: (33,45)
            cutoff=cutoff)
    elif (proj_name == 'lambertcylindrical'):
        proj = ccrs.LambertCylindrical(central_longitude=central_longitude)
    elif (proj_name == 'mercator'):
        proj = ccrs.Mercator(central_longitude=central_longitude,
                             min_latitude=min_latitude,
                             max_latitude=max_latitude,
                             latitude_true_scale=latitude_true_scale,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe,
                             scale_factor=None)  #########
    elif (proj_name == 'miller'):
        proj = ccrs.Miller(central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'mollweide'):
        proj = ccrs.Mollweide(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'orthographic'):
        proj = ccrs.Orthographic(central_longitude=central_longitude,
                                 central_latitude=central_latitude,
                                 globe=globe)
    elif (proj_name == 'robinson'):
        proj = ccrs.Robinson(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'sinusoidal'):
        proj = ccrs.Sinusoidal(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'stereographic'):
        proj = ccrs.Stereographic(central_latitude=central_latitude,
                                  central_longitude=central_longitude,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  true_scale_latitude=true_scale_latitude,
                                  scale_factor=scale_factor)
    elif (proj_name == 'transversemercator'):
        proj = ccrs.TransverseMercator(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            scale_factor=1.0,  ##########
            approx=approx)
    elif (proj_name == 'utm'):
        proj = ccrs.UTM(zone,
                        southern_hemisphere=southern_hemisphere,
                        globe=globe)
    elif (proj_name == 'interruptedgoodehomolosine'):
        proj = ccrs.InterruptedGoodeHomolosine(
            central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'rotatedpole'):
        proj = ccrs.RotatedPole(
            pole_longitude=pole_longitude,
            pole_latitude=pole_latitude,
            globe=globe,
            central_rotated_longitude=central_rotated_longitude)
    elif (proj_name == 'osgb'):
        proj = ccrs.OSGB(approx=approx)
    elif (proj_name == 'europp'):
        proj = ccrs.EuroPP
    elif (proj_name == 'geostationary'):
        proj = ccrs.Geostationary(central_longitude=central_longitude,
                                  satellite_height=satellite_height,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  sweep_axis=sweep_axis)
    elif (proj_name == 'nearsideperspective'):
        proj = ccrs.NearsidePerspective(central_longitude=central_longitude,
                                        central_latitude=central_latitude,
                                        satellite_height=satellite_height,
                                        false_easting=false_easting,
                                        false_northing=false_northing,
                                        globe=globe)
    elif (proj_name == 'eckerti'):
        proj = ccrs.EckertI(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertii'):
        proj = ccrs.EckertII(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertiii'):
        proj = ccrs.EckertIII(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'eckertiv'):
        proj = ccrs.EckertIV(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertv'):
        proj = ccrs.EckertV(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertvi'):
        proj = ccrs.EckertVI(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'equalearth'):
        proj = ccrs.EqualEarth(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'gnomonic'):
        proj = ccrs.Gnomonic(central_latitude=central_latitude,
                             central_longitude=central_longitude,
                             globe=globe)
    elif (proj_name == 'lambertazimuthalequalarea'):
        proj = ccrs.LambertAzimuthalEqualArea(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            globe=globe,
            false_easting=false_easting,
            false_northing=false_northing)
    elif (proj_name == 'northpolarstereo'):
        proj = ccrs.NorthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    elif (proj_name == 'osni'):
        proj = ccrs.OSNI(approx=approx)
    elif (proj_name == 'southpolarstereo'):
        proj = ccrs.SouthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    else:
        # This is same as "Geographic coordinates"
        proj = ccrs.PlateCarree(central_longitude=central_longitude,
                                globe=globe)

    return proj
Пример #20
0
def ATL15_browse_plots(args):

    # get projection
    if args.Hemisphere == 1:
        # set cartopy projection as EPSG 3413
        projection = ccrs.Stereographic(central_longitude=-45.0,
                                        central_latitude=+90.0,
                                        true_scale_latitude=+70.0)
#        DEM_file = '/Volumes/ice3/suzanne/arcticdem_mosaic_100m_v3.0.tif'
    else:
        # set cartopy projection as EPSG 3031
        projection = ccrs.Stereographic(central_longitude=+0.0,
                                        central_latitude=-90.0,
                                        true_scale_latitude=-71.0)
#        DEM_file = '/Volumes/ice3/suzanne/REMA_100m_dem.tif'

    lagtext = {
        'lag1': 'quarterly',
        'lag4': 'annual',
        'lag8': 'biennial',
        'lag12': 'triennial',
        'lag16': 'quadriennial'
    }

    # make a log file for errors
    if not args.nolog:
        log_file = '{}/ATL15_BrowsePlots_{}.log'.format(
            args.base_dir.rstrip('/'),
            dt.datetime.now().date())
        fhlog = open(log_file, 'a')

    # list of spatial averaging ATL15 files
    avgs = ['_01km', '_10km', '_20km', '_40km']
    for ii, ave in enumerate(avgs):
        filein = args.base_dir.rstrip(
            '/'
        ) + '/ATL15_' + args.region + '_' + args.cycles + ave + '_' + args.Release + '_' + args.version + '.nc'
        print('Making browse figures from ', filein)
        pngfile = args.base_dir.rstrip(
            '/'
        ) + '/ATL15_' + args.region + '_' + args.cycles + ave + '_' + args.Release + '_' + args.version + '_BRW'

        ds = Dataset(filein)
        #    # find group of largest lag
        #    lag=1
        #    for grp in ds.groups:
        #        if grp.startswith('dhdt_lag'):
        #            if int(grp[8:])>lag:
        #                lag=int(grp[8:])
        #    grp = 'dhdt_lag'+str(lag)

        x = ds.groups['dhdt_lag1']['x']
        y = ds.groups['dhdt_lag1']['y']
        extent = [np.min(x), np.max(x), np.min(y), np.max(y)]

        dhdt = ds.groups['dhdt_lag1']['dhdt']
        dhdt[:][dhdt[:] == ds.groups['dhdt_lag1']['dhdt']._FillValue] = np.nan
        dhdtmn = np.nanmean(dhdt, axis=0)
        dhdtstd = np.nanstd(dhdt, axis=0)

        if np.any(dhdtmn.ravel()):
            # get limits for colorbar
            h05mn = stats.mstats.scoreatpercentile(
                dhdtmn[~np.isnan(dhdtmn)].ravel(),
                5)  # dhdt is a masked array what?
            h95mn = stats.mstats.scoreatpercentile(
                dhdtmn[~np.isnan(dhdtmn)].ravel(), 95)
            h05std = stats.mstats.scoreatpercentile(
                dhdtstd[~np.isnan(dhdtstd)].ravel(),
                5)  # dhdt is a masked array what?
            h95std = stats.mstats.scoreatpercentile(
                dhdtstd[~np.isnan(dhdtstd)].ravel(), 95)
        else:
            fhlog.write(
                '{}: No valid dhdt data, no browse plot written.\n'.format(
                    filein))
            exit(-1)

        fig, ax = plt.subplots(1, 1)
        ax = plt.subplot(1, 1, 1, projection=projection)
        ax.add_feature(cfeature.LAND, facecolor='0.8')
        ax.coastlines(resolution='50m', linewidth=0.5)
        ax.gridlines(crs=ccrs.PlateCarree())
        h = ax.imshow(dhdtmn,
                      extent=extent,
                      cmap='Spectral',
                      vmin=h05mn,
                      vmax=h95mn,
                      origin='lower',
                      interpolation='nearest')
        fig.colorbar(h, ax=ax, label='dh/dt, m', shrink=1 / 2, extend='both')
        ax.set_title(f'Mean quarterly dh/dt: {os.path.basename(filein)}',
                     wrap=True)
        if args.Hemisphere == 1:
            plt.figtext(
                0.1,
                0.01,
                f'Figure 1. Average quarterly rate of height change (dhdt_lag1/dhdt) at {ave[1:]}-resolution, in meters, from cycle {args.cycles[0:2]} to cycle {args.cycles[2:4]}. Map is plotted in a polar-stereographic projection with a central longitude of 45W and a standard latitude of 70N.',
                wrap=True)
        elif args.Hemisphere == -1:
            plt.figtext(
                0.1,
                0.01,
                f'Figure 1. Average quarterly rate of height change (dhdt_lag1/dhdt) at {ave[1:]}-resolution, in meters, from cycle {args.cycles[0:2]} to cycle {args.cycles[2:4]}. Map is plotted in a polar-stereographic projection with a central longitude of 0W and a standard latitude of 71S.',
                wrap=True)
        fig.savefig(f'{pngfile}_default1.png')

        fig, ax = plt.subplots(1, 1)
        ax = plt.subplot(1, 1, 1, projection=projection)
        ax.add_feature(cfeature.LAND, facecolor='0.8')
        ax.coastlines(resolution='50m', linewidth=0.5)
        ax.gridlines(crs=ccrs.PlateCarree())
        h = ax.imshow(dhdtstd,
                      extent=extent,
                      cmap='viridis',
                      vmin=h05std,
                      vmax=h95std,
                      origin='lower',
                      interpolation='nearest')
        fig.colorbar(h,
                     ax=ax,
                     label='dh/dt standard deviation, m',
                     shrink=1 / 2,
                     extend='both')
        ax.set_title(
            f'Standard deviation of quarterly dh/dt: {os.path.basename(filein)}',
            wrap=True)
        if args.Hemisphere == 1:
            plt.figtext(
                0.1,
                0.01,
                f'Figure 2. Standard deviation of quarterly rate of height change (dhdt_lag1/dhdt) at {ave[1:]}-resolution, in meters, from cycle {args.cycles[0:2]} to cycle {args.cycles[2:4]}. Map is plotted in a polar-stereographic projection with a central longitude of 45W and a standard latitude of 70N.',
                wrap=True)
        elif args.Hemisphere == -1:
            plt.figtext(
                0.1,
                0.01,
                f'Figure 2. Standard deviation of quarterly rate of height change (dhdt_lag1/dhdt) at {ave[1:]}-resolution, in meters, from cycle {args.cycles[0:2]} to cycle {args.cycles[2:4]}. Map is plotted in a polar-stereographic projection with a central longitude of 0W and a standard latitude of 71S.',
                wrap=True)
        fig.savefig(f'{pngfile}_default2.png')

        #    print(glob.glob(f'{args.base_dir.rstrip("/")}/ATL15_{args.region}_{args.cycles}{ave}_{args.Release}_{args.version}_BRW_default*.png'))

        # write images to browse .h5 file
        brwfile = args.base_dir.rstrip(
            '/'
        ) + '/ATL15_' + args.region + '_' + args.cycles + ave + '_' + args.Release + '_' + args.version + '_BRW.h5'
        print(f'Making file {brwfile}')
        if os.path.isfile(brwfile):
            os.remove(brwfile)
        shutil.copyfile('surfaceChange/resources/BRW_template.h5', brwfile)
        with h5py.File(brwfile, 'r+') as hf:
            hf.require_group('/default')
            for ii, name in enumerate(
                    sorted(
                        glob.glob(
                            f'{args.base_dir.rstrip("/")}/ATL15_{args.region}_{args.cycles}{ave}_{args.Release}_{args.version}_BRW_default*.png'
                        ))):
                img = imageio.imread(name, pilmode='RGB')
                #print(ii,name)

                #            ave = os.path.basename(name).split('_')[3]
                dset = hf.create_dataset(f'default/default{ii+1}', \
                                         img.shape, data=img.data, \
                                         chunks=img.shape, \
                                         compression='gzip',compression_opts=6)
                dset.attrs['CLASS'] = np.string_('IMAGE')
                dset.attrs['IMAGE_VERSION'] = np.string_('1.2')
                dset.attrs['IMAGE_SUBCLASS'] = np.string_('IMAGE_TRUECOLOR')
                dset.attrs['INTERLACE_MODE'] = np.string_('INTERLACE_PIXEL')

    #    plt.show(block=False)
    #    plt.pause(0.001)
    #    input('Press enter to end.')
    #    plt.close('all')
    #    exit(-1)

        fhlog.close()
Пример #21
0
    def _draw_cartopy(self,
                      proj_prop=None,
                      vmin_polygons=None,
                      vmax_polygons=None,
                      **kwargs):
        if proj_prop is None:
            raise ValueError(
                'No projection properties are given! Please modify or choose a different backend!'
            )

        if proj_prop['projection'] in [
                'robin', 'TransverseMercator', 'mercator', 'stereo'
        ]:
            pass
        else:
            raise ValueError('Unsupported projection type')

        if hasattr(self.x, 'data'):
            plot_data_field = True
        else:
            plot_data_field = False

        if plot_data_field:
            xm = self.x.timmean()
            Z = xm
            lon = self.x.lon
            lat = self.x.lat

            if np.prod(lon.shape) == 0:  # no geometry
                print 'ERROR: invalid shape for plotting!'
                return

        if proj_prop['projection'] == 'robin':
            act_ccrs = ccrs.Robinson()
        elif proj_prop['projection'] == 'stereo':
            act_ccrs = ccrs.Stereographic(
                central_longitude=proj_prop.pop('central_longitude', 0.),
                central_latitude=proj_prop.pop('central_latitude', 0.))
        elif proj_prop['projection'] == 'TransverseMercator':
            act_ccrs = ccrs.TransverseMercator(
                central_longitude=proj_prop.pop('central_longitude', 0.),
                central_latitude=proj_prop.pop('central_latitude', 0.))
        elif proj_prop['projection'] == 'mercator':
            if 'extent' in proj_prop.keys():
                ymin = proj_prop['extent']['ymin']
                ymax = proj_prop['extent']['ymax']
            else:
                raise ValueError('Need to specify extent!')
            act_ccrs = ccrs.Mercator(central_longitude=proj_prop.pop(
                'central_longitude', 0.),
                                     min_latitude=ymin,
                                     max_latitude=ymax)
        else:
            raise ValueError('Unsupported projection')

        self.pax = self._ax2geoax(self.pax, act_ccrs)

        # add cyclic coordinates if possible
        if plot_data_field:
            if self.x._equal_lon():
                try:
                    lon1, lat1, Z1 = self._add_cyclic_to_field(
                        self.x._get_unique_lon(), lat, Z)
                except:
                    lon1 = None
                if lon1 is not None:
                    lon = lon1
                    lat = lat1
                    Z = Z1

        # plot and ancillary plots
        if 'extent' in proj_prop.keys():
            if proj_prop['projection'] == 'mercator':
                pass
            else:
                xmin = proj_prop['extent']['xmin']
                xmax = proj_prop['extent']['xmax']
                ymin = proj_prop['extent']['ymin']
                ymax = proj_prop['extent']['ymax']
                try:
                    # , crs=act_ccrs)  # problem was fixed by explicitely setting CRS
                    self.pax.set_extent([xmin, xmax, ymin, ymax])
                    # NO! the problem can not be fixed by providing the CRS
                    # explicitely! this results in strange results for the
                    # final maps!
                except:
                    print 'ERROR in set_extent. This is a known problem for cartopy geoaxes (see documentation in set_extent routine). Can not be fixed here.'
                    # try workaround
                    try:
                        # problem might be fixed by explicitely setting CRS
                        self.pax.set_extent([xmin, xmax, ymin, ymax],
                                            crs=act_ccrs)
                        # CAUTION This can result however in weird plots!!!
                        # Caused problems in the past!
                    except:
                        print 'Workaround did also not work, try to continue without setting extent!'
        else:
            self.pax.set_global()  # ensure global plot
        self.pax.coastlines()

        if plot_data_field:
            try:
                self.im = self.pax.pcolormesh(lon,
                                              lat,
                                              Z,
                                              transform=ccrs.PlateCarree(),
                                              **kwargs)
            except:
                print '*** WARNING: something did not work with pcolormesh plotting in mapping.py'
                self.im = None
        else:
            self.im = None

        self.pax.gridlines()

        # plot polygons
        if self.polygons is not None:
            if len(self.polygons) > 0:
                if False:  # plot all polygons individually
                    for p in self.polygons:
                        self._add_single_polygon_cartopy(p)
                else:  # all polygons as collection
                    self._add_polygons_as_collection_cartopy(
                        act_ccrs, vmin=vmin_polygons, vmax=vmax_polygons)
Пример #22
0
Dataset('temp.nc', 'w').close()  # Work around bug where it needs an existing netCDF file
nc = Dataset('temp.nc', 'r', memory=data)

###############################
# Pull the needed information out of the netCDF file
prcpvar = nc.variables['observation']
data = masked_array(prcpvar[:], units(prcpvar.units.lower())).to('mm')
x = nc.variables['x'][:]
y = nc.variables['y'][:]
proj_var = nc.variables[prcpvar.grid_mapping]

###############################
# Set up the projection information within CartoPy
globe = ccrs.Globe(semimajor_axis=proj_var.earth_radius)
proj = ccrs.Stereographic(central_latitude=90.0,
                          central_longitude=proj_var.straight_vertical_longitude_from_pole,
                          true_scale_latitude=proj_var.standard_parallel, globe=globe)

###############################
# Create the figure and plot the data
# create figure and axes instances
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1, projection=proj)

# draw coastlines, state and country boundaries, edge of map.
ax.coastlines()
ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.STATES)

# draw filled contours.
clevs = [0, 1, 2.5, 5, 7.5, 10, 15, 20, 30, 40,
Пример #23
0
    'urn:ogc:def:crs:EPSG::27700': 1,
    'urn:ogc:def:crs:EPSG::900913': 1,
    'urn:ogc:def:crs:OGC:1.3:CRS84': _WGS84_METERS_PER_UNIT,
    'urn:ogc:def:crs:EPSG::3031': 1,
    'urn:ogc:def:crs:EPSG::3413': 1,
    'urn:ogc:def:crs:EPSG::3857': 1,
    'urn:ogc:def:crs:EPSG:6.18.3:3857': 1
}

_URN_TO_CRS = collections.OrderedDict(
    [('urn:ogc:def:crs:OGC:1.3:CRS84', ccrs.PlateCarree()),
     ('urn:ogc:def:crs:EPSG::4326', ccrs.PlateCarree()),
     ('urn:ogc:def:crs:EPSG::900913', ccrs.GOOGLE_MERCATOR),
     ('urn:ogc:def:crs:EPSG::27700', ccrs.OSGB(approx=True)),
     ('urn:ogc:def:crs:EPSG::3031', ccrs.Stereographic(
         central_latitude=-90,
         true_scale_latitude=-71)),
     ('urn:ogc:def:crs:EPSG::3413', ccrs.Stereographic(
         central_longitude=-45,
         central_latitude=90,
         true_scale_latitude=70)),
     ('urn:ogc:def:crs:EPSG::3857', ccrs.GOOGLE_MERCATOR),
     ('urn:ogc:def:crs:EPSG:6.18.3:3857', ccrs.GOOGLE_MERCATOR)
     ])

# XML namespace definitions
_MAP_SERVER_NS = '{http://mapserver.gis.umn.edu/mapserver}'
_GML_NS = '{http://www.opengis.net/gml}'


def _warped_located_image(image, source_projection, source_extent,
Пример #24
0
    'urn:ogc:def:crs:EPSG::27700': 1,
    'urn:ogc:def:crs:EPSG::900913': 1,
    'urn:ogc:def:crs:OGC:1.3:CRS84': _WGS84_METERS_PER_UNIT,
}

_URN_TO_CRS = {
    'urn:ogc:def:crs:EPSG::27700':
    ccrs.OSGB(),
    'urn:ogc:def:crs:EPSG::4326':
    ccrs.PlateCarree(),
    'urn:ogc:def:crs:EPSG::900913':
    ccrs.GOOGLE_MERCATOR,
    'urn:ogc:def:crs:OGC:1.3:CRS84':
    ccrs.PlateCarree(),
    'urn:ogc:def:crs:EPSG::3031':
    ccrs.Stereographic(central_latitude=-90, true_scale_latitude=-71)
}

# XML namespace definitions
_MAP_SERVER_NS = '{http://mapserver.gis.umn.edu/mapserver}'
_GML_NS = '{http://www.opengis.net/gml}'


class WMSRasterSource(RasterSource):
    """
    A WMS imagery retriever which can be added to a map.

    .. note:: Requires owslib and Pillow to work.

    .. note::
Пример #25
0
def makeCatalogImages(webdir, logger):

    logger.info('--- Looping through catalog entries to make images, getting details and data from ERDDAP ---')
    
    catalogFn = webdir + '/config/catalog_temp.json'

    with open(catalogFn) as catalogfile:    
      cataloginfo = json.load(catalogfile)

    ddir = webdir +'/images/'     
    if not os.path.exists(ddir): os.makedirs(ddir)

    # For each Entry in the PW catalog
    # Get data for each dataset from ERDDAP
    # Plot it as thumbnail for catalog view

    for e in cataloginfo:
      #print(cataloginfo)
      entry = cataloginfo[e]
      logger.info(' * '+entry['entryId'])
      #print(entry)

      # Check to see if the whole entry is invalid
      if sum(entry['validDatasets']) > 0:
        
          print('   So far this is a valid entry. Continuing Plotting Loop.')
          subEntry = 0
          plottime = []  
          epsg3411_globe = ccrs.Globe(semimajor_axis=6378273, semiminor_axis=None, inverse_flattening =298.279411123064,
                           ellipse=None)

          cartopy_crs_dict = {
            "ccrs_3031": ccrs.Stereographic(central_latitude=-90, central_longitude=0.0,true_scale_latitude=-71,globe=ccrs.Globe(datum='WGS84',ellipse='WGS84')),
            "ccrs_3412": ccrs.Stereographic(central_latitude=-90, central_longitude=0.0,true_scale_latitude=-70,globe=ccrs.Globe(datum='WGS84',ellipse='WGS84')),
            "ccrs_3413": ccrs.Stereographic(central_latitude=90, central_longitude=-45,true_scale_latitude=70,globe=ccrs.Globe(datum='WGS84',ellipse='WGS84')),
            "ccrs_3411": ccrs.Stereographic(central_latitude=90, central_longitude=-45,true_scale_latitude=70,globe=epsg3411_globe),
            "ccrs_4326": ccrs.PlateCarree()
            }
          # Dataset Loop
          # Generate plots for all sub entry datasets (daily, weekly, monthly)

          for thisDataset in entry['datasets']:
            
            datasetId = thisDataset['id']
            logger.info('  ###### ' + datasetId +'  ########')
            thisDataset['time'] = {}
            thisDataset['thumbnail'] = {}
            thisDataset['thumbnail']['entryId'] = entry['entryId']
                        
            # Check that this dataset is in catalog
            if thisDataset['inERDDAP'] == 1:
              
                print('    - Dataset is in ERDDAP (according to alldatasets list). Continuing with making thumbnail plots')
                #print(thisDataset)
                
                # PREPARE FOR DATA REQUEST FOR PLOTS

                # See if we are creating a dataset from a variable (ie. eumetsat ice)
                makeEntryFlag = entry["makeEntryFlag"]
                erddapVarName = entry["erddapVarName"]
                
                thisDataset["thumbnail"]["iceDisplay"] = entry["iceDisplay"] # whether or not to display ice on catalog plot
                subname = thisDataset["subname"] # usually daily, weekly...
                print(subname)
                
                # Get Parameter to use for plots, using first parameter
                thisDataset["thumbnail"]["eparname"] = thisDataset['parameters'][0]['name']            
                
                # 0 because only generating thumbnails for first parameter in list
                thisDataset["thumbnail"]["cbmin"] = float(thisDataset["parameters"][0]["colorbar"]["colorbarmin"])
                thisDataset["thumbnail"]["cbmax"] = float(thisDataset["parameters"][0]["colorbar"]["colorbarmax"])

                thisDataset["thumbnail"]["cbpalette"] = thisDataset["parameters"][0]["colorbar"]["palette"]
                
                thisDataset["thumbnail"]["cblog"] = thisDataset["parameters"][0]["colorbar"]["logscale"]

                # Get information about this dataset
                ei = thisDataset["allDatasets"];

                dontplot =0    
                print(dontplot)
                if dontplot == 0:
                    # PREPARE TO GET DATA    
                    
                    #adjust bounds order for erddap if needed
                    qbounds = getRequestBounds(thisDataset)
                    
                    # Setup Time Query
                    time_latest = ei[10]
                    #time_start = time_latest
                    thisDataset["thumbnail"]["time_end"] = time_latest

                    print('#### GETTING DATA #####')
                    logger.info(datasetId)
                    dataObj = getData(datasetId, thisDataset["thumbnail"]["eparname"], qbounds, time_latest)
                    logger.info(dataObj["inERDDAP"])
                    logger.info(dataObj["goodFile"])
                    
                    # handle errors first
                    if dataObj["inERDDAP"] == 0:
                        # update all the places where we are keeping track of valid datasets...
                        print('not in erddap')
                        print(dataObj)

                    # make plots
                    if dataObj["goodFile"] == 1:
                        
                        this_data_netcdf_dataset = dataObj["data_netcdf_dataset"]
                        print(thisDataset["thumbnail"]["eparname"])
                        # check data file for expected altitude dimension response 
                        # pull out parameter data and x, y
                        if len(np.shape(this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["eparname"]])) == 3: 
                            thisDataset["thumbnail"]["data"] = this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["eparname"]][0, :, :]
                        elif len(np.shape(this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["eparname"]])) == 4: 
                            thisDataset["thumbnail"]["data"] = this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["eparname"]][0, 0,:, :]
                        elif len(np.shape(this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["eparname"]])) == 2: 
                            thisDataset["thumbnail"]["data"] = this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["eparname"]][:, :]   
                        
                        thisDataset["thumbnail"]["ycoord_dimension"]=next((dimension for dimension in thisDataset["dimensions"] if dimension["axis"] == "Y"))
                        thisDataset["thumbnail"]["xcoord_dimension"]=next((dimension for dimension in thisDataset["dimensions"] if dimension["axis"] == "X"))  

                        thisDataset["thumbnail"]["xgrid"] = this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["xcoord_dimension"]["name"]][:]
                        thisDataset["thumbnail"]["ygrid"] = this_data_netcdf_dataset.variables[thisDataset["thumbnail"]["ycoord_dimension"]["name"]][:]

                        thisDataset["thumbnail"]["xmin"] = float(thisDataset["thumbnail"]["xgrid"][0])
                        thisDataset["thumbnail"]["xmax"] = float(thisDataset["thumbnail"]["xgrid"][len(thisDataset["thumbnail"]["xgrid"])-1])
                        thisDataset["thumbnail"]["ymin"] = float(thisDataset["thumbnail"]["ygrid"][len(thisDataset["thumbnail"]["ygrid"])-1])
                        thisDataset["thumbnail"]["ymax"] = float(thisDataset["thumbnail"]["ygrid"][0])             # note: ymax should be bigger than ymin and is towards top of plot

                        # to do: does this really help?
                        thisDataset["thumbnail"]["cellHeight"] = float(getDimensionInfo(thisDataset["dimensions"], thisDataset["thumbnail"]["ycoord_dimension"]["name"], 'averageSpacing'))
                        thisDataset["thumbnail"]["cellWidth"] = float(getDimensionInfo(thisDataset["dimensions"], thisDataset["thumbnail"]["ycoord_dimension"]["name"], 'averageSpacing'))

                        thisDataset["thumbnail"]["xgridMod"] = thisDataset["thumbnail"]["xgrid"] - (thisDataset["thumbnail"]["cellWidth"]/2)
                        thisDataset["thumbnail"]["xgridMod"] = np.append(thisDataset["thumbnail"]["xgridMod"], thisDataset["thumbnail"]["xgridMod"][len(thisDataset["thumbnail"]["xgridMod"])-1] + thisDataset["thumbnail"]["cellWidth"])
                        #print(xgridMod)
                        thisDataset["thumbnail"]["ygridMod"] = thisDataset["thumbnail"]["ygrid"] + (thisDataset["thumbnail"]["cellHeight"]/2)
                        thisDataset["thumbnail"]["ygridMod"] = np.append(thisDataset["thumbnail"]["ygridMod"], thisDataset["thumbnail"]["ygridMod"][len(thisDataset["thumbnail"]["ygridMod"])-1] - thisDataset["thumbnail"]["cellHeight"])

                        thisDataset["thumbnail"]["X"], thisDataset["thumbnail"]["Y"] = np.meshgrid(thisDataset["thumbnail"]["xgrid"], thisDataset["thumbnail"]["ygrid"])    

                        plotList = []
                        plotdate = dateutil.parser.parse(time_latest)

                        plotdatestr = plotdate.strftime("%b %d, %Y")
                        thisDataset['time']['plotTime'] = plotdatestr
                        plottime.append(plotdatestr)
                    
                        for region in entry["regions"]:
                            
                            if region.get("arctic") == 1:
                                # Make Arctic Plot
                                print('Making Arctic Thumbnail Plot')
                                makeThumbnail(webdir, logger, cartopy_crs_dict, thisDataset, 'arctic')
                                plotList.append('arctic')
                            else:
                                print("Dataset does not have arctic set as a region, not making Arctic thumbnail plot")    
                            if region.get("antarctic") == 1:
                                # Make Antarctic Plot
                                print('Making Antarctic Thumbnail Plot')
                                makeThumbnail(webdir, logger, cartopy_crs_dict, thisDataset, 'antarctic')
                                plotList.append('antarctic')
                            else:
                                print("Dataset does not have Antarctic set as a region, not making Antarctic thumbnail plot")    
                        thisDataset["thumbnail"]=[]
                        cataloginfo[e]["plotList"] = plotList; 

                else:
                    logger.info('Not plotting - Data not retrieved from ERDDAP')

            subEntry = subEntry + 1

          print('Finished making thumbnails.')
          cataloginfo[e]["plotTime"] = plottime
      #print(cataloginfo[e])
   
    print(cataloginfo)
    # Add any new fields to temporary catalog file
    with open(catalogFn,"w") as catalogfile:
        json.dump(cataloginfo, catalogfile)

    logger.info('Make Images End')
    logger.info('=================')
    return(1)
Пример #26
0
    def plot(self,
             variable=None,
             vmin=None,
             vmax=None,
             filename=None,
             title=None,
             buffer=1,
             lscale='auto',
             show_GSHHS = False):
        """Plot geographical coverage of reader."""

        import matplotlib.pyplot as plt
        from matplotlib.patches import Polygon
        import cartopy.crs as ccrs
        import cartopy.feature as cfeature

        fig = plt.figure()
        plt.ion()

        corners = self.xy2lonlat([self.xmin, self.xmin, self.xmax, self.xmax],
                                 [self.ymax, self.ymin, self.ymax, self.ymin])
        lonmin = np.min(corners[0]) - buffer * 2
        lonmax = np.max(corners[0]) + buffer * 2
        latmin = np.min(corners[1]) - buffer
        latmax = np.max(corners[1]) + buffer
        latspan = latmax - latmin

        # Initialise map
        if latspan < 90:
            # Stereographic projection centred on domain, if small domain
            x0 = (self.xmin + self.xmax) / 2
            y0 = (self.ymin + self.ymax) / 2
            lon0, lat0 = self.xy2lonlat(x0, y0)
            sp = ccrs.Stereographic(central_longitude=lon0,
                                    central_latitude=lat0)
            ax = fig.add_subplot(1, 1, 1, projection=sp)
            corners_stere = sp.transform_points(ccrs.PlateCarree(),
                                                np.array(corners[0]),
                                                np.array(corners[1]))
        else:
            # Global map if reader domain is large
            sp = ccrs.Mercator()
            ax = fig.add_subplot(1, 1, 1, projection=sp)
            #map = Basemap(np.array(corners[0]).min(), -89,
            #              np.array(corners[0]).max(), 89,
            #              resolution='c', projection='cyl')

        if show_GSHHS :

            # add GSHHS coastlines for comparison
            f = cfeature.GSHHSFeature(scale=lscale,
                                      levels=[1],
                                      facecolor=cfeature.COLORS['land'])
            ax.add_geometries(f.intersecting_geometries(
                [lonmin, lonmax, latmin, latmax]),
                              ccrs.PlateCarree(),
                              facecolor=cfeature.COLORS['land'],
                              edgecolor='black')

        gl = ax.gridlines(ccrs.PlateCarree())
        gl.xlabels_top = False

        # Get boundary
        npoints = 10  # points per side
        x = np.array([])
        y = np.array([])
        x = np.concatenate((x, np.linspace(self.xmin, self.xmax, npoints)))
        y = np.concatenate((y, [self.ymin] * npoints))
        x = np.concatenate((x, [self.xmax] * npoints))
        y = np.concatenate((y, np.linspace(self.ymin, self.ymax, npoints)))
        x = np.concatenate((x, np.linspace(self.xmax, self.xmin, npoints)))
        y = np.concatenate((y, [self.ymax] * npoints))
        x = np.concatenate((x, [self.xmin] * npoints))
        y = np.concatenate((y, np.linspace(self.ymax, self.ymin, npoints)))
        # from x/y vectors create a Patch to be added to map
        lon, lat = self.xy2lonlat(x, y)
        lat[lat > 89] = 89.
        lat[lat < -89] = -89.
        p = sp.transform_points(ccrs.PlateCarree(), lon, lat)
        xsp = p[:, 0]
        ysp = p[:, 1]

        # add shapely features of custom_landmak
        if variable is None:
            for poly in self.mask.__dict__['context']:
                # to access xy of shapely prepared feature:
                # self.mask.__dict__['context'][0].exterior.xy
                #
                # The data are defined in lat/lon coordinate system, so PlateCarree() is the appropriate choice
                # https://scitools.org.uk/cartopy/docs/latest/tutorials/understanding_transform.html
                ax.add_geometries([poly],
                                  crs=ccrs.PlateCarree(),
                                  facecolor= 'darkgrey',
                                  edgecolor='red',
                                  alpha=0.75)
            # could maybe use feature.ShapelyFeature ?
            # feature.ShapelyFeature(self.mask, crs = ccrs.PlateCarree())
            self.mask.__dict__['context']

            buf = (xsp.max() -
                   xsp.min()) * .1  # Some whitespace around polygon
            buf = 0
            try:
                ax.set_extent([
                    xsp.min() - buf,
                    xsp.max() + buf,
                    ysp.min() - buf,
                    ysp.max() + buf
                ],
                              crs=sp)
            except:
                pass
        if title is None:
            plt.title(self.name)
        else:
            plt.title(title)
        plt.xlabel('Time coverage: %s to %s' %
                   (self.start_time, self.end_time))

        try:  # Activate figure zooming
            mng = plt.get_current_fig_manager()
            mng.toolbar.zoom()
        except:
            pass

        if filename is not None:
            plt.savefig(filename)
            plt.close()
        else:
            plt.ion()
            plt.show()
            # import pdb;pdb.set_trace()
Пример #27
0
    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,
Пример #28
0
def test_transform_points_empty():
    """Test CRS.transform_points with empty array."""
    crs = ccrs.Stereographic()
    result = crs.transform_points(ccrs.PlateCarree(), np.array([]),
                                  np.array([]))
    assert_array_equal(result, np.array([], dtype=np.float64).reshape(0, 3))
Пример #29
0
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

plt.figure(figsize=(3, 3))
ax = plt.axes(projection=ccrs.Stereographic())
ax.coastlines(resolution='110m')
ax.gridlines()
Пример #30
0
    'urn:ogc:def:crs:EPSG::27700': 1,
    'urn:ogc:def:crs:EPSG::900913': 1,
    'urn:ogc:def:crs:OGC:1.3:CRS84': _WGS84_METERS_PER_UNIT,
    'urn:ogc:def:crs:EPSG::3031': 1,
    'urn:ogc:def:crs:EPSG::3413': 1,
    'urn:ogc:def:crs:EPSG::3857': 1,
    'urn:ogc:def:crs:EPSG:6.18.3:3857': 1
}

_URN_TO_CRS = collections.OrderedDict([
    ('urn:ogc:def:crs:OGC:1.3:CRS84', ccrs.PlateCarree()),
    ('urn:ogc:def:crs:EPSG::4326', ccrs.PlateCarree()),
    ('urn:ogc:def:crs:EPSG::900913', ccrs.GOOGLE_MERCATOR),
    ('urn:ogc:def:crs:EPSG::27700', ccrs.OSGB(approx=True)),
    ('urn:ogc:def:crs:EPSG::3031',
     ccrs.Stereographic(central_latitude=-90, true_scale_latitude=-71)),
    ('urn:ogc:def:crs:EPSG::3413',
     ccrs.Stereographic(central_longitude=-45,
                        central_latitude=90,
                        true_scale_latitude=70)),
    ('urn:ogc:def:crs:EPSG::3857', ccrs.GOOGLE_MERCATOR),
    ('urn:ogc:def:crs:EPSG:6.18.3:3857', ccrs.GOOGLE_MERCATOR)
])

# XML namespace definitions
_MAP_SERVER_NS = '{http://mapserver.gis.umn.edu/mapserver}'
_GML_NS = '{http://www.opengis.net/gml}'


def _warped_located_image(image, source_projection, source_extent,
                          output_projection, output_extent, target_resolution):