//---------------------------------------------------------
bool CWKSP_Shapes::Edit_Set_Attributes(void)
{
    CSG_Table_Record	*pSelection	= Get_Shapes()->Get_Selection(m_Edit_Index);

    if( pSelection )
    {
        for(int i=0; i<m_Edit_Attributes.Get_Record_Count(); i++)
        {
            if( !pSelection->Set_Value(i, m_Edit_Attributes.Get_Record(i)->asString(1)) )
            {
                m_Edit_Attributes.Get_Record(i)->Set_Value(1, pSelection->asString(i));
            }
        }

        Update_Views(false);

        return( true );
    }

    return( false );
}
//---------------------------------------------------------
bool CActive_Attributes_Control::_Set_Record(int iRecord)
{
	CSG_Table_Record *pRecord	= m_pTable->Get_Record(iRecord);

	if( m_Field_Offset )	// feature attributes
	{
		SetRowLabelValue(iRecord, pRecord->asString(0));
	}
	else					// grid cell values
	{
		SetRowLabelValue(iRecord, wxString::Format("%d", 1 + iRecord));
	}

	for(int iCol=0, iField=m_Field_Offset; iField<m_pTable->Get_Field_Count(); iCol++, iField++)
	{
		switch( m_pTable->Get_Field_Type(iField) )
		{
		default:
			SetCellValue(iRecord, iCol, pRecord->is_NoData(iField) ? SG_T("") : pRecord->asString(iField));
			break;

		case SG_DATATYPE_Color:
			SetCellBackgroundColour(iRecord, iCol, Get_Color_asWX(pRecord->asInt(iField)));
			break;
		}
	}

	if( pRecord->is_Selected() )
	{
		SelectRow(iRecord, true);
	}

	return( true );
}
void Cihacres_elev::_CreateTableSim()
{
	int i = 0; // used in function Get_Record(i)
	CSG_Table_Record	*pRecord;
	CSG_String			tmpName;
	double				sim_eb, sim;

	// creating the column titles
	m_pTable->Add_Field("Date",		SG_DATATYPE_String);
	m_pTable->Add_Field("Flow_OBS",	SG_DATATYPE_Double);

	for (int eb = 0; eb < m_nElevBands; eb++)
	{
		tmpName = SG_T("ELEVB_");
		tmpName += convert_sl::Int2String(eb+1).c_str();
		m_pTable->Add_Field(tmpName.c_str(),	SG_DATATYPE_Double);
	}
	m_pTable->Add_Field(SG_T("Flow_SIM"),	SG_DATATYPE_Double);

	for (int j = 0; j < m_nValues; j++)
	{
		m_pTable->Add_Record();
		pRecord = m_pTable->Get_Record(i);

		// writing the data into the rows
		pRecord->Set_Value(0,CSG_String(m_vec_date[j].c_str()));
		pRecord->Set_Value(1,m_p_Q_obs_m3s[j]);
		sim_eb = 0.0;
		sim = 0.0;
		for (int eb = 0; eb < m_nElevBands; eb++)
		{
			sim_eb = model_tools::mmday_to_m3s(m_p_elevbands[eb].m_p_streamflow_sim[j],m_p_elevbands[eb].m_area);
			//pRecord->Set_Value(3+eb,model_tools::mmday_to_m3s(m_p_elevbands[eb].m_p_streamflow_sim[j],m_p_elevbands[eb].m_area));
			pRecord->Set_Value(2+eb, sim_eb);
			sim += sim_eb;
		}
		pRecord->Set_Value(2+m_nElevBands,sim);
		i++;
	}
}
bool CCombineGrids::On_Execute(void){
	
	int x,y;
	int i;
	int iCellValue1, iCellValue2;
	int iTableValue1, iTableValue2;
	int iResultValue;
	
	CSG_Grid *pGrid1 = Parameters("GRID1")->asGrid(); 
	CSG_Grid *pGrid2 = Parameters("GRID2")->asGrid(); 
	CSG_Grid *pResult = Parameters("RESULT")->asGrid(); ;
	CSG_Table			*pLookup;
	CSG_Table_Record	*pRecord;

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

	for(y=0; y<Get_NY() && Set_Progress(y); y++){		
		for(x=0; x<Get_NX(); x++){
			iCellValue1 = pGrid1->asInt(x,y);
			iCellValue2 = pGrid2->asInt(x,y);
			for (i = 0; i < pLookup->Get_Record_Count(); i++){
				pRecord = pLookup->Get_Record(i);
				iTableValue1 = pRecord->asInt(0);
				iTableValue2 = pRecord->asInt(1);
				if (iTableValue1 == iCellValue1){
					if (iTableValue2 == iCellValue2){
						iResultValue = pRecord->asInt(2);
						pResult->Set_Value(x,y,iResultValue);
						break;
					}//if
				}//if				
			}//for
			if (i >= pLookup->Get_Record_Count()){
				pResult->Set_NoData(x,y);
			}//if
		}//for
	}//for
	return true;

}//method
//---------------------------------------------------------
bool CWKSP_Shapes::Edit_Set_Index(int Index)
{
	m_Edit_Attributes.Del_Records();

	if( Index > Get_Shapes()->Get_Selection_Count() )
	{
		Index	= Get_Shapes()->Get_Selection_Count();
	}

	CSG_Table_Record	*pSelection	= Get_Shapes()->Get_Selection(Index);

	if( pSelection )
	{
		m_Edit_Index	= Index;

		for(int i=0; i<Get_Shapes()->Get_Field_Count(); i++)
		{
			CSG_Table_Record	*pRecord	= m_Edit_Attributes.Add_Record();

			pRecord->Set_Value(0, pSelection->Get_Table()->Get_Field_Name(i));
			pRecord->Set_Value(1, pSelection->asString(i));
		}
	}
	else
	{
		m_Edit_Index	= 0;
	}

	return( true );
}
Example #6
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 );
}
//---------------------------------------------------------
void CVIEW_Table_Control::On_LClick(wxGridEvent &event)
{
	int					iField		= m_Field_Offset + event.GetCol();
	CSG_Table_Record	*pRecord	= m_pRecords[event.GetRow()];

	//-----------------------------------------------------
	if( event.AltDown() )
	{
		if( m_pTable->Get_Field_Type(iField) == SG_DATATYPE_String )
		{
			if( event.ControlDown() )
			{
				g_pData->Open   (pRecord->asString(iField));
			}
			else
			{
				Open_Application(pRecord->asString(iField));
			}
		}
	}

	//-----------------------------------------------------
	else if( event.ControlDown() )
	{
		m_pTable->Select(pRecord, true);

		Update_Selection();
	}

	else if( event.ShiftDown() )
	{
		SelectBlock(event.GetRow(), 0, GetGridCursorRow(), GetNumberCols(), false);
	}

	else
	{
		SelectRow(event.GetRow(), false);

		if( pRecord && iField >= m_Field_Offset && iField < m_pTable->Get_Field_Count() && m_pTable->Get_Field_Type(iField) == SG_DATATYPE_Color )
		{
			long	lValue;

			if( DLG_Color(lValue = pRecord->asInt(iField)) )
			{
				pRecord->Set_Value(iField, lValue);

				SetCellBackgroundColour(event.GetRow(), event.GetCol(), Get_Color_asWX(pRecord->asInt(iField)));

				ForceRefresh();
			}
		}
	}

	//-----------------------------------------------------
	SetGridCursor(event.GetRow(), event.GetCol());
}
Example #8
0
//---------------------------------------------------------
void CVIEW_Map_3D::_Play_Pos_Add(void)
{
	CSG_Table_Record	*pRecord;

	if( m_Play_Mode == PLAY_MODE_NONE )
	{
		pRecord	= m_Play.Add_Record();

		pRecord->Set_Value(PLAY_REC_ROTATE_X		, m_pImage->m_xRotate);
		pRecord->Set_Value(PLAY_REC_ROTATE_Y		, m_pImage->m_yRotate);
		pRecord->Set_Value(PLAY_REC_ROTATE_Z		, m_pImage->m_zRotate);
		pRecord->Set_Value(PLAY_REC_SHIFT_X			, m_pImage->m_xShift);
		pRecord->Set_Value(PLAY_REC_SHIFT_Y			, m_pImage->m_yShift);
		pRecord->Set_Value(PLAY_REC_SHIFT_Z			, m_pImage->m_zShift);
		pRecord->Set_Value(PLAY_REC_EXAGGERATION	, m_pImage->m_Exaggeration);
		pRecord->Set_Value(PLAY_REC_CENTRAL			, m_pImage->m_Central);
		pRecord->Set_Value(PLAY_REC_STEPS			, 10);
	}
}
//---------------------------------------------------------
bool CSG_Translator::Create(class CSG_Table *pTranslations, int iText, int iTranslation, bool bCmpNoCase)
{
	SG_UI_Msg_Lock(true);

	Destroy();

	if( iText != iTranslation && pTranslations && pTranslations->Get_Field_Count() > iText && pTranslations->Get_Field_Count() > iTranslation && pTranslations->Get_Record_Count() > 0 )
	{
		int		i;

		m_bCmpNoCase	= bCmpNoCase;

		if( m_bCmpNoCase )
		{
			for(i=0; i<pTranslations->Get_Record_Count(); i++)
			{
				CSG_Table_Record	*pRecord	= pTranslations->Get_Record(i);

				CSG_String	s	= pRecord->asString(iText);

				pRecord->Set_Value(iText, s.Make_Lower().c_str());
			}
		}

		pTranslations->Set_Index(iText, TABLE_INDEX_Ascending);

		m_Translations	= (CSG_Translation **)SG_Malloc(pTranslations->Get_Record_Count() * sizeof(CSG_Translation *));

		for(i=0; i<pTranslations->Get_Record_Count(); i++)
		{
			CSG_Table_Record	*pRecord	= pTranslations->Get_Record_byIndex(i);

			if( *pRecord->asString(iText) && *pRecord->asString(iTranslation) )
			{
				m_Translations[m_nTranslations++]	= new CSG_Translation(pRecord->asString(iText), pRecord->asString(iTranslation));
			}
		}

		if( m_nTranslations < pTranslations->Get_Record_Count() )
		{
			m_Translations	= (CSG_Translation **)SG_Realloc(m_Translations, m_nTranslations * sizeof(CSG_Translation *));
		}
	}

	SG_UI_Msg_Lock(false);

	return( m_nTranslations > 0 );
}
//---------------------------------------------------------
void CActive_Attributes_Control::On_LClick(wxGridEvent &event)
{
	int					iField		= m_Field_Offset + event.GetCol();
	CSG_Table_Record	*pRecord	= m_pTable->Get_Record(event.GetRow());

	//-----------------------------------------------------
	if( event.AltDown() )
	{
		if( m_pTable->Get_Field_Type(iField) == SG_DATATYPE_String )
		{
			Open_Application(pRecord->asString(iField));
		}
	}

	//-----------------------------------------------------
	if( event.ControlDown() )
	{
		if( m_pTable->Get_Field_Type(iField) == SG_DATATYPE_String )
		{
			g_pData->Open   (pRecord->asString(iField));
		}
	}

	//-----------------------------------------------------
	else
	{
		if( pRecord && iField >= m_Field_Offset && iField < m_pTable->Get_Field_Count() && m_pTable->Get_Field_Type(iField) == SG_DATATYPE_Color )
		{
			long	lValue;

			if( DLG_Color(lValue = pRecord->asInt(iField)) )
			{
				pRecord->Set_Value(iField, lValue);

				SetCellBackgroundColour(event.GetRow(), event.GetCol(), Get_Color_asWX(pRecord->asInt(iField)));

				ForceRefresh();
			}
		}
	}

	//-----------------------------------------------------
	SetGridCursor(event.GetRow(), event.GetCol());
}
Example #11
0
//---------------------------------------------------------
double CDVWK_SoilMoisture::Get_ETP_Haude(int Day)
{
	const double	f[]	=
	//	---   Jan   Feb   Mar   Apr   Mai   Jun   Jul   Aug   Sep   Okt   Nov   Dez
	{	0.00, 0.22, 0.22, 0.22, 0.29, 0.29, 0.28, 0.26, 0.25, 0.23, 0.22, 0.22, 0.22	};

	double	T14, U14, es, e, ETP_Haude;

	//-----------------------------------------------------
	CSG_Table_Record	*pRecord;

	if( (pRecord = pClimate->Get_Record(Day)) == NULL )
	{
		return( 0 );
	}

	T14		= pRecord->asDouble(1);
	U14		= pRecord->asDouble(2);


	//-----------------------------------------------------
	// VKR 4.6:		Berechnung des Saettigungsdampfdruckes (es [hPa])
	//
	//					               17,62 * T14
	//		es(T14)		= 6,11 * exp( -------------- );		bei T14 > 0
	//					               243,12 + T14
	//
	//					               22,46 * T14
	//		es(T14)		= 6,11 * exp( -------------- );		bei T14 < 0
	//					               272,62 + T14
	//
	//		T14			: Temperatur 14 Uhr [DegreeC]
	//

	if( T14 < 0 )
	{
		es	= 6.11 * exp( (22.46 * T14) / (272.62 + T14) );
	}
	else
	{
		es	= 6.11 * exp( (17.62 * T14) / (243.12 + T14) );
	}


	//-----------------------------------------------------
	// VKR 4.7:		Berechnung des aktuellen Dampfdruckes (e [hPa])
	//
	//		e		= es(T14) * U14 / 100
	//
	//		es(T14)		: Saettigungsdampfdruck 14 Uhr [hPa]
	//		U14			: relative Luftfeuchte 14 Uhr [%] (Dampfdruck in % des Saettigungsdampfdruckes)
	//

	e	= es * U14 / 100.0;


	//-----------------------------------------------------
	// VKR 4.8:		Berechnung der potentiellen Verdunstung nach Haude (ETPhaude [mm/d])
	//
	//		ETPhaude	= f(m) * (es - e)
	//
	//		f(m)		: Monatsfaktor [mm/mbar/d]
	//		e			: aktueller Dampfdruck [hPa]
	//		es			: Saettigungsdampfdruck
	//

	ETP_Haude	= f[Get_Month(Day)] * (es - e);

	return( ETP_Haude );
}
//---------------------------------------------------------
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 CGridsFromTableAndGrid::On_Execute(void)
{
	int						iField, iRecord, iAttribute, nAttributes, *Attribute;
	sLong					iCell, jCell;
	CSG_Parameter_Grid_List	*pGrids;
	CSG_Grid				*pClasses;
	CSG_Table				*pTable;

	//-----------------------------------------------------
	pClasses	= Parameters("CLASSES" )->asGrid();
	pGrids		= Parameters("GRIDS"   )->asGridList();
	pTable		= Parameters("TABLE"   )->asTable();
	iField		= Parameters("ID_FIELD")->asInt();

	pGrids->Del_Items();

	if( !pClasses->Set_Index() )
	{
		Error_Set(_TL("index creation failed"));

		return( false );
	}

	//-----------------------------------------------------
	if( pTable->Get_Field_Count() == 0 || pTable->Get_Count() == 0 )
	{
		Message_Add(_TL("selected table contains no valid records"));

		return( false );
	}

	//-----------------------------------------------------
	if( !pTable->Set_Index(iField, TABLE_INDEX_Ascending) )
	{
		Message_Add(_TL("failed to create index for table"));

		return( false );
	}

	//-----------------------------------------------------
	Attribute	= new int[pTable->Get_Field_Count()];

	for(iAttribute=0, nAttributes=0; iAttribute<pTable->Get_Field_Count(); iAttribute++)
	{
		if( iAttribute != iField && pTable->Get_Field_Type(iAttribute) != SG_DATATYPE_String )
		{
			Attribute[nAttributes++]	= iAttribute;

			CSG_Grid	*pGrid	= SG_Create_Grid(*Get_System());

			pGrid->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pClasses->Get_Name(), pTable->Get_Field_Name(iAttribute)));

			pGrids->Add_Item(pGrid);
		}
	}

	if( nAttributes == 0 )
	{
		delete[](Attribute);

		Message_Add(_TL("selected table does not have numeric attributes"));

		return( false );
	}

	//-----------------------------------------------------
	CSG_Table_Record	*pRecord	= pTable->Get_Record_byIndex(0);

	for(iCell=0, iRecord=0; iCell<Get_NCells() && pRecord && Set_Progress_NCells(iCell); iCell++)
	{
		if( pClasses->Get_Sorted(iCell, jCell, false, true) )
		{
			double	valClass	= pClasses->asDouble(jCell);

			while( pRecord && pRecord->asDouble(iField) < valClass )
			{
				pRecord	= pTable->Get_Record_byIndex(++iRecord);
			}

			if( !pRecord || pRecord->asDouble(iField) > valClass )
			{
				for(iAttribute=0; iAttribute<nAttributes; iAttribute++)
				{
					pGrids->asGrid(iAttribute)->Set_NoData(jCell);
				}
			}
			else
			{
				for(iAttribute=0; iAttribute<nAttributes; iAttribute++)
				{
					pGrids->asGrid(iAttribute)->Set_Value(jCell, pRecord->asDouble(Attribute[iAttribute]));
				}
			}
		}
	}

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

	return true;
}
Example #14
0
//---------------------------------------------------------
bool CSG_ODBC_Connection::Table_Insert(const CSG_String &Table_Name, const CSG_Table &Table, bool bCommit)
{
	//-----------------------------------------------------
	if( !is_Connected() )
	{
		_Error_Message(_TL("no database connection"));

		return( false );
	}

	if( !Table_Exists(Table_Name) )
	{
		return( false );
	}

	CSG_Table	Fields	= Get_Field_Desc(Table_Name);

	if( Fields.Get_Count() != Table.Get_Field_Count() )
	{
		return( false );
	}

	//-----------------------------------------------------
	try
	{
		bool	bLOB	= false;

		int				iField, iRecord;
		CSG_String		Insert;
		otl_stream		Stream;

		//-------------------------------------------------
		Insert.Printf(SG_T("INSERT INTO %s VALUES("), Table_Name.c_str());

		for(iField=0; iField<Table.Get_Field_Count(); iField++)
		{
			if( iField > 0 )
			{
				Insert	+= SG_T(",");
			}

			Insert	+= CSG_String::Format(SG_T(":f%d"), 1 + iField);

			switch( Table.Get_Field_Type(iField) )
			{
			default:
			case SG_DATATYPE_String:	Insert	+= SG_T("<varchar>");	break;
			case SG_DATATYPE_Date:		Insert	+= SG_T("<char[12]>");	break;
			case SG_DATATYPE_Char:		Insert	+= SG_T("<char>");		break;
			case SG_DATATYPE_Short:		Insert	+= SG_T("<short>");		break;
			case SG_DATATYPE_Int:		Insert	+= SG_T("<int>");		break;
			case SG_DATATYPE_Color:		Insert	+= SG_T("<long>");		break;
			case SG_DATATYPE_Long:		Insert	+= SG_T("<long>");		break;
			case SG_DATATYPE_Float:		Insert	+= SG_T("<float>");		break;
			case SG_DATATYPE_Double:	Insert	+= SG_T("<double>");	break;
			}
		}

		Insert	+= SG_T(")");

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

		std_string	valString;

		//-------------------------------------------------
		for(iRecord=0; iRecord<Table.Get_Count() && SG_UI_Process_Set_Progress(iRecord, Table.Get_Count()); iRecord++)
		{
			CSG_Table_Record	*pRecord	= Table.Get_Record(iRecord);

			for(iField=0; iField<Table.Get_Field_Count(); iField++)
			{
				if( pRecord->is_NoData(iField) )
				{
					Stream << otl_null();
				}
				else switch( Table.Get_Field_Type(iField) )
				{
				default:
				case SG_DATATYPE_String:
				case SG_DATATYPE_Date:
					valString	= CSG_String(pRecord->asString(iField));
					Stream << valString;
					break;

				case SG_DATATYPE_Char:		Stream << (char)pRecord->asChar  (iField);	break;
				case SG_DATATYPE_Short:		Stream <<       pRecord->asShort (iField);	break;
				case SG_DATATYPE_Int:		Stream <<       pRecord->asInt   (iField);	break;
				case SG_DATATYPE_Color:
				case SG_DATATYPE_Long:		Stream << (long)pRecord->asInt   (iField);	break;
				case SG_DATATYPE_Float:		Stream <<       pRecord->asFloat (iField);	break;
				case SG_DATATYPE_Double:	Stream <<       pRecord->asDouble(iField);	break;
				}
			}
		}
	}
	//-----------------------------------------------------
	catch( otl_exception &e )
	{
		_Error_Message(e);

		return( false );
	}

	return( true );
}
Example #15
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 );
}
Example #16
0
//---------------------------------------------------------
bool CFilter_3x3::On_Execute(void)
{
	int				x, y, ix, iy, dx, dy, fx, fy, fdx, fdy;
	double			Sum, nSum, **f;
	CSG_Grid			*pInput, *pResult;
	CSG_Table			*pFilter;
	CSG_Table_Record	*pRecord;

	//-----------------------------------------------------
	pInput	= Parameters("INPUT")->asGrid();
	pResult	= Parameters("RESULT")->asGrid();

	//-----------------------------------------------------
	pFilter	= Parameters("FILTER")->asTable();

	fdx		= pFilter->Get_Field_Count();
	fdy		= pFilter->Get_Record_Count();
	dx		= (fdx - 1) / 2;
	dy		= (fdy - 1) / 2;

	f		= (double **)SG_Malloc(fdy * sizeof(double *));
	f[0]	= (double  *)SG_Malloc(fdy * fdx * sizeof(double));

	for(fy=0; fy<fdy; fy++)
	{
		f[fy]	= f[0] + fy * fdx;

		pRecord	= pFilter->Get_Record(fy);

		for(fx=0; fx<fdx; fx++)
		{
			f[fy][fx]	= pRecord->asDouble(fx);
		}
	}

	//-----------------------------------------------------
	for(y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		for(x=0; x<Get_NX(); x++)
		{
			Sum		= nSum	= 0.0;

			for(fy=0, iy=y-dy; fy<fdy; fy++, iy++)
			{
				for(fx=0, ix=x-dx; fx<fdx; fx++, ix++)
				{
					if( pInput->is_InGrid(ix, iy) )
					{
						Sum		+= f[fy][fx] * pInput->asDouble(ix, iy);
						nSum	+= fabs(f[fy][fx]);
					}
				}
			}

			if( nSum > 0.0 )
			{
				pResult->Set_Value(x, y, Sum / nSum);
			}
			else
			{
				pResult->Set_NoData(x, y);
			}
		}
	}

	//-----------------------------------------------------
	SG_Free(f[0]);
	SG_Free(f);

	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 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);
}
//---------------------------------------------------------
bool CGrid_Table_Import::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_Table	Table;

	if( !Table.Create(Parameters("FILE")->asString()) )
	{
		Error_Fmt("%s [%s]", _TL("could not open table file"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	int	nx, ny, nHeadLines	= Parameters("HEADLINES")->asInt();

	if( (nx = Table.Get_Field_Count()) < 1 || (ny = Table.Get_Record_Count()) < 1 )
	{
		Error_Fmt("%s [%s]", _TL("no data in table file"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	TSG_Data_Type	Type;

	switch( Parameters("DATA_TYPE")->asInt() )
	{
	case  0:	Type	= SG_DATATYPE_Byte  ;	break;	// 1 Byte Integer (unsigned)
	case  1:	Type	= SG_DATATYPE_Char  ;	break;	// 1 Byte Integer (signed)
	case  2:	Type	= SG_DATATYPE_Word  ;	break;	// 2 Byte Integer (unsigned)
	case  3:	Type	= SG_DATATYPE_Short ;	break;	// 2 Byte Integer (signed)
	case  4:	Type	= SG_DATATYPE_DWord ;	break;	// 4 Byte Integer (unsigned)
	case  5:	Type	= SG_DATATYPE_Int   ;	break;	// 4 Byte Integer (signed)
	default:	Type	= SG_DATATYPE_Float ;	break;	// 4 Byte Floating Point
	case  7:	Type	= SG_DATATYPE_Double;	break;	// 8 Byte Floating Point
	}

	//-----------------------------------------------------
	CSG_Grid	*pGrid	= SG_Create_Grid(Type, nx, ny,
		Parameters("CELLSIZE")->asDouble(),
		Parameters("XMIN"    )->asDouble(),
		Parameters("YMIN"    )->asDouble()
	);

	pGrid->Set_Name        (SG_File_Get_Name(Parameters("FILE")->asString(), false));
	pGrid->Set_Unit        (Parameters("UNIT"   )->asString());
	pGrid->Set_NoData_Value(Parameters("NODATA" )->asDouble());
	pGrid->Set_Scaling     (Parameters("ZFACTOR")->asDouble());

	Parameters("GRID")->Set_Value(pGrid);

	//-----------------------------------------------------
	bool	bDown	= Parameters("TOPDOWN")->asInt() == 1;

	for(int y=0; y<ny && Set_Progress(y, ny); y++)
	{
		CSG_Table_Record	*pRecord	= Table.Get_Record(y + nHeadLines);

		for(int x=0, yy=bDown?ny-1-y:y; x<nx; x++)
		{
			pGrid->Set_Value(x, yy, pRecord->asDouble(x));
		}
	}

	//-----------------------------------------------------
	return( true );
}
//---------------------------------------------------------
bool CVIEW_Table_Control::_Set_Records(bool bSelection_To_Top)
{
	BeginBatch();

	//-----------------------------------------------------
	if( m_bSelOnly && m_pTable->Get_Selection_Count() <= 0 )
	{
		m_bSelOnly	= false;
	}

	int	Difference, nRecords	= m_bSelOnly ? m_pTable->Get_Selection_Count() : m_pTable->Get_Count();

	if( (Difference = nRecords - GetNumberRows()) > 0 )
	{
		AppendRows(Difference);
	}
	else if( Difference < 0 && (Difference = -Difference < GetNumberRows() ? -Difference : GetNumberRows()) > 0 )
	{
		DeleteRows(0, Difference);
	}

	m_pRecords	= (CSG_Table_Record **)SG_Realloc(m_pRecords, nRecords * sizeof(CSG_Table_Record *));

	ClearSelection();

	//-----------------------------------------------------
	if( m_bSelOnly )
	{
	//	#pragma omp parallel for
		for(int iRecord=0; iRecord<nRecords; iRecord++)
		{
			_Set_Record(iRecord, m_pTable->Get_Selection(iRecord));
		}
	}
	else if( !bSelection_To_Top )
	{
	//	#pragma omp parallel for
		for(int iRecord=0; iRecord<nRecords; iRecord++)
		{
			_Set_Record(iRecord, m_pTable->Get_Record_byIndex(iRecord));
		}
	}
	else // if( bSelection_To_Top && m_pTable->Get_Selection_Count() > 0 )
	{
		for(int iRecord=0, iSel=0, iNoSel=m_pTable->Get_Selection_Count(); iRecord<nRecords && PROGRESSBAR_Set_Position(iRecord, nRecords); iRecord++)
		{
			CSG_Table_Record	*pRecord	= m_pTable->Get_Record_byIndex(iRecord);

			if( pRecord->is_Selected() )
			{
				_Set_Record(iSel  ++, pRecord);
			}
			else
			{
				_Set_Record(iNoSel++, pRecord);
			}
		}

		PROCESS_Set_Okay();
	}

	//-----------------------------------------------------
	EndBatch();

	_Update_Views();

	return( true );
}
Example #21
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 );
}
Example #22
0
//---------------------------------------------------------
bool CGrid_Table_Import::On_Execute(void)
{
	bool			bDown;
	int				x, y, nx, ny;
	double			dxy, xmin, ymin, zFactor, zNoData;
	TSG_Data_Type		data_type;
	CSG_String		FileName, Unit;
	CSG_Grid			*pGrid;
	CSG_Table			Table;
	CSG_Table_Record	*pRecord;

	//-----------------------------------------------------
	FileName	= Parameters("FILE_DATA")		->asString();
	dxy			= Parameters("DXY")				->asDouble();
	xmin		= Parameters("XMIN")			->asDouble();
	ymin		= Parameters("YMIN")			->asDouble();
	bDown		= Parameters("TOPDOWN")			->asInt() == 1;
	Unit		= Parameters("UNIT")			->asString();
	zFactor		= Parameters("ZFACTOR")			->asDouble();
	zNoData		= Parameters("NODATA")			->asDouble();

	switch( Parameters("DATA_TYPE")->asInt() )
	{
	default:	data_type	= SG_DATATYPE_Undefined;	break;	// not handled
	case 0:		data_type	= SG_DATATYPE_Byte;			break;	// 1 Byte Integer (unsigned)
	case 1:		data_type	= SG_DATATYPE_Char;			break;	// 1 Byte Integer (signed)
	case 2:		data_type	= SG_DATATYPE_Word;			break;	// 2 Byte Integer (unsigned)
	case 3:		data_type	= SG_DATATYPE_Short;		break;	// 2 Byte Integer (signed)
	case 4:		data_type	= SG_DATATYPE_DWord;		break;	// 4 Byte Integer (unsigned)
	case 5:		data_type	= SG_DATATYPE_Int;			break;	// 4 Byte Integer (signed)
	case 6:		data_type	= SG_DATATYPE_Float;		break;	// 4 Byte Floating Point
	case 7:		data_type	= SG_DATATYPE_Double;		break;	// 8 Byte Floating Point
	}

	//-----------------------------------------------------
	if( Table.Create(FileName) && (nx = Table.Get_Field_Count()) > 0 && (ny = Table.Get_Record_Count()) > 0 )
	{
		pGrid	= SG_Create_Grid(data_type, nx, ny, dxy, xmin, ymin);

		for(y=0; y<ny && Set_Progress(y, ny); y++)
		{
			pRecord	= Table.Get_Record(bDown ? ny - 1 - y : y);

			for(x=0; x<nx; x++)
			{
				pGrid->Set_Value(x, y, pRecord->asDouble(x));
			}
		}

		pGrid->Set_Unit			(Unit);
		pGrid->Set_ZFactor		(zFactor);
		pGrid->Set_NoData_Value	(zNoData);
		pGrid->Set_Name			(SG_File_Get_Name(FileName, false));

		Parameters("GRID")->Set_Value(pGrid);

		return( true );
	}

	//-----------------------------------------------------
	return( false );
}
//---------------------------------------------------------
bool CTable_Record_Statistics_Base::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_Table	*pTable	= Parameters("TABLE")->asTable();

	if( !pTable->is_Valid() || pTable->Get_Field_Count() <= 0 || pTable->Get_Record_Count() <= 0 )
	{
		Error_Set(_TL("invalid table"));

		return( false );
	}

	//-----------------------------------------------------
	CSG_Array_Int	_Fields;

	int	*Fields	= (int *)Parameters("FIELDS")->asPointer();
	int	nFields	=        Parameters("FIELDS")->asInt    ();

	if( nFields == 0 )
	{
		for(int i=0; i<pTable->Get_Field_Count(); i++)
		{
			if( SG_Data_Type_is_Numeric(pTable->Get_Field_Type(i)) )
			{
				_Fields.Inc_Array(); _Fields[nFields++]	= i;
			}
		}

		if( nFields == 0 )
		{
			Error_Set(_TL("could not find any numeric attribute field"));

			return( false );
		}

		Fields	= _Fields.Get_Array();
	}

	//-----------------------------------------------------
	if( Parameters("RESULT")->asTable() && Parameters("RESULT")->asTable() != pTable )
	{
		pTable	= Parameters("RESULT")->asTable();
		pTable->Create( *Parameters("TABLE")->asTable());
		pTable->Set_Name(Parameters("TABLE")->asTable()->Get_Name());
	}

	//-----------------------------------------------------
	double	Quantile	= Parameters("PCTL_VAL")->asDouble();

	int	offResult	= pTable->Get_Field_Count();

	bool	bStats[STATS_COUNT];

	{
		for(int i=0; i<STATS_COUNT; i++)
		{
			if( (bStats[i] = Parameters(STATS[i][0])->asBool()) == true )
			{
				pTable->Add_Field(STATS[i][1], SG_DATATYPE_Double);
			}
		}

		if( pTable->Get_Field_Count() == offResult )
		{
			Error_Set(_TL("no statistical measure has been selected"));

			return( false );
		}
	}

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

		CSG_Simple_Statistics	s(bStats[STATS_PCTL]);

		for(int iField=0; iField<nFields; iField++)
		{
			if( !pRecord->is_NoData(Fields[iField]) )
			{
				s	+= pRecord->asDouble(Fields[iField]);
			}
		}

		//-------------------------------------------------
		int	iField	= offResult;

		if( s.Get_Count() > 0 )
		{
			if( bStats[STATS_MEAN ]	)	pRecord->Set_Value(iField++, s.Get_Mean    ());
			if( bStats[STATS_MIN  ]	)	pRecord->Set_Value(iField++, s.Get_Minimum ());
			if( bStats[STATS_MAX  ]	)	pRecord->Set_Value(iField++, s.Get_Maximum ());
			if( bStats[STATS_RANGE]	)	pRecord->Set_Value(iField++, s.Get_Range   ());
			if( bStats[STATS_SUM  ]	)	pRecord->Set_Value(iField++, s.Get_Sum     ());
			if( bStats[STATS_NUM  ]	)	pRecord->Set_Value(iField++, s.Get_Count   ());
			if( bStats[STATS_VAR  ]	)	pRecord->Set_Value(iField++, s.Get_Variance());
			if( bStats[STATS_STDV ]	)	pRecord->Set_Value(iField++, s.Get_StdDev  ());
			if( bStats[STATS_PCTL ]	)	pRecord->Set_Value(iField++, s.Get_Quantile(Quantile));
		}
		else
		{
			for(int i=0; i<STATS_COUNT; i++)
			{
				if( bStats[i] )
				{
					pRecord->Set_NoData(iField++);
				}
			}
		}
	}

	//-----------------------------------------------------
	if( pTable == Parameters("TABLE")->asTable() )
	{
		DataObject_Update(pTable);
	}

	return( true );
}
Example #24
0
//---------------------------------------------------------
bool CRGA_Basic::On_Execute(void)
{
	bool		bRefresh;
	int			x, y, i, Segment;
	CSG_Grid	*pSeeds;

	//-----------------------------------------------------
	m_pSegments		= Parameters("SEGMENTS"  )->asGrid();
	m_pFeatures		= Parameters("FEATURES"  )->asGridList();
	m_nFeatures		= m_pFeatures->Get_Count();

	pSeeds			= Parameters("SEEDS"     )->asGrid();
	m_pSeeds		= Parameters("TABLE"     )->asTable();

	m_pSimilarity	= Parameters("SIMILARITY")->asGrid();

	m_dNeighbour	= Parameters("NEIGHBOUR" )->asInt() == 0 ? 2 : 1;

	m_Var_1			= SG_Get_Square(Parameters("SIG_1")->asDouble());
	m_Var_2			= SG_Get_Square(Parameters("SIG_2")->asDouble());
	m_Threshold		= Parameters("THRESHOLD" )->asDouble();

	m_bNormalize	= Parameters("NORMALIZE" )->asBool();

	m_Method		= Parameters("METHOD"    )->asInt();
	bRefresh		= Parameters("REFRESH"   )->asBool();

	//-----------------------------------------------------
	m_pSegments		->Assign(-1);
	m_pSegments		->Set_NoData_Value(-1);

	m_pSimilarity	->Assign(-1);
	m_pSimilarity	->Set_NoData_Value(-1);

	//-----------------------------------------------------
	m_pSeeds->Destroy();

	m_pSeeds->Add_Field(_TL("ID"  ), SG_DATATYPE_Int);
	m_pSeeds->Add_Field(_TL("AREA"), SG_DATATYPE_Double);
	m_pSeeds->Add_Field(_TL("X"   ), SG_DATATYPE_Double);
	m_pSeeds->Add_Field(_TL("Y"   ), SG_DATATYPE_Double);

	for(i=0; i<m_pFeatures->Get_Count(); i++)
	{
		m_pSeeds->Add_Field(m_pFeatures->asGrid(i)->Get_Name(), SG_DATATYPE_Double);
	}

	m_Candidates.Create(Parameters("LEAFSIZE")->asInt());

	//-----------------------------------------------------
	for(y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		for(x=0; x<Get_NX(); x++)
		{
			if( !pSeeds->is_NoData(x, y) )
			{
				CSG_Table_Record	*pRec	= m_pSeeds->Add_Record();

				pRec->Set_Value(0, m_pSeeds->Get_Count() - 1);
				pRec->Set_Value(SEEDFIELD_X, x);
				pRec->Set_Value(SEEDFIELD_Y, y);

				for(i=0; i<m_pFeatures->Get_Count(); i++)
				{
					pRec->Set_Value(SEEDFIELD_Z + i, Get_Feature(x, y, i));
				}

				m_pSimilarity->Set_Value(x, y, 1.0);

				Add_To_Segment(x, y, m_pSeeds->Get_Count() - 1);
			}
		}
	}

	//-----------------------------------------------------
	if( m_pSeeds->Get_Count() > 1 )
	{
		sLong	n	= 0;

		while( n++ < Get_NCells() && Set_Progress_NCells(n) && Get_Next_Candidate(x, y, Segment) )
		{
			Add_To_Segment(x, y, Segment);

			if( bRefresh && (n % Get_NX()) == 0 )
			{
				DataObject_Update(m_pSegments, 0, m_pSeeds->Get_Count());

				Process_Set_Text(CSG_String::Format(SG_T("%.2f"), 100.0 * m_Candidates.Get_Count() / Get_NCells()));
			}
		}

		m_Candidates.Destroy();

		return( true );
	}

	//-----------------------------------------------------
	m_Candidates.Destroy();

	return( false );
}
Example #25
0
//---------------------------------------------------------
bool CPolygon_Transect::On_Execute(void)
{
    CSG_Table   *pTransect_Result;
    CSG_Shapes  *pTheme, *pTransect;

    CSG_Shape_Line    *pLine;
    CSG_Shape_Polygon *pTheme_Shape;
    int Theme_Field;

    pTransect   = Parameters("TRANSECT")->asShapes();
    pTheme      = Parameters("THEME")->asShapes();

    pTransect_Result = Parameters("TRANSECT_RESULT")->asTable();
    Theme_Field = Parameters("THEME_FIELD")->asInt();

    //-----------------------------------------------------
    // Check for valid parameter settings...
    //-----------------------------------------------------
    if (pTheme->Get_Type() != SHAPE_TYPE_Polygon){
        Error_Set(CSG_String("[THEME] is not a polygon file"));
        return(false);
    }
    if (pTransect->Get_Type() != SHAPE_TYPE_Line){
        Error_Set(CSG_String("[TRANSECT] is not a line shapefile"));
        return(false);
    }
    if (pTheme->Get_Count() ==0 || pTransect->Get_Count()==0)
    {
        Error_Set(CSG_String("[TRANSECT] or [THEME] is empty"));
        return(false);
    }
    if (!(pTheme->Get_Extent().Intersects(pTransect->Get_Extent())))
    {
        Error_Set(CSG_String("[TRANSECT] and [THEME] do not intersect"));
        return(false);
    }

    const int LINE_ID = pTransect_Result->Get_Field_Count();
    pTransect_Result->Add_Field(SG_T("line_id"), SG_DATATYPE_Int);
    const int START = pTransect_Result->Get_Field_Count();
    pTransect_Result->Add_Field(SG_T("start"), SG_DATATYPE_Double);
    const int END = pTransect_Result->Get_Field_Count();
    pTransect_Result->Add_Field(SG_T("end"), SG_DATATYPE_Double);
    const int POLY_ID = pTransect_Result->Get_Field_Count();
    pTransect_Result->Add_Field(SG_T("poly_id"), SG_DATATYPE_Int);
    const int FIELD = pTransect_Result->Get_Field_Count();
    pTransect_Result->Add_Field(SG_T("field"), pTheme->Get_Field_Type(Theme_Field));
    
    // Short description of the algorithm:
    // For every line it is checked whether it crosses a polygon. If it does, 
    // the points where it crosses are recorded in the map LineBorders, with 
    // the polygon_id as key.
    
    for (int iLine=0; iLine<pTransect->Get_Count() && Set_Progress(iLine, pTransect->Get_Count());
                iLine++)
    {
        pLine =(CSG_Shape_Line *) pTransect->Get_Shape(iLine);
        for (int iLinePart=0;iLinePart<pLine->Get_Part_Count();iLinePart++)
        {
            CSG_Shape_Part *pLinePart =pLine->Get_Part(iLinePart);
            CSG_Rect LinePartExtent = pLinePart->Get_Extent();
            map<int,list<double> > LineBorders;
            for (int iShape=0; iShape<pTheme->Get_Count();iShape++)
            {
                pTheme_Shape = (CSG_Shape_Polygon *) pTheme->Get_Shape(iShape);
                if (pLinePart->Get_Extent().Intersects(pTheme_Shape->Get_Extent())>0)
                {
                    for (int iPart=0; iPart<pTheme_Shape->Get_Part_Count(); iPart++)
                    {
                        CSG_Shape_Polygon_Part *pPart = (CSG_Shape_Polygon_Part *) pTheme_Shape->Get_Part(iPart);
                        if (pPart->Contains(pLinePart->Get_Point(0)))
                            LineBorders[iShape].push_back(0);
                        if (pPart->Contains(pLinePart->Get_Point(pLinePart->Get_Count())))
                            LineBorders[iShape].push_back(pLine->Get_Length(iLinePart));
                        for (int iPoint=0; iPoint<pPart->Get_Count();iPoint++)
                        {
                            int iPoint2 = (iPoint!=pPart->Get_Count()-1)?iPoint+1:0;
                            TSG_Point Crossing;
                            double Length=0;
                            for (int iLinePartPoint=0; iLinePartPoint<pLinePart->Get_Count(); iLinePartPoint++)
                            {
                                if (SG_Get_Crossing(Crossing,pPart->Get_Point(iPoint),pPart->Get_Point(iPoint2),
                                                    pLinePart->Get_Point(iLinePartPoint), pLinePart->Get_Point(iLinePartPoint+1)))
                                {
                                    LineBorders[iShape].push_back(Length+SG_Get_Distance(Crossing, pLinePart->Get_Point(iLinePartPoint)));
                                }
                                Length+=SG_Get_Distance(pLinePart->Get_Point(iLinePartPoint), pLinePart->Get_Point(iLinePartPoint+1));
                            }
                        }
                    }
                }
            }
            // convert LineBorders to the result table
            // the table contains the lineids and the distance to the origin of the line,
            // and it is sorted by lineid, polygonid
            CSG_Table_Record *pRecord;
            for (map<int,list<double> >::iterator shapeit=LineBorders.begin();shapeit!=LineBorders.end();++shapeit)
            {
                //shapeit->second.sort();
                bool start=1;
                for (list<double>::iterator i=shapeit->second.begin(); i!=shapeit->second.end();++i)
                {
                    if (start){
                        pRecord =pTransect_Result->Add_Record();
                        pRecord->Set_Value(LINE_ID, iLine);
                        pRecord->Set_Value(START, *i);
                        pRecord->Set_Value(POLY_ID, shapeit->first);
                        CSG_Table_Record *pTheme_Record =pTheme->Get_Shape(shapeit->first) ;
                        if(pTheme->Get_Field_Type(Theme_Field)== SG_DATATYPE_String )
                            pRecord->Set_Value(FIELD, pTheme_Record->asString(Theme_Field));
                        else
                            pRecord->Set_Value(FIELD, pTheme_Record->asDouble(Theme_Field));
                        start = 0;
                    }
                    else
                    {
                        pRecord->Set_Value(END, *i);
                        start=1;
                    }
                }
            }
        }
    }
    return( true );
}
//---------------------------------------------------------
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 );
}
Example #27
0
//---------------------------------------------------------
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 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
Example #29
0
//---------------------------------------------------------
bool CTable_Append_Rows::On_Execute(void)
{
	CSG_Table	*pTable, *pOutput, *pAppend;

	//-----------------------------------------------------
	pTable	= Parameters("INPUT" )->asTable();
	pOutput	= Parameters("OUTPUT")->asTable();
	pAppend	= Parameters("APPEND")->asTable();

	//-----------------------------------------------------
	if( pTable->Get_Record_Count() <= 0 )
	{
		Error_Set(_TL("no records in data set"));

		return( false );
	}

	if( pAppend->Get_Record_Count() <= 0 )
	{
		Error_Set(_TL("no records to append"));

		return( false );
	}

	//-----------------------------------------------------
	if( pOutput && pOutput != pTable )
	{
		pOutput->Create		(*pTable);
		pOutput->Set_Name	( pTable->Get_Name());
		pTable	= pOutput;
	}

	//-----------------------------------------------------
	int		iField, jField, aField, nRecords;

	nRecords	= pTable->Get_Count() < pAppend->Get_Count() ? pTable->Get_Count() : pAppend->Get_Count();
	aField		= pTable->Get_Field_Count();

	for(iField=0; iField<pAppend->Get_Field_Count(); iField++)
	{
		pTable->Add_Field(pAppend->Get_Field_Name(iField), pAppend->Get_Field_Type(iField));
	}

	//-----------------------------------------------------
	for(int iRecord=0; iRecord<nRecords && Set_Progress(iRecord, nRecords); iRecord++)
	{
		CSG_Table_Record	*pRec	= pTable ->Get_Record(iRecord);
		CSG_Table_Record	*pAdd	= pAppend->Get_Record(iRecord);

		for(iField=0, jField=aField; iField<pAppend->Get_Field_Count(); iField++)
		{
			*pRec->Get_Value(jField++)	= *pAdd->Get_Value(iField);
		}
	}

	//-----------------------------------------------------
	if( pTable == Parameters("INPUT")->asTable() )
	{
		DataObject_Update(pTable);
	}

	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 );
}