
///////////////////////////////////////////////////////////
//                                                       //
//                         SAGA                          //
//                                                       //
//      System for Automated Geoscientific Analyses      //
//                                                       //
//                     Tool Library                      //
//                    statistics_grid                    //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//              grid_statistics_bivariate.cpp            //
//                                                       //
//                 Copyright (C) 2026 by                 //
//                      Olaf Conrad                      //
//                                                       //
//-------------------------------------------------------//
//                                                       //
// This file is part of 'SAGA - System for Automated     //
// Geoscientific Analyses'. SAGA is free software; you   //
// can redistribute it and/or modify it under the terms  //
// of the GNU General Public License as published by the //
// Free Software Foundation, either version 2 of the     //
// License, or (at your option) any later version.       //
//                                                       //
// SAGA is distributed in the hope that it will be       //
// useful, but WITHOUT ANY WARRANTY; without even the    //
// implied warranty of MERCHANTABILITY or FITNESS FOR A  //
// PARTICULAR PURPOSE. See the GNU General Public        //
// License for more details.                             //
//                                                       //
// You should have received a copy of the GNU General    //
// Public License along with this program; if not, see   //
// <http://www.gnu.org/licenses/>.                       //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//    e-mail:     oconrad@saga-gis.org                   //
//                                                       //
//    contact:    Olaf Conrad                            //
//                Institute of Geography                 //
//                University of Hamburg                  //
//                Germany                                //
//                                                       //
///////////////////////////////////////////////////////////

//---------------------------------------------------------
#include "grid_statistics_bivariate.h"


///////////////////////////////////////////////////////////
//                                                       //
//                                                       //
//                                                       //
///////////////////////////////////////////////////////////

//---------------------------------------------------------
CGrid_Statistics_Bivariate::CGrid_Statistics_Bivariate(void)
{
	Set_Name		(_TL("Bivariate Grid Statistics"));

	Set_Author		("O.Conrad (c) 2026");

	Set_Description	(_TW(
		"Compare two grids. Calculates a set of bivariate statistics stored to a table. "
	));

	Parameters.Add_Grid ("", "GRID_A", CSG_String::Format("%s A", _TL("Grid")), _TL(""), PARAMETER_INPUT);
	Parameters.Add_Grid ("", "GRID_B", CSG_String::Format("%s B", _TL("Grid")), _TL(""), PARAMETER_INPUT);

	Parameters.Add_Table("", "STATISTICS", _TL("Statistics"), _TL(""), PARAMETER_OUTPUT);

	Parameters.Add_Int  ("", "SKIP", _TL("Skip"), _TL(""), 1, 1, true);
}


///////////////////////////////////////////////////////////
//                                                       //
///////////////////////////////////////////////////////////

//---------------------------------------------------------
bool CGrid_Statistics_Bivariate::On_Execute(void)
{
	CSG_Grid &A = *Parameters["GRID_A"].asGrid();
	CSG_Grid &B = *Parameters["GRID_B"].asGrid();

	int Skip = Parameters["SKIP"].asInt();

	CSG_Regression Regression; CSG_Simple_Statistics Statistics[3];

	//-----------------------------------------------------
	Process_Set_Text("%s 1...", _TL("pass"));

	for(sLong i=0; i<Get_NCells() && Set_Progress_Cells(i); i+=Skip)
	{
		if( !A.is_NoData(i) && !B.is_NoData(i) )
		{
			double a = A.asDouble(i), b = B.asDouble(i);

			Regression.Add_Values(a, b); Statistics[0] += a; Statistics[1] += b; Statistics[2] += a - b;
		}
	}

	if( Regression.Get_Count() < 1 )
	{
		Error_Set(_TL("No or not enough valid cells found!"));

		return( false );
	}

	//-----------------------------------------------------
	double Cov = 0., RMSE = 0.;

	Process_Set_Text("%s 2...", _TL("pass"));

	for(sLong i=0; i<Get_NCells() && Set_Progress_Cells(i); i+=Skip)
	{
		if( !A.is_NoData(i) && !B.is_NoData(i) )
		{
			double a = A.asDouble(i), b = B.asDouble(i);

			Cov  += (a - Statistics[0].Get_Mean()) * (b - Statistics[1].Get_Mean());

			RMSE += SG_Get_Square((a - b) - Statistics[2].Get_Mean());
		}
	}

	Cov /= Statistics[0].Get_Count(); RMSE = sqrt(RMSE / Statistics[2].Get_Count());

	//-----------------------------------------------------
	if( Regression.Calculate(REGRESSION_Linear, true) )
	{
		CSG_Table& Table = *Parameters["STATISTICS"].asTable();

		Table.Create(); Table.Fmt_Name("%s (%s / %s)", _TL("Bivariate Grid Statistics"), A.Get_Name(), B.Get_Name());

		Table.Add_Field(_TL("Variable"), SG_DATATYPE_String);
		Table.Add_Field(_TL("Value"   ), SG_DATATYPE_Double);

		#define Add_Variable(name, value) { CSG_Table_Record &r = *Table.Add_Record(); r.Set_Value(0, SG_T(name)); r.Set_Value(1, value); }

		Add_Variable("N"                      , Regression.Get_Count      ());
		Add_Variable("r"                      , Regression.Get_R          ());
		Add_Variable("r²"                     , Regression.Get_R2         ());
		Add_Variable("r²adj."                 , Regression.Get_R2_Adj     ());
		Add_Variable("Standard Error"         , Regression.Get_StdError   ());
		Add_Variable("Root Mean Squared Error", RMSE                        );
		Add_Variable("Covariance"             , Cov                         );
		Add_Variable("Intercept"              , Regression.Get_Constant   ());
		Add_Variable("Slope"                  , Regression.Get_Coefficient());

		DataObject_Update(&Table, SG_UI_DATAOBJECT_SHOW_MAP);

		return( true );
	}

	//-----------------------------------------------------
	return( false );
}


///////////////////////////////////////////////////////////
//                                                       //
//                                                       //
//                                                       //
///////////////////////////////////////////////////////////

//---------------------------------------------------------
