Domain presets on real data¶
A preset shines when the data matches its domain. This notebook pairs presets with real fields: a bundled elevation DEM, and NOAA ERSST v5 sea-surface temperature fetched from the internet (its anomaly too). Every plot is the same one-liner - field(data, style="<preset>").
%matplotlib inline
from pathlib import Path
import hashlib, urllib.request, warnings
import numpy as np
from pyramids.netcdf import NetCDF
from pyramids.dataset import Dataset, GeoReference
from digitalearth.static import Map
from digitalearth.static.view import projections as proj
DATA = Path('../../../examples/data') # notebook-relative path (docs/examples/presets -> repo root)
dem = Dataset.read_file(str(DATA / 'LisbonElevation.tif'))
# Real climate data, fetched from the internet: NOAA ERSST v5 monthly sea-surface temperature
# (2-degree global grid), via the pydata/xarray-data mirror on GitHub. It is committed under
# examples/data/global/ so this runs offline; the download below is only a fallback.
CACHE = Path('../../../examples/data/global'); CACHE.mkdir(parents=True, exist_ok=True)
SST_NC = CACHE / 'ersstv5.nc'
if not SST_NC.exists():
# Pinned to the commit that added the file (it has not changed since), not to master: a mutable
# branch ref in another organisation's repo would let this cell fetch different bytes over time.
SHA = '4c87bb96c6d011ff44a43f401110c229b80bc863'
DIGEST = '2ae53611d00069440641ad8ec36b216c9f543462161ae86589723c9d19ff90c6'
url = f'https://github.com/pydata/xarray-data/raw/{SHA}/ersstv5.nc'
print('downloading ERSST v5 ...')
blob = urllib.request.urlopen(
urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}), timeout=180).read()
if hashlib.sha256(blob).hexdigest() != DIGEST:
raise RuntimeError(f'ERSST download from {url} has sha256 {hashlib.sha256(blob).hexdigest()}, expected {DIGEST}')
SST_NC.write_bytes(blob)
nc = NetCDF.read_file(str(SST_NC)).get_variable('sst')
def to_dataset(arr2d):
"""A 2-D SST array -> a display-ready Dataset, shifting the 0-360 grid to -180..180."""
rolled = np.roll(np.where(arr2d < -1e30, np.nan, arr2d), arr2d.shape[1] // 2, axis=1)
return Dataset.from_array(
arr=rolled.astype('float32'),
geo_ref=GeoReference(geo=(-181.0, 2.0, 0, 89.0, 0, -2.0), epsg=4326),
)
def sst_month(band):
"""One month of SST as a -180..180 pyramids Dataset (land fill -> NaN)."""
return to_dataset(nc.read_array(band=band).astype('float32'))
Elevation - a terrain preset on a real DEM¶
m = Map(crs=dem.epsg, figsize=(9, 7))
m.field(dem, style='elevation')
m.colorbar(label='elevation (m)'); m.set_title("style='elevation'"); m.fig;
Sea-surface temperature - a real ocean field¶
The most recent month of ERSST v5, styled with the sea_surface_temperature preset.
sst = sst_month(nc.band_count - 1)
m = Map(crs=proj.robinson(), figsize=(11, 6))
m.field(sst, style='sea_surface_temperature')
m.colorbar(label='SST (\u00b0C)'); m.set_title("style='sea_surface_temperature'"); m.fig;
Anomaly - a diverging preset on the real record¶
The most recent month minus the 52-year mean, drawn with the diverging anomaly preset centred on zero.
cube = nc.read_array().astype('float32'); cube = np.where(cube < -1e30, np.nan, cube)
with warnings.catch_warnings():
warnings.simplefilter('ignore', RuntimeWarning)
anom = cube[-1] - np.nanmean(cube, axis=0)
m = Map(crs=proj.robinson(), figsize=(11, 6))
m.field(to_dataset(anom), style='anomaly')
m.colorbar(label='SST anomaly (\u00b0C)'); m.set_title("style='anomaly'"); m.fig;
Precipitation - an illustrative field¶
A quick synthetic wet field (no bundled global precipitation raster) shows the sequential precipitation preset; on real gridded precipitation the call is identical.
lat = np.linspace(60, -60, 90)[:, None]; lon = np.linspace(-180, 180, 180)[None, :]
precip = np.clip(220 * np.cos(np.deg2rad(lat))**2 + 40 * np.sin(np.deg2rad(lon))**2, 0, None).astype('float32')
pd_ = Dataset.from_array(arr=precip, geo_ref=GeoReference(geo=(-180.0, 2.0, 0.0, 60.0, 0.0, -120/90), epsg=4326))
m = Map(crs=4326, figsize=(10, 5))
m.field(pd_, style='precipitation')
m.colorbar(label='precipitation (mm)'); m.set_title("style='precipitation'"); m.fig;
The preset only changes the styling - the same field renders identically through field, contours or pcolormesh, and the choice of preset is always a single keyword. See 05_globe_and_projections for the same real data on the globe and across map projections.