{
"cells": [
{
"cell_type": "markdown",
"id": "a846b917",
"metadata": {},
"source": [
"# specMACS cloudmask\n",
"\n",
"The following script exemplifies the access and usage of specMACS data measured \n",
"during EUREC⁴A.\n",
"\n",
"The specMACS sensor consists of hyperspectral image sensors as well as polarization resolving image sensors.\n",
"The hyperspectral image sensors operate in the visible and near infrared (VNIR) and the short-wave infrared (SWIR) range.\n",
"The dataset investigated in this notebook is a cloud mask dataset based on data from the SWIR sensor.\n",
"More information on the dataset can be found on the [macsServer](https://macsserver.physik.uni-muenchen.de/campaigns/EUREC4A/products/cloudmask/). If you have questions or if you would like to use the data for a publication, please don't hesitate to get in contact with the dataset authors as stated in the dataset attributes `contact` and `author` list.\n",
"\n",
"Our plan is to analyze a section of the specMACS cloud mask dataset around the first `GOOD` dropsonde on the second HALO circle on the 5th of February (`HALO-0205_c2`). We'll first look at the cloudiness just along the flight track and later on create a map projection of the dataset. This notebook will guide you through the required steps."
]
},
{
"cell_type": "markdown",
"id": "d5efb2ff",
"metadata": {},
"source": [
"## Obtaining data\n",
"In order to work with EUREC⁴A datasets, we'll use the `eurec4a` library to access the datasets and also use `numpy` and `xarray` as our common tools to handle datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d7532682",
"metadata": {},
"outputs": [],
"source": [
"import eurec4a\n",
"import numpy as np\n",
"import xarray as xr"
]
},
{
"cell_type": "markdown",
"id": "f1b67d04",
"metadata": {},
"source": [
"### Finding the right sonde\n",
"All HALO flights were split up into flight phases or segments to allow for a precise selection in time and space of a circle or calibration pattern. For more information have a look at the respective [github repository](https://github.com/eurec4a/halo-flight-phase-separation)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "93b49702",
"metadata": {},
"outputs": [],
"source": [
"all_flight_segments = eurec4a.get_flight_segments()"
]
},
{
"cell_type": "markdown",
"id": "8289758d",
"metadata": {},
"source": [
"The flight segmentation data is organized by platform and flight, but as we want to look up a segment by its `segment_id`, we'll have to flatten the data and reorganize it by the `segment_id`. Additionally, we want to be able to extract the `flight_id` and `platform_id` back from a selected segment, so we add this information to each individual segment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "925971a8",
"metadata": {},
"outputs": [],
"source": [
"segments_by_segment_id = {\n",
" s[\"segment_id\"]: {\n",
" **s,\n",
" \"platform_id\": platform_id,\n",
" \"flight_id\": flight_id\n",
" }\n",
" for platform_id, flights in all_flight_segments.items()\n",
" for flight_id, flight in flights.items()\n",
" for s in flight[\"segments\"]\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "304faf81",
"metadata": {},
"source": [
"We want to extract the id of the first dropsonde of the second HALO circle on February 5 (`HALO-0205_c2`). By the way: In the {doc}`velox` example the measurement of this time is shown as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ec91e7bb",
"metadata": {},
"outputs": [],
"source": [
"segment = segments_by_segment_id[\"HALO-0205_c2\"]\n",
"first_dropsonde = segment[\"dropsondes\"][\"GOOD\"][0]\n",
"first_dropsonde"
]
},
{
"cell_type": "markdown",
"id": "9782255c",
"metadata": {},
"source": [
"Now we would like to know when this sonde was launched. The [JOANNE dataset](https://github.com/Geet-George/JOANNE#joanne---the-eurec4a-dropsonde-dataset) contains this information. We use level 3 data which contains quality checked data on a common grid and load it using the intake catalog. We then select the correct dropsonde by its `sonde_id` to find out the launch time of the dropsonde.\n",
"\n",
"More information on the data catalog can be found [here](https://github.com/eurec4a/eurec4a-intake#eurec4a-intake-catalogue)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c9a94c07",
"metadata": {},
"outputs": [],
"source": [
"cat = eurec4a.get_intake_catalog(use_ipfs=\"QmahMN2wgPauHYkkiTGoG2TpPBmj3p5FoYJAq9uE9iXT9N\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "af542bae",
"metadata": {},
"outputs": [],
"source": [
"dropsondes = cat.dropsondes.JOANNE.level3.to_dask()\n",
"sonde_dt = dropsondes.sel(sonde_id=first_dropsonde).launch_time.values\n",
"str(sonde_dt)"
]
},
{
"cell_type": "markdown",
"id": "895788f7",
"metadata": {},
"source": [
"### Finding the corresponding specMACS dataset\n",
"As specMACS data is organized as one dataset per flight, we have to obtain the `flight_id` from our selected segment to obtain the corresponding dataset. From this dataset, we select a two minute long measurement sequence of specMACS data around the dropsonde launch and have a look at the obtained dataset:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b2c9f5ce",
"metadata": {},
"outputs": [],
"source": [
"offset_time = np.timedelta64(60, \"s\")\n",
"\n",
"ds = cat.HALO.specMACS.cloudmaskSWIR[segment[\"flight_id\"]].to_dask()\n",
"ds_selection = ds.sel(time=slice(sonde_dt-offset_time, sonde_dt+offset_time))\n",
"ds_selection"
]
},
{
"cell_type": "markdown",
"id": "79759d7b",
"metadata": {},
"source": [
"You can get a list of available variables in the dataset from `ds_selection.variables.keys()` or by looking them up in the table above.\n",
"\n",
"## First plots\n",
"After selecting our datasets, we want to see what's inside, so here are some first plots."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e314adbe",
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import pathlib\n",
"import matplotlib.pyplot as plt\n",
"plt.style.use([pathlib.Path(\"./mplstyle/book\"), pathlib.Path(\"./mplstyle/wide\")])"
]
},
{
"cell_type": "markdown",
"id": "5b7af0a2",
"metadata": {},
"source": [
"First, we create a little helper to properly display a colorbar for categorical (in CF-Convention terms \"flag\") variables:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d195c907",
"metadata": {},
"outputs": [],
"source": [
"def flagbar(fig, mappable, variable):\n",
" ticks = variable.flag_values\n",
" labels = variable.flag_meanings.split(\" \")\n",
" cbar = fig.colorbar(mappable, ticks=ticks)\n",
" cbar.ax.set_yticklabels(labels);"
]
},
{
"cell_type": "markdown",
"id": "0eced001",
"metadata": {},
"source": [
"Figure 1: shows the SWIR camera cloud mask product along the flight track (x axis) for all observations in across track directions (y axis).\n",
"\n",
"```{note}\n",
"fetching the data and displaying it might take a few seconds\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef3274f1",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"cmplot = ds_selection.cloud_mask.T.plot(ax=ax,\n",
" cmap=plt.get_cmap('Greys_r', lut=3),\n",
" vmin=-0.5, vmax=2.5,\n",
" add_colorbar=False)\n",
"flagbar(fig, cmplot, ds_selection.cloud_mask)\n",
"start_time_rounded, end_time_rounded = ds_selection.time.isel(time=[0, -1]).values.astype('datetime64[s]')\n",
"ax.set_title(f\"specMACS cloud mask ({start_time_rounded} - {end_time_rounded})\");"
]
},
{
"cell_type": "markdown",
"id": "bc323f58",
"metadata": {},
"source": [
"The dataset also contains the minimal and maximal cloud fractions which are calculated for each temporal measurement. The minimal cloud fraction is derived from the ratio between the number of pixels classified as \"most likely cloudy\" and the total number of pixels in one measurement (times with unknown measurements are excluded). The maximal cloud fraction additionally includes the number of pixels classified as \"probably cloudy\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4f35a63a",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"ds_selection.CF_max.plot(color=\"lightgrey\",label=\"maximal cloud_fraction:\\nmost likely cloudy and probably cloudy\")\n",
"ds_selection.CF_min.plot(color=\"grey\", label=\"minimal cloud fraction:\\nmost_likely_cloudy\")\n",
"ax.axvline(sonde_dt, color=\"C3\", label=\"sonde launch time\")\n",
"ax.set_ylim(0, 1)\n",
"ax.set_ylabel(\"Cloud fraction\")\n",
"ax.set_title(f\"cloud fraction around sonde {first_dropsonde}\")\n",
"ax.legend(bbox_to_anchor=(1,1), loc=\"upper left\");"
]
},
{
"cell_type": "markdown",
"id": "ee8c8692",
"metadata": {},
"source": [
"## Camera view angles to latitude and longitude\n",
"\n",
"The cloud mask is given on a `time` $\\times$ `angle` grid where `angle`s are the internal camera angles. Sometimes it could be helpful to project the data onto a map. This means that we would like to know the corresponding **latitude** and **longitude** coordinates of each pixel of the cloud mask.\n",
"\n",
"```{figure} specmacs_lat_lon.jpg\n",
":alt: schematic drawing\n",
":width: 50%\n",
":align: center\n",
"```\n",
"The computation involves quite a few steps, so let's take a second to lay out a strategy.\n",
"We know already the position of the aircraft and the individual viewing directions of each sensor pixel at each point in time.\n",
"If we would start from the position of the aircraft and continue along each line of sight, until we hit something which we see in our dataset, we should end up at the location we are interested in.\n",
"Due to the curvature of the earth, we'll have to do a few coordinate transformations in the process, but no worries, we'll walk you through.\n",
"\n",
"### What we know\n",
"\n",
"We start out with five variables:\n",
"* position of the airplane: latitude, longitude and height above WGS84 (`ds.lat, ds.lon, ds.alt`)\n",
"* viewing directions of the camera pixels: viewing zenith angle and viewing azimuth angle (`ds.vza, ds.vaa`)\n",
"\n",
"Let's have a look a these variables"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3c0f7615",
"metadata": {
"tags": [
"hide-cell"
]
},
"outputs": [],
"source": [
"def attr_table(variables):\n",
" \"\"\"\n",
" Create a table of variable attributes from a list of variables (xr.DataArrays).\n",
"\n",
" The result is a HTML object, displayable by jupyter notebooks.\n",
" \"\"\"\n",
" from IPython.display import HTML\n",
" key_prio = {\"standard_name\": -2, \"units\": -1, \"description\": 1}\n",
" keys = list(sorted(\n",
" set(k for v in variables for k in v.attrs if not k.startswith(\"_\")),\n",
" key=lambda x: key_prio.get(x, 0)\n",
" ))\n",
" table = \"\"\n",
" table += \"\" + \"\".join(f\"\" for k in keys)\n",
" table += \"\"\n",
" table += \"\"\n",
" for var in variables:\n",
" table += f\"\"\n",
" table += \"\".join(f\"\" for k in keys) + \"\"\n",
" table += \"name | {k} |
---|

{var.name} | {var.attrs.get(k, '-')} |

\"\n",
" return HTML(table)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "001f3ea6",
"metadata": {},
"outputs": [],
"source": [
"attr_table([ds_selection[key] for key in [\"lat\", \"lon\", \"alt\", \"vza\", \"vaa\"]])"
]
},
{
"cell_type": "markdown",
"id": "8b03716f",
"metadata": {},
"source": [
"* The position of the HALO is saved in ellipsoidal coordinates. It is defined by the latitude (`lat`), longitude (`lon`) and height (`alt`) coordinates with respect to the WGS-84 ellipsoid.\n",
"* The viewing zenith (`vza`) and azimuth (`vaa`) angles are given with respect to the local horizon (`lh`) coordinate system at the position of the HALO. This system has its center at the `lat`/`lon`/`alt` position of the HALO and the x/y/z axis point into North, East and down directions.\n",
"\n",
"As the frame of reference rotates with the motion of HALO, a convenient way to work with such kind of data is to transform it into the Earth-Centered, Earth-Fixed (ECEF) coordinate system. The origin of this coordinate system is the center of the Earth. The z-axis passes through true north, the x-axis through the Equator and the prime meridian at 0° longitude. The y-axis is orthogonal to x and z. This cartesian system makes computations of distances and angles very easy.\n",
"\n",
"```{note}\n",
"The use of \"altitude\" and \"height\" can be confusing and is sometimes handled inconsistently. Usually, \"altitude\" describes the vertical distance above the geoid and \"height\" describes the vertical distance above the surface.\n",
"\n",
"In this notebook, we only use the vertical distance above the WGS84 reference ellipsoid. Neither \"altitude\" nor \"height\" as defined above matches this distance exactly, but both are commonly used. We try to use the term \"height\" as it seems to be more commonly used in coordinate computations and fall back to the term `alt` when talking about the variable in HALO datasets. Keep in mind that we actually mean vertical distance above WGS84 in both cases.\n",
"```\n",
"\n",
"### Transformation to ECEF\n",
"\n",
"In a first step we want to transform the position of the HALO into the ECEF coordinate system. We use the method [from ESA navipedia](https://gssc.esa.int/navipedia/index.php/Ellipsoidal_and_Cartesian_Coordinates_Conversion):"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6c8dcb1d",
"metadata": {
"tags": [
"hide-cell"
]
},
"outputs": [],
"source": [
"def ellipsoidal_to_ecef(lat, lon, height):\n",
" '''Transform ellipsoidal coordinates into the ECEF coordinate system according to:\n",
" https://gssc.esa.int/navipedia/index.php/Ellipsoidal_and_Cartesian_Coordinates_Conversion\n",
"\n",
" Parameters:\n",
" lat: latitude of ellipsoid [rad]\n",
" lon: longitude of ellipsoid [rad]\n",
" height: height above ellipsoid [m]\n",
" \n",
" Returns:\n",
" coordinates in ECEF coordinate system.\n",
" '''\n",
" \n",
" WGS_84_dict = {\"axes\": (6378137.0, 6356752.314245)} #m semi-minor and semi-major axis of WGS-84 geoid\n",
" a, b = WGS_84_dict[\"axes\"] #values come from: https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84\n",
" \n",
" e_squared = e2(a, b)\n",
" N = calc_N(a, e_squared, lat)\n",
"\n",
" x = (N + height) * np.cos(lat) * np.cos(lon)\n",
" y = (N + height) * np.cos(lat) * np.sin(lon)\n",
" z = ((1 - e_squared)*N + height) * np.sin(lat)\n",
" return np.stack([x,y,z], axis=-1)\n",
"\n",
"def calc_N(a, e_squared, lat):\n",
" '''Calculate the radius of curvature (N) in the prime vertical.\n",
" \n",
" Parameters:\n",
" e_squared: eccentricity\n",
" lat: latitude [rad]\n",
" \n",
" Returns:\n",
" Radius of curvature in prime vertical.\n",
" \n",
" '''\n",
" return a/np.sqrt(1 - e_squared*(np.sin(lat))**2)\n",
"\n",
"def e2(a, b):\n",
" '''This function calculates the squared eccentricity.\n",
" \n",
" Parameters:\n",
" a: semi-major axis\n",
" b: the semi-minor axis b \n",
" f: flattening factor f=1−ba\n",
" \n",
" Returns:\n",
" Squared eccentricity.\n",
" '''\n",
" f = 1 - (b/a)\n",
" e_squared = 2*f - f**2\n",
" return e_squared\n",
"\n",
"def ellipsoidal_to_ecef_ds(ds: xr.Dataset) -> xr.DataArray:\n",
" '''\n",
" This function applies the conversion from above directly to an xarray dataset.\n",
" '''\n",
" return xr.apply_ufunc(ellipsoidal_to_ecef, np.deg2rad(ds.lat), np.deg2rad(ds.lon), ds.alt,\n",
" output_core_dims=[(\"xyz_ecef\",)],\n",
" dask=\"allowed\")"
]
},
{
"cell_type": "markdown",
"id": "9f544b15",
"metadata": {},
"source": [
"With these functions it is easy to transform the `lat`/`lon`/`alt` position of the HALO into the ECEF-coordinate system."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f4bbdd40",
"metadata": {},
"outputs": [],
"source": [
"HALO_ecef = ellipsoidal_to_ecef_ds(ds_selection)"
]
},
{
"cell_type": "markdown",
"id": "e46f9445",
"metadata": {},
"source": [
"### Computing viewing lines\n",
"\n",
"As a next step we want to set up the vector of the viewing direction. We will need the rotation matrices `Rx`, `Ry` and `Rz` for this.\n",
"Using these fundamental rotation matrices, we can compute vectors along the instruments viewing direction in the local horizon (NED) coordinate system."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1bcd9139",
"metadata": {
"tags": [
"hide-cell"
]
},
"outputs": [],
"source": [
"def R(alpha, axis, dim_a=\"a\", dim_b=\"b\"):\n",
" dims = dict(zip(alpha.dims, alpha.shape))\n",
" s = np.sin(alpha)\n",
" c = np.cos(alpha)\n",
" z = xr.DataArray(0, dims=()).expand_dims(dim=dims)\n",
" o = xr.DataArray(1, dims=()).expand_dims(dim=dims)\n",
"\n",
" return xr.concat([\n",
" xr.concat([o, z, z], dim=dim_b),\n",
" xr.concat([z, c, s], dim=dim_b),\n",
" xr.concat([z, -s, c], dim=dim_b),\n",
" ], dim=dim_a) \\\n",
" .roll(shifts={dim_a: axis, dim_b: axis}, roll_coords=False)\n",
"\n",
"def Rx(alpha, dim_a=\"a\", dim_b=\"b\"):\n",
" return R(alpha, 0, dim_a, dim_b)\n",
"\n",
"def Ry(alpha, dim_a=\"a\", dim_b=\"b\"):\n",
" return R(alpha, 1, dim_a, dim_b)\n",
"\n",
"def Rz(alpha, dim_a=\"a\", dim_b=\"b\"):\n",
" return R(alpha, 2, dim_a, dim_b)\n",
"\n",
"\n",
"def vector_norm(x, dim, ord=None):\n",
" return xr.apply_ufunc(\n",
" np.linalg.norm, x, input_core_dims=[[dim]], kwargs={\"ord\": ord, \"axis\": -1}, dask=\"allowed\"\n",
" )\n",
"\n",
"def normalize(x, dim, ord=None):\n",
" return x / vector_norm(x, dim, ord)\n",
"\n",
"def vector_lh(ds):\n",
" '''Calculate the viewing direction relative to the local horizon (NED) coordinate system.\n",
" The viewing direction is defined by the viewing zenith and azimuth angles which \n",
" are part of the dataset. If one thinks of a single pixel having its own coordinate system\n",
" with +z being the central viewing direction of this pixel, the computation of the\n",
" viewing direction can be carried out using two rotations:\n",
" 1. Rotation around the y-axis with the viewing zenith angle (pixel -> intermediate)\n",
" 2. Rotation around the z-axis with the viewinzg azimuth angle (intermediate -> NED)\n",
" '''\n",
" down = xr.DataArray(np.array([0,0,1]), dims=(\"pixel\",))\n",
" rot_vza = Ry(np.deg2rad(-ds[\"vza\"]), \"intermediate\", \"pixel\")\n",
" rot_vaa = Rz(np.deg2rad(-ds[\"vaa\"]), \"NED\", \"intermediate\")\n",
" # to simplify things later on, we attach coordinate labels to this system\n",
" rot_vaa.coords[\"NED\"] = xr.DataArray([\"N\", \"E\", \"D\"], dims=(\"NED\",))\n",
"\n",
" return normalize(\n",
" xr.dot(rot_vaa, rot_vza, down, dims=(\"pixel\", \"intermediate\")),\n",
" \"NED\"\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "edb166ff",
"metadata": {},
"outputs": [],
"source": [
"view_lh = vector_lh(ds_selection)"
]
},
{
"cell_type": "markdown",
"id": "38120675",
"metadata": {},
"source": [
"We need an approximation of the cloud top height and will use 1000 m as a first guess. If you have better cloud height data just put in your data. You can also use different values along `time` and `angle` dimensions, xarray will take care of this."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9e32507d",
"metadata": {},
"outputs": [],
"source": [
"height_guess = 1000. #m\n",
"cth = xr.DataArray(height_guess, dims=())"
]
},
{
"cell_type": "markdown",
"id": "b8d6ad7b",
"metadata": {},
"source": [
"Now let's calculate the length of the vector connecting HALO and the cloud. We need the height of the HALO, the cloudheight and the viewing direction for this. `view_lh` provides the viewing direction while the distance between HALO and cloud normalized by the down-component of the viewing direction provides the distance along the view path."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c99b7b0",
"metadata": {},
"outputs": [],
"source": [
"viewpath_lh = view_lh * (ds_selection.alt - cth) / view_lh.sel(NED=\"D\")"
]
},
{
"cell_type": "markdown",
"id": "bcf89619",
"metadata": {},
"source": [
"Now we would like to transform this viewpath also into the ECEF coordinate system. We will stick to the method described [in navipedia](https://gssc.esa.int/navipedia/index.php/Transformations_between_ECEF_and_ENU_coordinates):"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "73b4c4fe",
"metadata": {
"tags": [
"hide-cell"
]
},
"outputs": [],
"source": [
"def lh_to_ecef(ned_vector, lat, lon):\n",
" '''\n",
" Transform vector of coordinates/directions with respect to the local horizon coordinate system\n",
" into the ECEF system. While the reference uses ENU coordinates, we use NED in this example.\n",
"\n",
" see: https://gssc.esa.int/navipedia/index.php/Transformations_between_ECEF_and_ENU_coordinates\n",
" \n",
" Parameters:\n",
" ned_vector: coordinates as expressed in local horizon coordinates/NED coordinates\n",
" lat: latitude of HALO position [degree]\n",
" lon: longitude of HALO position [degree]\n",
" \n",
" Returns:\n",
" Vector expressed in ECEF coordinates.\n",
" '''\n",
" rot_matrix_inv = xr.dot(\n",
" Ry(xr.DataArray(np.deg2rad(90), dims=()), \"xyz_ecef\", \"m\"),\n",
" Rx(-np.deg2rad(lon), \"m\", \"n\"),\n",
" Ry(np.deg2rad(lat), \"n\", \"NED\"),\n",
" dims=(\"m\", \"n\")\n",
" )\n",
" return xr.dot(rot_matrix_inv, ned_vector, dims=\"NED\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "907e3830",
"metadata": {},
"outputs": [],
"source": [
"viewpath_ecef = lh_to_ecef(viewpath_lh,\n",
" ds_selection[\"lat\"],\n",
" ds_selection[\"lon\"])"
]
},
{
"cell_type": "markdown",
"id": "e91c00f3",
"metadata": {},
"source": [
"### Cloud locations in 3D space\n",
"\n",
"If we add the viewpath to the position of the HALO the resulting point gives us the ECEF coordinates of the point on the cloud."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1b5dafdc",
"metadata": {},
"outputs": [],
"source": [
"cloudpoint_ecef = HALO_ecef + viewpath_ecef\n",
"x_cloud, y_cloud, z_cloud = cloudpoint_ecef.transpose(\"xyz_ecef\", \"time\", \"angle\")"
]
},
{
"cell_type": "markdown",
"id": "f847f237",
"metadata": {},
"source": [
"### Back to ellipsoidal coordinates\n",
"\n",
"The last step is to transform these coordinates into ellipsoidal coordinates. Again we stick to the description [at navipedia](https://gssc.esa.int/navipedia/index.php/Ellipsoidal_and_Cartesian_Coordinates_Conversion):"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "69aa126e",
"metadata": {
"tags": [
"hide-cell"
]
},
"outputs": [],
"source": [
"def ecef_to_ellipsoidal(x, y, z, iterations=10):\n",
" '''Transformation from ECEF coordinates to ellipsoidal coordinates according to:\n",
" https://gssc.esa.int/navipedia/index.php/Ellipsoidal_and_Cartesian_Coordinates_Conversion\n",
"\n",
" Parameters:\n",
" x, y, z: cartesian coordinates (ECEF)\n",
" iterations: increase this value if the change between two successive values \n",
" of latitude is larger than the precision required.\n",
" Returns:\n",
" Vector expressed in ellipsoidal coordinates.\n",
" '''\n",
" WGS_84_dict = {\"axes\": (6378137.0, 6356752.314245)} #m\n",
" a, b = WGS_84_dict[\"axes\"] #semi-major and semi-minor axis a and b of the WGS-84 ellipsoid\n",
" \n",
" lon = np.arctan2(y,x) #radians \n",
" e_squared = e2(a, b) \n",
" p = np.sqrt(x**2 + y**2) \n",
" lat = np.arctan2(z, (1 - e_squared)*p) \n",
" \n",
" for i in range(iterations):\n",
" N = calc_N(a, e_squared, lat)\n",
" height = p / np.cos(lat) - N\n",
" lat = np.arctan2(z, (1-e_squared * (N/(N+height)))*p)\n",
"\n",
" lat = np.rad2deg(lat)\n",
" lat.attrs[\"units\"] = \"degree_north\"\n",
" lon = np.rad2deg(lon)\n",
" lon.attrs[\"units\"] = \"degree_east\"\n",
" return {\"lat\": lat,\n",
" \"lon\": lon,\n",
" \"height\": height}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "df82a323",
"metadata": {},
"outputs": [],
"source": [
"ds_selection = ds_selection.assign_coords(\n",
" {\"cloud\" + k: v for k, v in ecef_to_ellipsoidal(x_cloud, y_cloud, z_cloud, iterations=10).items()}\n",
")\n",
"ds_selection"
]
},
{
"cell_type": "markdown",
"id": "1739df6a",
"metadata": {},
"source": [
"## Display on a map\n",
"`ds.cloudlon` and `ds.cloudlat` are the projected longitude and latitude coordinates of the cloud. Now it is possible to plot the cloudmask on a map!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2946209c",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"cmplot = ds_selection.cloud_mask.plot(ax=ax,\n",
" x='cloudlon', y='cloudlat',\n",
" cmap=plt.get_cmap('Greys_r', lut=3),\n",
" vmin=-0.5, vmax=2.5,\n",
" add_colorbar=False)\n",
"# approximate aspect ratio of latitude and longitude length scales\n",
"ax.set_aspect(1./np.cos(np.deg2rad(float(ds_selection.cloudlat.mean()))))\n",
"flagbar(fig, cmplot, ds_selection.cloud_mask);"
]
},
{
"cell_type": "markdown",
"id": "de07f976",
"metadata": {},
"source": [
"In this two-minute long sequence we can see the curvature of the HALO circle. By the way: you could also calculate the swath width of the measurements projected onto the cloud height that you specified. \n",
"\n",
"## Swath width\n",
"\n",
"The [haversine formula](https://en.wikipedia.org/wiki/Haversine_formula) is such an approximation. It calculates the great-circle distance between two points on a sphere. We just need the respective latitudes and longitudes of the points. We will use the coordinates of the two edge pixels of the first measurement."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "66252e69",
"metadata": {
"tags": [
"hide-cell"
]
},
"outputs": [],
"source": [
"def haversine_distance(lat1, lat2, lon1, lon2, R = 6371):\n",
" '''This formula calculates the great-circle distance between two points on a sphere with radius R in km.\n",
" (https://en.wikipedia.org/wiki/Haversine_formula)\n",
" \n",
" Parameters:\n",
" lat1: latitude of first point in radians\n",
" lat2: latitude of second point in radians\n",
" lon1: longitude of first point in radians\n",
" lon2: longitude of second point in radians\n",
" R : Radius of sphere in km\n",
" \n",
" Returns: \n",
" Great-circle distance in km.\n",
" '''\n",
" dlon = lon2-lon1\n",
" dlat = lat2-lat1\n",
" \n",
" a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2)**2\n",
" distance_haversine_formula = R * 2 * np.arcsin(np.sqrt(a))\n",
" return distance_haversine_formula\n",
"\n",
"\n",
"lat1 = np.deg2rad(ds_selection.isel(time=0).isel(angle=0).cloudlat)\n",
"lat2 = np.deg2rad(ds_selection.isel(time=0).isel(angle=-1).cloudlat)\n",
"\n",
"lon1 = np.deg2rad(ds_selection.isel(time=0).isel(angle=0).cloudlon)\n",
"lon2 = np.deg2rad(ds_selection.isel(time=0).isel(angle=-1).cloudlon)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7dd70119",
"metadata": {},
"outputs": [],
"source": [
"distance_haversine_formula = haversine_distance(lat1, lat2, lon1, lon2, R = 6371)\n",
"print('The across track swath width of the measurements is about {} km'.format(np.round(distance_haversine_formula.values,2)))"
]
}
],
"metadata": {
"jupytext": {
"text_representation": {
"extension": ".md",
"format_name": "myst",
"format_version": 0.13,
"jupytext_version": "1.11.5"
}
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"source_map": [
12,
26,
31,
35,
40,
42,
46,
57,
61,
65,
71,
75,
79,
84,
90,
97,
102,
106,
112,
120,
129,
133,
142,
166,
192,
194,
211,
273,
277,
279,
286,
342,
344,
348,
351,
355,
357,
361,
388,
392,
398,
401,
407,
443,
448,
453,
463,
471,
503
]
},
"nbformat": 4,
"nbformat_minor": 5
}