There are multiple ways to interactivcely visualise COG files and their pyramids, a lot of which rely on some sort of http connection or local file server running. There are generally more ways to visaulisae data, so long as you are happy viewing it in web mercator.
No data transformation are required as building the pyramids and overviews is part of the cog specification.
We present three ways:
Using local tile server, which is a lightweight tile server that shows data locally
HV Plot to interactively plot. HV plot is popular and part of the pangeo package and good for small and high resoulition datasets
Open Layers. Open layers is a Javascript library to generate dynamic maps and works in multple projections and from many data sources cog, parquet, geozarr , etc.
Generate the cog data from the OceanSoda Sample¶
import xarray as xr
zarr_href1 = 'https://s3.waw4-1.cloudferro.com/EarthCODE/OSCAssets/ocean-soda/dfco2.zarr'
ds = xr.open_zarr(zarr_href1)
da = ds.dfco2.sel(time='2020-06-06', method='nearest').sel(lon=slice(-6.062, 36.06), lat=slice(30.27, 45.98))
daimport rioxarray
da = da.rio.set_spatial_dims(
x_dim="lon",
y_dim="lat",
)
da = da.rio.write_crs("EPSG:4326")
da.rio.to_raster(
"fco2_difference_2020-06-04.tif",
driver="COG",
compress="DEFLATE",
)
Tile server quick view¶
# you need to run conda install -c conda-forge localtileserver ipyleaflet
# or pixi add localtileserver ipyleaflet
from localtileserver import TileClient, get_leaflet_tile_layer
from ipyleaflet import Map, basemaps, LayersControl
# plot the local or the remote cog
client = TileClient('fco2_difference_2020-06-04.tif')
layer = get_leaflet_tile_layer(
client,
indexes=1,
palette="inferno",
opacity=0.75,
)
m = Map(
center=(-80, 0),
zoom=2,
)
m.add_layer(layer)
m.add_control(LayersControl())
mHV plot - raw data plotting¶
import numpy as np
import rasterio
import rioxarray
import cartopy.crs as ccrs
import hvplot.xarray # registers .hvplot on xarray objects
import geoviews as gv
import geoviews.feature as gf
gv.extension("bokeh")
# ---------------------------------------------------------------------
# User inputs
# ---------------------------------------------------------------------
cog_path = "fco2_difference_2020-06-04.tif"
# For this small raster (63 x 168), full resolution is probably preferable.
# Set to None to use full resolution, or an integer to request an overview.
overview_level = None
# Data CRS / map projection
projection = ccrs.PlateCarree()
# ---------------------------------------------------------------------
# Inspect COG
# ---------------------------------------------------------------------
with rasterio.open(cog_path) as src:
overviews = src.overviews(1)
print(f"CRS: {src.crs}")
print(f"Bounds: {src.bounds}")
print(f"Native shape: {src.height} x {src.width}")
print(f"Overview factors: {overviews}")
# ---------------------------------------------------------------------
# Open raster
# ---------------------------------------------------------------------
open_kwargs = {
"masked": True,
"chunks": {"x": 1024, "y": 1024},
}
if overview_level is not None and overviews:
if overview_level >= len(overviews):
raise ValueError(
f"overview_level={overview_level} requested, "
f"but only {len(overviews)} overview levels exist."
)
open_kwargs["overview_level"] = overview_level
da = (
rioxarray.open_rasterio(
cog_path,
**open_kwargs,
)
.squeeze("band", drop=True)
)
da.name = "Air-sea fCO₂ difference"
print(f"Displayed shape: {da.sizes['y']} x {da.sizes['x']}")
# ---------------------------------------------------------------------
# Get geographic extent directly from the raster
# ---------------------------------------------------------------------
left, bottom, right, top = da.rio.bounds()
# Add a small amount of padding around the raster
xpad = (right - left) * 0.03
ypad = (top - bottom) * 0.03
map_xlim = (left - xpad, right + xpad)
map_ylim = (bottom - ypad, top + ypad)
# ---------------------------------------------------------------------
# Colour limits
# ---------------------------------------------------------------------
clim = (-100, 100)
# ---------------------------------------------------------------------
# Raster layer
# ---------------------------------------------------------------------
raster = da.hvplot.quadmesh(
x="x",
y="y",
# The COG coordinates are longitude/latitude
crs=ccrs.PlateCarree(),
# Display in the same geographic projection
projection=projection,
rasterize=True,
# Matches the variable metadata
cmap="RdBu_r",
clim=clim,
colorbar=True,
clabel="ΔfCO₂ (µatm)",
width=950,
height=550,
xlim=map_xlim,
ylim=map_ylim,
title="Surface ocean–atmosphere fCO₂ difference — 2020-06-04",
tools=["hover"],
)
# ---------------------------------------------------------------------
# Geographic context
# ---------------------------------------------------------------------
ocean = gf.ocean.opts(
scale="50m",
projection=projection,
)
land = gf.land.opts(
scale="50m",
projection=projection,
alpha=0.6,
)
coast = gf.coastline.opts(
scale="50m",
projection=projection,
line_width=1,
)
# Optional national borders
borders = gf.borders.opts(
scale="50m",
projection=projection,
line_width=0.6,
alpha=0.6,
)
# ---------------------------------------------------------------------
# Display interactive map
# ---------------------------------------------------------------------
plot = (
ocean
* land
* raster
* coast
* borders
).opts(
active_tools=["wheel_zoom"],
toolbar="above",
)
plotCRS: EPSG:4326
Bounds: BoundingBox(left=-6.0, bottom=46.0, right=36.0, top=30.25)
Native shape: 63 x 168
Overview factors: []
Displayed shape: 63 x 168
/home/krasen/hackathon_websites/ocean_hackathon/.pixi/envs/default/lib/python3.13/site-packages/cartopy/io/__init__.py:242: DownloadWarning: Downloading: https://naturalearth.s3.amazonaws.com/110m_cultural/ne_110m_admin_0_boundary_lines_land.zip
warnings.warn(f'Downloading: {url}', DownloadWarning)
OpenLayers COG viewer¶
For open layers you need to a remote file or to create an http server that allows cross origin requests using python for example, that will server the files. The javascript code should use the new open layers functionality, the correct crs and basemap.
const cogSource = new ol.source.GeoTIFF({
normalize: false,
interpolate: true,
sources: [
{
url: COG_URL,
nodata: NODATA
}
]
});
const band = ["band", 1];
const validData = [
"all",
["==", band, band], // filters NaN
[">", band, NODATA_THRESHOLD]
];
const cogLayer = new ol.layer.WebGLTile({
title: "Air-sea fCO₂ difference",
source: cogSource,
opacity: OPACITY,
style: {
color: [
"case",
validData,
[
"interpolate",
["linear"],
band,
// RdBu_r-style diverging colour scale
-100, ["color", 5, 48, 97, 0.90],
-75, ["color", 33, 102, 172, 0.90],
-50, ["color", 67, 147, 195, 0.90],
-25, ["color", 146, 197, 222, 0.90],
0, ["color", 247, 247, 247, 0.90],
25, ["color", 244, 165, 130, 0.90],
50, ["color", 214, 96, 77, 0.90],
75, ["color", 178, 24, 43, 0.90],
100, ["color", 103, 0, 31, 0.90]
],
// Transparent outside valid data
["color", 0, 0, 0, 0]
]
}
});
const projection = "EPSG:3857";
const dataExtent = ol.proj.transformExtent(
[-6, 30, 36, 46],
"EPSG:4326",
projection
);
const map = new ol.Map({
target: "map",
layers: [
basemap,
cogLayer
],
view: new ol.View({
projection,
// Center around the middle of the raster
center: ol.proj.fromLonLat([15, 38]),
zoom: 4,
minZoom: 2,
maxZoom: 12,
// Optional: constrain navigation to roughly the data region
extent: dataExtent
}),
controls: ol.control.defaults.defaults().extend([
new ol.control.ScaleLine()
])
});