ds18_hist = ds18_hist.sel(lon=slice(coord[0],coord[1]), lat=slice(coord[2],coord[3]))
ds18_present = ds18_present.sel(lon=slice(coord[0],coord[1]), lat=slice(coord[2],coord[3]))
top = top.sel(lon=slice(coord[0],coord[1]), lat=slice(coord[2],coord[3]))
tdummy = tdummy.sel(lon=slice(coord[0],coord[1]), lat=slice(coord[2],coord[3]), month=5)
tdummy2 = tdummy2.sel(lon=slice(coord[0],coord[1]), lat=slice(coord[2],coord[3]), month=5)
t2 = tdummy2['lst']
t = tdummy['lst']

ds18_hist.name = '2004-2008'
ds18_present.name = '2011-2015'

map = ds18_present.salem.get_map(cmap='viridis')
#map.set_shapefile(oceans=True)
map.set_shapefile(rivers=True)
# read the ocean shapefile (data from http://www.naturalearthdata.com)
oceans = salem.read_shapefile(salem.get_demo_file('ne_50m_ocean.shp'),
                              cached=True)

river = salem.read_shapefile('/users/global/cornkle/data/pythonWorkspace/proj_CEH/shapes/rivers/ne_10m_rivers_lake_centerlines.shp', cached=True)
lakes = salem.read_shapefile('/users/global/cornkle/data/pythonWorkspace/proj_CEH/shapes/lakes/ne_10m_lakes.shp', cached=True)
map.set_shapefile(lakes, edgecolor='k', facecolor='none', linewidth=2,)


srtm_on_ds = ds18_present.salem.lookup_transform(top)
t_on_ds = ds18_present.salem.transform(t)
t2_on_ds = ds18_present.salem.transform(t2)

grid = ds18_present.salem.grid
#deforestation
g = GeoTiff(lst)
ex = grid.extent_in_crs(crs=wgs84)  # l, r, b, t
Compute a land/sea mask from a shapefile.

This example illustrates the two different methods available to compute a
raster mask from shapefile polygons.
"""

import salem
import matplotlib.pyplot as plt

# make a local grid from which we will compute the mask
# we make it coarse so that we see the grid points
grid = salem.Grid(proj=salem.wgs84, x0y0=(-18, 3), nxny=(25, 15), dxdy=(1, 1))

# read the ocean shapefile (data from http://www.naturalearthdata.com)
oceans = salem.read_shapefile(salem.get_demo_file('ne_50m_ocean.shp'),
                              cached=True)

# 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)
Beispiel #3
0
the topography from the SRTM v4.1 dataset (resolution 3 minutes of arc,
so ~ 90m). For this we use the :py:meth:`DataArrayAccessor.lookup_transform`
method.

From the plot below, we see that the model topography is smoother than the
aggregated SRTM (this is a good thing, as atmospheric models do not like
steep gradients too much). The highest peaks or lowest valley aren't resolved
by the 1km topography.
"""

import numpy as np
from salem import get_demo_file, open_xr_dataset
import matplotlib.pyplot as plt

# get the topography data
srtm = open_xr_dataset(get_demo_file('riosan_srtm_hgt.nc')).srtm
wrf = open_xr_dataset(get_demo_file('riosan_wrf_hgt.nc')).HGT

# transform the high-res topography onto the coarse grid
# we ask for the lookup table to speed up the second transform
srtm_on_wrf, lut = wrf.salem.lookup_transform(srtm, return_lut=True)
srtm_on_wrf_std = wrf.salem.lookup_transform(srtm, method=np.std)

# for fun we compute the max and min for each grid point
srtm_on_wrf_min = wrf.salem.lookup_transform(srtm, method=np.min, lut=lut)
srtm_on_wrf_max = wrf.salem.lookup_transform(srtm, method=np.max, lut=lut)
# then compute the max absolute difference to wrf
absdif = np.abs(np.dstack([srtm_on_wrf_min - wrf, srtm_on_wrf_max - wrf]))
maxabsdif = np.max(absdif, axis=2)

# Get the map defined by the WRF grid
Beispiel #4
0
# -*- coding: utf-8 -*-
"""
====================
Customize Salem maps
====================

How to change the look of a Map?

"""

import salem
import matplotlib.pyplot as plt

# get the map from a WRF file
ds = salem.open_wrf_dataset(salem.get_demo_file('wrfout_d01.nc'))
smap = ds.salem.get_map(countries=False)

# Change the country borders
smap.set_shapefile(countries=True, color='C3', linewidths=2)

# Add oceans and lakes
smap.set_shapefile(oceans=True)
smap.set_shapefile(rivers=True)
smap.set_shapefile(lakes=True, facecolor='blue', edgecolor='blue')

# Change the lon-lat countour setting
smap.set_lonlat_contours(add_ytick_labels=False,
                         interval=5,
                         linewidths=1.5,
                         linestyles='-',
                         colors='C1')
Beispiel #5
0
and proposes an alternative based on cartopy.

The only problem at the pole is the plotting of the longitude contours. 
There is probably no easy way so solve this problem in salem,
hence the suggestion to use cartopy in this case. Note that if the pole isn't
in the domain, salem works just fine.
"""

from salem import open_xr_dataset, get_demo_file
import matplotlib.pyplot as plt

# prepare the figure
f = plt.figure(figsize=(8, 7))

# WRF polar file(s)
d1 = open_xr_dataset(get_demo_file('geo_em_d01_polarstereo.nc'))
d2 = open_xr_dataset(get_demo_file('geo_em_d02_polarstereo.nc'))

# Plot with salem
ax = plt.subplot(2, 2, 1)
d1.HGT_M.salem.quick_map(ax=ax, cmap='Oranges')
ax = plt.subplot(2, 2, 3)
d2.HGT_M.salem.quick_map(ax=ax, cmap='Oranges')

# Now with cartopy
proj = d1.salem.cartopy()
ax = plt.subplot(2, 2, 2, projection=proj)
ax.coastlines()
ax.gridlines()
d1.HGT_M.plot(ax=ax, transform=proj, cmap='Oranges')
ax.set_extent(d1.salem.grid.extent, crs=proj)
Beispiel #6
0
2003, and the map background is from 2016. This illustrates the retreat of
the Kesselwandferner glacier.

"""

import numpy as np
import pandas as pd
import salem
from salem import get_demo_file, DataLevels, GoogleVisibleMap, Map
import matplotlib.pyplot as plt

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

# read the shapefile and use its extent to define a ideally sized map
shp = salem.read_shapefile(get_demo_file('rgi_kesselwand.shp'))
# I you need to do a lot of maps you might want
# to use an API key and set it here with key='YOUR_API_KEY'
g = GoogleVisibleMap(x=[shp.min_x, shp.max_x], y=[shp.min_y, shp.max_y],
                     maptype='satellite')  # try out also: 'terrain'

# the google static image is a standard rgb image
ggl_img = g.get_vardata()
ax1.imshow(ggl_img)
ax1.set_title('Google static map')

# make a map of the same size as the image (no country borders)
sm = Map(g.grid, factor=1, countries=False)
sm.set_shapefile(shp)  # add the glacier outlines
sm.set_rgb(ggl_img)  # add the background rgb image
sm.visualize(ax=ax2)  # plot it
Beispiel #7
0
# -*- coding: utf-8 -*-
"""
=============
Plot overlays
=============

Add contours and wind arrows to a salem plot

"""

import salem
import numpy as np
import matplotlib.pyplot as plt

# get the data at the latest time step
ds = salem.open_wrf_dataset(salem.get_demo_file('wrfout_d01.nc')).isel(time=-1)

# get the wind data at 10000 m a.s.l.
u = ds.salem.wrf_zlevel('U', 10000.)
v = ds.salem.wrf_zlevel('V', 10000.)
ws = ds.salem.wrf_zlevel('WS', 10000.)

# get the axes ready
f, ax = plt.subplots()

# plot the salem map background, make countries in grey
smap = ds.salem.get_map(countries=False)
smap.set_shapefile(countries=True, color='grey')
smap.plot(ax=ax)

# transform the coordinates to the map reference system and contour the data
Beispiel #8
0
Plotting shapefiles
===================

Put some colors and labels on shapefiles

In this script, we use data from the `HydroSHEDS <http://www.hydrosheds.org/>`_
database to illustrate some functionalities of salem Maps. The data shows the
sub-basins of the Nam Co Lake catchment in Tibet. We navigate between the
various tributary catchments of the lake.
"""

import salem
import matplotlib.pyplot as plt

# read the shapefile
shpf = salem.get_demo_file('Lev_09_MAIN_BAS_4099000881.shp')
gdf = salem.read_shapefile(shpf)

# Get the google map which encompasses all geometries
g = salem.GoogleVisibleMap(x=[gdf.min_x.min(), gdf.max_x.max()],
                           y=[gdf.min_y.min(), gdf.max_y.max()],
                           maptype='satellite', 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
Beispiel #9
0
2003, and the map background is from 2016. This illustrates the retreat of
the Kesselwandferner glacier.

"""

import numpy as np
import pandas as pd
import salem
from salem import get_demo_file, DataLevels, GoogleVisibleMap, Map
import matplotlib.pyplot as plt

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

# read the shapefile and use its extent to define a ideally sized map
shp = salem.read_shapefile(get_demo_file('rgi_kesselwand.shp'))
# I you need to do a lot of maps you might want
# to use an API key and set it here with key='YOUR_API_KEY'
g = GoogleVisibleMap(x=[shp.min_x, shp.max_x],
                     y=[shp.min_y, shp.max_y],
                     maptype='satellite')  # try out also: 'terrain'

# the google static image is a standard rgb image
ggl_img = g.get_vardata()
ax1.imshow(ggl_img)
ax1.set_title('Google static map')

# make a map of the same size as the image (no country borders)
sm = Map(g.grid, factor=1, countries=False)
sm.set_shapefile(shp)  # add the glacier outlines
sm.set_rgb(ggl_img)  # add the background rgb image
Beispiel #10
0
ds.name = '100k'
ds2.name = '30k'

ds = ds.sel(lon=slice(-17.5,20), lat=slice(4.5,20))  # lake chad lon=slice(10,20), lat=slice(10,15)
ds2 = ds2.sel(lon=slice(-17.5,20), lat=slice(4.5,20))   # volta lon=slice(-10,8), lat=slice(4,10)
top = top.sel(lon=slice(-17.5,20), lat=slice(4.5,20))


# ds[ds == 0]=np.nan
# ds2[ds2 == 0] =np.nan

map = ds.salem.get_map(cmap='Greys')
map.set_shapefile(rivers=True)
# read the ocean shapefile (data from http://www.naturalearthdata.com)
oceans = salem.read_shapefile(salem.get_demo_file('ne_50m_ocean.shp'),
                              cached=True)

lakes = salem.read_shapefile(salem.get_demo_file('ne_50m_lakes.shp'), cached=True)
map.set_shapefile(lakes, edgecolor='k', facecolor='none', linewidth=2,)

grid = ds.salem.grid


#f,((ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8)) = plt.subplots(4,2,figsize = (18,15))

f,((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2,figsize = (11,6))



map.set_plot_params(levels=[-32,-16, -8,-4,4,8,16,32], cmap='RdBu')  #levels=[-0.6,-0.3, -0.15, 0.15, 0.3,0.6] levels=[-24,-16, -8,-4,4,8,16,20]
Beispiel #11
0
from pathlib import Path
from salem import get_demo_file, DataLevels, GoogleVisibleMap, Map
import matplotlib.pyplot as plt

data_dir = Path("/Volumes/Lees_Extend/data/ecmwf_sowc/")
path = data_dir / "chirps_kenya.nc"

ds = xr.open_dataset(path, decode_times=False)
times = pd.date_range("1900-01-01", "2019-12-31", freq="M")
ds["time"] = times
da = ds.precip
# sds = salem.open_xr_dataset(path, **dict(decode_times=False))

fig, ax = plt.subplots()
map_ = da.mean(dim="time").salem.quick_map(ax=ax)
map_

# conda install -c motionless
# prepare the figure
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# read the shapefile and use its extent to define a ideally sized map
shp = salem.read_shapefile(get_demo_file("rgi_kesselwand.shp"))

g = GoogleVisibleMap(
    x=[shp.min_x, shp.max_x],
    y=[shp.min_y, shp.max_y],
    scale=2,  # scale is for more details
    maptype="satellite",
)  # try out also: 'terrain'
Beispiel #12
0
"""

from salem import mercator_grid, Map, get_demo_file
import matplotlib.pyplot as plt

# prepare the figure
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 7))

# map extent
grid = mercator_grid(center_ll=(10.76, 46.79), extent=(18000, 14000))
sm = Map(grid, countries=False)
sm.set_lonlat_contours(interval=0)
sm.set_scale_bar()

# add topography
fpath = get_demo_file('hef_srtm.tif')
sm.set_topography(fpath)
sm.visualize(ax=ax1, addcbar=False, title='relief_factor=0.7 (default)')

# stronger shading
sm.set_topography(fpath, relief_factor=1.4)
sm.visualize(ax=ax2, addcbar=False, title='relief_factor=1.4')

# add color shading
z = sm.set_topography(fpath)
sm.set_data(z)
sm.set_cmap('topo')
sm.visualize(ax=ax3, title='Color with shading', addcbar=False)

# color without topo shading
sm.set_topography()
Beispiel #13
0
import pdb
import numpy as np
from functools import partial
from salem import get_demo_file, open_xr_dataset, GeoTiff, wgs84



dat = xr.open_dataarray('/users/global/cornkle/data/pythonWorkspace/proj_CEH/topo/gtopo_1min.nc')
#dat=dat.sel(lon=slice(-18,120), lat=slice(-30,60))

#dat=dat.sel(lon=slice(-100,-40), lat=slice(-30,60))

grid = dat.salem.grid

grid50 = grid.regrid(factor=0.03)
lakes = salem.read_shapefile(salem.get_demo_file('ne_50m_rivers_lake_centerlines.shp'), cached=True)


top_on_grid50 = grid50.lookup_transform(dat, method=np.std)

sm = dat.salem.get_map(cmap='topo')
lakes = salem.read_shapefile(salem.get_demo_file('ne_50m_rivers_lake_centerlines.shp'), cached=True)
sm.set_shapefile(lakes, edgecolor='k', facecolor='none', linewidth=2,)
mask_lakes = grid.region_of_interest(shape=lakes)
sm.set_data(top_on_grid50, grid50)
sm.set_plot_params(vmin=20, vmax=500)
#sm.set_data(dat, grid)
sm.visualize()

f = plt.figure()
Beispiel #14
0
"""

from salem import mercator_grid, Map, get_demo_file
import matplotlib.pyplot as plt

# prepare the figure
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 7))

# map extent
grid = mercator_grid(center_ll=(10.76, 46.79), extent=(18000, 14000))
sm = Map(grid, countries=False)
sm.set_lonlat_contours(interval=0)

# add topography
fpath = get_demo_file('hef_srtm.tif')
sm.set_topography(fpath)
sm.visualize(ax=ax1, addcbar=False, title='relief_factor=0.7 (default)')

# stronger shading
sm.set_topography(fpath, relief_factor=1.4)
sm.visualize(ax=ax2, addcbar=False, title='relief_factor=1.4')

# add color shading
z = sm.set_topography(fpath)
sm.set_data(z)
sm.set_cmap('topo')
sm.visualize(ax=ax3, title='Color with shading', addcbar=False)

# color without topo shading
sm.set_topography()
Beispiel #15
0
Plotting shapefiles
===================

Put some colors and labels on shapefiles

In this script, we use data from the `HydroSHEDS <http://www.hydrosheds.org/>`_
database to illustrate some functionalities of salem Maps. The data shows the
sub-basins of the Nam Co Lake catchment in Tibet. We navigate between the
various tributary catchments of the lake.
"""

import salem
import matplotlib.pyplot as plt

# read the shapefile
shpf = salem.get_demo_file('Lev_09_MAIN_BAS_4099000881.shp')
gdf = salem.read_shapefile(shpf)

# Get the google map which encompasses all geometries
g = salem.GoogleVisibleMap(x=[gdf.min_x.min(),
                              gdf.max_x.max()],
                           y=[gdf.min_y.min(),
                              gdf.max_y.max()],
                           maptype='satellite',
                           scale=2,
                           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 = []