{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "525f4c15-e090-4c0d-aba0-212138ea6a1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import xarray as xr\n",
    "import xsar\n",
    "import numpy as np\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a212dee-5133-4093-9d95-0e434743edb5",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Raster masks from vector masks\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ba9240f-0662-4a8d-9360-caab5d03a1c3",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Sentinel 1 example"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1ab1e9d-1d51-410f-b7ee-44c8a5d8302d",
   "metadata": {
    "tags": []
   },
   "source": [
    "[xsar.Sentinel1Dataset.dataset](../basic_api.rst#xsar.Sentinel1Dataset.dataset) has a `land_mask` variable by default, rasterized from [cartopy.feature.NaturalEarthFeature('physical', 'land', '10m')](https://scitools.org.uk/cartopy/docs/latest/matplotlib/feature_interface.html#cartopy.feature.NaturalEarthFeature)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30ee86ce-89ac-4dc5-acef-3340dbb83f69",
   "metadata": {},
   "source": [
    "### Mask sigma0 over land\n",
    "\n",
    "Replacing `sigma0` values with `nan` over ocean can be done with `xarray.where`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efcf8a7b-ce6c-4b0a-b1c6-295e82e60d9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "ds = xsar.open_dataset(xsar.get_test_file('S1B_IW_GRDH_1SDV_20181013T062322_20181013T062347_013130_018428_Z010.SAFE'), resolution='1000m')\n",
    "\n",
    "# apply land_mask. The final transpose is done to preserve dimensions ordering\n",
    "ds['sigma0_land'] = xr.where(ds['land_mask'], ds['sigma0'], np.nan).transpose(*ds['sigma0'].dims)\n",
    "ds['sigma0_land']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6e5b081-8af9-4c8c-859e-e1fabac5ac9d",
   "metadata": {},
   "source": [
    "### Adding masks\n",
    "\n",
    "Masks can be added with [xsar.BaseMeta.set_mask_feature](../basic_api.rst#xsar.BaseMeta.set_mask_feature), providing a shapefile or a [cartopy.feature.Feature](https://scitools.org.uk/cartopy/docs/latest/matplotlib/feature_interface.html) object.\n",
    "\n",
    "For a default mask for all SAFE, use classmethod `xsar.BaseMeta.set_mask_feature` \n",
    "\n",
    "Here, we add a `ocean_mask` dataset variable:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "463bf8db-9074-4e8a-a084-5994db6035f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "xsar.Sentinel1Meta.set_mask_feature('ocean', os.path.join(xsar.get_test_file('water-polygons-split-4326'), 'water_polygons.shp'))\n",
    "\n",
    "\n",
    "s1meta = xsar.Sentinel1Meta(xsar.get_test_file('S1B_IW_GRDH_1SDV_20181013T062322_20181013T062347_013130_018428_Z010.SAFE'))\n",
    "ds = xsar.open_dataset(s1meta, resolution='200m')\n",
    "ds['sigma0_ocean'] = xr.where(ds['ocean_mask'], ds['sigma0'], np.nan).transpose(*ds['sigma0'].dims)\n",
    "ds[['sigma0_ocean','ocean_mask']]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb1a5ad1-2134-497a-977d-2ce08b830ea0",
   "metadata": {},
   "source": [
    "Masks are available as a shapely object (lon/lat coordinates), with [xsar.BaseMeta.get_mask](../basic_api.rst#xsar.BaseMeta.get_mask):"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8b08ff3-4019-49db-aed7-7ec62a02374f",
   "metadata": {},
   "source": [
    "When using this `s1meta` object with  [xsar.Sentinel1Meta.footprint](../basic_api.rst#xsar.Sentinel1Meta.footprint), mask are rasterized over the dataset, and variables postfixed with `_mask` are created."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a0aa1d4-48dc-4423-901d-12b6e64df964",
   "metadata": {},
   "source": [
    "### Convert a mask to dataset coordinates\n",
    "\n",
    "[xsar.BaseMeta.ll2coords](../basic_api.rst#xsar.BaseMeta.ll2coords) allow converting lon/lat coordinates on shapely objects.\n",
    "\n",
    "So it's possible to plot the vector mask on a raster variable:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0fdca85-ab43-4433-b345-951680857a36",
   "metadata": {},
   "outputs": [],
   "source": [
    "import holoviews as hv\n",
    "import geoviews.feature as gf\n",
    "hv.extension('bokeh')\n",
    "from holoviews.operation.datashader import datashade,rasterize\n",
    "\n",
    "\n",
    "# get the shapely polygon of the mask (on the footprint, lon/lat)\n",
    "land_poly = s1meta.get_mask('ocean')\n",
    "\n",
    "# convert lon/lat to line/sample\n",
    "land_poly_coords = s1meta.ll2coords(s1meta.get_mask('ocean'))\n",
    "\n",
    "# plot masked sigma0, with coastline\n",
    "\n",
    "(\n",
    "    hv.Image(ds['sigma0_ocean'].sel(pol='VV')).opts(cmap='gray',clim=(0,0.2), colorbar=True,tools=['hover'],title=\"xsar\") \\\n",
    "    * hv.Path(land_poly_coords).opts(color='lightgreen',width=800,height=800) \n",
    ").opts(invert_axes=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a0d0be9-77c0-457c-901d-eb6262830da8",
   "metadata": {
    "tags": []
   },
   "source": [
    "## RadarSat 2 example"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b0cab95-dd6a-4210-98b7-3c303ba4f84f",
   "metadata": {
    "tags": []
   },
   "source": [
    "[xsar.RadarSat2Dataset.dataset](../basic_api.rst#xsar.RadarSat2Dataset.dataset) has a `land_mask` variable by default, rasterized from [cartopy.feature.NaturalEarthFeature('physical', 'land', '10m')](https://scitools.org.uk/cartopy/docs/latest/matplotlib/feature_interface.html#cartopy.feature.NaturalEarthFeature)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce15d4aa-8188-4cb5-8f74-075cc6069807",
   "metadata": {},
   "source": [
    "### Mask sigma0 over land\n",
    "\n",
    "Replacing `sigma0` values with `nan` over ocean can be done with `xarray.where`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "785b8ae7-b2b4-42e3-8a8f-391f505c0094",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "ds = xsar.open_dataset(xsar.get_test_file('RS2_OK135107_PK1187782_DK1151894_SCWA_20220407_182127_VV_VH_SGF'), resolution='1000m')\n",
    "\n",
    "# apply land_mask. The final transpose is done to preserve dimensions ordering\n",
    "ds['sigma0_land'] = xr.where(ds['land_mask'], ds['sigma0'], np.nan).transpose(*ds['sigma0'].dims)\n",
    "ds['sigma0_land']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ac20f5f-a148-4f65-9068-a38c787d52f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds['sigma0_land'].sel(pol='VH').plot(vmin=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cf12c23-ddb1-4040-ac11-2c8209de7ded",
   "metadata": {
    "tags": []
   },
   "source": [
    "## RCM example"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5967453d-ad6f-480b-8d6a-6d89484088ff",
   "metadata": {
    "tags": []
   },
   "source": [
    "[xsar.RcmDataset.dataset](../basic_api.rst#xsar.RcmDataset.dataset) has a `land_mask` variable by default, rasterized from [cartopy.feature.NaturalEarthFeature('physical', 'land', '10m')](https://scitools.org.uk/cartopy/docs/latest/matplotlib/feature_interface.html#cartopy.feature.NaturalEarthFeature)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "679635f2-186d-47da-b3d2-e762d5ad82a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f6eb695-4e2b-4b84-9953-822029979929",
   "metadata": {},
   "source": [
    "### Mask sigma0 over land\n",
    "\n",
    "Replacing `sigma0` values with `nan` over ocean can be done with `xarray.where`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c9934b5-4752-4076-b03c-d575c46f5994",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "ds = xsar.open_dataset(xsar.get_test_file('RCM1_OK1050603_PK1050605_1_SC50MB_20200214_115905_HH_HV_Z010'), resolution='1000m')\n",
    "\n",
    "# apply land_mask. The final transpose is done to preserve dimensions ordering\n",
    "ds['sigma0_land'] = xr.where(ds['land_mask'], ds['sigma0'], np.nan).transpose(*ds['sigma0'].dims)\n",
    "ds['sigma0_land']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db2f79fc-7c23-4a52-bc0f-93d05293d853",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds['sigma0_land'].sel(pol='HV').plot(vmin=0)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env_xsar",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
