{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Lee refined speckle filter evaluation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "\n",
    "import os\n",
    "\n",
    "\n",
    "from polsarpro.dev.devtools import parse_psp_parameter_string\n",
    "from pathlib import Path\n",
    "from polsarpro.io import open_netcdf_beam, polmat_to_netcdf\n",
    "from polsarpro.dev.io import read_C3_psp, read_T3_psp\n",
    "from polsarpro.speckle_filters import refined_lee\n",
    "from polsarpro.util import S_to_C3, S_to_T3\n",
    "from polsarpro.dev.metrics import summarize_metrics, visualize_errors\n",
    "import shutil\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# optional import for progress bar\n",
    "from dask.diagnostics import ProgressBar\n",
    "\n",
    "# change to your local C-PolSARpro install dir\n",
    "c_psp_dir = \"/home/c_psp/Soft/bin/\"\n",
    "os.environ[\"PATH\"]+=os.pathsep+f\"{c_psp_dir}/speckle_filter/\"\n",
    "\n",
    "# change to your data paths\n",
    "# original dataset\n",
    "input_alos_data = Path(\"/data/psp/test_files/SAN_FRANCISCO_ALOS1_slc.nc\")\n",
    "\n",
    "# S2 inputs generated with C-PSP\n",
    "input_test_dir = Path(\"/data/psp/SAN_FRANCISCO_ALOS1\")\n",
    "\n",
    "# output files from C\n",
    "output_test_dir = Path(\"/data/psp/res/ref_lee_c\")\n",
    "if not output_test_dir.exists():\n",
    "    output_test_dir.mkdir(parents=True)\n",
    "\n",
    "output_type = \"T3\"\n",
    "if output_type not in [\"T3\", \"C3\"]:\n",
    "    raise ValueError(\"output_type must be T3 or C3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run the C-version on some test data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_str= f\"\"\"id: {input_test_dir} \n",
    "od: {output_test_dir}\n",
    "iodf: S2{output_type}\n",
    "nw: 11\n",
    "nlk: 1\n",
    "ofr: 0\n",
    "ofc: 0\n",
    "fnr: 18432\n",
    "fnc: 1248\n",
    "errf: /tmp/MemoryAllocError.txt\n",
    "mask: {input_test_dir}/mask_valid_pixels.bin\n",
    "\"\"\"\n",
    "result = parse_psp_parameter_string(input_str)\n",
    "os.system(f\"lee_refined_filter.exe {result}\")\n",
    "\n",
    "# CPSP does not create another config file in output dir\n",
    "shutil.copy(input_test_dir / \"config.txt\", output_test_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load ALOS data and C outputs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# uncomment to test on S matrix made with SNAP\n",
    "S = open_netcdf_beam(input_alos_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Apply the decomposition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if os.path.exists(output_test_dir / f\"refined_lee_{output_type}_py.nc\"):\n",
    "    os.remove(output_test_dir / f\"refined_lee_{output_type}_py.nc\")\n",
    "\n",
    "with ProgressBar():\n",
    "    if output_type == \"T3\":\n",
    "        out_py = refined_lee(S_to_T3(S), window_size=11, num_looks=1)\n",
    "    else:\n",
    "        out_py = refined_lee(S_to_C3(S), window_size=11, num_looks=1)\n",
    "    # use custom function that writes complex data and preserves chunks\n",
    "    polmat_to_netcdf(out_py, output_test_dir / f\"refined_lee_{output_type}_py.nc\")\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Numerical evaluation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if output_type == \"T3\":\n",
    "    out_c = read_T3_psp(output_test_dir).compute()\n",
    "else:\n",
    "    out_c = read_C3_psp(output_test_dir).compute()\n",
    "out_py = open_netcdf_beam(output_test_dir / f\"refined_lee_{output_type}_py.nc\").compute()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = summarize_metrics(out_c, out_py)\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "visualize_errors(out_py=out_py, out_c=out_c)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "psp",
   "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.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
