# 🌊 Bathymetrix-AI V7.7: Complete User Manual & Outputs Guide

Welcome to the definitive guide for **Bathymetrix-AI V7.7**. This document serves as an all-in-one, easy-to-read reference for understanding the terminology, the exact outputs generated by each phase grouped by folders and files, and the editable parameters available in the user interface.

---

## 📖 1. Abbreviations & Terminology

*   **SDB (Satellite-Derived Bathymetry):** The science of calculating water depth using the color (spectral reflectance) of the seabed captured by satellite sensors.
*   **OSW (Optically Shallow Water):** The coastal zone where sunlight successfully hits the sea bottom and bounces back to the satellite. Bathymetry is **only** valid here.
*   **ROI (Region of Interest):** A custom polygon you provide to tell the algorithm: *"Sample the pixels inside this shape to calibrate your thresholds."*
*   **NIR (Near-Infrared):** A band of light that water absorbs heavily. It's used to detect the edge of water, land, and deep ocean.
*   **NDWI (Normalized Difference Water Index):** A mathematical formula used to easily distinguish water from dry land.
*   **Residuals (Prediction Error):** The exact difference (in meters) between what the ML model guessed and the true depth measured by the ICESat-2 laser.
*   **MSI (Morphological Stability Index):** A normalized index indicating how physically stable or volatile the seabed is over multiple years.

---

## 📁 2. Pipeline Outputs by Directory Structure

All files and directories generated by Bathymetrix-AI are organized inside your specified `Output Folder`. The directory tree is structured as follows:

```
[Output Folder] (Main Project Folder)
│
├── SDB_Validation_Dashboard.html
├── SDB_Full_Log.txt
├── 5_FINAL_SUMMARY.txt
├── 5_Stratified_Error_Analysis.csv
├── 5_Validation_Raw_Data.csv
├── 5_Plot_Scatter_Comparison.png
├── 5_Plot_Residuals.png
├── 5_Plot_Error_Histogram.png
│
├── 📁 Phase_01_Preprocessing/
│   ├── 01_Land_Water_Mask.tif
│   ├── 02_Sunglint_Corrected.tif
│   ├── 03_Feature_Stack.tif
│   ├── 04_DeepWater_Threshold_Stats.csv
│   ├── 05_ShallowWater_Pixel_Mask.tif
│   ├── 06_Final_OSW_Mask.tif
│   └── 07_OSW_Boundary_Polygon.gpkg
│
├── 📁 Phase_02_Filtering/
│   ├── 2_Cleaned_Training_Data.shp
│   ├── 2_Outliers_Rejected.shp
│   ├── 2_Plot_1_Trend.png
│   ├── 2_Plot_2_Variance.png
│   └── 2_Plot_3_Envelope.png
│
├── 📁 Phase_03_Initial_Modeling/
│   ├── 3_Actual_Model_Input_Points.shp
│   ├── 3_Feature_Analysis_Report.txt
│   ├── 3_Feature_Correlation_Plot.png
│   ├── 3_All_Algorithms_Benchmark.csv
│   ├── Phase3_Depth_Cleaned.tif
│   └── 📁 [Algorithm_Name]/
│       └── Validation_Scatter_Plot.png
│
├── 📁 Phase_04_Adaptive_Refinement/
│   ├── 4_Feature_Analysis_Report.txt
│   ├── 4_Feature_Correlation_Plot.png
│   ├── 4-Residual_Error_Map.tif
│   ├── 4_All_Algorithms_Benchmark.csv
│   └── Final_Depth_Cleaned.tif
│
└── 📁 Coastal_Dynamics_Analysis/ (Standalone Tool)
    ├── Temporal_Analytics_Report.html
    ├── Sediment_Mass_Balance.csv
    ├── Benthic_Classification_Stats.csv
    ├── SDB_[YYYY].tif
    ├── Volumetric_Erosion_Accretion_[First]_[Last].tif
    ├── Morphological_Stability_Index_[First]_[Last].tif
    └── Shoreline_Change_Polygons_[First]_[Last].shp
```

### 🏠 Main Project Folder (Root Directory)
This directory contains the final validation outputs, logs, and the web dashboard.
*   **`SDB_Validation_Dashboard.html`** (Interactive Web Dashboard):
    *   A comprehensive, premium-themed HTML dashboard visualizing project metrics, AutoML leaderboards, filtering plots, and scientific validation graphs.
    *   Features an **Interactive 3D Seabed Explorer** with real-time **Z-Scale (Vertical Exaggeration)** controls (`0.05x`, `0.1x`, `0.25x`, `0.5x`, `1x`, `2x`, `3.5x`, `5x`, `+`/`−` steppers) and camera presets (`Front 3/4`, `Top-Down`, `Side Profile`, `Reset`) to inspect submarine morphology, sandbanks, reefs, and bathymetric gradients clearly.
    *   Features the project folder, processing status, and developer credentials (`Mohamed Aly Nasef`) along with the tool identifier (`SDB MasterFlow`) in the header.
*   **`SDB_Full_Log.txt`** (Processing Log):
    *   The complete running log of the pipeline containing timestamps, execution warnings, and information messages from all phases, featuring unified module completion banners with clickable `file:///` URLs for direct access to generated maps and folders.
*   **`5_FINAL_SUMMARY.txt`** (Scientific Report):
    *   Text report comparing the overall accuracy statistics (RMSE, R2, MAE, wMAPE) between Phase 03 and Phase 04.
*   **`5_Stratified_Error_Analysis.csv`** (Spreadsheet):
    *   A breakdown of model accuracy metrics across specific depth intervals (e.g., 0-5m, 5-10m).
*   **`5_Validation_Raw_Data.csv`** (Spreadsheet):
    *   Spreadsheet dumping all validation points containing their actual coordinates, observed depth, and predicted SDB depth.
*   **`5_Plot_Scatter_Comparison.png`** (Image):
    *   A 1:1 scatter comparison plot of predicted vs. observed depths to evaluate overall correlation.
*   **`5_Plot_Residuals.png`** (Image):
    *   A residuals plot showing prediction error (residuals) against observed depth to inspect any systematic models bias.
*   **`5_Plot_Error_Histogram.png`** (Image):
    *   A density histogram displaying error distribution (centered on 0 indicates an unbiased prediction).

---

### 📁 Phase_01_Preprocessing/
Contains the results of water masking, sunglint correction, and optically shallow water extraction.

> 💡 **Best Practice & Workflow Recommendation (Optimization of Water Masking & OSW Filters)**:
> Satellite imagery varies widely in water clarity, coastal turbidity, bottom reflectance (sand vs. seagrass vs. reefs), and sun-glint. **Users are strongly advised to run Module 01 (Preprocessing) independently first** to test and compare the available Water Masking and OSW methods on their specific scene before launching the full end-to-end MasterFlow:
> 
> 1. **Testing Water Masking Methods**:
>    * **`Otsu (Automatic NDWI)`**: Fast, optimal for sharp, clear contrast between land and water.
>    * **`Smart Hybrid (Dynamic Auto)`**: Best for complex coastlines, wet intertidal sands, and tidal flats.
>    * **`3 Indices Equation (NDWI, MNDWI, NWI)`**: Multi-spectral synthesis ideal for difficult coastal edges and inland lagoons.
>    * **`Manual NDWI Threshold`**: Precise threshold control when automated methods over- or under-segment.
> 
> 2. **Testing OSW (Optically Shallow Water) Filtering Methods**:
>    * **`0. Automated Knee-Point Extinction [Recommended]`**: Automatic physics-based cutoff detecting the true optical extinction point on NIR absorption.
>    * **`1. Turbidity-Invariant Log-Ratio Extinction`**: Recommended when dealing with river plumes, estuarine sediment, or high suspended particulate matter.
>    * **`2. Multi-Otsu / GMM Spectral Clustering`**: Recommended for complex reef lagoons and heterogeneous benthic environments.
>    * **`3. Automatic (NIR Percentile Fallback)`**: Allows manual tuning of the deep-water percentile (e.g., 5% to 15%).
>    * **`4. Manual Polygon ROI / 5. Custom OSW Polygon`**: Gives full manual control by defining deep-water samples or exact shallow vector boundaries.
> 
> 👉 **Visual Quality Check in QGIS**: Load `01_Land_Water_Mask.tif` and `06_Final_OSW_Mask.tif` on top of your satellite image in QGIS to verify that shallow coastal areas are fully preserved while deep ocean waters are completely masked out.

*   **`01_Land_Water_Mask.tif`** (Binary Raster: 0/1):
    *   **What it is:** The boundaries of water. `1` = Water, `0` = Land/Clouds.
    *   **Why it matters:** Acts as a cookie-cutter to ensure processing is only done on water, saving time and memory.
*   **`02_Sunglint_Corrected.tif`** (Float32 Raster):
    *   **What it is:** Original satellite image but wave-induced sun reflections have been mathematically subtracted.
    *   **Why it matters:** Removes surface glare to reveal the true seabed color underneath.
*   **`03_Feature_Stack.tif`** (Float32 Raster):
    *   **What it is:** The ML dataset containing mathematically calculated Log-Ratios and Indices (e.g., NDWI, Blue/Green, Green/NIR).
    *   **Why it matters:** Linearizes light decay in water. The ML model learns depth exclusively from this file.
*   **`04_DeepWater_Threshold_Stats.csv`** (Spreadsheet):
    *   **What it is:** The mathematical limits showing the exact Mean, Standard Deviation, Cutoff value, and pixel counts computed by the active OSW method (`0. Automated Knee-Point Extinction`, `1. Turbidity-Invariant Log-Ratio Extinction`, or `2. Multi-Otsu / GMM Spectral Clustering`).
    *   **Why it matters:** Documents the exact physical and statistical thresholds used to isolate deep ocean waters dynamically.
*   **`05_ShallowWater_Pixel_Mask.tif`** (Binary Raster: 0/1):
    *   **What it is:** The raw filter result of pixels that passed the Deep Water thresholding (`1`=Shallow, `0`=Deep).
    *   **Why it matters:** Shows the raw statistical cutoffs before any spatial smoothing is applied.
*   **`06_Final_OSW_Mask.tif`** (Binary Raster: 0/1):
    *   **What it is:** The clean footprint of the Optically Shallow Water (OSW) mask.
    *   **Why it matters:** Polished using automated Knee-point inflection detection, connected-component topological cleaning, and internal gap filling to represent the true bathymetric prediction zone.
*   **`07_OSW_Boundary_Polygon.gpkg`** (Vector Polygon):
    *   **What it is:** The vector boundary outlining the clean OSW mask.
    *   **Why it matters:** Automatically clips the final ML depth maps in Phase 03 and Phase 04 so they don't predict fake depths in the deep ocean.
    *   **Coordinate System:** Automatically inherits and embeds the Spatial Reference System (SRS/CRS) of the source satellite image to ensure seamless alignment and prevent GDAL cutline warnings during subsequent clipping phases.

---

### 📁 Phase_02_Filtering/
Contains the results of robust point filtering and outlier rejection.
*   **`2_Cleaned_Training_Data.shp`** (Vector Points):
    *   **What it is:** Ground truth data containing clean ICESat-2 depths.
    *   **Why it matters:** The RANSAC/Variance filter aggressively deletes noise (waves, birds, etc.), ensuring the ML model only trains on perfect data.
*   **`2_Outliers_Rejected.shp`** (Vector Points):
    *   **What it is:** The points that the algorithm flagged as noise or outliers and removed.
*   **`2_Plot_1_Trend.png`**, **`2_Plot_2_Variance.png`**, **`2_Plot_3_Envelope.png`** (Images):
    *   **What they are:** Diagnostic plots showing the statistical fit and uncertainty envelopes used during filtering. These plots use dynamic robust scaling to prevent extreme outliers from squishing the main data trends.

---

### 📁 Phase_03_Initial_Modeling/
Contains Auto-ML benchmarking, band selection reports, and initial SDB depth maps.
*   **`3_Actual_Model_Input_Points.shp`** (Vector Points):
    *   **What it is:** The final points list used directly for model training after collision handling. Features safe coordinate reprojection to prevent out-of-bounds errors.
*   **`3_Feature_Analysis_Report.txt`** & **`3_Feature_Correlation_Plot.png`**:
    *   **What they are:** Report and plot showing how much each input band correlates with or contributes to the ML model's predictions, with a visual threshold for selected bands.
*   **`3_All_Algorithms_Benchmark.csv`** (Spreadsheet):
    *   **What it is:** CSV benchmark leaderboard of all tested Auto-ML models and Ensembles ranked by the selected strategy (Winner Stability, Max SDB Score, Highest R², Lowest RMSE, Lowest wMAPE, Lowest |Bias|, or Lowest MAE).
*   **`3_Score_Sensitivity_Rounds.csv`** (Spreadsheet):
    *   **What it is:** Comprehensive Monte Carlo simulation log recording the exact sampled metric weights ($w_{R^2}, w_{RMSE}, w_{wMAPE}, w_{Bias}, w_{MAE}$), algorithm scores, and winning model for each simulation round (e.g. 20–100 rounds).
    *   **Why it matters:** Provides full scientific transparency into the model selection process, proving which algorithm consistently dominates across varying weight scenarios without human bias.
*   **`Phase3_Depth_Cleaned.tif`** (Float32 Raster):
    *   **What it is:** The Base SDB Map generated by the winning ML algorithm, cleaned and clipped to the valid shallow water zone. Uses chunk-based ML prediction for memory efficiency and supports Uncertainty-Weighted Pixel Fusion for ensemble blending.
*   **📁 [Algorithm_Name]/`Validation_Scatter_Plot.png`** (Image):
    *   **What it is:** Local validation scatter plot generated for each benchmarked algorithm.

---

### 📁 Phase_04_Adaptive_Refinement/
Contains the results of residual error correction and final refined SDB maps.
*   **`4_Feature_Analysis_Report.txt`** & **`4_Feature_Correlation_Plot.png`**:
    *   **What they are:** Identical to Phase 03, but specific to the residual retraining step.
*   **`4-Residual_Error_Map.tif`** (Float32 Raster):
    *   **What it is:** The Error Map showing exactly where Phase 03 was wrong and by how much.
    *   **Why it matters:** Uses K-NN/Kriging to interpolate errors across the entire area to catch geographic biases.
*   **`4_All_Algorithms_Benchmark.csv`** (Spreadsheet):
    *   **What it is:** Benchmark leaderboard of Auto-ML models after adaptive refinement ranked by the active selection strategy.
*   **`4_Score_Sensitivity_Rounds.csv`** (Spreadsheet):
    *   **What it is:** Monte Carlo simulation log for Phase 04 models recording round-by-round weights, scores, and winner stability.
*   **`4-Refined_Uncertainty.tif`** (Float32 Raster):
    *   **What it is:** Empirical residual prediction uncertainty map at 95% confidence ($1.96 \sigma$).
    *   **Why it matters:** Evaluates spatial confidence for every pixel across the refined SDB map.
*   **`Final_Depth_Cleaned.tif`** (Float32 Raster):
    *   **What it is:** The Final SDB Map.
    *   **Why it matters:** The ultimate, highest-accuracy map where zero-mean centered spatial residual corrections and LOO robust Huber/smoothed IDW error surfaces have been applied to fix local biases. Incorporates Uncertainty-Weighted Pixel Fusion for robust model stacking.

---

### 🌊 📁 Aggregated_Results/ (SpatioSpectral Masterflow & Module 07)
Contains the merged results of multiple imageries processed with the same training dataset.
*   **`Aggregated_Depth_[Method].tif`** (Float32 Raster):
    *   **What it is:** The final selected depth map using statistical fusion (e.g., Weighted Median based on R2/RMSE).
    *   **Why it matters:** Harnesses the strengths of multiple satellite images, delivering the highest quality SDB output.
*   **`Aggregated_Intersection_Mask.tif`** (Binary Raster):
    *   **What it is:** The common valid area across all fused imageries.

---

### ⏳ 📁 Year_[YYYY]/ & Global_Model/ (SDB Spatiotemporal Masterflow)
Contains the multi-year spatiotemporal model artifacts, yearly global predictions, and adaptive refinement outputs.
*   **`Global_Model/`** (Directory):
    *   Contains the trained Global Auto-ML models (`3_Global_Model.pkl`, `3_All_Algorithms_Benchmark.csv`, etc.) where `Year` is learned as an explicit continuous feature across all available calibration points from valid years.
*   **`Year_[YYYY]/Phase_03_Initial_Modeling/3_Initial_Global_Depth_[YYYY].tif`** (Float32 Raster):
    *   **What it is:** The global spatiotemporal depth prediction for that specific calendar year.
    *   **Data Sufficiency Filter:** Only years with sufficient valid calibration data ($\ge 10$ points) are processed and mapped. Years lacking training data are cleanly skipped with informative warnings without causing workflow failures.
*   **`Year_[YYYY]/Phase_03_Initial_Modeling/3_Huber_Variance_Model_[YYYY].pkl`** (Model File):
    *   **What it is:** A localized `HuberRegressor` variance model trained to eliminate local residual bias when local training points are available ($\ge 10$ points).

---

### 🌊 📁 Coastal Dynamics Analysis (Standalone Module 06)
Contains the results of the volume calculations and shoreline migration tracking.
*   **`Temporal_Analytics_Report.html`** (Interactive Report):
    *   **What it is:** A comprehensive HTML report detailing volumetric changes, dredging volumes, target sub-region ROI metrics, uncertainty mode settings, and morphological stability with a color-coded spreadsheet.
    *   **Quality Control (QC) Value:** The Target ROI metrics within this report allow users to validate the model's real-world accuracy by confirming that calculated erosion/accretion quantities align with expected physical changes (e.g., known dredging volumes).
*   **`Quantile_Uncertainty_[Year].tif`** (Float32 Raster - generated when Quantile Regression mode is active):
    *   **What it is:** Spatially-adaptive uncertainty raster map ($\sigma$) estimated using Quantile Regression ($q_{\text{lower}}$ and $q_{\text{upper}}$) fitted on ground-truth ICESat-2 data.
*   **`Full_Process_Log.txt`** (Text File):
    *   **What it is:** Real-time log file recording all execution details, warnings, and processing steps throughout the Temporal Intelligence pipeline run.
*   **`Volumetric_Erosion_Accretion_[First]_[Last].tif`** (Float32 Raster):
    *   **What it is:** Measures the Magnitude and Direction of physical sand volume change (in cubic meters).
    *   **Methodology:** Uses a robust **Linear Regression (Time-Series Trend)** across all provided years. This mathematically filters out deep-water random noise and calculates the true rate of sand movement, identifying dredging (Erosion) and shoaling (Accretion). 
    *   **Mathematical Equation (Long-term Trend):**
        *   $Z_{diff} = Z_{arr} - \bar{Z}$
        *   $T_{diff} = T - \bar{T}$
        *   $\text{Slope (m/yr)} = \frac{\sum (T_{diff} \times Z_{diff})}{\sum (T_{diff}^2)}$
        *   $\Delta Z = \text{Slope} \times (\text{Year}_{last} - \text{Year}_{first})$
    *   **Auto-Detection:** Features **Auto-Detection** for Depth (positive) vs Elevation (negative) inputs via median analysis `np.nanmean(z1[valid]) > 0`, ensuring flawless sand tracking regardless of data format.
*   **`Morphological_Stability_Index_[First]_[Last].tif`** (Float32 Raster):
    *   **What it is:** Measures the Volatility and Consistency of the seabed, regardless of whether it is eroding or accreting.
    *   **Methodology:** A normalized index from 0 to 1 (0 = Highly Unstable, 1 = Highly Stable).
    *   **Mathematical Equation:**
        *   $MSI = 1.0 - \frac{\sigma_{true}}{|\mu| + 0.5}$
        *   Where $\sigma_{true} = \sqrt{\max(0, \sigma_{obs}^2 - \bar{\sigma}_u^2)}$ ($\bar{\sigma}_u$ is the mean uncertainty of the inputs).
*   **`StatCD_Uncertainty_Thresholding`** (Applied during Volume Calculation):
    *   The algorithm enforces a **Statistical Level of Detection (StatCD)** before calculating volumes. Any pixel where the magnitude of change $|\Delta Z|$ is less than the combined uncertainty $U_{comb}$ is forced to 0 (No Change).
    *   **Mathematical Equations (By Mode):**
        *   **Classical Mode (Z-score 1.96 $\sigma$):** $U_{comb} = 1.96 \times \sqrt{\sigma_1^2 + \sigma_2^2}$
        *   **MAD Mode (Median Absolute Deviation):** $U_{comb} = 1.4826 \times \text{MAD}$
        *   **Quantile Mode:** $U_{comb} = \frac{q_{upper} - q_{lower}}{1.349}$
    ├── Shoreline_Movement.shp
    ├── 📁 Volumetric_Change_Rasters/
    └── 📁 Morphological_Stability_Index/
```

---

## 🎛️ 3. User Interface (UI) Parameters & Defaults

This section explains editable parameters in the MasterFlow and Modular plugins, organized according to the **V7.7 Unified Interface Layout**:

### ⚙️ [0] General Settings & Workspaces
*   **Input Satellite Image / Workspace Folder:** Specifies the source imagery or multi-scene/temporal directory structure.
*   **Processing Threads** `[Default: 4]`
    *   **What it does:** Dictates how many CPU multi-processing workers to use.

### 📡 [1] Phase 01: Pre-processing & Feature Extraction
*   **Enable Phase 01 Pre-processing** `[Default: True]`
    *   **What it does:** Header toggle for all pre-processing and feature generation.
*   **Coastal/Blue/Green/Red/NIR/SWIR Bands** `[Defaults: 1, 2, 3, 4, 8, 11]`
    *   **What it does:** Maps the specific spectral band indices of your satellite image.
*   **Apply Sunglint Correction** `[Default: True]`
    *   **What it does:** Removes surface glint reflections using Hedley's algorithm.
*   **Enable Automated Water Masking** `[Default: True]`
    *   **What it does:** Controls water segmentation. When disabled (`False`), both automated masking (NDWI/MNDWI/NWI) and any user-provided Ready-made Water Mask Polygon are completely bypassed.
*   **Water Masking Method & Ready-made Polygon:**
    *   **What it does:** Chooses between automated 3-indices / Otsu thresholding or directly ingesting a pre-made vector mask polygon.
*   **Output Feature Stack & Custom Band Math:**
    *   **What it does:** Selects depth-sensitive features (e.g. Physics-based Log bands, Band Ratios, Indices) and allows entering custom formula strings (e.g. `(B2-B3)/(B2+B3)`).
*   **Apply Deep Water Filter:**
    *   **What it does:** Separates Optically Shallow Water (OSW) from deep ocean using Automated Knee-Point Extinction, Turbidity-Invariant Log-Ratio Extinction, Multi-Otsu 3D Clustering, or Manual ROI.

### 🛡️ [2] Phase 02: ICESat-2 Data Filtering
*   **Enable Phase 02 Data Filtering** `[Default: True]`
    *   **What it does:** Top-level header toggle for training noise removal. When unchecked (`False`), the input training points (`INPUT_TRAIN`) pass directly and untouched into Phase 03, completely bypassing RANSAC/variance outlier rejection.
*   **Main Training Points (ICESat-2 / In-situ):**
    *   **What it does:** Vector point layer containing training observations.
*   **Depth Field & Weight Field [optional]:**
    *   **What it does:** Selects the numeric depth attribute (e.g. `ortho_h`, `Field_3`) and confidence weighting field.
*   **Filtering Strategy & Log-Ratio Bands** `[Default: LS Variance Fit]`
    *   **What it does:** Selects between Linear RANSAC, Least-Squares (LS) Variance Fit, and Huber Variance Fit with numerator/denominator spectral band selection.

### 🤖 [3] Phase 03: Global Auto-ML SDB Modeling
*   **Global Auto-ML SDB Modeling (Algorithms to Benchmark):**
    *   **What it does:** Selects which machine learning models to benchmark (Extra Trees, XGBoost, LightGBM, CatBoost, Random Forest, SVR, MLP, Stacking Ensembles, etc.).
*   **Hyperparameter Optimizer Method** `[Default: Random Search]`
    *   **What it does:** Selects between Random Search, Grid Search, or Bayesian Optimization.
*   **Feature Correlation Method & Threshold:**
    *   **What it does:** Evaluates band collinearity (Pearson, Spearman, Auto-RANSAC, Auto-Random Forest) to eliminate redundant features.
*   **Enable Spatial Block Cross-Validation:**
    *   **What it does:** Enforces spatial independence in validation folds to prevent optimistic spatial autocorrelation.

### 🎯 [4] Phase 04: Adaptive Refinement (Decoupled Architecture)
*   **Enable Phase 04 Adaptive Refinement** `[Default: False]`
    *   **What it does:** Main toggle for Phase 04 spatial post-processing.
*   **Enable Depth Variance Correction (Datum Mean Shift)** `[Default: False]`
    *   **What it does:** Performs a global vertical datum shift based on adaptive control points to zero-mean the systematic prediction offset.
*   **Enable Spatial Residual Correction (KNN / Kriging Grid)** `[Default: True]`
    *   **What it does:** Analyzes local prediction errors against control points and generates a 2D spatial correction grid via Standard KNN, Robust KNN (Huber Weights), or Gaussian Process / Kriging.
*   **Features for Retraining:**
    *   **What it does:** Selects components to feed into the adaptive re-training stage (`Feature Stack`, `Phase 03 Depth Map`, `Residual Error Grid`).

### 📉 [5] Phase 05: Validation & Reporting
*   **Enable Validation** `[Default: False]`
    *   **What it does:** Triggers the creation of the Phase 05 reports, statistics, and graphs.
*   **Remove Positive Depths** `[Default: True]`
    *   **What it does:** Cleans the final map by deleting any fake elevations (like boats or piers) above 0m sea level.
*   **Apply Slope Filter** `[Default: True]`
    *   **What it does:** Deletes physically impossible sharp spikes or drops in the seabed caused by model glitches.
*   **Slope Filter Threshold** `[Default: 35.0]`
    *   **What it does:** Sets the maximum allowable slope (in degrees). Anything steeper is deleted.

### 🧩 [0.2] SpatioSpectral Aggregator Settings
*   **Aggregation Method** `[Default: Weighted Median (R2/RMSE)]`
    *   **What it does:** Determines how multiple depth maps from different dates are combined.
    *   **Select Best Scene (Highest R2 / Lowest RMSE):** Automatically scans the log files and selects the single highest-performing scene based on its training metrics.
    *   **Weighted Median / Weighted Mean:** Combines all scenes but mathematically gives more influence (higher weight) to scenes that had higher accuracy (R2) and lower error (RMSE) during training.
    *   **Median / Mean:** Simple, unweighted combination of all scenes.

---

## 🏆 4. Customizable Auto-ML Benchmark Scoring & Model Selection

Bathymetrix-AI features a streamlined, multi-criteria Auto-ML ranking and selection engine with **3 compact, intuitive UI controls**:

### 🎯 1. Model Selection Strategies (`SCORE_SELECTION_STRATEGY`)
* **Winner Stability (Monte Carlo Sensitivity Analysis) [Default]:**
  * Performs $N$ Monte Carlo simulation rounds with varying equation weights sampled within variation bounds. The model that wins the highest percentage of rounds (`Stability %` and `Wins`) is selected as the overall champion.
* **Highest SDB Composite Score (0–100):**
  * Selects the model with the highest single composite score calculated using the active normalized weights.
* **Highest $R^2$ Accuracy:** Selects the model with the highest coefficient of determination ($R^2$).
* **Lowest RMSE (Root Mean Squared Error):** Selects the model with the minimum vertical metric error ($\text{m}$).
* **Lowest wMAPE (%):** Selects the model with the lowest weighted mean absolute percentage error.
* **Lowest |Bias| (Zero-Mean Residual Offset):** Selects the model closest to zero systematic vertical offset ($\text{m}$).
* **Lowest MAE (Mean Absolute Error):** Selects the model with the minimum mean absolute error ($\text{m}$).

### ⚖️ 2. Checkbox Metric Selection with Auto-Balancing (`SCORE_METRICS`)
Users can select which evaluation metrics participate in the score calculation using a multi-select checkbox list:
* ☑️ **$R^2$ Accuracy (Correlation & Explained Variance)** `[Default: Checked]`
* ☑️ **RMSE (Root Mean Squared Error)** `[Default: Checked]`
* ☑️ **wMAPE (Weighted Mean Absolute Percentage Error)** `[Default: Checked]`
* ☑️ **|Bias| (Zero-Mean Residual Offset)** `[Default: Checked]`
* ⬜ **MAE (Mean Absolute Error)** `[Default: Unchecked]`

> [!TIP]
> **Automatic Weight Balancing:** When metrics are checked or unchecked, the engine **automatically distributes and normalizes the weights proportionally** to sum exactly to 100% (1.0). Unchecked metrics are strictly excluded with weight `0.0`.

### 🎛️ 3. Optional Custom Score Matrix & Settings (`SCORE_CUSTOM_CONFIG`)
An optional parameter field allowing custom weight assignments and Monte Carlo sensitivity tuning without needing to edit complex templates:
* **Default Value:** `""` (Empty — automatically balanced via `SCORE_METRICS` checkboxes).
* **How to Customize:**
  * **Custom Weight Overrides:** Specify only the metrics you want to assign explicit weights to, e.g. `"R2: 50, MAE: 50"` or `"MAE: 40, RMSE: 30, R2: 30"`.
  * **Auto-Normalization:** You don't need to manually calculate percentages to reach 100 — the engine automatically scales active weights to sum to 1.0 (100%).
  * **Simulation Tuning:** Modify rounds and variation tolerance directly (e.g. `"Rounds: 50, Variation: +/-20%"`).
  * **Seamless Checkbox Integration:** When selecting `MAE` from `SCORE_METRICS`, the system immediately includes MAE in the auto-balancing equation proportionally without requiring manual string edits.

