{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "\n",
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "import numpy as np\n",
    "import xarray as xr\n",
    "from dask.diagnostics import ProgressBar\n",
    "\n",
    "from polsarpro.io import open_netcdf_beam\n",
    "from polsarpro.util import pauli_rgb\n",
    "\n",
    "# change to your local C-PolSARpro install dir\n",
    "# Kept for consistency with the other dev notebooks, but unused in this\n",
    "# UAVSAR-only variant.\n",
    "c_psp_dir = \"/home/c_psp/Soft/bin/\"\n",
    "os.environ[\"PATH\"] += os.pathsep + f\"{c_psp_dir}/data_process_sngl/\"\n",
    "os.environ[\"PATH\"] += os.pathsep + f\"{c_psp_dir}/data_convert/\"\n",
    "\n",
    "input_uavsar_nc = Path(\"/data/psp/test_files/blackw_20801_22010_006_220507_L090_CX_02_ML5X5.nc\")\n",
    "incidence_angle_file = Path(\n",
    "    \"/data/psp/test_files/blackw_20801_22010_006_220507_L090_CX_02.inc\"\n",
    ")\n",
    "file_out = Path(\"/data/psp/res/test_dubois_surface_inversion_uavsar.nc\")\n",
    "\n",
    "with xr.open_dataset(input_uavsar_nc) as raw_ds:\n",
    "    center_wavelength_cm = raw_ds[\"metadata\"].attrs[\"Annotation:CenterWavelength\"]\n",
    "\n",
    "# Dubois expects GHz; UAVSAR metadata stores the center wavelength in cm.\n",
    "freq_ghz = 29.9792458 / float(center_wavelength_cm)\n",
    "\n",
    "# Leave thresholds as-is for now.\n",
    "thresh1_db = 0.0\n",
    "thresh2_db = -10.0\n",
    "calibration_coeff = 1.0\n",
    "\n",
    "print(f\"Derived radar frequency: {freq_ghz:.6f} GHz\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load UAVSAR data and incidence angle raster"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "C3 = open_netcdf_beam(input_uavsar_nc)\n",
    "row_dim, col_dim = C3.dims\n",
    "# nlines = C3.sizes[row_dim]\n",
    "# ncols = C3.sizes[col_dim]\n",
    "\n",
    "# use lines from .ann file\n",
    "# inc.set_rows                                      (pixels)    = 12344                  ; INC Lines\n",
    "# inc.set_cols                                      (pixels)    = 11248                  ; INC Samples\n",
    "\n",
    "nlines = 12344\n",
    "ncols = 11248\n",
    "\n",
    "# The incidence-angle file is a little-endian float32 stream in radians.\n",
    "# Read only the raster-sized prefix and reshape it to the UAVSAR grid.\n",
    "incidence_angle_values = np.fromfile(\n",
    "    incidence_angle_file,\n",
    "    dtype=\"<f4\",\n",
    "    count=nlines * ncols,\n",
    ")\n",
    "\n",
    "# reduce to the same dimensions as multilooked 5x5 image\n",
    "incidence_angle_values[incidence_angle_values==-10000] = np.nan\n",
    "incidence_angle = xr.DataArray(\n",
    "    incidence_angle_values.reshape(nlines, ncols),\n",
    "    dims=(row_dim, col_dim),\n",
    "    # coords={row_dim: C3.coords[row_dim], col_dim: C3.coords[col_dim]},\n",
    "    name=\"incidence_angle\",\n",
    ").coarsen(y=5, x=5, boundary=\"trim\").mean()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# rgb = pauli_rgb(C3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# rgb[:,::4,1000:].plot.imshow()\n",
    "import matplotlib.pyplot as plt\n",
    "plt.figure(figsize=(10, 10))\n",
    "plt.imshow(rgb.transpose(\"y\", \"x\", \"band\"), interpolation=\"nearest\")\n",
    "# plt.colorbar(fraction=0.046, pad=0.04)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# rgb[:,::4,1000:].plot.imshow()\n",
    "import matplotlib.pyplot as plt\n",
    "plt.figure(figsize=(10, 10))\n",
    "# plt.imshow(incidence_angle[::5, ::5], interpolation=\"bilinear\")\n",
    "plt.imshow(incidence_angle, interpolation=\"nearest\")\n",
    "plt.colorbar(fraction=0.046, pad=0.04)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.12.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
