Exemplo n.º 1
0
def test_plot_region_model():

    gdirs = random_for_plot()

    dfc = utils.compile_task_log(gdirs, task_names=['run_random_climate_plot'])
    assert np.all(dfc['run_random_climate_plot'] == 'SUCCESS')

    # We prepare for the plot, which needs our own map to proceed.
    # Lets do a local mercator grid
    g = salem.mercator_grid(center_ll=(10.86, 46.85), extent=(27000, 21000))
    # And a map accordingly
    sm = salem.Map(g, countries=False)
    sm.set_topography(get_demo_file('srtm_oetztal.tif'))

    # Give this to the plot function
    fig, ax = plt.subplots()
    graphics.plot_modeloutput_map(gdirs,
                                  smap=sm,
                                  ax=ax,
                                  filesuffix='_plot',
                                  vmax=250,
                                  modelyr=10,
                                  linewidth=1.5)

    fig.tight_layout()
    return fig
Exemplo n.º 2
0
def plot_googlemap(gdir, ax=None):
    """Plots the glacier over a googlemap."""

    # TODO: center grid or corner grid???
    crs = gdir.grid.center_grid

    dofig = False
    if ax is None:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        dofig = True

    s = salem.read_shapefile(gdir.get_filepath('outlines'))
    gm = salem.GoogleVisibleMap(np.array(s.geometry[0].exterior.xy[0]),
                                np.array(s.geometry[0].exterior.xy[1]),
                                crs=s.crs,
                                key='AIzaSyDWG_aTgfU7CeErtIzWfdGxpStTlvDXV_o')

    img = gm.get_vardata()
    cmap = salem.Map(gm.grid, countries=False, nx=gm.grid.nx)
    cmap.set_rgb(img)

    cmap.set_shapefile(gdir.get_filepath('outlines'))

    cmap.plot(ax)
    title = gdir.rgi_id
    if gdir.name is not None and gdir.name != '':
        title += ': ' + gdir.name
    ax.set_title(title)

    if dofig:
        plt.tight_layout()
Exemplo n.º 3
0
    def newplotfunc(gdir,
                    ax=None,
                    add_colorbar=True,
                    title=None,
                    title_comment=None,
                    horizontal_colorbar=False,
                    lonlat_contours_kwargs=None,
                    **kwargs):

        dofig = False
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
            dofig = True

        mp = salem.Map(gdir.grid, countries=False, nx=gdir.grid.nx)
        if lonlat_contours_kwargs is not None:
            mp.set_lonlat_contours(**lonlat_contours_kwargs)

        out = plotfunc(gdir, ax=ax, salemmap=mp, **kwargs)

        if add_colorbar and 'cbar_label' in out:
            cbprim = out.get('cbar_primitive', mp)
            if horizontal_colorbar:
                cb = cbprim.append_colorbar(ax, "bottom", size="5%", pad=0.4)
            else:
                cb = cbprim.append_colorbar(ax, "right", size="5%", pad=0.2)
            cb.set_label(out['cbar_label'])

        if title is None:
            if 'title' not in out:
                # Make a defaut one
                title = gdir.rgi_id
                if gdir.name is not None and gdir.name != '':
                    title += ': ' + gdir.name
                out['title'] = title

            if title_comment is None:
                title_comment = out.get('title_comment', '')

            out['title'] += title_comment
            ax.set_title(out['title'])
        else:
            ax.set_title(title)

        if dofig:
            plt.tight_layout()
Exemplo n.º 4
0
def test_plot_region_inversion():

    gdirs = up_to_inversion()

    # We prepare for the plot, which needs our own map to proceed.
    # Lets do a local mercator grid
    g = salem.mercator_grid(center_ll=(10.86, 46.85), extent=(27000, 21000))
    # And a map accordingly
    sm = salem.Map(g, countries=False)
    sm.set_topography(get_demo_file('srtm_oetztal.tif'))

    # Give this to the plot function
    fig, ax = plt.subplots()
    graphics.plot_inversion(gdirs, smap=sm, ax=ax, linewidth=1.5, vmax=250)

    fig.tight_layout()
    return fig
Exemplo n.º 5
0
def plot_googlemap(gdirs, ax=None, figsize=None):
    """Plots the glacier(s) over a googlemap."""

    dofig = False
    if ax is None:
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111)
        dofig = True

    gdirs = utils.tolist(gdirs)

    xx, yy = [], []
    for gdir in gdirs:
        xx.extend(gdir.extent_ll[0])
        yy.extend(gdir.extent_ll[1])

    gm = salem.GoogleVisibleMap(xx,
                                yy,
                                key='AIzaSyDWG_aTgfU7CeErtIzWfdGxpStTlvDXV_o')

    img = gm.get_vardata()
    cmap = salem.Map(gm.grid, countries=False, nx=gm.grid.nx)
    cmap.set_rgb(img)

    for gdir in gdirs:
        cmap.set_shapefile(gdir.read_shapefile('outlines'))

    cmap.plot(ax)
    title = ''
    if len(gdirs) == 1:
        title = gdir.rgi_id
        if gdir.name is not None and gdir.name != '':
            title += ': ' + gdir.name
    ax.set_title(title)

    if dofig:
        plt.tight_layout()
Exemplo n.º 6
0
# read the lake shapefile (data from http://www.naturalearthdata.com)
lakes = salem.read_shapefile(salem.get_demo_file('ne_50m_lakes.shp'),
                             cached=True)

# The default is to keep only the pixels which center is within the polygon:
mask_default = grid.region_of_interest(shape=oceans)
mask_default = grid.region_of_interest(shape=lakes, roi=mask_default)

# But we can also compute a mask from all touched pixels
mask_all_touched = grid.region_of_interest(shape=oceans, all_touched=True)
mask_all_touched = grid.region_of_interest(shape=lakes,
                                           all_touched=True,
                                           roi=mask_all_touched)

# Make a map to check our results
sm = salem.Map(grid, countries=False)
sm.set_shapefile(oceans, edgecolor='k', facecolor='none', linewidth=2)
sm.set_shapefile(lakes, edgecolor='k', facecolor='none', linewidth=2)
sm.set_plot_params(cmap='Blues', vmax=2)

# prepare the figure
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3))

# plot 1
sm.set_data(mask_default)
sm.visualize(ax=ax1, addcbar=False, title='Default')
# plot 2
sm.set_data(mask_all_touched)
sm.visualize(ax=ax2, addcbar=False, title='All touched')

# plot!
Exemplo n.º 7
0
    def newplotfunc(gdirs,
                    ax=None,
                    smap=None,
                    add_colorbar=True,
                    title=None,
                    title_comment=None,
                    horizontal_colorbar=False,
                    lonlat_contours_kwargs=None,
                    cbar_ax=None,
                    autosave=False,
                    add_scalebar=True,
                    figsize=None,
                    savefig=None,
                    savefig_kwargs=None,
                    **kwargs):

        dofig = False
        if ax is None:
            fig = plt.figure(figsize=figsize)
            ax = fig.add_subplot(111)
            dofig = True

        # Cast to list
        gdirs = utils.tolist(gdirs)

        if smap is None:
            mp = salem.Map(gdirs[0].grid, countries=False, nx=gdirs[0].grid.nx)
        else:
            mp = smap

        if lonlat_contours_kwargs is not None:
            mp.set_lonlat_contours(**lonlat_contours_kwargs)

        if add_scalebar:
            mp.set_scale_bar()
        out = plotfunc(gdirs, ax=ax, smap=mp, **kwargs)

        if add_colorbar and 'cbar_label' in out:
            cbprim = out.get('cbar_primitive', mp)
            if cbar_ax:
                cb = cbprim.colorbarbase(cbar_ax)
            else:
                if horizontal_colorbar:
                    cb = cbprim.append_colorbar(ax,
                                                "bottom",
                                                size="5%",
                                                pad=0.4)
                else:
                    cb = cbprim.append_colorbar(ax,
                                                "right",
                                                size="5%",
                                                pad=0.2)
            cb.set_label(out['cbar_label'])

        if title is None:
            if 'title' not in out:
                # Make a defaut one
                title = ''
                if len(gdirs) == 1:
                    gdir = gdirs[0]
                    title = gdir.rgi_id
                    if gdir.name is not None and gdir.name != '':
                        title += ': ' + gdir.name
                out['title'] = title

            if title_comment is None:
                title_comment = out.get('title_comment', '')

            out['title'] += title_comment
            ax.set_title(out['title'])
        else:
            ax.set_title(title)

        if dofig:
            plt.tight_layout()

        if autosave:
            savefig = os.path.join(cfg.PATHS['working_dir'], 'plots')
            utils.mkdir(savefig)
            savefig = os.path.join(
                savefig, plotfunc.__name__ + '_' + gdirs[0].rgi_id + '.png')

        if savefig is not None:
            plt.savefig(savefig, **savefig_kwargs)
            plt.close()
Exemplo n.º 8
0
def plot_modeloutput_map(gdir, ax=None, salemmap=None, model=None, vmax=None):
    """Plots the result of the model output."""

    with netCDF4.Dataset(gdir.get_filepath('gridded_data')) as nc:
        topo = nc.variables['topo'][:]

    geom = gdir.read_pickle('geometries', div_id=0)
    poly_pix = geom['polygon_pix']

    ds = salem.GeoDataset(gdir.grid)
    mlines = shpg.GeometryCollection([l.line for l in model.fls] + [poly_pix])
    ml = mlines.bounds
    corners = ((ml[0], ml[1]), (ml[2], ml[3]))

    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=RuntimeWarning)
        ds.set_subset(corners=corners, margin=10, crs=gdir.grid)

    salemmap = salem.Map(ds.grid, countries=False, nx=gdir.grid.nx)
    salemmap.set_topography(topo, crs=gdir.grid)

    # TODO: center grid or corner grid???
    crs = gdir.grid.center_grid
    salemmap.set_geometry(poly_pix, crs=crs, fc='none', zorder=2, linewidth=.2)
    for l in poly_pix.interiors:
        salemmap.set_geometry(l, crs=crs, color='black', linewidth=0.5)

    toplot_th = np.array([])
    toplot_lines = []

    # plot Centerlines
    cls = model.fls
    for l in cls:
        salemmap.set_geometry(l.line,
                              crs=crs,
                              color='gray',
                              linewidth=1.2,
                              zorder=50)
        toplot_th = np.append(toplot_th, l.thick)
        widths = l.widths.copy()
        widths = np.where(l.thick > 0, widths, 0.)
        for wi, cur, (n1, n2) in zip(widths, l.line.coords, l.normals):
            l = shpg.LineString([
                shpg.Point(cur + wi / 2. * n1),
                shpg.Point(cur + wi / 2. * n2)
            ])
            toplot_lines.append(l)

    cm = plt.cm.get_cmap('YlOrRd')
    dl = salem.DataLevels(cmap=cm,
                          nlevels=256,
                          data=toplot_th,
                          vmin=0,
                          vmax=vmax)
    colors = dl.to_rgb()
    for l, c in zip(toplot_lines, colors):
        salemmap.set_geometry(l, crs=crs, color=c, linewidth=3, zorder=50)
    salemmap.plot(ax)

    return dict(cbar_label='Section thickness [m]',
                cbar_primitive=dl,
                title_comment=' -- year: {:d}'.format(np.int64(model.yr)))
Exemplo n.º 9
0
from .itmix_cfg import DATA_DIR, ITMIX_ODIR, PLOTS_DIR

pdir = os.path.join(PLOTS_DIR, 'submitted') + '/'
if not os.path.exists(pdir):
    os.mkdir(pdir)

for dgn in glob.glob(os.path.join(ITMIX_ODIR, '*')):
    gname = os.path.basename(dgn)
    print(gname)

    ifile = find_path(os.path.join(DATA_DIR, 'itmix', 'glaciers_sorted'),
                      '02_surface_' + gname + '*.asc')
    ds = salem.EsriITMIX(ifile)
    itmix_topo = ds.get_vardata()

    ifiles = find_path(ITMIX_ODIR, '*' + gname + '*.asc', allow_more=True)
    for ifile in ifiles:
        ds2 = salem.EsriITMIX(ifile)
        oggm_topo = ds2.get_vardata()

        thick = itmix_topo - oggm_topo

        cm = salem.Map(ds.grid)
        cm.set_plot_params(nlevels=256)
        cm.set_cmap(plt.get_cmap('viridis'))
        cm.set_data(thick)
        cm.visualize()

        pname = os.path.basename(ifile).split('.')[0]
        plt.savefig(os.path.join(pdir, pname) + '.png')
        plt.close()
Exemplo n.º 10
0
                           size_x=400,
                           size_y=400)
ggl_img = g.get_vardata()

# Get each level draining into the lake, then into the last level, and so on
gds = []
prev_id = [gdf.iloc[0].MAIN_BAS]
while True:
    gd = gdf.loc[gdf.NEXT_DOWN.isin(prev_id)]
    if len(gd) == 0:
        break
    gds.append(gd)
    prev_id = gd.HYBAS_ID.unique()

# make a map of the same size as the image
sm = salem.Map(g.grid, factor=1)
sm.set_rgb(ggl_img)  # add the background rgb image
# add all the draining basins
cmap = plt.get_cmap('Blues')
for i, gd in enumerate(gds):
    # here we use a trick. set_shapefile uses PatchCollections internally,
    # which is fast but does not support legend labels.
    # so we use set_geometry instead:
    for g, geo in enumerate(gd.geometry):
        # we don't want more than one label per level
        label = 'Level {:02d}'.format(i + 1) if g == 0 else None
        sm.set_geometry(geo,
                        facecolor=cmap(i / (len(gds) - 1)),
                        alpha=0.8,
                        label=label)
Exemplo n.º 11
0
                    filesuffix='_tbias')

utils.compile_run_output(gdirs, filesuffix='_defaults')
utils.compile_run_output(gdirs, filesuffix='_tbias')

# ds = xr.open_dataset(os.path.join(base_dir, 'run_output_defaults.nc'))
# (ds.volume.sum(dim='rgi_id') * 1e-9).plot()
# plt.show()
# exit()

# We prepare for the plot, which needs our own map to proceed.
# Lets do a local mercator grid
g = salem.mercator_grid(center_ll=(-19.61, 63.63),
                        extent=(18000, 14500))
# And a map accordingly
sm = salem.Map(g, countries=False)
sm.set_lonlat_contours(add_xtick_labels=False)
z = sm.set_topography('/home/mowglie/disk/OGGM_INPUT/tmp/ISL.tif')
sm.set_data(z)

# Figs
f = 0.9
f, axs = plt.subplots(2, 1, figsize=(7*f, 10*f))

graphics.plot_domain(gdirs, ax=axs[0], smap=sm)


sm.set_data()
sm.set_lonlat_contours()
sm.set_geometry()
sm.set_text()
Exemplo n.º 12
0
# -*- coding: utf-8 -*-
"""
==============================
Add a Natural Earth background
==============================

An alternative to Google Static Maps
"""

import salem
import matplotlib.pyplot as plt

# get the map from a predefined grid
grid = salem.mercator_grid(transverse=False,
                           center_ll=(16., 0.),
                           extent=(8e6, 9e6))
smap = salem.Map(grid)

# Add the background (other resolutions include: 'mr', 'hr')
smap.set_rgb(natural_earth='lr')

# done!
smap.visualize()
plt.show()
Exemplo n.º 13
0
# create the correct projection
x0 = -4e5
y0 = -5e5
pwrf = '+proj=lcc +lat_1={:2.5f} +lat_2={:2.5f} ' \
    '+lat_0={:2.5f} +lon_0={:2.5f} ' \
          '+x_0={:f} +y_0={:f}'.format(lat1,lat2,lat0,lonc,0,0)
grid = salem.Grid(nxny=(nx, ny), x0y0=(x0, y0), dxdy=(dx, dy), proj=pwrf)

lon1d = np.min(grid.ll_coordinates[0])
lon2d = np.max(grid.ll_coordinates[0])
lat1d = np.min(grid.ll_coordinates[1])
lat2d = np.max(grid.ll_coordinates[1])

# output an overview of the topography
sm = salem.Map(grid)
if preview:
    print '  * approximate boundaries (WESN):{:3.0f},{:3.0f},{:3.0f},{:3.0f}'.format(
        lon1d, lon2d, lat1d, lat2d)
    if plots:
        sm.visualize()
        print '    creating preview file...'
        plt.savefig('./{:s}_preview.pdf'.format(name))
    sys.exit(0)
else:
    print '  * {:3.1f}N to {:3.1f}N and {:3.1f}W to {:3.1f}W at {:2.1f}m x {:2.1f}m as {:s}'.format(
        lon1d, lat1d, lon2d, lat2d, dx, dy, name)

script_path = os.path.dirname(os.path.realpath(__file__))

# calculate an average dlon and dlat to decided which data source to use