//---------------------------------------------------------
CFilter_3x3::CFilter_3x3(void)
{
	//-----------------------------------------------------
	Set_Name		(_TL("User Defined Filter"));

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

	Set_Description	(_TW(
		"User defined filter matrix. The filter can be chosen from loaded tables. "
		"If not specified a fixed table with 3 rows (and 3 columns) will be used. "
	));

	//-----------------------------------------------------
	Parameters.Add_Grid(
		"", "INPUT"		, _TL("Grid"),
		_TL(""),
		PARAMETER_INPUT
	);

	Parameters.Add_Grid(
		"", "RESULT"		, _TL("Filtered Grid"),
		_TL(""),
		PARAMETER_OUTPUT
	);

	Parameters.Add_Table(
		"", "FILTER"		, _TL("Filter Matrix"),
		_TL(""),
		PARAMETER_INPUT_OPTIONAL
	);

	Parameters.Add_Bool(
		"", "ABSOLUTE"	, _TL("Absolute Weighting"),
		_TL(""),
		true
	);

	//-----------------------------------------------------
	CSG_Table	Filter;

	Filter.Add_Field("1", SG_DATATYPE_Double);
	Filter.Add_Field("2", SG_DATATYPE_Double);
	Filter.Add_Field("3", SG_DATATYPE_Double);

	Filter.Add_Record();
	Filter.Add_Record();
	Filter.Add_Record();

	Filter[0][0]	= 0.5;	Filter[0][1]	= 1.0;	Filter[0][2]	= 0.5;
	Filter[1][0]	= 1.0;	Filter[1][1]	=-6.0;	Filter[1][2]	= 1.0;
	Filter[2][0]	= 0.5;	Filter[2][1]	= 1.0;	Filter[2][2]	= 0.5;

	Parameters.Add_FixedTable(
		"", "FILTER_3X3"	, _TL("Default Filter Matrix (3x3)"),
		_TL(""),
		&Filter
	);
}
Beispiel #2
0
//---------------------------------------------------------
CFilter_3x3::CFilter_3x3(void)
{
	//-----------------------------------------------------
	Set_Name		(_TL("User Defined Filter (3x3)"));

	Set_Author		(SG_T("(c) 2001 by O.Conrad"));

	Set_Description	(_TW(
		"User defined 3x3 sub-window filter. The filter is entered as a table with 3 rows and 3 columns."
	));

	//-----------------------------------------------------
	Parameters.Add_Grid(
		NULL, "INPUT"	, _TL("Grid"),
		_TL(""),
		PARAMETER_INPUT
	);

	Parameters.Add_Grid(
		NULL, "RESULT"	, _TL("Filtered Grid"),
		_TL(""),
		PARAMETER_OUTPUT
	);

	//-----------------------------------------------------
	CSG_Table	Filter;

	Filter.Add_Field("1", SG_DATATYPE_Double);
	Filter.Add_Field("2", SG_DATATYPE_Double);
	Filter.Add_Field("3", SG_DATATYPE_Double);

	Filter.Add_Record();
	Filter[0][0]	= 0.25;
	Filter[0][1]	= 0.5;
	Filter[0][2]	= 0.25;

	Filter.Add_Record();
	Filter[1][0]	= 0.5;
	Filter[1][1]	=-1.0;
	Filter[1][2]	= 0.5;

	Filter.Add_Record();
	Filter[2][0]	= 0.25;
	Filter[2][1]	= 0.5;
	Filter[2][2]	= 0.25;

	Parameters.Add_FixedTable(
		NULL, "FILTER"	, _TL("Filter Matrix"),
		_TL(""),
		&Filter
	);
}
Beispiel #3
0
//---------------------------------------------------------
bool CTable_List::On_Execute(void)
{
	CSG_Table	*pTables	= Parameters("TABLES")->asTable();

	pTables->Destroy();
	pTables->Set_Name(_TL("Tables"));

	pTables->Add_Field(_TL("Table"), SG_DATATYPE_String);

	if( Get_Connection() )
	{
		CSG_Strings	Tables;

		Get_Connection()->Get_Tables(Tables);

		for(int i=0; i<Tables.Get_Count(); i++)
		{
			CSG_Table_Record	*pTable	= pTables->Add_Record();

			pTable->Set_Value(0, Tables[i]);
		}

		pTables->Set_Name(Get_Connection()->Get_Server() + " [" + _TL("Tables") + "]");

		return( true );
	}

	return( false );
}
//---------------------------------------------------------
void CVIEW_ScatterPlot::On_AsTable(wxCommandEvent &event)
{
	if( m_Trend.Get_Data_Count() > 1 )
	{
		CSG_Table	*pTable	= new CSG_Table;

		pTable->Fmt_Name("%s: [%s]-[%s]", _TL("Scatterplot"), m_sX.c_str(), m_sY.c_str());

		pTable->Add_Field("ID", SG_DATATYPE_Int   );
		pTable->Add_Field(m_sX, SG_DATATYPE_Double);
		pTable->Add_Field(m_sY, SG_DATATYPE_Double);

		for(int i=0; i<m_Trend.Get_Data_Count() && PROGRESSBAR_Set_Position(i, m_Trend.Get_Data_Count()); i++)
		{
			CSG_Table_Record	*pRecord	= pTable->Add_Record();

			pRecord->Set_Value(0, i + 1);
			pRecord->Set_Value(1, m_Trend.Get_Data_X(i));
			pRecord->Set_Value(2, m_Trend.Get_Data_Y(i));
		}

		PROGRESSBAR_Set_Position(0);

		g_pData->Add(pTable);
	}
}
Beispiel #5
0
//---------------------------------------------------------
void CGrid_Cluster_Analysis::Save_Statistics(CSG_Parameter_Grid_List *pGrids, bool bNormalize, const CSG_Cluster_Analysis &Analysis)
{
	int			iCluster, iFeature;
	CSG_String	s;
	CSG_Table	*pTable	= Parameters("STATISTICS")->asTable();

	pTable->Destroy();
	pTable->Set_Name(_TL("Cluster Analysis"));

	pTable->Add_Field(_TL("ClusterID")	, SG_DATATYPE_Int);
	pTable->Add_Field(_TL("Elements")	, SG_DATATYPE_Int);
	pTable->Add_Field(_TL("Std.Dev.")	, SG_DATATYPE_Double);

	s.Printf(SG_T("\n%s:\t%d \n%s:\t%ld \n%s:\t%d \n%s:\t%d \n%s:\t%f\n\n%s\t%s\t%s"),
		_TL("Number of Iterations")	, Analysis.Get_Iteration(),
		_TL("Number of Elements")	, Analysis.Get_nElements(),
		_TL("Number of Variables")	, Analysis.Get_nFeatures(),
		_TL("Number of Clusters")	, Analysis.Get_nClusters(),
		_TL("Standard Deviation")	, sqrt(Analysis.Get_SP()),
		_TL("Cluster"), _TL("Elements"), _TL("Std.Dev.")
	);

	for(iFeature=0; iFeature<Analysis.Get_nFeatures(); iFeature++)
	{
		s	+= CSG_String::Format(SG_T("\t%s"), pGrids->asGrid(iFeature)->Get_Name());

		pTable->Add_Field(pGrids->asGrid(iFeature)->Get_Name(), SG_DATATYPE_Double);
	}

	Message_Add(s);

	for(iCluster=0; iCluster<Analysis.Get_nClusters(); iCluster++)
	{
		s.Printf(SG_T("\n%d\t%d\t%f"), iCluster, Analysis.Get_nMembers(iCluster), sqrt(Analysis.Get_Variance(iCluster)));

		CSG_Table_Record	*pRecord	= pTable->Add_Record();

		pRecord->Set_Value(0, iCluster);
		pRecord->Set_Value(1, Analysis.Get_nMembers(iCluster));
		pRecord->Set_Value(2, sqrt(Analysis.Get_Variance(iCluster)));

		for(iFeature=0; iFeature<Analysis.Get_nFeatures(); iFeature++)
		{
			double	Centroid	= Analysis.Get_Centroid(iCluster, iFeature);

			if( bNormalize )
			{
				Centroid	= pGrids->asGrid(iFeature)->Get_Mean() + Centroid * pGrids->asGrid(iFeature)->Get_StdDev();
			}

			s	+= CSG_String::Format(SG_T("\t%f"), Centroid);

			pRecord->Set_Value(iFeature + 3, Centroid);
		}

		Message_Add(s, false);
	}
}
Beispiel #6
0
	bool					Add_Edge			(int ID, double Direction)
	{
		CSG_Table_Record	*pEdge	= m_Edges.Add_Record();

		pEdge->Set_Value(0, ID);
		pEdge->Set_Value(1, Direction);

		m_Edges.Set_Index(1, TABLE_INDEX_Ascending);

		return( true );
	}
Beispiel #7
0
//---------------------------------------------------------
bool CFilter_Rank::Get_Value(int x, int y, double Rank, double &Value)
{
	if( m_pInput->is_InGrid(x, y) )
	{
		CSG_Table	Values;

		Values.Add_Field("Z", SG_DATATYPE_Double);

		for(int i=0; i<m_Kernel.Get_Count(); i++)
		{
			int	ix	= m_Kernel.Get_X(i, x);
			int	iy	= m_Kernel.Get_Y(i, y);

			if( m_pInput->is_InGrid(ix, iy) )
			{
				Values.Add_Record()->Set_Value(0, m_pInput->asDouble(ix, iy));
			}
		}

		switch( Values.Get_Count() )
		{
		case 0:
			return( false );

		case 1:
			Value	= Values[0].asDouble(0);
			return( true );

		case 2:
			Value	= (Values[0].asDouble(0) + Values[1].asDouble(0)) / 2.0;
			return( true );

		default:
			{
				Values.Set_Index(0, TABLE_INDEX_Ascending);

				Rank	= Rank * (Values.Get_Count() - 1.0);

				int	i	= (int)Rank;

				Value	= Values.Get_Record_byIndex(i)->asDouble(0);

				if( Rank - i > 0.0 && i < Values.Get_Count() - 1 )
				{
					Value	= (Value + Values.Get_Record_byIndex(i + 1)->asDouble(0)) / 2.0;
				}
			}

			return( true );
		}
	}

	return( false );
}
//---------------------------------------------------------
bool CGrid_Histogram_Surface::Get_Lines(bool bRows)
{
	int			i, j, n_i, n_j;
	CSG_Table	Values;
	CSG_Grid	*pHist;

	//-----------------------------------------------------
	Parameters("HIST")->Set_Value(pHist	= SG_Create_Grid(m_pGrid));

	pHist->Set_NoData_Value_Range(
		m_pGrid->Get_NoData_Value(),
		m_pGrid->Get_NoData_hiValue()
	);

	n_i	= bRows ? Get_NX() : Get_NY();
	n_j	= bRows ? Get_NY() : Get_NX();

	Values.Add_Field(SG_T("Z"), SG_DATATYPE_Double);

	for(i=0; i<n_i; i++)
	{
		Values.Add_Record();
	}

	//-----------------------------------------------------
	for(j=0; j<n_j && Set_Progress(j, n_j); j++)
	{
		for(i=0; i<n_i; i++)
		{
			Values.Get_Record(i)->Set_Value(0, bRows ? m_pGrid->asDouble(i, j) : m_pGrid->asDouble(j, i));
		}

		Values.Set_Index(0, TABLE_INDEX_Ascending);

		for(i=0; i<n_i; i++)
		{
			int		k	= i % 2 ? i / 2 : n_i - 1 - i / 2;

			if( bRows )
			{
				pHist->Set_Value(k, j, Values.Get_Record_byIndex(i)->asDouble(0));
			}
			else
			{
				pHist->Set_Value(j, k, Values.Get_Record_byIndex(i)->asDouble(0));
			}
		}
	}

	//-----------------------------------------------------
	return( true );
}
Beispiel #9
0
//---------------------------------------------------------
int CTL_Extract::Read_File(const SG_Char *File, CSG_Table &Elements)
{
	//-----------------------------------------------------
	CSG_File	Stream;

	if( !Stream.Open(File, SG_FILE_R, false) )
	{
		return( 0 );
	}

	Process_Set_Text(CSG_String::Format("%s: %s", SG_T("scanning"), File));

	//-----------------------------------------------------
	CSG_String	String, Text;

	if( !Stream.Read(String, Stream.Length()) )
	{
		return( 0 );
	}

	//-----------------------------------------------------
	const SG_Char	Function[2][4]	= {	SG_T("_TL"), SG_T("_TW") };

	const SG_Char	*p		= String;

	bool			bLong	= Parameters("LONG")->asBool();

	while( *p != '\0' )
	{
		if(	!(p[0] == Function[0][0] && p[1] == Function[0][1] && p[2] == Function[0][2])
		&&	!(p[0] == Function[1][0] && p[1] == Function[1][1] && p[2] == Function[1][2] && bLong) )
		{
			p	++;
		}
		else
		{
			p	+= Read_Text(p, Text);

			if( Text.Length() > 0 )
			{
				CSG_Table_Record	*pRecord	= Elements.Add_Record();

				pRecord->Set_Value(0, Text);
				pRecord->Set_Value(1, File);
			}
		}
	}

	return( 1 );
}
//---------------------------------------------------------
bool CShapes_Split_by_Attribute::On_Execute(void)
{
	int			iField;
	CSG_Table	*pTable;

	//-----------------------------------------------------
	pTable	= Parameters("TABLE")	->asTable();
	iField	= Parameters("FIELD")	->asInt();

	Parameters("CUTS")->asTableList()->Del_Items();

	//-----------------------------------------------------
	if( pTable->is_Valid() && pTable->Set_Index(iField, TABLE_INDEX_Ascending) )
	{
		CSG_String	sValue;
		CSG_Table	*pCut	= NULL;

		for(int iRecord=0; iRecord<pTable->Get_Count() && Set_Progress(iRecord, pTable->Get_Count()); iRecord++)
		{
			CSG_Table_Record	*pRecord	= pTable->Get_Record_byIndex(iRecord);

			if( !pCut || sValue.Cmp(pRecord->asString(iField)) )
			{
				pCut	= pTable->Get_ObjectType() == DATAOBJECT_TYPE_Shapes
						? SG_Create_Shapes(((CSG_Shapes *)pTable)->Get_Type(), SG_T(""), pTable)
						: SG_Create_Table(pTable);

				pCut->Set_Name(CSG_String::Format(SG_T("%s [%s = %s]"),
					pTable->Get_Name(),
					pTable->Get_Field_Name(iField),
					pRecord->asString(iField)
				));

				Parameters("CUTS")->asTableList()->Add_Item(pCut);

				sValue	= pRecord->asString(iField);
			}

			pCut->Add_Record(pRecord);
		}

		return( pCut != NULL );
	}

	return( false );
}
Beispiel #11
0
//---------------------------------------------------------
CSG_Table CSG_MetaData::asTable(int Flags) const
{
	CSG_Table	t;

	t.Add_Field("NAME" , SG_DATATYPE_String);
	t.Add_Field("VALUE", SG_DATATYPE_String);

	for(int i=0; i<Get_Children_Count(); i++)
	{
		CSG_Table_Record	*r	= t.Add_Record();

		r->Set_Value(0, Get_Child(i)->Get_Name());
		r->Set_Value(1, Get_Child(i)->Get_Content());
	}

	return( t );
}
Beispiel #12
0
//---------------------------------------------------------
CSG_Table CSG_ODBC_Connection::Get_Field_Desc(const CSG_String &Table_Name) const
{
	CSG_Table	Fields;

	Fields.Set_Name(CSG_String::Format(SG_T("%s [%s]"), Table_Name.c_str(), _TL("Field Description")));

	if( is_Connected() )
	{
		try
		{
			int				i, n;
			std_string		s;
			otl_column_desc	*desc;
			otl_stream		Stream;

			Stream.set_all_column_types(otl_all_num2str|otl_all_date2str);

			Stream.open(m_Size_Buffer, CSG_String::Format(SG_T("$SQLColumns $3:'%s'"), Table_Name.c_str()), m_Connection);	// get a list of all columns.

			desc	= Stream.describe_select(n);

			for(i=0; i<n; i++)
			{
				Fields.Add_Field(CSG_String(desc[i].name), SG_DATATYPE_String);
			}

			while( !Stream.eof() )
			{
				CSG_Table_Record	*pField	= Fields.Add_Record();

				for(i=0; i<n; i++)
				{
					Stream >> s;

					pField->Set_Value(i, CSG_String(s.c_str()));
				}
			}
		}
		catch( otl_exception &e )
		{
			_Error_Message(e);
		}
	}

	return( Fields );
}
//---------------------------------------------------------
bool CBifurcation::On_Execute(void)
{
	int					i;
	double				p, r, dr, max, min, seed, nValues, nPreIterations;
	CSG_Table_Record		*pRecord;
	CSG_Table				*pTable;

	nPreIterations	= Parameters("ITERATIONS")->asInt();
	nValues			= Parameters("NVALUES")->asInt();
	seed			= Parameters("SEED")->asDouble();
	min				= Parameters("RANGE")->asRange()->Get_Min();
	max				= Parameters("RANGE")->asRange()->Get_Max();
	dr				= (max - min) / 1000.0;

	pTable			= Parameters("TABLE")->asTable();
	pTable->Destroy();
	pTable->Set_Name(_TL("Feigenbaum's Bifurcation"));

	pTable->Add_Field("Growth"	, SG_DATATYPE_Double);

	for(i=0; i<nValues; i++)
	{
		pTable->Add_Field(CSG_String::Format(SG_T("VALUE_%d"), i + 1), SG_DATATYPE_Double);
	}

	for(r=min; r<=max; r+=dr)
	{
		pRecord	= pTable->Add_Record();
		pRecord->Set_Value(0, r);

		p		= seed;

		for(i=0; i<nPreIterations; i++)
		{
			p		= r * p * (1.0 - p);
		}

		for(i=0; i<nValues; i++)
		{
			p	= r * p * (1.0 - p);
			pRecord->Set_Value(i + 1, p);
		}
	}

	return( true );
}
CCombineGrids::CCombineGrids(void){

	CSG_Table *pLookup;
	CSG_Table_Record *pRecord;

	Parameters.Set_Name(_TL("Combine Grids"));
	Parameters.Set_Description(_TW(
		"(c) 2005 by Victor Olaya."));

	Parameters.Add_Grid(NULL, 
						"GRID1",
						_TL("Grid 1"), 						
						_TL(""), 
						PARAMETER_INPUT);
	
	Parameters.Add_Grid(NULL, 
						"GRID2",
						_TL("Grid 2"), 						
						_TL(""), 
						PARAMETER_INPUT);

	Parameters.Add_Grid(NULL, 
						"RESULT",
						_TL("Result"), 						
						_TL(""), 
						PARAMETER_OUTPUT);

	pLookup	= Parameters.Add_FixedTable(NULL, 
										"LOOKUP", 
										_TL("LookUp Table"),
										_TL(""))->asTable();

	pLookup->Add_Field(_TL("Value in Grid 1"), SG_DATATYPE_Double);
	pLookup->Add_Field(_TL("Value in Grid 2"), SG_DATATYPE_Double);
	pLookup->Add_Field(_TL("Resulting Value"), SG_DATATYPE_Double);

	pRecord	= pLookup->Add_Record();	
	pRecord->Set_Value(0, 0.0);	
	pRecord->Set_Value(1, 0.0);	
	pRecord->Set_Value(2, 0.0);

						
}//constructor
Beispiel #15
0
//---------------------------------------------------------
bool CTable_List::On_Execute(void)
{
	CSG_Table	*pTables	= Parameters("TABLES")->asTable();

	pTables->Destroy();
	pTables->Set_Name(Get_Connection()->Get_Connection() + " [" + _TL("Tables") + "]");

	pTables->Add_Field(_TL("Table"), SG_DATATYPE_String);
	pTables->Add_Field(_TL("Type" ), SG_DATATYPE_String);

	CSG_Strings	Tables;

	if( Get_Connection()->Get_Tables(Tables) )
	{
		CSG_Table	t;

		for(int i=0; i<Tables.Get_Count(); i++)
		{
			CSG_Table_Record	*pTable	= pTables->Add_Record();

			pTable->Set_Value(0, Tables[i]);

			if( Get_Connection()->Table_Load(t, "geometry_columns", "type", CSG_String::Format("f_table_name='%s'", Tables[i].c_str())) && t.Get_Count() == 1 )
			{
				pTable->Set_Value(1, t[0][0].asString());
			}
			else if( Get_Connection()->Table_Load(t, "raster_columns", "*", CSG_String::Format("r_table_name='%s'", Tables[i].c_str())) && t.Get_Count() == 1 )
			{
				pTable->Set_Value(1, "RASTER");
			}
			else
			{
				pTable->Set_Value(1, "TABLE");
			}
		}
	}

	return( pTables->Get_Count() > 0 );
}
//---------------------------------------------------------
CGrid_Value_Replace::CGrid_Value_Replace(void)
{
	//-----------------------------------------------------
	Set_Name		(_TL("Change Grid Values"));

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

	Set_Description	(_TW(
		"Changes values of a grid according to the rules of a user defined lookup table. "
		"Values or value ranges that are not listed in the lookup table remain unchanged. "
		"If the target is not set, the changes will be stored to the original grid. "
	));

	//-----------------------------------------------------
	Parameters.Add_Grid(NULL,
		"INPUT"		, _TL("Grid"),
		_TL(""),
		PARAMETER_INPUT
	);

	Parameters.Add_Grid(NULL,
		"OUTPUT"	, _TL("Changed Grid"),
		_TL(""),
		PARAMETER_OUTPUT_OPTIONAL
	);

	Parameters.Add_Choice(NULL,
		"METHOD"	, _TL("Replace Condition"),
		_TL(""),
		CSG_String::Format("%s|%s|%s|",
			_TL("identity"),
			_TL("range"),
			_TL("synchronize look-up table classification")
		)
	);

	//-----------------------------------------------------
	CSG_Table	*pLUT;

	pLUT	= Parameters.Add_FixedTable(NULL,
		"IDENTITY"	, _TL("Lookup Table"),
		_TL("")
	)->asTable();

	pLUT->Add_Field(_TL("New Value"), SG_DATATYPE_Double);
	pLUT->Add_Field(_TL("Value"    ), SG_DATATYPE_Double);
	pLUT->Add_Record();

	pLUT	= Parameters.Add_FixedTable(NULL,
		"RANGE"		, _TL("Lookup Table"),
		_TL("")
	)->asTable();

	pLUT->Add_Field(_TL("New Value"), SG_DATATYPE_Double);
	pLUT->Add_Field(_TL("Minimum"  ), SG_DATATYPE_Double);
	pLUT->Add_Field(_TL("Maximum"  ), SG_DATATYPE_Double);
	pLUT->Add_Record();

	Parameters.Add_Grid(NULL,
		"GRID"		, _TL("Grid Classification"),
		_TL("Synchronize with look-up table classification of another grid (gui only)."),
		PARAMETER_INPUT
	);
}
//---------------------------------------------------------
bool CTable_PCA::Get_Components(CSG_Matrix &Eigen_Vectors, CSG_Vector &Eigen_Values)
{
    int		i, j, n, field0;
    double	Sum, Cum;

    ///////////////////////////////////////////////////////
    //-----------------------------------------------------
    for(i=0, Sum=0.0; i<m_nFeatures; i++)
    {
        Sum	+= Eigen_Values[i];
    }

    Sum	= Sum > 0.0 ? 100.0 / Sum : 0.0;

    Message_Add(CSG_String::Format(SG_T("\n%s, %s, %s\n"), _TL("explained variance"), _TL("explained cumulative variance"), _TL("Eigenvalue")), false);

    for(j=m_nFeatures-1, Cum=0.0; j>=0; j--)
    {
        Cum	+= Eigen_Values[j] * Sum;

        Message_Add(CSG_String::Format(SG_T("%6.2f\t%6.2f\t%18.5f\n"), Eigen_Values[j] * Sum, Cum, Eigen_Values[j]), false);
    }

    Message_Add(CSG_String::Format(SG_T("\n%s:\n"), _TL("Eigenvectors")), false);

    for(j=0; j<m_nFeatures; j++)
    {
        for(i=0; i<m_nFeatures; i++)
        {
            Message_Add(CSG_String::Format(SG_T("%12.4f"), Eigen_Vectors[j][m_nFeatures - 1 - i]), false);
        }

        Message_Add(SG_T("\n"), false);
    }

    ///////////////////////////////////////////////////////
    //-----------------------------------------------------
    n	= Parameters("NFIRST")->asInt();

    if( n <= 0 || n > m_nFeatures )
    {
        n	= m_nFeatures;
    }

    //-----------------------------------------------------
    CSG_Table	*pPCA	= Parameters("PCA")->asTable();

    if( pPCA == NULL )
    {
        pPCA	= m_pTable;
    }

    if( pPCA != m_pTable )
    {
        pPCA->Destroy();
        pPCA->Set_Name(CSG_String::Format(SG_T("%s [%s]"), m_pTable->Get_Name(), _TL("Principal Components")));
    }

    //-----------------------------------------------------
    field0	= pPCA->Get_Field_Count();

    for(i=0; i<n; i++)
    {
        pPCA->Add_Field(CSG_String::Format(SG_T("%s %d"), _TL("Component"), i + 1), SG_DATATYPE_Double);
    }

    //-----------------------------------------------------
    for(int iElement=0; iElement<m_pTable->Get_Count() && Set_Progress(iElement, m_pTable->Get_Count()); iElement++)
    {
        if( !is_NoData(iElement) )
        {
            CSG_Table_Record	*pElement	= pPCA == m_pTable ? pPCA->Get_Record(iElement) : pPCA->Add_Record();

            for(i=0, j=m_nFeatures-1; i<n; i++, j--)
            {
                double	d	= 0.0;

                for(int k=0; k<m_nFeatures; k++)
                {
                    d	+= Get_Value(k, iElement) * Eigen_Vectors[k][j];
                }

                pElement->Set_Value(field0 + i, d);
            }
        }
    }

    //-----------------------------------------------------
    if( pPCA == m_pTable )
    {
        DataObject_Update(m_pTable);
    }

    return( true );
}
Beispiel #18
0
//---------------------------------------------------------
CPC_Reclass_Extract::CPC_Reclass_Extract(void)
{
	CSG_Parameter	*pNode;

	//-----------------------------------------------------
	Set_Name(_TL("Point Cloud Reclassifier / Subset Extractor"));

	Set_Author(SG_T("Volker Wichmann (c) 2009, LASERDATA GmbH"));

	Set_Description	(_TW(
		"The tool can be used to either reclassify a Point Cloud attribute or to extract "
		"a subset of a Point Cloud based on the values of an attribute.\n\n"
		"The tool provides three different options:\n"
		"(a) reclassification of (or extraction based on) single values,\n"
		"(b) reclassification of (or extraction based on) a range of values and\n"
		"(c) reclassification of (or extraction based on) value ranges specified in a lookup table.\n\n"
		"Each of these three options provides it's own parameters. The 'new value' parameters are "
		"irrelevant in case a subset is extracted.\n\n"
		"In addition to these settings, two special cases ('NoData values' and 'other values' not "
		"included in the parameter setup) are supported:\n"
		"In mode (a) and (b) the 'NoData option' is evaluated before the method settings, in mode "
		"(c) the option is evaluated only if the NoData value isn't included in the lookup table.\n"
		"The 'other values' option is always evaluated after checking the method settings.\n\n")
	);


	//-----------------------------------------------------
	Parameters.Add_PointCloud(
		NULL	, "INPUT"		,_TL("Point Cloud"),
		_TL("Point Cloud to reclassify/extract"),
		PARAMETER_INPUT
	);

	Parameters.Add_Table_Field(
		Parameters("INPUT"), "ATTRIB", _TL("Attribute"),
		_TL("Attribute to process."),
		false
	);

	Parameters.Add_PointCloud(
		NULL	, "RESULT"		, _TL("Result"),
		_TL("Reclassified or extracted Point Cloud."),
		PARAMETER_OUTPUT
	);

	Parameters.Add_Choice(
		NULL	, "MODE"	, _TL("Mode of operation"),
		_TL("Choose whether to reclassify a Point Cloud or to extract a subset from a Point Cloud."),
		_TL("Reclassify|Extract Subset|"), 0
	);

	Parameters.Add_Value(
		NULL	, "CREATE_ATTRIB"	, _TL("Create new Attribute"),
		_TL("Check this to create a new attribute with the reclassification result. If unchecked, the existing attribute is updated."),
		PARAMETER_TYPE_Bool, false
	);

	Parameters.Add_Choice(
		NULL	, "METHOD"		, _TL("Method"),
		_TL("Select the desired method: 1. a single value or a range defined by a single value is reclassified, 2. a range of values is reclassified, 3. the lookup table is used to reclassify the grid."),
		_TL("single|range|simple table|user supplied table|"), 0
	);


	//-----------------------------------------------------
	Parameters.Add_Value(
		NULL	, "OLD"			, _TL("old value"),
		_TL("Value to reclassify."),
		PARAMETER_TYPE_Double, 0
	);

	Parameters.Add_Value(
		NULL	, "NEW"			, _TL("new value"),
		_TL("New value."),
		PARAMETER_TYPE_Double, 1
	);

	Parameters.Add_Choice(
		NULL	, "SOPERATOR"	, _TL("operator"),
		_TL("Select the desired operator (<;.;=; >;.); it is possible to define a range above or below the old value."),

		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|"),
			_TL("="),
			_TL("<"),
			_TL("<="),
			_TL(">="),
			_TL(">")
		), 0
	);

	//-----------------------------------------------------
	Parameters.Add_Value(
		NULL	, "MIN"			, _TL("minimum value"),
		_TL("Minimum value of the range to be reclassified."),
		PARAMETER_TYPE_Double, 0
	);

	Parameters.Add_Value(
		NULL	, "MAX"			, _TL("maximum value"),
		_TL("Maximum value of the range to be reclassified."),
		PARAMETER_TYPE_Double, 10
	);

	Parameters.Add_Value(
		NULL	, "RNEW"		, _TL("new value"),
		_TL("new value"),
		PARAMETER_TYPE_Double, 5
	);

	Parameters.Add_Choice(
		NULL	, "ROPERATOR"	, _TL("operator"),
		_TL("Select operator: eg. min < value < max."),

		CSG_String::Format(SG_T("%s|%s|"),
			_TL("<="),
			_TL("<")
		), 0
	);

	//-----------------------------------------------------
	Parameters.Add_FixedTable(
		NULL	, "RETAB"		, _TL("Lookup Table"),
		_TL("Lookup table used in method \"table\"")
	);

	Parameters.Add_Choice(
		NULL	, "TOPERATOR"	, _TL("operator"),
		_TL("Select the desired operator (min < value < max; min . value < max; min .value . max; min < value . max)."),

		CSG_String::Format(SG_T("%s|%s|%s|%s|"),
			_TL("min <= value < max"),
			_TL("min <= value <= max"),
			_TL("min < value <= max"),
			_TL("min < value < max")
		), 0
	);

	//-----------------------------------------------------
	pNode	= Parameters.Add_Table(
		NULL	, "RETAB_2"		, _TL("Lookup Table"),
		_TL("Lookup table used in method \"user supplied table\""),
		PARAMETER_INPUT_OPTIONAL
	);

	Parameters.Add_Table_Field(
		pNode	, "F_MIN"		, _TL("minimum value"),
		_TL("")
	);

	Parameters.Add_Table_Field(
		pNode	, "F_MAX"		, _TL("maximum value"),
		_TL("")
	);

	Parameters.Add_Table_Field(
		pNode	, "F_CODE"		, _TL("new value"),
		_TL("")
	);

	//-----------------------------------------------------
	pNode	= Parameters.Add_Node(
		NULL, "OPTIONS"			, _TL("Special cases"),
		_TL("Parameter settings for No-Data and all other values.")
	);

	Parameters.Add_Value(
		pNode	, "NODATAOPT"	, _TL("no data values"),
		_TL("Use this option to reclassify No-Data values independently of the method settings."),
		PARAMETER_TYPE_Bool, false
	);

	Parameters.Add_Value(
		Parameters("NODATAOPT")	, "NODATA"		, _TL("new value"),
		_TL("new value"),
		PARAMETER_TYPE_Double, 0
	);

	Parameters.Add_Value(
		pNode	, "OTHEROPT"	, _TL("other values"),
		_TL("Use this option to reclassify all other values that are not specified in the options above."),
		PARAMETER_TYPE_Bool, false
	);

	Parameters.Add_Value(
		Parameters("OTHEROPT")	, "OTHERS"		, _TL("new value"),
		_TL("new value"),
		PARAMETER_TYPE_Double, 0
	);

	//-----------------------------------------------------
	CSG_Table			*pLookup;
	CSG_Table_Record	*pRecord;

	pLookup	= Parameters("RETAB")->asTable();

	pLookup->Add_Field(_TL("minimum")	, SG_DATATYPE_Double);
	pLookup->Add_Field(_TL("maximum")	, SG_DATATYPE_Double);
	pLookup->Add_Field(_TL("new")		, SG_DATATYPE_Double);

	pRecord	= pLookup->Add_Record();	pRecord->Set_Value(0,  0.0);	pRecord->Set_Value(1, 10.0);	pRecord->Set_Value(2, 1.0);
	pRecord	= pLookup->Add_Record();	pRecord->Set_Value(0, 10.0);	pRecord->Set_Value(1, 20.0);	pRecord->Set_Value(2, 2.0);
}
//---------------------------------------------------------
bool CGrid_Value_Replace::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_Grid	*pGrid	= Parameters("OUTPUT")->asGrid();

	if( !pGrid || pGrid == Parameters("INPUT")->asGrid() )
	{
		pGrid	= Parameters("INPUT")->asGrid();
	}
	else
	{
		pGrid->Assign(Parameters("INPUT")->asGrid());

		DataObject_Set_Parameters(pGrid, Parameters("INPUT")->asGrid());

		pGrid->Fmt_Name("%s [%s]", Parameters("INPUT")->asGrid()->Get_Name(), _TL("Changed"));
	}

	//-----------------------------------------------------
	int		Method	= Parameters("METHOD")->asInt();

	CSG_Table	LUT;

	switch( Method )
	{
	default:	LUT.Create(*Parameters("IDENTITY")->asTable());	break;
	case  1:	LUT.Create(*Parameters("RANGE"   )->asTable());	break;
	case  2:	LUT.Create( Parameters("RANGE"   )->asTable());
		if( SG_UI_Get_Window_Main()	// gui only
		&&  DataObject_Get_Parameter(Parameters("GRID" )->asGrid(), "LUT")
		&&  DataObject_Get_Parameter(Parameters("INPUT")->asGrid(), "LUT") )
		{
			CSG_Table	LUTs[2];

			LUTs[0].Create(*DataObject_Get_Parameter(Parameters("GRID" )->asGrid(), "LUT")->asTable());
			LUTs[1].Create(*DataObject_Get_Parameter(Parameters("INPUT")->asGrid(), "LUT")->asTable());

			for(int i=0; i<LUTs[0].Get_Count(); i++)
			{
				CSG_String	Name	= LUTs[0][i].asString(1);

				for(int j=LUTs[1].Get_Count()-1; j>=0; j--)
				{
					if( !Name.Cmp(LUTs[1][j].asString(1)) )
					{
						CSG_Table_Record	*pReplace	= LUT.Add_Record();

						pReplace->Set_Value(0, LUTs[0][i].asDouble(3));
						pReplace->Set_Value(1, LUTs[1][j].asDouble(3));
						pReplace->Set_Value(2, LUTs[1][j].asDouble(4));

						LUTs[1].Del_Record(j);

						break;
					}
				}
			}

			for(int j=0; j<LUTs[1].Get_Count(); j++)
			{
				LUTs[0].Add_Record(LUTs[1].Get_Record(j));
			}

			DataObject_Add(pGrid);
			CSG_Parameter	*pLUT	= DataObject_Get_Parameter(pGrid, "LUT");
			pLUT->asTable()->Assign_Values(&LUTs[0]);
			DataObject_Set_Parameter(pGrid, pLUT);
		}
		break;
	}

	//-----------------------------------------------------
	if( LUT.Get_Count() == 0 )
	{
		Error_Set(_TL("empty look-up table, nothing to replace"));

		return( false );
	}

	//-----------------------------------------------------
	for(int y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		#ifndef _DEBUG
		#pragma omp parallel for
		#endif
		for(int x=0; x<Get_NX(); x++)
		{
			double	Value	= pGrid->asDouble(x, y);

			for(int i=0; i<LUT.Get_Count(); i++)
			{
				if( Method == 0 )
				{
					if( LUT[i].asDouble(1) == Value )
					{
						pGrid->Set_Value(x, y, LUT[i].asDouble(0));

						break;
					}
				}
				else
				{
					if( LUT[i].asDouble(1) <= Value && Value <= LUT[i].asDouble(2) )
					{
						pGrid->Set_Value(x, y, LUT[i].asDouble(0));

						break;
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	if( pGrid == Parameters("INPUT")->asGrid() )
	{
		DataObject_Update(pGrid);
	}

	return( true );
}
//---------------------------------------------------------
bool CPC_Cluster_Analysis::On_Execute(void)
{
	int				nCluster;
	long			nElements;
	double			SP;
	CSG_Parameters Parms;

	m_bUpdateView = false;

	//-----------------------------------------------------
	nCluster	= Parameters("NCLUSTER")->asInt();
	pInput		= Parameters("PC_IN")	->asPointCloud();
	pResult		= Parameters("PC_OUT")	->asPointCloud();

	if( SG_UI_Get_Window_Main() )
		m_bUpdateView = Parameters("UPDATEVIEW")->asBool();

	//-------------------------------------------------
	m_Features	= (int *)Parameters("FIELDS")->asPointer();
	m_nFeatures	=        Parameters("FIELDS")->asInt    ();

	if( !m_Features || m_nFeatures <= 0 )
	{
		Error_Set(_TL("no features in selection"));

		return( false );
	}


	//-----------------------------------------------------
	pResult->Create(pInput);
	pResult->Set_Name(CSG_String::Format(SG_T("%s_cluster"), pInput->Get_Name()));
	pResult->Add_Field(SG_T("CLUSTER"), SG_DATATYPE_Int);
	DataObject_Update(pResult);

	pResult->Set_NoData_Value(-1.0);
	clustField	= pResult->Get_Field_Count() - 1;


	//-----------------------------------------------------
	Process_Set_Text(_TL("Initializing ..."));

	for( int i=0; i<m_nFeatures; i++ )
		vValues.push_back( std::vector<double>() );

	for( int i=0; i<pInput->Get_Record_Count() && SG_UI_Process_Set_Progress(i, pInput->Get_Record_Count()); i++ )
	{
		pResult->Add_Point(pInput->Get_X(i), pInput->Get_Y(i), pInput->Get_Z(i));

		for( int j=0; j<pInput->Get_Attribute_Count(); j++ )
			pResult->Set_Attribute(i, j, pInput->Get_Attribute(i, j));

		pResult->Set_NoData(i, clustField);
		
		bool bNoData = false;

		for( int j=0; j<m_nFeatures; j++)
		{
			if( pInput->is_NoData(i, m_Features[j]) )
			{
				bNoData = true;
				break;
			}
		}

		if( !bNoData )
		{
			for( int j=0; j<m_nFeatures; j++ )
			{
				if( Parameters("NORMALISE")->asBool() )
					vValues.at(j).push_back( (pInput->Get_Value(i, m_Features[j]) - pInput->Get_Mean(m_Features[j])) / pInput->Get_StdDev(m_Features[j]) );
				else
					vValues.at(j).push_back(pInput->Get_Value(i, m_Features[j]));
			}
		}
		else
		{
			for( int j=0; j<m_nFeatures; j++ )
			{
				vValues.at(j).push_back(pInput->Get_NoData_Value());
			}
		}
	}


	if( m_bUpdateView )
	{
		if( DataObject_Get_Parameters(pResult, Parms) && Parms("COLORS_TYPE") && Parms("METRIC_ATTRIB") && Parms("METRIC_COLORS") && Parms("METRIC_ZRANGE") )
		{
			Parms("COLORS_TYPE")					->Set_Value(2);			// graduated color
			Parms("METRIC_COLORS")->asColors()		->Set_Count(nCluster);
			Parms("METRIC_ATTRIB")					->Set_Value(clustField);
			Parms("METRIC_ZRANGE")->asRange()		->Set_Range(0, nCluster);
		}
		DataObject_Set_Parameters(pResult, Parms);
		DataObject_Update(pResult, SG_UI_DATAOBJECT_SHOW_LAST_MAP);
	}


	nMembers	= (int     *)SG_Malloc(nCluster * sizeof(int));
	Variances	= (double  *)SG_Malloc(nCluster * sizeof(double));
	Centroids	= (double **)SG_Malloc(nCluster * sizeof(double *));

	for( int i=0; i<nCluster; i++ )
	{
		Centroids[i]	= (double  *)SG_Malloc(m_nFeatures * sizeof(double));
	}

	//-------------------------------------------------
	nElements	= pInput->Get_Point_Count();

	switch( Parameters("METHOD")->asInt() )
	{
	case 0:
		SP	= MinimumDistance	(nElements, nCluster);
		break;

	case 1:
		SP	= HillClimbing		(nElements, nCluster);
		break;

	case 2:
		SP	= MinimumDistance	(nElements, nCluster);

		nElements	= pInput->Get_Point_Count();	// may have been diminished because of no data values...

		SP	= HillClimbing		(nElements, nCluster);
		break;
	}

	//-------------------------------------------------
	if( Parameters("NORMALISE")->asBool() )
	{
		int		iv = 0;

		for( int i=0; i<m_nFeatures; i++ )
		{
			for( int j=0; j<nCluster; j++ )
			{
				Centroids[j][iv]	= sqrt(pInput->Get_Variance(m_Features[i])) * Centroids[j][iv] + pInput->Get_Mean(m_Features[i]);
			}

			iv++;
		}
	}

	Write_Result(Parameters("STATISTICS")->asTable(), nElements, nCluster, SP);

	//-------------------------------------------------
	if( DataObject_Get_Parameters(pResult, Parms) && Parms("COLORS_TYPE") && Parms("LUT") && Parms("LUT_ATTRIB") )
	{
		CSG_Table_Record	*pClass;
		CSG_Table			*pLUT	= Parms("LUT")->asTable();

		for( int i=0; i<nCluster; i++ )
		{
			if( (pClass = pLUT->Get_Record(i)) == NULL )
			{
				pClass	= pLUT->Add_Record();
				pClass->Set_Value(0, SG_GET_RGB(rand() * 255.0 / RAND_MAX, rand() * 255.0 / RAND_MAX, rand() * 255.0 / RAND_MAX));
			}

			pClass->Set_Value(1, CSG_String::Format(SG_T("%s %d"), _TL("Class"), i));
			pClass->Set_Value(2, CSG_String::Format(SG_T("%s %d"), _TL("Class"), i));
			pClass->Set_Value(3, i);
			pClass->Set_Value(4, i);
		}

		while( pLUT->Get_Record_Count() > nCluster )
		{
			pLUT->Del_Record(pLUT->Get_Record_Count() - 1);
		}

		Parms("COLORS_TYPE")	->Set_Value(1);	// Color Classification Type: Lookup Table
		Parms("LUT_ATTRIB")		->Set_Value(clustField);

		DataObject_Set_Parameters(pResult, Parms);
	}

	//-------------------------------------------------
	for( int i=0; i<nCluster; i++ )
	{
		SG_Free(Centroids[i]);
	}

	SG_Free(Centroids);
	SG_Free(Variances);
	SG_Free(nMembers);

	vValues.clear();

	return( true );
}
Beispiel #21
0
//---------------------------------------------------------
bool CSG_ODBC_Connection::_Table_Load(CSG_Table &Table, const CSG_String &Select, const CSG_String &Name, bool bLOB)
{
	//-----------------------------------------------------
	if( !is_Connected() )
	{
		_Error_Message(_TL("no database connection"));

		return( false );
	}

	//-----------------------------------------------------
	try
	{
		int				valInt, iField, nFields;
		long			valLong;
		float			valFloat;
		double			valDouble;
		std_string		valString;
		otl_long_string	valRaw(m_Connection.get_max_long_size());
		otl_column_desc	*Fields;
		otl_stream		Stream;
		CSG_Bytes		BLOB;

		Stream.set_all_column_types	(otl_all_date2str);
		Stream.set_lob_stream_mode	(bLOB);
		Stream.open					(bLOB ? 1 : m_Size_Buffer, Select, m_Connection);

		Fields	= Stream.describe_select(nFields);

		if( Fields == NULL || nFields <= 0 )
		{
			_Error_Message(_TL("no fields in selection"));

			return( false );
		}

		//-------------------------------------------------
		Table.Destroy();
		Table.Set_Name(Name);

		for(iField=0; iField<nFields; iField++)
		{
			if( _Get_Type_From_SQL(Fields[iField].otl_var_dbtype) == SG_DATATYPE_Undefined )
			{
				return( false );
			}

			Table.Add_Field(Fields[iField].name, _Get_Type_From_SQL(Fields[iField].otl_var_dbtype));
		}

		//-------------------------------------------------
		while( !Stream.eof() && SG_UI_Process_Get_Okay() )	// while not end-of-data
		{
			CSG_Table_Record	*pRecord	= Table.Add_Record();

			for(iField=0; iField<nFields; iField++)
			{
				switch( Table.Get_Field_Type(iField) )
				{
				case SG_DATATYPE_String:	Stream >> valString; if( Stream.is_null() ) pRecord->Set_NoData(iField); else pRecord->Set_Value(iField, CSG_String(valString.c_str()));	break;
				case SG_DATATYPE_Short:			
				case SG_DATATYPE_Int:		Stream >> valInt;    if( Stream.is_null() ) pRecord->Set_NoData(iField); else pRecord->Set_Value(iField, valInt);		break;
				case SG_DATATYPE_DWord:
				case SG_DATATYPE_Long:		Stream >> valLong;   if( Stream.is_null() ) pRecord->Set_NoData(iField); else pRecord->Set_Value(iField, valLong);		break;
				case SG_DATATYPE_Float:		Stream >> valFloat;  if( Stream.is_null() ) pRecord->Set_NoData(iField); else pRecord->Set_Value(iField, valFloat);		break;
				case SG_DATATYPE_Double:	Stream >> valDouble; if( Stream.is_null() ) pRecord->Set_NoData(iField); else pRecord->Set_Value(iField, valDouble);	break;
				case SG_DATATYPE_Binary:	Stream >> valRaw;    if( Stream.is_null() ) pRecord->Set_NoData(iField); else
					{
						BLOB.Clear();

						for(int i=0; i<valRaw.len(); i++)
						{
							BLOB.Add((BYTE)valRaw[i]);
						}

						pRecord->Set_Value(iField, BLOB);
					}
					break;
				}
			}
		}
	}
	//-----------------------------------------------------
	catch( otl_exception &e )
	{
		_Error_Message(e);

		return( false );
	}

	return( true );
}
//---------------------------------------------------------
bool CGrid_Aspect_Slope_Map::On_Execute(void)
{
	CSG_Grid	*pAspect, *pSlope, *pAspectSlope;
	CSG_Table	*pLUT;

	int						iAspectCount	= 9;
	static const double		AspectBreaks[]	= {0.000, 0.393, 1.178, 1.963, 2.749, 3.534, 4.320, 5.105, 5.890, 6.283};
	static const int		AspectClass[]	= {1, 2, 3, 4, 5, 6, 7, 8, 1};

	int						iSlopeCount		= 4;
	static const double		SlopeBreaks[]	= {0.000, 0.087, 0.349, 0.698, 1.571};
	static const int		SlopeClass[]	= {10, 20, 30, 40};


	pAspect			= Parameters("ASPECT")->asGrid();
	pSlope			= Parameters("SLOPE")->asGrid();
	pAspectSlope	= Parameters("ASPECT_SLOPE")->asGrid();
	pLUT			= Parameters("LUT")->asTable();


	//-----------------------------------------------------
	if( pLUT == NULL )
		pLUT = new CSG_Table();
	else
		pLUT->Destroy();

	pLUT->Set_Name(SG_T("LUT_Aspect-Slope"));

	pLUT->Add_Field(SG_T("COLOR"),			SG_DATATYPE_Int);
	pLUT->Add_Field(SG_T("NAME"),			SG_DATATYPE_String);
	pLUT->Add_Field(SG_T("DESCRIPTION"),	SG_DATATYPE_String);
	pLUT->Add_Field(SG_T("MINIMUM"),		SG_DATATYPE_Int);
	pLUT->Add_Field(SG_T("MAXIMUM"),		SG_DATATYPE_Int);

	for(int i=0; i<25; i++)
	{
		CSG_Table_Record	*pRecord = pLUT->Add_Record();

		pRecord->Set_Value(0, LUT_COLOR[i]);
		pRecord->Set_Value(1, LUT_NAME[i]);
		pRecord->Set_Value(2, SG_T(""));
		pRecord->Set_Value(3, LUT_BREAK[i]);
		pRecord->Set_Value(4, LUT_BREAK[i+1]);
	}


	//-----------------------------------------------------
	#pragma omp parallel for
	for(sLong n=0; n<Get_NCells(); n++)
	{
		int		iAspectClass, iSlopeClass;

		if( pAspect->is_NoData(n) || pSlope->is_NoData(n) )
		{
			pAspectSlope->Set_NoData(n);
		}
		else
		{
			iAspectClass	= Get_Class(pAspect->asDouble(n), iAspectCount, AspectBreaks, AspectClass);
			iSlopeClass		= Get_Class(pSlope->asDouble(n), iSlopeCount, SlopeBreaks, SlopeClass);

			pAspectSlope->Set_Value(n, iAspectClass + iSlopeClass);
		}
	}


	//-----------------------------------------------------
	CSG_Parameters	Parms;

	if( DataObject_Get_Parameters(pAspectSlope, Parms) && Parms("COLORS_TYPE") && Parms("LUT") )
	{
		Parms("LUT")->asTable()->Assign(pLUT);
		Parms("COLORS_TYPE")->Set_Value(1);

		DataObject_Set_Parameters(pAspectSlope, Parms);
	}

	if( Parameters("LUT")->asTable() == NULL )
	{
		delete pLUT;
	}


	//-----------------------------------------------------
	return( true );
}
//---------------------------------------------------------
bool CGSPoints_Semi_Variances::On_Execute(void)
{
	int					i, j, k, n, nDistances, nSkip, Attribute;
	double				zi, zj, zMean, v, c, maxDistance, lagDistance;
	TSG_Point			Pt_i, Pt_j;
	CSG_Vector			Count, Variance, Covariance;
	CSG_Table_Record	*pRecord;
	CSG_Table			*pTable;
	CSG_Shape			*pPoint;
	CSG_Shapes			*pPoints;

	//-----------------------------------------------------
	pPoints		= Parameters("POINTS")		->asShapes();
	pTable		= Parameters("RESULT")		->asTable();
	Attribute	= Parameters("FIELD")		->asInt();
	nSkip		= Parameters("NSKIP")		->asInt();
	maxDistance	= Parameters("DISTMAX")		->asDouble();
	nDistances	= Parameters("DISTCOUNT")	->asInt();

	if( maxDistance <= 0.0 )
	{
		maxDistance	= SG_Get_Length(pPoints->Get_Extent().Get_XRange(), pPoints->Get_Extent().Get_YRange());
	}

	lagDistance	= maxDistance / nDistances;

	zMean		= pPoints->Get_Mean(Attribute);

	Count		.Create(nDistances);
	Variance	.Create(nDistances);
	Covariance	.Create(nDistances);

	//-----------------------------------------------------
	for(i=0, n=0; i<pPoints->Get_Count() && Set_Progress(n, SG_Get_Square(pPoints->Get_Count()/nSkip)/2); i+=nSkip)
	{
		pPoint	= pPoints->Get_Shape(i);

		if( !pPoint->is_NoData(Attribute) )
		{
			Pt_i	= pPoint->Get_Point(0);
			zi		= pPoint->asDouble(Attribute);

			for(j=i+nSkip; j<pPoints->Get_Count(); j+=nSkip, n++)
			{
				pPoint	= pPoints->Get_Shape(j);

				if( !pPoint->is_NoData(Attribute) )
				{
					Pt_j	= pPoint->Get_Point(0);
					k		= (int)(SG_Get_Distance(Pt_i, Pt_j) / lagDistance);

					if( k < nDistances )
					{
						zj	= pPoint->asDouble(Attribute);

						v	= SG_Get_Square(zi - zj);
						c	= (zi - zMean) * (zj - zMean);

						Count	  [k]	++;
						Variance  [k]	+= v;
						Covariance[k]	+= c;
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	pTable->Destroy();
	pTable->Set_Name(CSG_String::Format(SG_T("%s [%s: %s]"), pPoints->Get_Name(), _TL("Variogram"), pPoints->Get_Field_Name(Attribute)));
	pTable->Add_Field(_TL("Class")		, SG_DATATYPE_Int);		// FIELD_CLASSNR
	pTable->Add_Field(_TL("Distance")	, SG_DATATYPE_Double);	// FIELD_DISTANCE
	pTable->Add_Field(_TL("Count")		, SG_DATATYPE_Int);		// FIELD_COUNT
	pTable->Add_Field(_TL("Variance")	, SG_DATATYPE_Double);	// FIELD_VARIANCE
	pTable->Add_Field(_TL("Cum.Var.")	, SG_DATATYPE_Double);	// FIELD_VARCUMUL
	pTable->Add_Field(_TL("Covariance")	, SG_DATATYPE_Double);	// FIELD_COVARIANCE
	pTable->Add_Field(_TL("Cum.Covar.")	, SG_DATATYPE_Double);	// FIELD_COVARCUMUL

	for(i=0, v=0.0, c=0.0, n=0; i<nDistances; i++)
	{
		if( Count[i] > 0 )
		{
			n	+= (int)Count[i];
			v	+= Variance  [i];
			c	+= Covariance[i];

			pRecord	= pTable->Add_Record();
			pRecord->Set_Value(FIELD_CLASSNR	, (i + 1));
			pRecord->Set_Value(FIELD_DISTANCE	, (i + 1) * lagDistance);
			pRecord->Set_Value(FIELD_COUNT		, Count[i]);
			pRecord->Set_Value(FIELD_VARIANCE	, 0.5 * Variance  [i] / Count[i]);
			pRecord->Set_Value(FIELD_VARCUMUL	, 0.5 * v / n);
			pRecord->Set_Value(FIELD_COVARIANCE	, 1.0 * Covariance[i] / Count[i]);
			pRecord->Set_Value(FIELD_COVARCUMUL	, 1.0 * c / n);
		}
	}

	return( true );
}
//---------------------------------------------------------
bool CChange_Detection::Get_Classes(CSG_Table &Classes, CSG_Grid *pGrid, bool bInitial)
{
	CSG_Table	*pClasses;

	Classes.Destroy();

	Classes.Add_Field(_TL("NAME")	, SG_DATATYPE_String);
	Classes.Add_Field(_TL("MIN")	, SG_DATATYPE_Double);
	Classes.Add_Field(_TL("MAX")	, SG_DATATYPE_Double);

	//-----------------------------------------------------
	if( (pClasses = Parameters(bInitial ? "INI_LUT" : "FIN_LUT")->asTable()) != NULL )
	{
		int	fNam	= Parameters(bInitial ? "INI_LUT_NAM" : "FIN_LUT_NAM")->asInt();
		int	fMin	= Parameters(bInitial ? "INI_LUT_MIN" : "FIN_LUT_MIN")->asInt();
		int	fMax	= Parameters(bInitial ? "INI_LUT_MAX" : "FIN_LUT_MAX")->asInt();

		if( fNam < 0 || fNam >= pClasses->Get_Field_Count() )	{	fNam	= fMin;	}
		if( fMax < 0 || fMax >= pClasses->Get_Field_Count() )	{	fMax	= fMin;	}

		for(int iClass=0; iClass<pClasses->Get_Count(); iClass++)
		{
			CSG_Table_Record	*pClass	= Classes.Add_Record();

			pClass->Set_Value(CLASS_NAM, pClasses->Get_Record(iClass)->asString(fNam));
			pClass->Set_Value(CLASS_MIN, pClasses->Get_Record(iClass)->asDouble(fMin));
			pClass->Set_Value(CLASS_MAX, pClasses->Get_Record(iClass)->asDouble(fMax));
		}
	}

	//-----------------------------------------------------
	else if( DataObject_Get_Parameter(pGrid, "LUT") )
	{
		pClasses	= DataObject_Get_Parameter(pGrid, "LUT")->asTable();

		for(int iClass=0; iClass<pClasses->Get_Count(); iClass++)
		{
			CSG_Table_Record	*pClass	= Classes.Add_Record();

			pClass->Set_Value(CLASS_NAM, pClasses->Get_Record(iClass)->asString(1));
			pClass->Set_Value(CLASS_MIN, pClasses->Get_Record(iClass)->asDouble(3));
			pClass->Set_Value(CLASS_MAX, pClasses->Get_Record(iClass)->asDouble(4));
		}
	}

	//-----------------------------------------------------
	else
	{
		double	z;

		for(sLong i=0; i<Get_NCells() && Set_Progress_NCells(i); i++)
		{
			double iz	= pGrid->asDouble(pGrid->Get_Sorted(i, false, false));

			if( i == 0 || iz != z )
			{
				CSG_Table_Record	*pClass	= Classes.Add_Record();

				pClass->Set_Value(CLASS_NAM, z = iz);
				pClass->Set_Value(CLASS_MIN, z);
				pClass->Set_Value(CLASS_MAX, z);
			}
		}
	}

	//-----------------------------------------------------
	return( Classes.Get_Count() > 0 );
}
//---------------------------------------------------------
bool CChange_Detection::On_Execute(void)
{
	bool		bNoChange;
	int			iInitial, iFinal;
	CSG_Matrix	Identity;
	CSG_Table	Initial, Final, *pChanges;
	CSG_Grid	*pInitial, *pFinal, *pChange;

	//-----------------------------------------------------
	pInitial	= Parameters("INITIAL")	->asGrid();
	pFinal		= Parameters("FINAL")	->asGrid();
	pChange		= Parameters("CHANGE")	->asGrid();
	pChanges	= Parameters("CHANGES")	->asTable();
	bNoChange	= Parameters("NOCHANGE")->asBool();

	if( !Get_Classes(Initial, pInitial, true) )
	{
		Error_Set(_TL("no class definitions for initial state"));

		return( false );
	}

	if( !Get_Classes(Final, pFinal, false) )
	{
		Error_Set(_TL("no class definitions for final state"));

		return( false );
	}

	if( !Get_Changes(Initial, Final, pChanges, Identity) )
	{
		return( false );
	}

	//-----------------------------------------------------
	for(int y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		for(int x=0; x<Get_NX(); x++)
		{
			iInitial	= Get_Class(Initial, pInitial->asDouble(x, y));
			iFinal		= Get_Class(Final  , pFinal  ->asDouble(x, y));

			if( bNoChange || !Identity[iInitial][iFinal] )
			{
				pChanges->Get_Record(iInitial)->Add_Value(1 + iFinal, 1);

				pChange->Set_Value(x, y, (pChanges->Get_Field_Count() - 1) * iInitial + iFinal);
			}
			else
			{
				pChange->Set_Value(x, y, -1);
			}
		}
	}

	//-----------------------------------------------------
	CSG_Parameters	P;

	if( DataObject_Get_Parameters(pChange, P) && P("COLORS_TYPE") && P("LUT") )
	{
		CSG_Table	*pLUT	= P("LUT")->asTable();

		CSG_Colors	cRandom(pChanges->Get_Count());

		cRandom.Random();

		pLUT->Del_Records();

		for(iInitial=0; iInitial<pChanges->Get_Count(); iInitial++)
		{
			CSG_Colors	cRamp(pChanges->Get_Field_Count() - 1);

			cRamp.Set_Ramp(cRandom[iInitial], cRandom[iInitial]);
			cRamp.Set_Ramp_Brighness(225, 50);

			for(iFinal=0; iFinal<pChanges->Get_Field_Count()-1; iFinal++)
			{
				if( pChanges->Get_Record(iInitial)->asInt(1 + iFinal) > 0 )
				{
					CSG_Table_Record	*pClass	= pLUT->Add_Record();

					pClass->Set_Value(0, cRamp.Get_Color(iFinal));
					pClass->Set_Value(1, CSG_String::Format(SG_T("%s >> %s"), pChanges->Get_Record(iInitial)->asString(0), pChanges->Get_Field_Name(1 + iFinal)));
					pClass->Set_Value(3, (pChanges->Get_Field_Count() - 1) * iInitial + iFinal);
					pClass->Set_Value(4, (pChanges->Get_Field_Count() - 1) * iInitial + iFinal);
				}
			}
		}

		P("COLORS_TYPE")->Set_Value(1);	// Color Classification Type: Lookup Table

		DataObject_Set_Parameters(pChange, P);
	}

	//-----------------------------------------------------
	double	Factor;

	switch( Parameters("OUTPUT")->asInt() )
	{
	default:	Factor	= 1.0;						break;	// cells
	case 1:		Factor	= 100.0 / Get_NCells();		break;	// percent
	case 2:		Factor	= M_SQR(Get_Cellsize());	break;	// area
	}

	if( Factor != 1.0 )
	{
		for(iInitial=0; iInitial<pChanges->Get_Count(); iInitial++)
		{
			for(iFinal=0; iFinal<pChanges->Get_Field_Count()-1; iFinal++)
			{
				pChanges->Get_Record(iInitial)->Mul_Value(1 + iFinal, Factor);
			}
		}
	}

	//-----------------------------------------------------
	pChanges	->Set_Name(CSG_String::Format(SG_T("%s [%s >> %s]"), _TL("Changes"), pInitial->Get_Name(), pFinal->Get_Name()));

	pChange		->Set_Name(CSG_String::Format(SG_T("%s [%s >> %s]"), _TL("Changes"), pInitial->Get_Name(), pFinal->Get_Name()));
	pChange		->Set_NoData_Value(-1);

	return( true );
}
//---------------------------------------------------------
bool CTOBIA::On_Execute(void)
{
	double		fB	= Parameters("fB")->asDouble();
	double		fC	= Parameters("fC")->asDouble();
	
	CSG_Grid	*pA, *pB, *pC, *pD, *pE, *pF;

	pA	= Parameters("A"	)->asGrid();		//slope
	pB	= Parameters("B"	)->asGrid();		//aspect
	pC	= Parameters("C"	)->asGrid();		//dip grid
	pD	= Parameters("D"	)->asGrid();		//dip dir grid
	pE	= Parameters("E"	)->asGrid();		//output TOBIA classes
	pF	= Parameters("F"	)->asGrid();		//output TOBIA index
	

	for(int y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		#pragma omp parallel for
		for(int x=0; x<Get_NX(); x++)
		{
			double a, b, c, d, e, f;
		
			a	=	pA->asDouble(x, y);
			b	=	pB->asDouble(x, y);						//Abfrage ob Raster oder Globalwerte
			c	=	pC ? pC->asDouble(x, y) : fB;
			d	=	pC ? pD->asDouble(x, y) : fC;

			if (pA->is_NoData(x, y))
			{
				pE->Set_NoData(x, y);

				if (pF)
					pF->Set_NoData(x, y);

			}

			else if ((pC || pD) && (pC->is_NoData(x, y) || (pD->is_NoData(x, y))))
			{
				pE->Set_NoData(x, y);

				if (pF)
					pF->Set_NoData(x, y);

			}

			else
			{

				e	=	pow(pow((cos(d/57.2958) - cos(b)), 2) + pow((sin(d/57.2958) - sin(b)), 2), 0.5);												//TOBIA-classes
		
				if (((0 <= e) && (e < 0.7654)) && ((c - (a*57.2958)) > 5))
					pE->Set_Value(x, y, TO_UNDERDIP_SLOPE);
				else if (((0 <= e) && (e < 0.7654)) && ((-5 <= (c - (a*57.2958))) && ((c - (a*57.2958) <= 5))))
					pE->Set_Value(x, y, TO_DIP_SLOPE);
				else if (((0 <= e) && (e < 0.7654)) && ((c - (a*57.2958)) < -5))
					pE->Set_Value(x, y, TO_OVERDIP_SLOPE);
				else if (((1.8478 < e) && (e <= 2)) && ((c - (a*57.2958)) < -5))
					pE->Set_Value(x, y, TO_STEEPENED_ESCARPMENT);
				else if (((1.8478 < e) && (e <= 2)) && ((-5 <= (c - (a*57.2958))) && ((c - (a*57.2958) <= 5))))
					pE->Set_Value(x, y, TO_NORMAL_ESCARPMENT);
				else if (((1.8478 < e) && (e <= 2)) && ((c - (a*57.2958)) > 5))
					pE->Set_Value(x, y, TO_SUBDUED_ESCARPMENT);
				else if ((0.7654 < e) && (e <= 1.8478))
					pE->Set_Value(x, y, TO_ORTHOCLINAL_SLOPE);
				else
					pE->Set_NoData_Value(0);

				if (pF)
				{
					f	=	(cos((c/57.2958)) * (cos(a))) + (sin(c/57.2958) * sin(a) * ((cos((d/57.2958) - b))));				//TOBIA-index
					pF->Set_Value(x, y, f);
				}

			}
		}
	}

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

	CSG_Parameters	P;

	if( DataObject_Get_Parameters(pE, P) && P("COLORS_TYPE") && P("LUT") )
	{
		int TO_Colors[TO_COUNT]	=
		{
			SG_GET_RGB(255, 255,   0),	// TO_UNDERDIP
			SG_GET_RGB(255,	128,   0),	// TO_DIP
			SG_GET_RGB(255,   0,   0),	// TO_OVERDIP
			SG_GET_RGB(  0,   0, 128),	// TO_STEEPENED
			SG_GET_RGB(  0, 128, 255),	// TO_NORMAL
			SG_GET_RGB(128, 255, 255),	// TO_SUBDUED
			SG_GET_RGB(  0, 255,  64),  // TO_ORTHOCLINAL
		};

		//-------------------------------------------------
		CSG_Strings	Name, Desc;

		Name	+= _TL("Underdip slope");			Desc	+= _TL("");
		Name	+= _TL("Dip slope");				Desc	+= _TL("");
		Name	+= _TL("Overdip slope");			Desc	+= _TL("");
		Name	+= _TL("Steepened escarpment");		Desc	+= _TL("");
		Name	+= _TL("Normal escarpment");		Desc	+= _TL("");
		Name	+= _TL("Subdued escarpment");		Desc	+= _TL("");
		Name	+= _TL("Orthoclinal slope");		Desc	+= _TL("");
		

		//-------------------------------------------------
		CSG_Table	*pTable	= P("LUT")->asTable();

		pTable->Del_Records();

		for(int i=0; i<TO_COUNT; i++)
		{
			CSG_Table_Record	*pRecord	= pTable->Add_Record();

			pRecord->Set_Value(0, TO_Colors[i]);
			pRecord->Set_Value(1, Name[i].c_str());
			pRecord->Set_Value(2, Desc[i].c_str());
			pRecord->Set_Value(3, i);
			pRecord->Set_Value(4, i);
		}

		P("COLORS_TYPE")->Set_Value(1);	// Color Classification Type: Lookup Table

		DataObject_Set_Parameters(pE, P);
	}

	return( true );
}
Beispiel #27
0
//---------------------------------------------------------
bool CWator::On_Execute(void)
{
	//-----------------------------------------------------
	m_pWator	= m_Grid_Target.Get_Grid("GRID", SG_DATATYPE_Byte);

	if( !m_pWator )
	{
		Error_Set(_TL("could not create target grid"));

		return( false );
	}

	//-----------------------------------------------------
	m_pWator->Set_Name(_TL("Wa-Tor"));
	m_pWator->Set_NoData_Value(-1);

	CSG_Colors	Colors(3);

	Colors.Set_Color(0, SG_COLOR_BLACK);
	Colors.Set_Color(1, SG_COLOR_GREEN);
	Colors.Set_Color(2, SG_COLOR_RED  );

	DataObject_Add       (m_pWator);
	DataObject_Set_Colors(m_pWator, Colors);
	DataObject_Update    (m_pWator, 0, 2, SG_UI_DATAOBJECT_SHOW);

	//-----------------------------------------------------
	if( Parameters("REFRESH")->asBool() )
	{
		double	Fish_perc	= Parameters("INIT_FISH" )->asDouble();
		double	Shark_perc	= Parameters("INIT_SHARK")->asDouble() + Fish_perc;

		#pragma omp parallel for
		for(int y=0; y<m_pWator->Get_NY(); y++)
		{
			for(int x=0; x<m_pWator->Get_NX(); x++)
			{
				double	perc	= CSG_Random::Get_Uniform(0, 100);

				if( perc <= Fish_perc )
				{
					m_pWator->Set_Value(x, y, FISH);
				}
				else if( perc <= Shark_perc )
				{
					m_pWator->Set_Value(x, y, SHARK);
				}
				else
				{
					m_pWator->Set_Value(x, y, 0);
				}
			}
		}
	}

	//-----------------------------------------------------
	CSG_Table	*pTable	= Parameters("TABLE")->asTable();

	pTable->Destroy();
	pTable->Set_Name(_TL("Wa-Tor"));

	pTable->Add_Field("Cycle" , SG_DATATYPE_Int);
	pTable->Add_Field("Fishes", SG_DATATYPE_Int);
	pTable->Add_Field("Sharks", SG_DATATYPE_Int);

	//-----------------------------------------------------
	m_Fish_Birth	= Parameters("FISH_BIRTH"  )->asInt();
	m_Shark_Birth	= Parameters("SHARK_BIRTH" )->asInt();
	m_Shark_Starve	= Parameters("SHARK_STARVE")->asInt();

	m_Next  .Create(m_pWator, SG_DATATYPE_Byte);
	m_Age   .Create(m_pWator, SG_DATATYPE_Byte);
	m_Starve.Create(m_pWator, SG_DATATYPE_Byte);

	#pragma omp parallel for
	for(int y=0; y<m_pWator->Get_NY(); y++)
	{
		for(int x=0; x<m_pWator->Get_NX(); x++)
		{
			switch( m_pWator->asByte(x, y) )
			{
			case FISH:
				m_Age   .Set_Value(x, y, CSG_Random::Get_Uniform(0.0, m_Fish_Birth  ));
				break;

			case SHARK:
				m_Age   .Set_Value(x, y, CSG_Random::Get_Uniform(0.0, m_Shark_Birth ));
				m_Starve.Set_Value(x, y, CSG_Random::Get_Uniform(0.0, m_Shark_Starve));
				break;
			}
		}
	}

	//-----------------------------------------------------
	int		i;

	SG_UI_Progress_Lock(true);

	for(i=1; Process_Get_Okay(true) && Next_Cycle(); i++)
	{
		Process_Set_Text("%s: %d", _TL("Life Cycle"), i);

		CSG_Table_Record	*pRecord	= pTable->Add_Record();

		pRecord->Set_Value(0, i);
		pRecord->Set_Value(1, m_nFishes);
		pRecord->Set_Value(2, m_nSharks);

		DataObject_Update(m_pWator, 0, 2);
		DataObject_Update(pTable);
	}

	SG_UI_Progress_Lock(false);

	//-----------------------------------------------------
	m_Next  .Destroy();
	m_Age   .Destroy();
	m_Starve.Destroy();

	if( is_Progress() )
	{
		Message_Fmt("\n%s %d %s", _TL("Dead after"), i, _TL("Life Cycles"));
	}

	return( true );
}
//---------------------------------------------------------
bool CGSGrid_Zonal_Statistics::On_Execute(void)
{
	bool					bShortNames;
	int						x, y, nCatGrids, nStatGrids, iGrid, zoneID, catID, NDcount, catLevel, NDcountStat;
	double					statID;

	CSG_Grid				*pZones, *pGrid, *pAspect;
	CSG_Parameter_Grid_List	*pCatList;
	CSG_Parameter_Grid_List	*pStatList;

	CList_Conti				*newZone, *startList, *runList, *newSub, *parent, *runSub, *subList;
	CList_Stat				*runStats;
	CSG_Table				*pOutTab;
	CSG_Table_Record		*pRecord;
	CSG_String				fieldName, tmpName;


	pZones		= Parameters("ZONES")		->asGrid();
	pCatList	= Parameters("CATLIST")		->asGridList();
	pStatList	= Parameters("STATLIST")	->asGridList();
	pAspect		= Parameters("ASPECT")		->asGrid();
	pOutTab		= Parameters("OUTTAB")		->asTable();
	bShortNames	= Parameters("SHORTNAMES")	->asBool();

	nCatGrids	= pCatList	->Get_Count();
	nStatGrids	= pStatList	->Get_Count();
	
	NDcount		= 0;						// NoData Counter (ZoneGrid)
	NDcountStat	= 0;						// NoData Counter (StatGrids)

	if (pOutTab != NULL)
		pOutTab->Destroy();

	newZone		= new CList_Conti();								// create first list entry (dummy)
	startList	= newZone;

	for(y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		for(x=0; x<Get_NX(); x++)
		{	
			runList		= startList;
			zoneID		= pZones->asInt(x, y);								// get zone ID

			while( runList->next != NULL && runList->cat < zoneID )			// search for last entry in list or insert point
			{
				runList = runList->next;
			}

			if( runList->dummy == true )
			{
				runList->cat = zoneID;										// first list entry, write and
				runList->dummy = false;										// setup
			}
			else if( runList->cat == zoneID )
				runList = runList;											// zoneID found				
			else if( runList->next == NULL && runList->cat < zoneID )		// append zoneID
			{
				newZone = new CList_Conti();
				newZone->previous	= runList;
				runList->next		= newZone;

				newZone->cat	= zoneID;									// ... and write info		
				newZone->dummy	= false;
				runList			= newZone;
			}
			else															// insert new entry
			{
				newZone = new CList_Conti();

				newZone->next = runList;
				if( runList->previous != NULL )
				{
					newZone->previous = runList->previous;
					runList->previous->next = newZone;
				}
				runList->previous = newZone;
					
				if( runList == startList )
					startList = newZone;									// if new entry is first element, update startList pointer

				newZone->cat	= zoneID;									// ... and write info
				newZone->dummy	= false;
				runList			= newZone;
			}


			for(iGrid=0; iGrid<nCatGrids; iGrid++)							// collect categories
			{
				parent  = runList;
				if( runList->sub == NULL )									// no sub class found
				{
					newSub = new CList_Conti();
					runList->sub = newSub;
				}

				runList = runList->sub;

				pGrid	= pCatList->asGrid(iGrid);
				if( !pGrid->is_NoData(x, y) )
					catID	= pGrid->asInt(x, y);
				else
					catID	= (int)pGrid->Get_NoData_Value();


				while( runList->next != NULL && runList->cat < catID )		// search for last entry in list or insert point
				{
					runList = runList->next;
				}

				if( runList->dummy == true )
				{
					runList->cat	= catID;								// first list entry, write and
					runList->dummy	= false;								// setup
					runList->parent	= parent;
				}
				else if( runList->cat == catID )
					runList = runList;										// zoneID found, all infos already written
				else if( runList->next == NULL && runList->cat < catID)		// append zoneID
				{
					newSub = new CList_Conti();
					newSub->cat			= catID;							// ... and write info
					newSub->previous	= runList;
					newSub->parent		= parent;
					newSub->dummy		= false;
					runList->next		= newSub;
					runList				= newSub;
				}
				else														// insert new entry
				{
					newSub = new CList_Conti();
					newSub->cat		= catID;								// ... and write info
					newSub->next	= runList;
					newSub->parent	= parent;
					newSub->dummy	= false;
					if( runList->previous != NULL )
					{
						newSub->previous = runList->previous;
						runList->previous->next = newSub;
					}
					else
						parent->sub	 = newSub;
							
					runList->previous = newSub;
					runList	= newSub;
				}
			}


			for(iGrid=0; iGrid<nStatGrids; iGrid++)							// collect statistics for StatGrids
			{
				if( iGrid == 0 )
				{
					if( runList->stats == NULL )
						runList->stats = new CList_Stat();
						
					runStats = runList->stats;
				}
				else
				{
					if( runStats->next == NULL )
						runStats->next = new CList_Stat();

					runStats = runStats->next;
				}
				if( !pStatList->asGrid(iGrid)->is_NoData(x, y) )
				{
					statID		= pStatList->asGrid(iGrid)->asDouble(x, y);
						
					if( runStats->dummy == true )
					{
						runStats->min = statID;
						runStats->max = statID;
						runStats->dummy = false;
					}
					if( runStats->min > statID )	
						runStats->min = statID;
					if( runStats->max < statID )
						runStats->max = statID;

					runStats->sum += statID;
					runStats->dev += pow(statID, 2);
				}
				else
					NDcountStat += 1;
			}
			
			if( pAspect != NULL )
			{
				for( int i=0; i<2; i++ )
				{
					if( nStatGrids == 0 && i == 0 )
					{
						if( runList->stats == NULL )
							runList->stats = new CList_Stat();
							
						runStats = runList->stats;
					}
					else
					{
						if( runStats->next == NULL )
							runStats->next = new CList_Stat();

						runStats = runStats->next;
					}
					if( !pAspect->is_NoData(x, y) )
					{
						statID	= pAspect->asDouble(x, y);

						if( i == 0 )
						{
							if( runStats->dummy == true )
							{
								runStats->min = statID;
								runStats->max = statID;
								runStats->dummy = false;
							}
							if( runStats->min > statID )	
								runStats->min = statID;
							if( runStats->max < statID )
								runStats->max = statID;

							statID	= sin(statID);
						}
						else
							statID	= cos(statID);

						runStats->sum += statID;
					}
					else
						NDcountStat += 1;
				}
			}

			runList->count += 1;											// sum up unique condition area
		}
	}


	// Create fields in output table (1st = Zone, 2nd = Catgrid1, 3rd = Catgrid 2, ...)
	fieldName = CSG_String::Format(SG_T("%s"),pZones->Get_Name()).BeforeFirst(SG_Char('.'));
	if (bShortNames && fieldName.Length() > 10)
		fieldName.Remove(10, fieldName.Length()-10);
	pOutTab->Add_Field(fieldName, SG_DATATYPE_Int);

	for(iGrid=0; iGrid<nCatGrids; iGrid++)
	{
		fieldName = CSG_String::Format(SG_T("%s"),pCatList->asGrid(iGrid)->Get_Name()).BeforeFirst(SG_Char('.'));
		if (bShortNames && fieldName.Length() > 10)
			fieldName.Remove(10, fieldName.Length()-10);
		pOutTab->Add_Field(fieldName, SG_DATATYPE_Int);
	}

	pOutTab->Add_Field("Count", SG_DATATYPE_Int);
	
	for( iGrid=0; iGrid<nStatGrids; iGrid++ )
	{
		tmpName		= CSG_String::Format(SG_T("%s"),pStatList->asGrid(iGrid)->Get_Name()).BeforeFirst(SG_Char('.'));
		fieldName	= tmpName;
		if (bShortNames && fieldName.Length()+3 > 10)
			fieldName.Remove(7, fieldName.Length()-7);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sMIN")   , fieldName.c_str()), SG_DATATYPE_Double);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sMAX")   , fieldName.c_str()), SG_DATATYPE_Double);
		fieldName	= tmpName;
		if (bShortNames && fieldName.Length()+4 > 10)
			fieldName.Remove(6, fieldName.Length()-6);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sMEAN")  , fieldName.c_str()), SG_DATATYPE_Double);
		fieldName	= tmpName;
		if (bShortNames && fieldName.Length()+6 > 10)
			fieldName.Remove(4, fieldName.Length()-4);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sSTDDEV"), fieldName.c_str()), SG_DATATYPE_Double);
		fieldName	= tmpName;
		if (bShortNames && fieldName.Length()+3 > 10)
			fieldName.Remove(7, fieldName.Length()-7);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sSUM")   , fieldName.c_str()), SG_DATATYPE_Double);
	}

	if( pAspect != NULL )
	{
		tmpName		= CSG_String::Format(SG_T("%s"),pAspect->Get_Name()).BeforeFirst(SG_Char('.'));
		fieldName	= tmpName;
		if (bShortNames && fieldName.Length()+3 > 10)
			fieldName.Remove(7, fieldName.Length()-7);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sMIN")   , fieldName.c_str()), SG_DATATYPE_Double);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sMAX")   , fieldName.c_str()), SG_DATATYPE_Double);
		fieldName	= tmpName;
		if (bShortNames && fieldName.Length()+4 > 10)
			fieldName.Remove(6, fieldName.Length()-6);
		pOutTab->Add_Field(CSG_String::Format(SG_T("%sMEAN")  , fieldName.c_str()), SG_DATATYPE_Double);
	}

	while( startList != NULL )												// scan zone layer list and write cat values in table
	{
		runList = startList;
		while( runList->sub != NULL )										// fall down to lowest layer
			runList = runList->sub;
		
		subList = runList;													// use pointer to scan horizontal

		while( subList != NULL )											// move forward and read all categories of this layer (including the parent layers)
		{
			runSub = subList;
			catLevel = nCatGrids;
			pRecord	= pOutTab->Add_Record();								// create new record in table
			pRecord->Set_Value((catLevel+1), runSub->count);				// read/write field count			

			for(iGrid=0; iGrid<nStatGrids; iGrid++)							// read/write statistics
			{
				if( iGrid == 0 )
					runStats = runSub->stats;
				else
					runStats = runStats->next;

				pRecord->Set_Value(catLevel+2+iGrid*5, runStats->min);
				pRecord->Set_Value(catLevel+3+iGrid*5, runStats->max);
				pRecord->Set_Value(catLevel+4+iGrid*5, runStats->sum/runSub->count);
				pRecord->Set_Value(catLevel+5+iGrid*5, sqrt((runStats->dev - runSub->count*pow(runStats->sum/runSub->count, 2)) / (runSub->count - 1))); // sample
				//pRecord->Set_Value(catLevel+5+iGrid*5, sqrt((runStats->dev - pow(runStats->sum/runSub->count, 2)) / runSub->count)); // population
				pRecord->Set_Value(catLevel+6+iGrid*5, runStats->sum);
			}

			if( pAspect != NULL )
			{
				iGrid		= nStatGrids * 5;

				if( runSub->cat == pAspect->Get_NoData_Value() )
				{
					for( int i=2; i<5; i++ )
						pRecord->Set_Value(catLevel+i+iGrid, 0.0);
				}
				else
				{
					double		min, max, sumYcomp, sumXcomp, val, valYcomp, valXcomp;

					if( nStatGrids == 0 )
						runStats	= runSub->stats;
					else
						runStats	= runStats->next;
					min			= runStats->min;
					max			= runStats->max;
					sumXcomp	= runStats->sum;

					runStats	= runStats->next;
					sumYcomp	= runStats->sum;

					pRecord		->Set_Value(catLevel+2+iGrid, min*M_RAD_TO_DEG);
					pRecord		->Set_Value(catLevel+3+iGrid, max*M_RAD_TO_DEG);
					valXcomp	= sumXcomp / runSub->count;
					valYcomp	= sumYcomp / runSub->count;
					val			= valXcomp ? fmod(M_PI_270 + atan2(valYcomp, valXcomp), M_PI_360) : (valYcomp > 0 ? M_PI_270 : (valYcomp < 0 ? M_PI_090 : -1));
					val			= fmod(M_PI_360 - val, M_PI_360);
					pRecord		->Set_Value(catLevel+4+iGrid, val*M_RAD_TO_DEG);
				}
			}
			
			while( runSub != NULL )											// read/write categories
			{
				pRecord->Set_Value(catLevel, runSub->cat);
				runSub = runSub->parent;
				catLevel -= 1;
			}
			subList = subList->next;
		}

		while( runList->parent != NULL && runList->parent->next == NULL )	// move up to next 'Caterory with -> next'
			runList = runList->parent;

		if( runList->parent != NULL )										// if not upper layer (zones)
		{	
			runList = runList->parent;										// move to parent of next 'Caterory with -> next'
			if( runList->next != NULL && runList->parent != NULL )
				runList->parent->sub = runList->next;						// redirect pointer to category which is next 'Categora with -> next' next
			else if (runList->parent == NULL && runList->next != NULL )				
				startList = runList->next;									// when upper layer (zones) is reached, move to next zone
			else
				startList = NULL;											// reading finished
			
			if( runList->parent == NULL )
				startList = runList->next;									// ?? when upper layer is reached, move to next zone
			else
				runList->sub = runList->sub->next;							// on sub layers redirect pointer to ->next
		}
		else
		{
			if( nCatGrids == 0 )
				startList = NULL;
			else
				startList = runList->next;									// ?? upper layer is reached, move to next zone
		}


		runList->next = NULL;					
		delete (runList);													// delete disconneted part of the list

	}


	if( NDcountStat > 0 )
	{
		Message_Add(CSG_String::Format(SG_T("\n\n\n%s: %d %s\n\n\n"), _TL("WARNING"), NDcountStat, _TL("NoData value(s) in statistic grid(s)!")));
	}

	return (true);
}
Beispiel #29
0
//---------------------------------------------------------
bool CJoin_Tables_Base::On_Execute(void)
{
	//-----------------------------------------------------
	int			id_A, id_B;
	CSG_Table	*pT_A, *pT_B;

	pT_A	= Parameters("TABLE_A")->asTable();
	id_A	= Parameters("ID_A"   )->asInt();

	pT_B	= Parameters("TABLE_B")->asTable();
	id_B	= Parameters("ID_B"   )->asInt();

	if(	id_A < 0 || id_A >= pT_A->Get_Field_Count() || pT_A->Get_Count() <= 0
	||	id_B < 0 || id_B >= pT_B->Get_Field_Count() || pT_B->Get_Count() <= 0 )
	{
		return( false );
	}

	//-----------------------------------------------------
	if( Parameters("RESULT")->asTable() && Parameters("RESULT")->asTable() != pT_A )
	{
		pT_A	= Parameters("RESULT")->asTable();

		if( Parameters("RESULT")->asTable()->Get_ObjectType() == DATAOBJECT_TYPE_Shapes )
		{
			((CSG_Shapes *)pT_A)->Create(*Parameters("TABLE_A")->asShapes());
		}
		else
		{
			pT_A->Create(*Parameters("TABLE_A")->asTable());
		}
	}

	//-----------------------------------------------------
	int		nJoins, *Join, Offset	= pT_A->Get_Field_Count();

	if( Parameters("FIELDS_ALL")->asBool() )
	{
		if( (nJoins = pT_B->Get_Field_Count() - 1) <= 0 )
		{
			Error_Set(_TL("no fields to add"));

			return( false );
		}

		Join	= new int[nJoins];

		for(int i=0, j=0; i<pT_B->Get_Field_Count(); i++)
		{
			if( i != id_B )
			{
				pT_A->Add_Field(pT_B->Get_Field_Name(i), pT_B->Get_Field_Type(i));

				Join[j++]	= i;
			}
		}
	}
	else
	{
		CSG_Parameter_Table_Fields	*pFields	= Parameters("FIELDS")->asTableFields();

		if( (nJoins = pFields->Get_Count()) <= 0 )
		{
			Error_Set(_TL("no fields to add"));

			return( false );
		}

		Join	= new int[nJoins];

		for(int j=0; j<pFields->Get_Count(); j++)
		{
			int	i	= pFields->Get_Index(j);

			pT_A->Add_Field(pT_B->Get_Field_Name(i), pT_B->Get_Field_Type(i));

			Join[j]	= i;
		}
	}

	pT_A->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pT_A->Get_Name(), pT_B->Get_Name()));

	//-----------------------------------------------------
	bool	bCmpNumeric	=  SG_Data_Type_is_Numeric(pT_A->Get_Field_Type(id_A))
						|| SG_Data_Type_is_Numeric(pT_B->Get_Field_Type(id_B));

	CSG_Table	Delete;	if( !Parameters("KEEP_ALL")->asBool() )	Delete.Add_Field("ID", SG_DATATYPE_Int);

	pT_A->Set_Index(id_A, TABLE_INDEX_Ascending);
	pT_B->Set_Index(id_B, TABLE_INDEX_Ascending);

	CSG_Table_Record	*pRecord_B	= pT_B->Get_Record_byIndex(0);

	for(int a=0, b=0, Cmp; pRecord_B && a<pT_A->Get_Count() && Set_Progress(a, pT_A->Get_Count()); a++)
	{
		CSG_Table_Record	*pRecord_A	= pT_A->Get_Record_byIndex(a);

		while( pRecord_B && (Cmp = Cmp_Keys(pRecord_A->Get_Value(id_A), pRecord_B->Get_Value(id_B), bCmpNumeric)) < 0 )
		{
			pRecord_B	= pT_B->Get_Record_byIndex(++b);
		}

		if( pRecord_B && Cmp == 0 )
		{
			for(int i=0; i<nJoins; i++)
			{
				*pRecord_A->Get_Value(Offset + i)	= *pRecord_B->Get_Value(Join[i]);
			}
		}
		else if( Delete.Get_Field_Count() == 0 )
		{
			for(int i=0; i<nJoins; i++)
			{
				pRecord_A->Set_NoData(Offset + i);
			}
		}
		else
		{
			Delete.Add_Record()->Set_Value(0, pRecord_A->Get_Index());
		}
	}

	//-----------------------------------------------------
	delete[](Join);

	pT_A->Set_Index(id_A, TABLE_INDEX_None);
	pT_B->Set_Index(id_B, TABLE_INDEX_None);

	if( Delete.Get_Count() > 0 )
	{
		Delete.Set_Index(0, TABLE_INDEX_Descending);

		for(int i=0; i<Delete.Get_Count(); i++)
		{
		//	((CSG_Shapes *)pT_A)->Del_Shape(Delete[i].asInt(0));

			pT_A->Del_Record(Delete[i].asInt(0));
		}

		Message_Add(CSG_String::Format(SG_T("%d %s"), pT_A->Get_Selection_Count(), _TL("unjoined records have been removed")));
	}

	if( pT_A == Parameters("TABLE_A")->asTable() )
	{
		DataObject_Update(pT_A);
	}

	return( pT_A->Get_Count() > 0 );
}
bool CProfileFromPoints::On_Execute(void){
	
	CSG_Table* pTable;	
	CSG_Table* pProfileTable;
	CSG_Table_Record* pRecord;
	CSG_Grid* pGrid;	
	int iXField, iYField;	
	int i;
	int x1,x2,y1,y2;
	float fPartialDist;
	float fDist = 0;


	pGrid = Parameters("GRID")->asGrid();
	pTable = Parameters("TABLE")->asTable();
	pProfileTable = Parameters("RESULT")->asTable();
	iXField = Parameters("X")->asInt();
	iYField = Parameters("Y")->asInt();	
	
	pProfileTable->Create((CSG_Table*)NULL);
	pProfileTable->Set_Name(_TL("Profile"));
	pProfileTable->Add_Field(_TL("Distance"), SG_DATATYPE_Double);
	pProfileTable->Add_Field("Z", SG_DATATYPE_Double);

	for (i = 0; i < pTable->Get_Record_Count()-1; i++){
		
		x1=(int)(0.5 + (pTable->Get_Record(i  )->asDouble(iXField) - pGrid->Get_XMin()) / pGrid->Get_Cellsize());
		x2=(int)(0.5 + (pTable->Get_Record(i+1)->asDouble(iXField) - pGrid->Get_XMin()) / pGrid->Get_Cellsize());
		y1=(int)(0.5 + (pTable->Get_Record(i  )->asDouble(iYField) - pGrid->Get_YMin()) / pGrid->Get_Cellsize());			
		y2=(int)(0.5 + (pTable->Get_Record(i+1)->asDouble(iYField) - pGrid->Get_YMin()) / pGrid->Get_Cellsize());			

        int x = x1, y = y1, D = 0, HX = x2 - x1, HY = y2 - y1,
                c, M, xInc = 1, yInc = 1, iLastX = x1, iLastY = y1;

        if (HX < 0) {
            xInc = -1;
            HX = -HX;
        }//if
        if (HY < 0) {
            yInc = -1;
            HY = -HY;
        }//if
        if (HY <= HX) {
            c = 2 * HX;
            M = 2 * HY;
            for (;;) {                
                fPartialDist = (float)(M_GET_LENGTH(x-iLastX, y-iLastY) * pGrid->Get_Cellsize());
                if (pGrid->is_InGrid(x,y) && fPartialDist){
					fDist+=fPartialDist;
                	pRecord = pProfileTable->Add_Record();
					pRecord->Set_Value(0, fDist);
					pRecord->Set_Value(1, pGrid->asFloat(x,y));
                }//if
                iLastX = x;
                iLastY = y;
                if (x == x2) {
                    break;
                }// if
                x += xInc;
                D += M;
                if (D > HX) {
                    y += yInc;
                    D -= c;
                }// if
            }// for
        }// if
        else {
            c = 2 * HY;
            M = 2 * HX;
            for (;;) {
                fPartialDist = (float)(M_GET_LENGTH(x-iLastX, y-iLastY) * pGrid->Get_Cellsize());
                if (pGrid->is_InGrid(x,y) && fPartialDist){
					fDist+=fPartialDist;
                	pRecord = pProfileTable->Add_Record();
					pRecord->Set_Value(0, fDist);
					pRecord->Set_Value(1, pGrid->asFloat(x,y));
                }//if
                iLastX = x;
                iLastY = y;
                if (y == y2) {
                    break;
                }// if
                y += yInc;
                D += M;
                if (D > HY) {
                    x += xInc;
                    D -= c;
                }// if
            }// for
        }// else        
     
	}//for

	return true;

}// method