Пример #1
0
//---------------------------------------------------------
bool CTable_Text_Export::On_Execute(void)
{
    CSG_String	StrFormat, Separator;
    CSG_File	Stream;
    CSG_Table	*pTable;

    //-----------------------------------------------------
    pTable		= Parameters("TABLE"   )->asTable();
    StrFormat	= Parameters("STRQUOTA")->asBool() ? SG_T("\"%s\"") : SG_T("%s");

    switch( Parameters("SEPARATOR")->asInt() )
    {
    case 0:
        Separator	= "\t";
        break;
    case 1:
        Separator	=  ";";
        break;
    case 2:
        Separator	=  ",";
        break;
    case 3:
        Separator	=  " ";
        break;
    default:
        Separator	= Parameters("SEP_OTHER")->asString();
        break;
    }

    //-----------------------------------------------------
    if( !Stream.Open(Parameters("FILENAME")->asString(), SG_FILE_W, false) )
    {
        Message_Add(_TL("file could not be opened."));
    }

    //-----------------------------------------------------
    else
    {
        if( Parameters("HEADLINE")->asBool() )
        {
            for(int iField=0; iField<pTable->Get_Field_Count(); iField++)
            {
                Stream.Printf(StrFormat.c_str(), pTable->Get_Field_Name(iField));
                Stream.Printf(iField < pTable->Get_Field_Count() - 1 ? Separator.c_str() : SG_T("\n"));
            }
        }

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

            for(int iField=0; iField<pTable->Get_Field_Count(); iField++)
            {
                switch( pTable->Get_Field_Type(iField) )
                {
                default:
                case SG_DATATYPE_Char:
                case SG_DATATYPE_String:
                case SG_DATATYPE_Date:
                    Stream.Printf(StrFormat.c_str(), pRecord->asString(iField));
                    break;

                case SG_DATATYPE_Short:
                case SG_DATATYPE_Int:
                case SG_DATATYPE_Color:
                    Stream.Printf(SG_T("%d")	, pRecord->asInt(iField));
                    break;

                case SG_DATATYPE_Long:
                    Stream.Printf(SG_T("%ld")	, (long)pRecord->asDouble(iField));
                    break;

                case SG_DATATYPE_ULong:
                    Stream.Printf(SG_T("%lu")	, (unsigned long)pRecord->asDouble(iField));
                    break;

                case SG_DATATYPE_Float:
                case SG_DATATYPE_Double:
                    Stream.Printf(SG_T("%f")	, pRecord->asDouble(iField));
                    break;
                }

                Stream.Printf(iField < pTable->Get_Field_Count() - 1 ? Separator.c_str() : SG_T("\n"));
            }
        }

        //-------------------------------------------------
        Stream.Close();

        return( true );
    }

    return( false );
}
Пример #2
0
//---------------------------------------------------------
bool CGrid_Tiling::On_Execute(void)
{
	bool					bSaveTiles;
	int						ix, iy, nx, ny, Overlap;
	double					y, x, dx, dy, dCell;
	CSG_String				FilePath, BaseName;
	TSG_Data_Type			Type;
	TSG_Rect				Extent;
	TSG_Grid_Resampling	Interpolation;
	CSG_Grid				*pGrid, *pTile;
	CSG_Parameter_Grid_List	*pTiles;

	//-----------------------------------------------------
	pGrid	= Parameters("GRID")	->asGrid();
	pTiles	= Parameters("TILES")	->asGridList();
	Overlap	= Parameters("OVERLAP")	->asInt();

	bSaveTiles	= Parameters("SAVE_TILES")		->asBool();
	BaseName	= Parameters("TILE_BASENAME")	->asString();
	FilePath	= Parameters("TILE_PATH")		->asString();


	switch( Parameters("METHOD")->asInt() )
	{
	case 0: default:
		Extent.xMin		= pGrid->Get_XMin();
		Extent.xMax		= pGrid->Get_XMax();
		Extent.yMin		= pGrid->Get_YMin();
		Extent.yMax		= pGrid->Get_YMax();
		dCell			= pGrid->Get_Cellsize();
		nx				= Parameters("NX")		->asInt();
		ny				= Parameters("NY")		->asInt();
		dx				= dCell * nx;
		dy				= dCell * ny;
		Type			= pGrid->Get_Type();
		Interpolation	= GRID_RESAMPLING_NearestNeighbour;
		break;

	case 1:
		Extent.xMin		= Parameters("XRANGE")	->asRange()->Get_LoVal();
		Extent.xMax		= Parameters("XRANGE")	->asRange()->Get_HiVal();
		Extent.yMin		= Parameters("YRANGE")	->asRange()->Get_LoVal();
		Extent.yMax		= Parameters("YRANGE")	->asRange()->Get_HiVal();
		dCell			= Parameters("DCELL")	->asDouble();
		dx				= Parameters("DX")		->asDouble();
		dy				= Parameters("DY")		->asDouble();
		nx				= (int)(dx / dCell);
		ny				= (int)(dy / dCell);
		Type			= pGrid->Get_Type();
		Interpolation	= GRID_RESAMPLING_Undefined;
		break;
	}

	switch( Parameters("OVERLAP_SYM")->asInt() )
	{
	case 0: default:	// symetric
		nx		+= Overlap * 2;
		ny		+= Overlap * 2;
		break;

	case 1:				// bottom / left
		nx		+= Overlap;
		ny		+= Overlap;
		break;

	case 2:				// top / right
		nx		+= Overlap;
		ny		+= Overlap;
		Overlap	 = 0;
		break;
	}

	pTiles->Del_Items();

	//-----------------------------------------------------
	if( dx <= 0.0 || dy <= 0.0 || dCell <= 0.0 )
	{
		Message_Add(_TL("no intersection with mask grid."));

		return( false );
	}

	if( bSaveTiles )
	{
		if( !SG_STR_CMP(BaseName, SG_T("")) )
		{
			SG_UI_Msg_Add_Error(_TL("Please provide a valid base name for the output files!"));
			return( false );
		}
		if( !SG_STR_CMP(FilePath, SG_T("")) )
		{
			SG_UI_Msg_Add_Error(_TL("Please provide a valid output directory for the output files!"));
			return( false );
		}
	}


	//-----------------------------------------------------
	int		iTiles = 0;

	for(y=Extent.yMin, iy=1; y<Extent.yMax && Process_Get_Okay(); y+=dy, iy++)
	{
		for(x=Extent.xMin, ix=1; x<Extent.xMax; x+=dx, ix++)
		{
			pTile	= SG_Create_Grid(Type, nx, ny, dCell, x - dCell * Overlap, y - dCell * Overlap);
			pTile	->Assign(pGrid, Interpolation);
			pTile	->Set_Name(CSG_String::Format(SG_T("%s [%d, %d]"), pGrid->Get_Name(), iy, ix));

			if( pTile->Get_NoData_Count() == pTile->Get_NCells() )
			{
				delete(pTile);
			}
			else
			{
				if( bSaveTiles )
				{
					CSG_String FileName = CSG_String::Format(SG_T("%s/%s_%d_%d"), FilePath.c_str(), BaseName.c_str(), iy, ix);
					pTile->Save(FileName);
					delete(pTile);
				}
				else
				{
					pTiles->Add_Item(pTile);
				}

				iTiles++;
			}
		}
	}

	SG_UI_Msg_Add(CSG_String::Format(_TL("%d tiles created."), iTiles), true);

	return( iTiles > 0 );
}
Пример #3
0
//---------------------------------------------------------
bool CShapes2Grid::On_Execute(void)
{
	//-----------------------------------------------------
	m_pShapes			= Parameters("INPUT"    )->asShapes();

	m_Method_Lines		= Parameters("LINE_TYPE")->asInt();
	m_Method_Polygon	= Parameters("POLY_TYPE")->asInt();
	m_Method_Multi		= Parameters("MULTIPLE" )->asInt();

	if( m_pShapes->Get_Type() == SHAPE_TYPE_Polygon && m_Method_Polygon == 1 )	// all cells intersected have to be marked
	{
		m_Method_Lines	= 1;	// thick, each cell crossed by polygon boundary will be marked additionally
	}

	//-----------------------------------------------------
	int		iField;

	switch( Parameters("OUTPUT")->asInt() )
	{
	case 0:	iField	= -1;	break;
	case 1:	iField	= -2;	break;
	case 2:
		if( (iField = Parameters("FIELD")->asInt()) < 0 || !SG_Data_Type_is_Numeric(m_pShapes->Get_Field_Type(iField)) )
		{
			iField		= -2;

			Message_Add(_TL("WARNING: selected attribute is not numeric; generating unique identifiers instead."));
		}
		break;
	}

	//-----------------------------------------------------
	m_Grid_Target.Cmd_Update(m_pShapes);	// if called from saga_cmd

	if( (m_pGrid = m_Grid_Target.Get_Grid("GRID", Get_Grid_Type(Parameters("GRID_TYPE")->asInt()))) == NULL )
	{
		return( false );
	}

	if( iField < 0 )
	{
		m_pGrid->Set_NoData_Value(0.0);
	}

	m_pGrid->Set_Name(CSG_String::Format("%s [%s]", m_pShapes->Get_Name(), iField < 0 ? _TL("ID") : m_pShapes->Get_Field_Name(iField)));
	m_pGrid->Assign_NoData();

	//-------------------------------------------------
	m_pCount	= m_Grid_Target.Get_Grid("COUNT", m_pShapes->Get_Count() < 256 ? SG_DATATYPE_Byte : SG_DATATYPE_Word);

	if( m_pCount == NULL )
	{
		m_Count.Create(m_pGrid->Get_System(), SG_DATATYPE_Word);

		m_pCount	= &m_Count;
	}

	m_pCount->Set_Name(CSG_String::Format("%s [%s]", m_pShapes->Get_Name(), _TL("Count")));
	m_pCount->Set_NoData_Value(0.0);
	m_pCount->Assign(0.0);

	//-----------------------------------------------------
	for(int iShape=0; iShape<m_pShapes->Get_Count() && Set_Progress(iShape, m_pShapes->Get_Count()); iShape++)
	{
		CSG_Shape	*pShape	= m_pShapes->Get_Shape(iShape);

		if( m_pShapes->Get_Selection_Count() <= 0 || pShape->is_Selected() )
		{
			if( iField < 0 || !pShape->is_NoData(iField) )
			{
				m_Value	= iField >= 0 ? pShape->asDouble(iField) : iField == -2 ? iShape + 1 : 1;

				if( pShape->Intersects(m_pGrid->Get_Extent()) )
				{
					switch( m_pShapes->Get_Type() )
					{
					case SHAPE_TYPE_Point:	case SHAPE_TYPE_Points:
						Set_Points	(pShape);
						break;

					case SHAPE_TYPE_Line:
						Set_Line	(pShape);
						break;

					case SHAPE_TYPE_Polygon:
						Set_Polygon	(pShape);

						if( m_Method_Polygon == 1 )	// all cells intersected have to be marked
						{
							Set_Line(pShape);	// thick, each cell crossed by polygon boundary will be marked additionally
						}
						break;
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	if( m_Method_Multi == 4 )	// mean
	{
		for(int y=0; y<m_pGrid->Get_NY() && Set_Progress(y, m_pGrid->Get_NY()); y++)
		{
			for(int x=0; x<m_pGrid->Get_NX(); x++)
			{
				if( m_pCount->asInt(x, y) > 1 )
				{
					m_pGrid->Mul_Value(x, y, 1.0 / m_pCount->asDouble(x, y));
				}
			}
		}
	}

	//-----------------------------------------------------
	m_Count.Destroy();

	return( true );
}
Пример #4
0
bool CCreateGridSystem::On_Execute(void)		
{
	CSG_Grid					*pDummy;
	CSG_Shapes					*pShapes;
	CSG_Rect					extent;
	CSG_Parameter_Shapes_List	*pShapesList;
	CSG_Parameter_Grid_List		*pGridList;
	CSG_Grid_System				System;

	double		xMin, xMax, yMin, yMax, cellsize, offset_x, offset_y, xRange, yRange, n, initVal;
	int			NX, NY, m_extent, m_adjust, i;
	bool		useoff;


	xMin		= Parameters("XMIN")->asDouble();
	yMin		= Parameters("YMIN")->asDouble();
	xMax		= Parameters("XMAX")->asDouble();
	yMax		= Parameters("YMAX")->asDouble();
	NX			= Parameters("NX")->asInt();
	NY			= Parameters("NY")->asInt();
	cellsize	= Parameters("CELLSIZE")->asDouble();
	offset_x	= Parameters("XOFFSET")->asDouble();
	offset_y	= Parameters("YOFFSET")->asDouble();
	useoff		= Parameters("USEOFF")->asBool();
	m_extent	= Parameters("M_EXTENT")->asInt();
	m_adjust	= Parameters("ADJUST")->asInt();
    initVal     = Parameters("INIT")->asDouble();
	pShapesList	= Parameters("SHAPESLIST")->asShapesList();
	pGridList	= Parameters("GRIDLIST")->asGridList();


	if( useoff )
	{
		xMin += offset_x;
		yMin += offset_y;
		xMax += offset_x;
		yMax += offset_y;
	}

	switch( m_extent )
	{
	case 0:					// xMin, yMin, NX, NY

		System.Assign(cellsize, xMin, yMin, NX, NY);
		break;

	case 1:					// xMin, yMin, xMax, yMax

		if( xMin > xMax || yMin > yMax )
		{
			Message_Add(CSG_String::Format(_TL("\nError: Please verify your xMin, yMin, xMax, yMax settings!\n")));
			return false;
		}

		xRange = xMax - xMin;
		yRange = yMax - yMin;

		if( m_adjust == 0 )			// extent to cellsize
		{
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) floor(xRange / cellsize + 0.5);
				xMax = xMin + NX * cellsize;
			}
			
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) floor(yRange / cellsize + 0.5);
				yMax = yMin + NY * cellsize;
			}
		}
		else if( m_adjust == 1)		// cellsize to W-E extent
		{
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) (xRange/cellsize);
				cellsize = xRange/NX;
			}			
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) floor(yRange / cellsize + 0.5);
				yMax = yMin + NY * cellsize;
			}
		}
		else						// cellsize to S-N extent
		{
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) (yRange/cellsize);
				cellsize = yRange/NY;
			}	
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) floor(xRange / cellsize + 0.5);
				xMax = xMin + NX * cellsize;
			}
		}

		System.Assign(cellsize, xMin, yMin, xMax, yMax);
		break;

	case 2:			// Shape(s)

		if( pShapesList == NULL || pShapesList->Get_Count() == 0)
		{
			Message_Add(CSG_String::Format(_TL("\nError: the method Extent by Shape(s) requires shape(s) as input!\n")));
			return false;
		}

		for (i=0; i<pShapesList->Get_Count(); i++)
		{
			pShapes = pShapesList->asShapes(i);
			extent = pShapes->Get_Extent();

			if (i==0)
			{
				xMin = extent.Get_XMin();
				yMin = extent.Get_YMin();
				xMax = extent.Get_XMax();
				yMax = extent.Get_YMax();
			}
			else
			{
				xMin = (extent.Get_XMin() < xMin) ? extent.Get_XMin() : xMin;
				yMin = (extent.Get_YMin() < yMin) ? extent.Get_YMin() : yMin;
				xMax = (extent.Get_XMax() > xMax) ? extent.Get_XMax() : xMax;
				yMax = (extent.Get_YMax() > yMax) ? extent.Get_YMax() : yMax;
			}		
		}

		if( useoff )
		{
			xMin += offset_x;
			xMax += offset_x;
			yMin += offset_y;
			yMax += offset_y;
		}

		xRange = xMax - xMin;
		yRange = yMax - yMin;

		if( m_adjust == 0 )			// extent to cellsize
		{
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) floor(xRange / cellsize + 0.5);
				xMax = xMin + NX * cellsize;
			}
			
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) floor(yRange / cellsize + 0.5);
				yMax = yMin + NY * cellsize;
			}
		}
		else if( m_adjust == 1)		// cellsize to W-E extent
		{
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) (xRange/cellsize);
				cellsize = xRange/NX;
			}	
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) floor(yRange / cellsize + 0.5);
				yMax = yMin + NY * cellsize;
			}
		}
		else						// cellsize to S-N extent
		{
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) (yRange/cellsize);
				cellsize = yRange/NY;
			}
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) floor(xRange / cellsize + 0.5);
				xMax = xMin + NX * cellsize;
			}
		}

		System.Assign(cellsize, xMin, yMin, xMax, yMax);
		break;	

	case 3:				// Grid(s)

		if( pGridList == NULL || pGridList->Get_Count() == 0)
		{
			Message_Add(CSG_String::Format(_TL("\nError: the method Extent by Grid(s) requires grid(s) as input!\n")));
			return false;
		}
				
		for (i=0; i<pGridList->Get_Count(); i++)
		{
			pDummy = pGridList->asGrid(i);
			extent = pDummy->Get_Extent();

			if (i==0)
			{
				xMin = extent.Get_XMin();
				yMin = extent.Get_YMin();
				xMax = extent.Get_XMax();
				yMax = extent.Get_YMax();
			}
			else
			{
				xMin = (extent.Get_XMin() < xMin) ? extent.Get_XMin() : xMin;
				yMin = (extent.Get_YMin() < yMin) ? extent.Get_YMin() : yMin;
				xMax = (extent.Get_XMax() > xMax) ? extent.Get_XMax() : xMax;
				yMax = (extent.Get_YMax() > yMax) ? extent.Get_YMax() : yMax;
			}		
		}

		if( useoff )
		{
			xMin += offset_x;
			xMax += offset_x;
			yMin += offset_y;
			yMax += offset_y;
		}

		xRange = xMax - xMin;
		yRange = yMax - yMin;

		if( m_adjust == 0 )			// extent to cellsize
		{
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) floor(xRange / cellsize + 0.5);
				xMax = xMin + NX * cellsize;
			}
			
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) floor(yRange / cellsize + 0.5);
				yMax = yMin + NY * cellsize;
			}
		}
		else if( m_adjust == 1)		// cellsize to W-E extent
		{
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) (xRange/cellsize);
				cellsize = xRange/NX;
			}			
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) floor(yRange / cellsize + 0.5);
				yMax = yMin + NY * cellsize;
			}
		}
		else						// cellsize to S-N extent
		{
			if( modf((yRange/cellsize), &n) != 0.0 )
			{
				NY = (int) (yRange/cellsize);
				cellsize = yRange/NY;
			}			
			if( modf((xRange/cellsize), &n) != 0.0 )
			{
				NX = (int) floor(xRange / cellsize + 0.5);
				xMax = xMin + NX * cellsize;
			}
		}

		System.Assign(cellsize, xMin, yMin, xMax, yMax);
		break;
	}
		
	pDummy = SG_Create_Grid(System, SG_DATATYPE_Double);
	pDummy->Assign(initVal);
	pDummy->Set_Name(_TL("Dummy Grid"));
	Parameters("GRID")->Set_Value(pDummy);

	return (true);

}
Пример #5
0
//---------------------------------------------------------
bool CGCS_Grid_Longitude_Range::On_Execute(void)
{
	CSG_Parameter_Grid_List	*pInput		= Parameters("INPUT" )->asGridList();
	CSG_Parameter_Grid_List	*pOutput	= Parameters("OUTPUT")->asGridList();

	if( pInput->Get_Count() <= 0 )
	{
		Message_Dlg(_TL("nothing to do: no data in selection"));

		return( false );
	}

	pOutput->Del_Items();

	//-----------------------------------------------------
	int				xZero;
	CSG_Grid_System	Target;

	//-----------------------------------------------------
	if( Parameters("DIRECTION")->asInt() == 0 )	// 0 - 360 >> -180 - 180
	{
		if( Get_XMax() <= 180.0 )
		{
			Message_Add(_TL("Nothing to do. Raster is already within target range."));

			return( true );
		}
		else if( Get_XMin() >= 180.0 )
		{
			xZero	= 0;

			Target.Assign(Get_Cellsize(), Get_XMin() - 360.0, Get_YMin(), Get_NX(), Get_NY());
		}
		else if( Get_XMax() - 360.0 < Get_XMin() - Get_Cellsize() )
		{
			Error_Set(_TL("Nothing to do be done. Raster splitting is not supported."));

			return( false );
		}
		else
		{
			xZero	= (int)(0.5 + 180.0 / Get_Cellsize());

			Target.Assign(Get_Cellsize(), Get_XMin() - 180.0, Get_YMin(), Get_NX(), Get_NY());
		}
	}

	//-----------------------------------------------------
	else										// -180 - 180 >> 0 - 360
	{
		if( Get_XMin() >= 0.0 )
		{
			Message_Add(_TL("Nothing to do. Raster is already within target range."));

			return( true );
		}
		else if( Get_XMax() <= 0.0 )
		{
			xZero	= 0;

			Target.Assign(Get_Cellsize(), Get_XMin() + 360.0, Get_YMin(), Get_NX(), Get_NY());
		}
		else if( Get_XMin() + 360.0 > Get_XMax() + Get_Cellsize() )
		{
			Error_Set(_TL("Nothing to do be done. Raster splitting is not supported."));

			return( false );
		}
		else
		{
			xZero	= (int)(0.5 + 180.0 / Get_Cellsize());

			Target.Assign(Get_Cellsize(), Get_XMin() - 180.0, Get_YMin(), Get_NX(), Get_NY());
		}
	}

	//-----------------------------------------------------
	for(int i=0; i<pInput->Get_Count() && Process_Get_Okay(); i++)
	{
		CSG_Grid	*pIn	= pInput->asGrid(i);
		CSG_Grid	*pOut	= SG_Create_Grid(Target, pIn->Get_Type());

		pOut->Set_Name(pIn->Get_Name());
		pOut->Set_NoData_Value_Range(pIn->Get_NoData_Value(), pIn->Get_NoData_hiValue());
		pOut->Set_ZFactor(pIn->Get_ZFactor());

		pOutput->Add_Item(pOut);

		for(int y=0; y<Get_NY() && Set_Progress(y); y++)
		{
			for(int x=0, xx=xZero; x<Get_NX(); x++, xx++)
			{
				if( xx >= Get_NX() )
				{
					xx	= 0;
				}

				pOut->Set_Value(xx, y, pIn->asDouble(x, y));
			}
		}
	}

	//-----------------------------------------------------
	return( true );
}
Пример #6
0
//---------------------------------------------------------
bool CSelect_Location::On_Execute(void)
{
	int		Method, Condition;

	m_pShapes		= Parameters("SHAPES")		->asShapes();
	m_pLocations	= Parameters("LOCATIONS")	->asShapes();
	Condition		= Parameters("CONDITION")	->asInt();
	Method			= Parameters("METHOD")		->asInt();

	//-----------------------------------------------------
	switch( Condition )
	{
	case 0:	// intersect
		if( ((m_pShapes   ->Get_Type() == SHAPE_TYPE_Point || m_pShapes   ->Get_Type() == SHAPE_TYPE_Points) && m_pLocations->Get_Type() != SHAPE_TYPE_Polygon)
		||	((m_pLocations->Get_Type() == SHAPE_TYPE_Point || m_pLocations->Get_Type() == SHAPE_TYPE_Points) && m_pShapes   ->Get_Type() != SHAPE_TYPE_Polygon) )
		{
			Error_Set(_TL("points can only intersect with polygons"));

			return( false );
		}
		break;

	case 1:	// are completely within
	case 3:	// have their centroid in
		if( m_pLocations->Get_Type() != SHAPE_TYPE_Polygon )
		{
			Error_Set(_TL("this operation requires locations to be of type polygon"));

			return( false );
		}
		break;

	case 2:	// completely contain
	case 4:	// contain the centroid of
		if( m_pShapes->Get_Type() != SHAPE_TYPE_Polygon )
		{
			Error_Set(_TL("this operation requires selectable shapes to be of type polygon"));

			return( false );
		}
		break;
	}

	//-----------------------------------------------------
	for(int i=0; i<m_pShapes->Get_Count() && Set_Progress(i, m_pShapes->Get_Count()); i++)
	{
		CSG_Shape	*pShape	= m_pShapes->Get_Shape(i);

		switch( Method )
		{
		case 0:	// New selection
			if( ( pShape->is_Selected() && !Do_Select(pShape, Condition))
			||	(!pShape->is_Selected() &&  Do_Select(pShape, Condition)) )
			{
				m_pShapes->Select(i, true);
			}
			break;

		case 1:	// Add to current selection
			if(  !pShape->is_Selected() &&  Do_Select(pShape, Condition) )
			{
				m_pShapes->Select(i, true);
			}
			break;

		case 2:	// Select from current selection
			if(   pShape->is_Selected() && !Do_Select(pShape, Condition) )
			{
				m_pShapes->Select(i, true);
			}
			break;

		case 3:	// Remove from current selection
			if(   pShape->is_Selected() &&  Do_Select(pShape, Condition) )
			{
				m_pShapes->Select(i, true);
			}
			break;
		}
	}

	//-----------------------------------------------------
	Message_Add(CSG_String::Format(SG_T("%s: %d"), _TL("selected shapes"), m_pShapes->Get_Selection_Count()));

	DataObject_Update(m_pShapes);

	return( true );
}
Пример #7
0
bool CFit::On_Execute(void)
{
	int i, j,  NrVars;
	vector < double> x, y, StartValue, Result;
	CSG_String	msg;	
	
	CSG_Parameters StartParameters;

	const SG_Char *formel	=	Parameters("FORMEL")->asString();

	Formel.Add_Function(SG_T("NUG"), (TSG_PFNC_Formula_1) NUG, 1, 0);
	Formel.Add_Function(SG_T("SPH"), (TSG_PFNC_Formula_1) SPH, 2, 0);
	Formel.Add_Function(SG_T("EXP"), (TSG_PFNC_Formula_1) EXP, 2, 0);
    Formel.Add_Function(SG_T("LIN"), (TSG_PFNC_Formula_1) LIN, 2, 0);
	
	
	Formel.Set_Formula(formel);
	
	
	if (Formel.Get_Error(msg))
	{
		Message_Add(msg);

		return false;
	}
	
	const SG_Char *uservars = NULL;
	
	uservars = Formel.Get_Used_Variables();
	

	NrVars	=	0;
	for (i = 0; i < SG_STR_LEN(uservars); i++)
	{
		if (uservars[i] >='a' && uservars[i] <= 'z')
		{
			if (uservars[i] != 'x')
				vars[NrVars++] = uservars[i];
		}
	}
	
	vars[NrVars] =(char) 0;
	
	StartParameters.Add_Info_String(NULL, _TL(""), _TL("Formula"), _TL("Formula"), formel);
	
	for (i = 0; i < strlen(vars); i++)
	{
		CSG_String	c(vars[i]);
		StartParameters.Add_Value(NULL, c, c, _TL("Start Value"), PARAMETER_TYPE_Double, 1.0);
	}
	
	Dlg_Parameters(&StartParameters, _TL("Start Values"));
	
	for (i = 0; i < strlen(vars); i++)
	{
		char c[3];
		sprintf(c, "%c", vars[i]);
		StartValue.push_back(StartParameters(c)->asDouble());
	}
	
	CSG_Table	*pTable	= Parameters("SOURCE")->asTable();
	int Record_Count = pTable->Get_Record_Count();
	
	int	yField		= Parameters("YFIELD")->asInt();
	int	xField		= Parameters("XFIELD")->asInt();
	bool Use_X		= Parameters("USE_X")->asBool();
	
	pTable->Add_Field(_TL("Fit")				, SG_DATATYPE_Double);	
	
	for (i = 0; i < Record_Count; i++)
	{
		CSG_Table_Record *	Record = pTable->Get_Record(i);
		if (Use_X)
		{
			x.push_back(Record->asDouble(xField));
		}
		else
		{
			x.push_back(i);
		}
		
		y.push_back(Record->asDouble(yField));
	}
	
	TLMFit *Fit;
	
	Fit = new TLMFit(x, y, StartValue,  FitFunc);
	
	int max_iter = Parameters("ITER")->asInt();
	double Max_lamda = Parameters("LAMDA")->asInt();
	
	int iter = 0; 
	
	try
	{
		Fit->Fit();
		
		while ((Fit->Alamda() < Max_lamda) &&(iter < max_iter) &&Process_Get_Okay(true))
		{
			Fit->Fit();
			iter++;
		}
	}
	catch (ESingularMatrix &E)
	{
		if (E.Type == 1 || E.Type == 2)
		{
			msg.Printf(_TL("Matrix signular\n"));
			
			Message_Add(msg);
			
			return false;
		}
	}
	
	Result    = Fit->Param();
	
	for (i = 0; i < NrVars; i++)
	{
		Formel.Set_Variable(vars[i], (double) Result[i]);
	}
	
	msg.Printf(_TL("Model Parameters:"));
	Message_Add(msg);
	for (i = 0; i < NrVars; i++)
	{
		msg.Printf(SG_T("%c = %f\n"), vars[i], Result[i]);
		Message_Add(msg);
	}
	
	msg.Printf(_TL("\nRMS  of Residuals (stdfit):\t%f\n"), sqrt(Fit->Chisq()/x.size()));
	Message_Add(msg);
	
	msg.Printf(_TL("Correlation Matrix of the Fit Parameters:\n"));
	Message_Add(msg);
	
	vector< vector < double> > covar = Fit->Covar();
	
	msg.Printf(_TL(""));
	for (j = 0; j < NrVars; j++)
		msg.Printf(SG_T("%s\t%c"), msg.c_str(), vars[j]);
	
	msg.Printf(SG_T("%s\n"), msg.c_str());
	
	Message_Add(msg);
	
	for (i = 0; i < NrVars; i++)
	{
		msg.Printf(SG_T("%c"), vars[i]);
		for (j = 0; j <= i; j++)
		{	
			msg.Printf(SG_T("%s\t%f"), msg.c_str(), covar[i][j]/covar[i][i]);
		}
		msg.Printf(SG_T("%s\n"), msg.c_str());
		
		Message_Add(msg);
	}
	
	int Field_Count  = pTable->Get_Field_Count();
	
	for (i = 0; i < Record_Count; i++)
	{
		CSG_Table_Record *	Record = pTable->Get_Record(i);
		
		Record->Set_Value(Field_Count - 1, Formel.Get_Value(x[i]));
	}

//	API_FREE (uservars);
	return (true);
}
Пример #8
0
//---------------------------------------------------------
bool CKriging_Base::On_Execute(void)
{
	bool	bResult	= false;

	//-----------------------------------------------------
	m_Block		= Parameters("BLOCK"   )->asBool() ? Parameters("DBLOCK")->asDouble() / 2.0 : 0.0;
	m_bStdDev	= Parameters("TQUALITY")->asInt() == 0;
	m_bLog		= Parameters("LOG"     )->asBool();

	m_pPoints	= Parameters("POINTS"  )->asShapes();
	m_zField	= Parameters("ZFIELD"  )->asInt();

	if( m_pPoints->Get_Count() <= 1 )
	{
		SG_UI_Msg_Add(_TL("not enough points for interpolation"), true);

		return( false );
	}

	//-----------------------------------------------------
	CSG_Table	Variogram;

	if( SG_UI_Get_Window_Main() )
	{
		static CVariogram_Dialog	dlg;

		if( dlg.Execute(m_pPoints, m_zField, m_bLog, &Variogram, &m_Model) )
		{
			bResult	= true;
		}
	}
	else
	{
		int		nSkip		= Parameters("VAR_NSKIP"   )->asInt();
		int		nClasses	= Parameters("VAR_NCLASSES")->asInt();
		double	maxDistance	= Parameters("VAR_MAXDIST" )->asDouble();

		m_Model.Set_Formula(Parameters("VAR_MODEL")->asString());

		if( CSG_Variogram::Calculate(m_pPoints, m_zField, m_bLog, &Variogram, nClasses, maxDistance, nSkip) )
		{
			m_Model.Clr_Data();

			for(int i=0; i<Variogram.Get_Count(); i++)
			{
				CSG_Table_Record	*pRecord	= Variogram.Get_Record(i);

				m_Model.Add_Data(pRecord->asDouble(CSG_Variogram::FIELD_DISTANCE), pRecord->asDouble(CSG_Variogram::FIELD_VAR_EXP));
			}

			bResult	= m_Model.Get_Trend() || m_Model.Get_Parameter_Count() == 0;
		}
	}

	//-----------------------------------------------------
	if( bResult && (bResult = _Initialise_Grids() && On_Initialize()) )
	{
		Message_Add(CSG_String::Format(SG_T("%s: %s"), _TL("variogram model"), m_Model.Get_Formula(SG_TREND_STRING_Formula_Parameters).c_str()), false);

		for(int y=0; y<m_pGrid->Get_NY() && Set_Progress(y, m_pGrid->Get_NY()); y++)
		{
			#pragma omp parallel for
			for(int x=0; x<m_pGrid->Get_NX(); x++)
			{
				double	z, v;

				if( Get_Value(m_pGrid->Get_System().Get_Grid_to_World(x, y), z, v) )
				{
					Set_Value(x, y, z, v);
				}
				else
				{
					Set_NoData(x, y);
				}
			}
		}
	}

	//-----------------------------------------------------
	m_Model.Clr_Data();

	On_Finalize();

	return( bResult );
}
Пример #9
0
//---------------------------------------------------------
bool CShapes_Save::On_Execute(void)
{
	if( !Get_Connection()->has_PostGIS() )
	{
		Error_Set(_TL("not a valid PostGIS database!"));

		return( false );
	}

	//-----------------------------------------------------
	CSG_Shapes	*pShapes;
	CSG_String	SQL, Name, Type, Field, SavePoint;

	pShapes		= Parameters("SHAPES")->asShapes();
	Name		= Parameters("NAME"  )->asString();	if( Name.Length() == 0 )	Name	= pShapes->Get_Name();

	Field		= "geometry";

	int	SRID	= Get_SRID();

	//-----------------------------------------------------
	if( !CSG_Shapes_OGIS_Converter::from_ShapeType(Type, pShapes->Get_Type(), pShapes->Get_Vertex_Type()) )
	{
		Error_Set(_TL("invalid or unsupported shape or vertex type"));

		return( false );
	}

	//-----------------------------------------------------
	Get_Connection()->Begin(SavePoint = Get_Connection()->is_Transaction() ? "SHAPES_SAVE" : "");

	//-----------------------------------------------------
	if( Get_Connection()->Table_Exists(Name) )
	{
		Message_Add(_TL("table already exists") + CSG_String(": ") + Name);

		switch( Parameters("EXISTS")->asInt() )
		{
		case 0:	// abort export
			return( false );

		case 1:	// replace existing table
			Message_Add(_TL("trying to drop table") + CSG_String(": ") + Name);

			if( !Get_Connection()->Table_Drop(Name, false) )
			{
				Message_Add(CSG_String(" ...") + _TL("failed") + "!");

				return( false );
			}

			break;

		case 2:	// append records, if table structure allows
			break;
		}
	}

	//-----------------------------------------------------
	if( !Get_Connection()->Table_Exists(Name) )
	{
		if( !Get_Connection()->Table_Create(Name, *pShapes, Get_Constraints(&Parameters, "SHAPES"), false) )
		{
			Error_Set(_TL("could not create table"));

			Get_Connection()->Rollback(SavePoint);

			return( false );
		}

		//-------------------------------------------------
		// SELECT AddGeometryColumn(<table_name>, <column_name>, <srid>, <type>, <dimension>)

		SQL.Printf(SG_T("SELECT AddGeometryColumn('%s', '%s', %d, '%s', %d)"),
			Name.c_str(), Field.c_str(), SRID, Type.c_str(),
			pShapes->Get_Vertex_Type() == SG_VERTEX_TYPE_XY  ? 2 :
			pShapes->Get_Vertex_Type() == SG_VERTEX_TYPE_XYZ ? 3 : 4
		);

		if( !Get_Connection()->Execute(SQL) )
		{
			Error_Set(_TL("could not create geometry field"));

			Get_Connection()->Rollback(SavePoint);

			return( false );
		}
	}

	//-----------------------------------------------------
	bool	bBinary	= Get_Connection()->has_Version(9);

	int		iShape, iField, nAdded;

	CSG_String	Insert	= "INSERT INTO \"" + Name + "\" (" + Field;

	for(iField=0; iField<pShapes->Get_Field_Count(); iField++)
	{
		Insert	+= CSG_String(", ") + pShapes->Get_Field_Name(iField);
	}

	Insert	+= ") VALUES (";

	//-----------------------------------------------------
	for(iShape=0, nAdded=0; iShape==nAdded && iShape<pShapes->Get_Count() && Set_Progress(iShape, pShapes->Get_Count()); iShape++)
	{
		CSG_Shape	*pShape	= pShapes->Get_Shape(iShape);

		if( pShape->is_Valid() )
		{
			SQL	= Insert;

			if( bBinary )
			{
				CSG_Bytes	WKB;

				CSG_Shapes_OGIS_Converter::to_WKBinary(pShape, WKB);

				SQL	+= "ST_GeomFromWKB(E'\\\\x" + WKB.toHexString() + CSG_String::Format("', %d)", SRID);
			}
			else
			{
				CSG_String	WKT;

				CSG_Shapes_OGIS_Converter::to_WKText(pShape, WKT);

				SQL	+= "ST_GeomFromText('" + WKT + CSG_String::Format("', %d)", SRID);
			}

			for(iField=0; iField<pShapes->Get_Field_Count(); iField++)
			{
				CSG_String	s = pShape->asString(iField);

				if( pShapes->Get_Field_Type(iField) == SG_DATATYPE_String )
				{
					if( 1 )
					{
						char	*_s	= NULL; if( s.to_ASCII(&_s) ) s = _s; SG_FREE_SAFE(_s);
					}

					s.Replace("'", "\"");

					s	= "'" + s + "'";
				}

				SQL	+= ", "  + s;
			}

			SQL	+= ")";

			if( Get_Connection()->Execute(SQL) )
			{
				nAdded++;
			}
			else
			{
				Message_Add(CSG_String::Format("%s [%d/%d]", _TL("could not save shape"), 1 + iShape, pShapes->Get_Count()));
			}
		}
	}

	//-----------------------------------------------------
	if( nAdded < pShapes->Get_Count() )
	{
		Message_Add(SQL);

		Get_Connection()->Rollback(SavePoint);

		return( false );
	}

	Get_Connection()->Commit(SavePoint);

	Get_Connection()->GUI_Update();

	Get_Connection()->Add_MetaData(*pShapes, Name);

	pShapes->Set_Modified(false);

	return( true );
}
Пример #10
0
//---------------------------------------------------------
bool CTL_Extract::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_Table	Elements;

	Elements.Add_Field(SG_T("TEXT"), SG_DATATYPE_String);
	Elements.Add_Field(SG_T("FILE"), SG_DATATYPE_String);

	int	nFiles	= Read_Directory(Parameters("DIRECTORY")->asString(), Elements);

	if( nFiles <= 0 )
	{
		Error_Set(SG_T("no source code files found"));

		return( false );
	}

	Message_Add(CSG_String::Format("\n%s: %d", SG_T("number of scanned files"), nFiles), false);
		
	if( Elements.Get_Count() <= 0 )
	{
		Error_Set(SG_T("no translatable text elements found"));

		return( false );
	}

	Message_Add(CSG_String::Format("\n%s: %d", SG_T("number of translatable elements"), Elements.Get_Count()), false);

	//-----------------------------------------------------
	Process_Set_Text(SG_T("collecting elements"));

	CSG_String	Text;

	bool		bLocation	= Parameters("LOCATION" )->asBool();

	CSG_Table	*pTarget	= Parameters("TARGET")->asTable();

	pTarget->Destroy();
	pTarget->Set_Name(SG_T("Translatable Elements"));

	pTarget->Add_Field("TEXT"       , SG_DATATYPE_String);
	pTarget->Add_Field("TRANSLATION", SG_DATATYPE_String);

	if( bLocation )
	{
		pTarget->Add_Field("FILE"   , SG_DATATYPE_String);
	}

	Elements.Set_Index(0, TABLE_INDEX_Ascending);

	for(int i=0; i<Elements.Get_Count() && Set_Progress(i, Elements.Get_Count()); i++)
	{
		if( i == 0 || Text.Cmp(Elements.Get_Record_byIndex(i)->asString(0)) )
		{
			Text	= Elements.Get_Record_byIndex(i)->asString(0);

			CSG_Table_Record	*pRecord	= pTarget->Add_Record();

			pRecord->Set_Value(0, Text);

			if( bLocation )
			{
				pRecord->Set_Value(2, Elements.Get_Record_byIndex(i)->asString(1));
			}
		}
	}

	//-----------------------------------------------------
	return( true );
}
Пример #11
0
//---------------------------------------------------------
bool CShapes_Buffer::On_Execute(void)
{
	int			Field, nZones;
	CSG_Shapes	*pShapes, *pBuffers;

	//-----------------------------------------------------
	pShapes			= Parameters("SHAPES"    )->asShapes();
	pBuffers		= Parameters("BUFFER"    )->asShapes();
	nZones			= Parameters("NZONES"    )->asInt();
	Field			= Parameters("DIST_FIELD")->asInt();
	m_dArc			= Parameters("DARC"      )->asDouble() * M_DEG_TO_RAD;
	m_bPolyInner	= Parameters("POLY_INNER")->asBool() && pShapes->Get_Type() == SHAPE_TYPE_Polygon;

	//-----------------------------------------------------
	if( !pShapes->is_Valid() )
	{
		Message_Add(_TL("Invalid Shapes"));

		return( false );
	}

	if( Field < 0 && Parameters("DIST_FIELD")->asDouble() <= 0.0 )
	{
		Message_Add(_TL("Invalid Buffer Distance"));

		return( false );
	}

	//-----------------------------------------------------
	if( nZones == 1 )
	{
		Get_Buffers(pShapes, Field, pBuffers, 1.0, Parameters("DISSOLVE")->asBool());
	}

	//-----------------------------------------------------
	else if( nZones > 1 )
	{
		CSG_Shape	*pBuffer;
		CSG_Shapes	Buffers;

		pBuffers->Create(SHAPE_TYPE_Polygon);
		pBuffers->Add_Field(_TL("ID")	, SG_DATATYPE_Int);
		pBuffers->Add_Field(_TL("ZONE")	, SG_DATATYPE_Double);

		double	dZone	= 1.0 / nZones;

		for(int iZone=0; iZone<nZones; iZone++)
		{
			Get_Buffers(pShapes, Field, &Buffers, (nZones - iZone) * dZone, true);

			if( iZone > 0 )
			{
				SG_Polygon_Difference(pBuffer, Buffers.Get_Shape(0));
			}

			pBuffer	= pBuffers->Add_Shape(Buffers.Get_Shape(0));
			pBuffer	->Set_Value(0, (nZones - iZone) + 1);
			pBuffer	->Set_Value(1, (nZones - iZone) * dZone * 100.0);
		}
	}

	//-----------------------------------------------------
	pBuffers->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pShapes->Get_Name(), _TL("Buffer")));

	return( pBuffers->is_Valid() );
}
Пример #12
0
//---------------------------------------------------------
bool CWatershed_Segmentation::On_Execute(void)
{
    //-----------------------------------------------------
    m_pGrid		= Parameters("GRID")		->asGrid();
    m_pSeeds	= Parameters("SEEDS")		->asShapes();
    m_pSegments	= Parameters("SEGMENTS")	->asGrid();
    m_bDown		= Parameters("DOWN")		->asInt() == 1;

    //-----------------------------------------------------
    m_pSeeds->Create(SHAPE_TYPE_Point, CSG_String::Format(SG_T("%s [%s]"), m_pGrid->Get_Name(), _TL("Seeds")));

    m_pSeeds->Add_Field(SG_T("XCELL")	, SG_DATATYPE_Int);		// SEED_X
    m_pSeeds->Add_Field(SG_T("YCELL")	, SG_DATATYPE_Int);		// SEED_Y
    m_pSeeds->Add_Field(SG_T("VALUE")	, SG_DATATYPE_Double);	// SEED_Z
    m_pSeeds->Add_Field(SG_T("ID")		, SG_DATATYPE_Int);		// SEED_ID
    m_pSeeds->Add_Field(SG_T("ID_JOIN")	, SG_DATATYPE_Int);		// SEED_JOIN

    //-----------------------------------------------------
    m_pSegments->Set_Name(CSG_String::Format(SG_T("%s [%s]"), m_pGrid->Get_Name(), _TL("Segments")));
    m_pSegments->Set_NoData_Value(-999999.0);

    m_Dir.Create(*Get_System(), SG_DATATYPE_Char);

    //-----------------------------------------------------
    if( !Get_Seeds() )
    {
        Message_Add(_TL("no seed points identified"));

        return( false );
    }

    //-----------------------------------------------------
    Get_Segments();

    //-----------------------------------------------------
    if( Parameters("OUTPUT")->asInt() == 0 )
    {
        for(int y=0; y<Get_NY() && Set_Progress(y); y++)
        {
            for(int x=0; x<Get_NX(); x++)
            {
                int	ID	= m_pSegments->asInt(x, y);

                if( ID >= 0 )
                {
                    m_pSegments->Set_Value(x, y, m_pSeeds->Get_Shape(ID)->asDouble(SEED_Z));
                }
            }
        }
    }

    //-----------------------------------------------------
    if( Parameters("BBORDERS")->asBool() )
    {
        Get_Borders();
    }

    //-----------------------------------------------------
    m_Dir.Destroy();

    return( true );
}
//---------------------------------------------------------
bool CPolygon_Shared_Edges::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_Shapes	*pPolygons	= Parameters("POLYGONS")->asShapes();

	m_Field		= Parameters("ATTRIBUTE")->asInt();

	m_pEdges	= Parameters("EDGES")->asShapes();
	m_pEdges->Create(SHAPE_TYPE_Line, CSG_String::Format(SG_T("%s [%s]"), pPolygons->Get_Name(), _TL("Edges")));
	m_pEdges->Add_Field("ID_A", m_Field < 0 ? SG_DATATYPE_Int : pPolygons->Get_Field_Type(m_Field));
	m_pEdges->Add_Field("ID_B", m_Field < 0 ? SG_DATATYPE_Int : pPolygons->Get_Field_Type(m_Field));

//	m_pNodes	= Parameters("NODES")->asShapes();
//	m_pNodes->Create(SHAPE_TYPE_Point, CSG_String::Format(SG_T("%s [%s]"), pPolygons->Get_Name(), _TL("Nodes")));
//	m_pNodes->Add_Field("ID", SG_DATATYPE_Int);

	bool	bVertices	= Parameters("VERTICES")->asBool  ();
	double	Epsilon		= Parameters("EPSILON" )->asDouble();

	int	iPolygon, nAdded	= 0, nRemoved	= 0;

	//-----------------------------------------------------
	if( bVertices )
	{
		for(iPolygon=0; iPolygon<pPolygons->Get_Count() && Set_Progress(iPolygon, pPolygons->Get_Count()); iPolygon++)
		{
			CSG_Shape_Polygon	*pPolygon	= (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon);

			for(int iPart=0; iPart<pPolygon->Get_Part_Count() && Process_Get_Okay(); iPart++)
			{
				CSG_Shape_Part	*pPart	= pPolygon->Get_Part(iPart);

				CSG_Point	A	= pPart->Get_Point(pPart->Get_Count() - 1);

				if( A != pPart->Get_Point(0) )
				{
					pPart->Add_Point(A);
				}

				for(int iPoint=pPart->Get_Count()-2; iPoint>=0; iPoint--)
				{
					CSG_Point	B	= A;	A	= pPart->Get_Point(iPoint);

					if( A == B )
					{
						pPart->Del_Point(iPoint + 1);

						nRemoved--;
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	for(iPolygon=0; iPolygon<pPolygons->Get_Count()-1 && Set_Progress(iPolygon, pPolygons->Get_Count()-1); iPolygon++)
	{
		CSG_Shape_Polygon	*pA	= (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon);

		for(int jPolygon=iPolygon+1; jPolygon<pPolygons->Get_Count() && Process_Get_Okay(); jPolygon++)
		{
			CSG_Shape_Polygon	*pB	= (CSG_Shape_Polygon *)pPolygons->Get_Shape(jPolygon);

			for(int iPart=0; iPart<pA->Get_Part_Count() && Process_Get_Okay(); iPart++)
			{
				for(int jPart=0; jPart<pB->Get_Part_Count() && Process_Get_Okay(); jPart++)
				{
					if( pA->Get_Part(iPart)->Get_Extent().Intersects(pB->Get_Part(jPart)->Get_Extent()) )
					{
						if( bVertices )
						{
							nAdded	+= Check_Vertices(pA->Get_Part(iPart), pB->Get_Part(jPart), Epsilon);
							nAdded	+= Check_Vertices(pB->Get_Part(jPart), pA->Get_Part(iPart), Epsilon);
						}

						Get_Shared_Edges(pA->Get_Part(iPart), pB->Get_Part(jPart), Epsilon);
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	if( Parameters("DOUBLE")->asBool() )
	{
		for(int iEdge=0, nEdges=m_pEdges->Get_Count(); iEdge<nEdges && Set_Progress(iEdge, nEdges); iEdge++)
		{
			CSG_Shape	*pA	= m_pEdges->Get_Shape(iEdge);
			CSG_Shape	*pB	= m_pEdges->Add_Shape(pA);

			*(pB->Get_Value(0))	= *(pA->Get_Value(1));
			*(pB->Get_Value(1))	= *(pA->Get_Value(0));
		}
	}

	//-----------------------------------------------------
	if( nAdded > 0 || nRemoved > 0 )
	{
		Message_Add(CSG_String::Format(SG_T("\n%s: %d %s, %d %s\n"), _TL("Vertices"),
			nAdded  , _TL("added"  ),
			nRemoved, _TL("removed")
		), false);

		DataObject_Update(pPolygons);
	}

	return( true );
}
Пример #14
0
//---------------------------------------------------------
bool CTable_Text_Import_Fixed_Cols::On_Execute(void)
{
    bool			bHeader;
    int				i, nChars, iField, nFields, *iFirst, *iLength;
    CSG_String		sLine;
    CSG_File		Stream;
    CSG_Table		*pTable;

    //-----------------------------------------------------
    pTable	= Parameters("TABLE")		->asTable();
    bHeader	= Parameters("HEADLINE")	->asBool();

    //-----------------------------------------------------
    if( !Stream.Open(Parameters("FILENAME")->asString(), SG_FILE_R, true) )
    {
        Message_Add(_TL("file could not be opened"));

        return( false );
    }

    if( !Stream.Read_Line(sLine) || (nChars = (int)sLine.Length()) <= 0 )
    {
        Message_Add(_TL("empty or corrupted file"));

        return( false );
    }

    //-----------------------------------------------------
    pTable->Destroy();
    pTable->Set_Name(SG_File_Get_Name(Parameters("FILENAME")->asString(), false));

    switch( Parameters("FIELDDEF")->asInt() )
    {
    //-----------------------------------------------------
    case 0:
    {
        CSG_Parameters	*pBreaks	= Get_Parameters("BREAKS");

        pBreaks->Del_Parameters();

        for(i=0; i<nChars; i++)
        {
            pBreaks->Add_Value(NULL,
                               CSG_String::Format(SG_T("%03d"), i),
                               CSG_String::Format(SG_T("%03d %c"), i + 1, sLine[i]),
                               _TL(""), PARAMETER_TYPE_Bool, false
                              );
        }

        if( !Dlg_Parameters("BREAKS") )
        {
            return( false );
        }

        //-------------------------------------------------
        for(i=0, nFields=1; i<pBreaks->Get_Count(); i++)
        {
            if( pBreaks->Get_Parameter(i)->asBool() )
            {
                nFields++;
            }
        }

        //-------------------------------------------------
        iFirst		= new int[nFields];
        iLength		= new int[nFields];

        iFirst[0]	= 0;

        for(i=0, iField=1; i<pBreaks->Get_Count() && iField<nFields; i++)
        {
            if( pBreaks->Get_Parameter(i)->asBool() )
            {
                iFirst[iField++]	= i + 1;
            }
        }

        //-------------------------------------------------
        for(iField=0; iField<nFields; iField++)
        {
            iLength[iField]	= (iField < nFields - 1 ? iFirst[iField + 1] : (int)sLine.Length()) - iFirst[iField];

            pTable->Add_Field(bHeader ? sLine.Mid(iFirst[iField], iLength[iField]) : CSG_String::Format(SG_T("FIELD%03d"), iField + 1), SG_DATATYPE_String);
        }
    }
    break;

    //-----------------------------------------------------
    case 1:
    {
        CSG_Parameters	*pFields	= Get_Parameters("FIELDS");

        pFields->Del_Parameters();

        nFields	= Parameters("NFIELDS")->asInt();

        for(iField=0; iField<nFields; iField++)
        {
            CSG_String		s		= CSG_String::Format(SG_T("%03d"), iField);
            CSG_Parameter	*pNode	= pFields->Add_Node(NULL, SG_T("NODE") + s, _TL("Field") + s, _TL(""));
            pFields->Add_Value	(pNode, SG_T("LENGTH") + s, _TL("Length"), _TL(""), PARAMETER_TYPE_Int, 1, 1, true);
            //	pFields->Add_Value	(pNode, SG_T("IMPORT") + s, _TL("Import"), _TL(""), PARAMETER_TYPE_Bool, true);
            pFields->Add_Choice	(pNode, SG_T("TYPE")   + s, _TL("Type")  , _TL(""), CSG_String::Format(SG_T("%s|%s|%s|%s|%s|"),
                                 _TL("text"),
                                 _TL("2 byte integer"),
                                 _TL("4 byte integer"),
                                 _TL("4 byte float"),
                                 _TL("8 byte float"))
                                );
        }

        if( !Dlg_Parameters("FIELDS") )
        {
            return( false );
        }

        //-------------------------------------------------
        iFirst		= new int[nFields];
        iLength		= new int[nFields];

        iFirst[0]	= 0;

        for(iField=0, i=0; iField<nFields && i<nChars; iField++)
        {
            CSG_String		s		= CSG_String::Format(SG_T("%03d"), iField);

            iFirst [iField]	= i;
            iLength[iField]	= pFields->Get_Parameter(SG_T("LENGTH") + s)->asInt();

            i	+= iLength[iField];

            CSG_String		Name	= bHeader ? sLine.Mid(iFirst[iField], iLength[iField]) : CSG_String::Format(SG_T("FIELD%03d"), iField + 1);

            switch( pFields->Get_Parameter(SG_T("TYPE") + s)->asInt() )
            {
            default:
            case 0:
                pTable->Add_Field(Name, SG_DATATYPE_String);
                break;
            case 1:
                pTable->Add_Field(Name, SG_DATATYPE_Short);
                break;
            case 2:
                pTable->Add_Field(Name, SG_DATATYPE_Int);
                break;
            case 3:
                pTable->Add_Field(Name, SG_DATATYPE_Float);
                break;
            case 4:
                pTable->Add_Field(Name, SG_DATATYPE_Double);
                break;
            }
        }
    }
    break;

    //-----------------------------------------------------
    case 2:
    {
        CSG_Table	*pList	= Parameters("LIST")->asTable();

        nFields	= pList->Get_Count();

        //-------------------------------------------------
        iFirst		= new int[nFields];
        iLength		= new int[nFields];

        iFirst[0]	= 0;

        for(iField=0, i=0; iField<nFields && i<nChars; iField++)
        {
            iFirst [iField]	= i;
            iLength[iField]	= pList->Get_Record(iField)->asInt(1);

            i	+= iLength[iField];

            CSG_String		Name	= bHeader ? sLine.Mid(iFirst[iField], iLength[iField]) : CSG_String(pList->Get_Record(iField)->asString(0));

            switch( pList->Get_Record(iField)->asInt(2) )
            {
            case 0:
                pTable->Add_Field(Name, SG_DATATYPE_String);
                break;
            case 1:
                pTable->Add_Field(Name, SG_DATATYPE_Short);
                break;
            case 2:
                pTable->Add_Field(Name, SG_DATATYPE_Int);
                break;
            case 3:
                pTable->Add_Field(Name, SG_DATATYPE_Float);
                break;
            default:
            case 4:
                pTable->Add_Field(Name, SG_DATATYPE_Double);
                break;
            }
        }
    }
    break;
    }

    //-----------------------------------------------------
    if( bHeader )
    {
        Stream.Read_Line(sLine);
    }

    //-----------------------------------------------------
    int		fLength	= Stream.Length();

    do
    {
        if( sLine.Length() == nChars )
        {
            CSG_Table_Record	*pRecord	= pTable->Add_Record();

            for(iField=0; iField<nFields; iField++)
            {
                pRecord->Set_Value(iField, sLine.Mid(iFirst[iField], iLength[iField]));
            }
        }
    }
    while( Stream.Read_Line(sLine) && Set_Progress(Stream.Tell(), fLength) );

    //-----------------------------------------------------
    delete[](iFirst);
    delete[](iLength);

    //-----------------------------------------------------
    return( true );
}
Пример #15
0
bool CFlowDepth::On_Execute_Position(CSG_Point ptWorld, TSG_Module_Interactive_Mode Mode){	

	int iX, iY;	
	int iNextX, iNextY;
	int x,y;
	int iOutletX, iOutletY;
	double fArea;
	double fDepth, fPreviousDepth = 0;

	if(	Mode != MODULE_INTERACTIVE_LDOWN || !Get_Grid_Pos(iOutletX, iOutletY) )
	{
		return( false );
	}

	m_pFlowDepth->Assign((double)0);

	fArea = m_pCatchArea->asFloat(iOutletX, iOutletY);
	
	if (fArea < m_dThreshold * 2.){ //check outlet point
		iNextX = iOutletX;
		iNextY = iOutletY;
		do{
			iOutletX = iNextX;
			iOutletY = iNextY;
			getNextCell(m_pDEM, iOutletX, iOutletY, iNextX, iNextY);
		}while (m_pCatchArea->asFloat(iOutletX, iOutletY) < m_dThreshold * 2. &&
				(iOutletX != iNextX || iOutletY != iNextY));
			
		if (m_pCatchArea->asFloat(iOutletX, iOutletY) < m_dThreshold * 2.){
			Message_Add(_TL("** Error : Wrong outlet point selected **"));
			return false;
		}//if
		Message_Add(_TL("** Warning : Outlet point was modified **"));
    }//if

	CalculateBasinGrid(m_pBasinGrid, m_pDEM, iOutletX, iOutletY);

	m_fMaxFlowAcc = m_pCatchArea->asFloat(iOutletX, iOutletY);		
    
    for(y=0; y<Get_NY() && Set_Progress(y); y++){		
		for(x=0; x<Get_NX(); x++){
			if (m_pCatchArea->asFloat(x,y) > m_dThreshold){
				if (isHeader(x,y)){					
					iNextX = x;
					iNextY = y;
					do {
						iX = iNextX;
						iY = iNextY;
						if (m_pFlowDepth->asFloat(iX,iY) == 0. && m_pBasinGrid->asInt(iX, iY) != 0){
							getNextCell(m_pDEM, iX, iY, iNextX, iNextY);
							fDepth = CalculateFlowDepth(iX,iY);
							if (fDepth == NO_DEPTH){
								m_pFlowDepth->Set_Value(iX,iY, fPreviousDepth);
							}//if
							else{
								fPreviousDepth = fDepth;
							}//else
						}//if
					}while ((iX != iOutletX || iY != iOutletY)
							&& (iX != iNextX || iY != iNextY));
				}//if
			}//if
		}//for
	}// for

	DataObject_Update(m_pFlowDepth);

	return true;

}//method
Пример #16
0
//---------------------------------------------------------
bool CGPS_Track_Aggregation::On_Execute(void)
{
	bool					bVerbose, bPolar;
	int						Time_Span, fRefID, fX, fY, fTrack, fDate, fTime, fParameter, Observation, iDropped, nDropped;
	double					eps_Space, eps_Time, off_Time, iTime;
	TSG_Point				Position;
	CSG_String				iTrack, iDate;
	CSG_Table_Record		*pAggregate, *pObservation;
	CSG_Shape				*pReference, *pNearest;
	CSG_Simple_Statistics	Statistic, Time;
	CSG_Table				*pObservations, *pAggregated, Observations;
	CSG_Shapes_Search		Reference;

	//-----------------------------------------------------
	pObservations	= Parameters("OBSERVATIONS")	->asTable ();
	pAggregated		= Parameters("AGGREGATED")		->asTable ();
	fRefID			= Parameters("REFERENCE_ID")	->asInt   ();
	fX				= Parameters("X")				->asInt   ();
	fY				= Parameters("Y")				->asInt   ();
	fTrack			= Parameters("TRACK")			->asInt   ();
	fDate			= Parameters("DATE")			->asInt   ();
	fTime			= Parameters("TIME")			->asInt   ();
	fParameter		= Parameters("PARAMETER")		->asInt   ();
	Time_Span		= Parameters("TIME_SPAN")		->asInt   ();
	eps_Space		= Parameters("EPS_SPACE")		->asDouble();
	off_Time		= Parameters("OFF_TIME")		->asDouble() * 60.0;
	bVerbose		= Parameters("VERBOSE")			->asBool  ();
	bPolar			= Parameters("POLAR")			->asBool  ();

	switch( Time_Span )
	{
	default:	eps_Time	= 0.0;											break;
	case  1:	eps_Time	= Parameters("EPS_TIME")->asDouble();			break;
	case  2:	eps_Time	= Parameters("FIX_TIME")->asDouble() * 60.0;	break;
	}

	if( eps_Time <= 0.0 )
	{
		Time_Span	= 0;
	}

	//-----------------------------------------------------
	if( !Reference.Create(Parameters("REFERENCE")->asShapes()) )
	{
		Error_Set(_TL("could not initialize reference point search engine"));

		return( false );
	}

	//-----------------------------------------------------
	if( Time_Span == 2 )	// pre-processing for 'fix' time span
	{
		Observations.Create(*pObservations);
		Observations.Add_Field(SG_T("REF_ID"), SG_DATATYPE_String);

		fTrack			= pObservations->Get_Field_Count();
		pObservations	= &Observations;

		for(Observation=0; Observation<pObservations->Get_Count() && Set_Progress(Observation, pObservations->Get_Count()); Observation++)
		{
			pObservation	= pObservations->Get_Record(Observation);
			pNearest		= Reference.Get_Point_Nearest(pObservation->asDouble(fX), pObservation->asDouble(fY));
			pObservation	->Set_Value(fTrack, pNearest->asString(fRefID));
		}
	}

	//-----------------------------------------------------
	if( !pObservations->Set_Index(fTrack, TABLE_INDEX_Ascending, fDate, TABLE_INDEX_Ascending, fTime, TABLE_INDEX_Ascending) )
	{
		Error_Set(_TL("could not create index on observations"));

		return( false );
	}

	//-----------------------------------------------------
	pAggregated->Destroy();
	pAggregated->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pObservations->Get_Name(), _TL("aggregated")));

	pAggregated->Add_Field(SG_T("REFID")		, SG_DATATYPE_String);	// AGG_ID
	pAggregated->Add_Field(SG_T("TRACK")		, SG_DATATYPE_String);	// AGG_TRACK
	pAggregated->Add_Field(SG_T("DATE")			, SG_DATATYPE_String);	// AGG_DATE
	pAggregated->Add_Field(SG_T("TIME")			, SG_DATATYPE_String);	// AGG_TIME

	pAggregated->Add_Field(pObservations->Get_Field_Name(fParameter), SG_DATATYPE_Double);	// AGG_PARM

	if( bVerbose )
	{
		pAggregated->Add_Field(SG_T("MIN")			, SG_DATATYPE_Double);	// AGG_MIN,
		pAggregated->Add_Field(SG_T("MAX")			, SG_DATATYPE_Double);	// AGG_MAX
		pAggregated->Add_Field(SG_T("RANGE")		, SG_DATATYPE_Double);	// AGG_RANGE
		pAggregated->Add_Field(SG_T("STDDEV")		, SG_DATATYPE_Double);	// AGG_STDDEV,
		pAggregated->Add_Field(SG_T("COUNT")		, SG_DATATYPE_Int   );	// AGG_COUNT,
		pAggregated->Add_Field(SG_T("DROPPED")		, SG_DATATYPE_Int   );	// AGG_DROPPED,
		pAggregated->Add_Field(SG_T("DTIME")		, SG_DATATYPE_Double);	// AGG_DTIME,
		pAggregated->Add_Field(SG_T("X")			, SG_DATATYPE_Double);	// AGG_X
		pAggregated->Add_Field(SG_T("Y")			, SG_DATATYPE_Double);	// AGG_Y
	}

	//-----------------------------------------------------
	pAggregate	= NULL;
	nDropped	= 0;
	iDropped	= 0;

	//-----------------------------------------------------
	for(Observation=0; Observation<pObservations->Get_Count() && Set_Progress(Observation, pObservations->Get_Count()); Observation++)
	{
		pObservation	= pObservations->Get_Record_byIndex(Observation);

		if( !pAggregate
		||	iTrack.Cmp(pObservation->asString(fTrack))
		||	iDate .Cmp(pObservation->asString(fDate ))
		||	(eps_Time > 0.0 && eps_Time <= pObservation->asDouble(fTime) - iTime) )
		{
			pReference	= NULL;
		}

		Position.x	= pObservation->asDouble(fX);
		Position.y	= pObservation->asDouble(fY);
		pNearest	= Reference.Get_Point_Nearest(Position.x, Position.y);

		if( eps_Space > 0.0 && eps_Space <= (bPolar ? SG_Get_Distance_Polar(Position, pNearest->Get_Point(0)) : SG_Get_Distance(Position, pNearest->Get_Point(0))) )
		{
			nDropped++;
			iDropped++;
		}
		else
		{
			if( pReference != pNearest )
			{
				Set_Statistic(pAggregate, Statistic, Time, iDropped, bVerbose);

				Statistic	.Invalidate();
				Time		.Invalidate();

				iDropped	= 0;

				iTrack		= pObservation->asString(fTrack);
				iDate		= pObservation->asString(fDate );

				switch( Time_Span )
				{
				default:	iTime	= 0.0;	break;
				case  1:	iTime	= pObservation->asDouble(fTime);	break;
				case  2:	iTime	= (int)(pObservation->asDouble(fTime) / eps_Time) * eps_Time - off_Time;	break;
				}

				pReference	= pNearest;

				pAggregate	= pAggregated->Add_Record();
				pAggregate	->Set_Value(AGG_ID   , pReference->asString(fRefID));
				pAggregate	->Set_Value(AGG_TRACK, iTrack);
				pAggregate	->Set_Value(AGG_DATE , iDate );

				if( bVerbose )
				{
					pAggregate	->Set_Value(AGG_X, pReference->Get_Point(0).x);
					pAggregate	->Set_Value(AGG_Y, pReference->Get_Point(0).y);
				}
			}

			Statistic	+= pObservation->asDouble(fParameter);
			Time		+= pObservation->asDouble(fTime     );
		}
	}

	Set_Statistic(pAggregate, Statistic, Time, iDropped, bVerbose);

	//-----------------------------------------------------
	if( nDropped > 0 )
	{
		Message_Add(CSG_String::Format(SG_T("%s: %d"), _TL("number of dropped observations"), nDropped));
	}

	//-----------------------------------------------------
	return( true );
}
Пример #17
0
//---------------------------------------------------------
bool CClip_Points::On_Execute(void)
{
	int							Method, iField;
	CSG_Shapes					*pPoints, *pPolygons, *pClip;
	CSG_Parameter_Shapes_List	*pClips;

	//-----------------------------------------------------
	pPoints		= Parameters("POINTS")		->asShapes();
	pPolygons	= Parameters("POLYGONS")	->asShapes();
	pClips		= Parameters("CLIPS")		->asShapesList();
	Method		= Parameters("METHOD")		->asInt();
	iField		= Parameters("FIELD")		->asInt();

	//-----------------------------------------------------
	if( !pPoints->is_Valid() )
	{
		Message_Add(_TL("Invalid points layer."));

		return( false );
	}
	else if( !pPolygons->is_Valid() )
	{
		Message_Add(_TL("Invalid polygon layer."));

		return( false );
	}

	//-----------------------------------------------------
	if( iField >= pPolygons->Get_Field_Count() )
	{
		iField	= -1;
	}

	pClips->Del_Items();

	if( Method == 0 )
	{
		pClip	= SG_Create_Shapes(SHAPE_TYPE_Point, CSG_String::Format(SG_T("%s [%s]"), pPoints->Get_Name(), pPolygons->Get_Name()), pPoints);

		if( iField >= 0 )
		{
			pClip->Add_Field(pPolygons->Get_Field_Name(iField), pPolygons->Get_Field_Type(iField));
		}
	}

	//-----------------------------------------------------
	for(int iPolygon=0; iPolygon<pPolygons->Get_Count() && Set_Progress(iPolygon, pPolygons->Get_Count()); iPolygon++)
	{
		CSG_Shape_Polygon	*pPolygon	= (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon);

		if( Method == 1 )
		{
			CSG_String	Name(pPoints->Get_Name());

			Name	+= iField >= 0
					? CSG_String::Format(SG_T(" [%s]"), pPolygon->asString(iField))
					: CSG_String::Format(SG_T(" [%00d]"), 1 + pClips->Get_Count());

			pClip	= SG_Create_Shapes(SHAPE_TYPE_Point, Name, pPoints);

			if( iField >= 0 )
			{
				pClip->Add_Field(pPolygons->Get_Field_Name(iField), pPolygons->Get_Field_Type(iField));
			}
		}

		for(int iPoint=0; iPoint<pPoints->Get_Count() && Process_Get_Okay(false); iPoint++)
		{
			CSG_Shape	*pPoint	= pPoints->Get_Shape(iPoint);

			if( pPolygon->Contains(pPoint->Get_Point(0)) )
			{
				pPoint	= pClip->Add_Shape(pPoint, SHAPE_COPY);

				if( iField >= 0 )
				{
					pPoint->Set_Value(pPoints->Get_Field_Count(), pPolygon->asString(iField));
				}
			}
		}

		if( Method == 1 )
		{
			if( pClip->Get_Count() > 0 )
			{
				pClips->Add_Item(pClip);
			}
			else
			{
				delete(pClip);
			}
		}
	}

	//-----------------------------------------------------
	if( Method == 0 )
	{
		if( pClip->Get_Count() > 0 )
		{
			pClips->Add_Item(pClip);
		}
		else
		{
			delete(pClip);
		}
	}

	return( pClips->Get_Count() > 0 );
}
Пример #18
0
//---------------------------------------------------------
bool CGrid_Fill::On_Execute_Position(CSG_Point ptWorld, TSG_Module_Interactive_Mode Mode)
{
	//-----------------------------------------------------
	if(  Mode == MODULE_INTERACTIVE_LDOWN )
	{
		int		x, y, i, ix, iy, nReplaced;
		double	z, zMin, zMax;

		x	= Get_System()->Get_xWorld_to_Grid(ptWorld.Get_X());
		y	= Get_System()->Get_yWorld_to_Grid(ptWorld.Get_Y());

		if( m_pGrid && m_pGrid->is_InGrid(x, y, m_bNoData) )
		{
			Message_Add(_TL("Starting flood fill..."));

			switch( m_Method )
			{
			case 0:	z	= m_pGrid->asDouble(x, y);	break;	// value at mouse position
			case 1:	z	= m_zFixed;					break;	// fixed value
			case 2:	z	= 0.0;						break;	// tolerance as absolute values
			}

			zMin		= z + m_zTolerance_Min;
			zMax		= z + m_zTolerance_Max;

			m_iStack	= 0;
			nReplaced	= 1;

			Push(x, y);

			//---------------------------------------------
			while( m_iStack > 0 && Set_Progress(nReplaced, m_pGrid->Get_NCells()) )
			{
				Pop(x, y);

				for(i=0; i<8; i+=2)
				{
					ix	= Get_xTo(i, x);
					iy	= Get_yTo(i, y);

					if(	m_pGrid->is_InGrid(ix, iy, m_bNoData) )
					{
						z	= m_pGrid->asDouble(ix, iy);

						if( z != m_zFill && z >= zMin && z <= zMax )
						{
							Push(ix, iy);

							m_pGrid->Set_Value(ix, iy, m_zFill);

							nReplaced++;
						}
					}
				}
			}

			//---------------------------------------------
			Message_Add(_TL("ready"), false);
			Message_Add(CSG_String::Format(SG_T("%d %s"), nReplaced, _TL("replacements")));

			DataObject_Update(m_pGrid, m_pGrid->Get_ZMin(), m_pGrid->Get_ZMax());

			return( true );
		}
	}

	return( false );
}
Пример #19
0
//---------------------------------------------------------
bool CGrid_Calculator::On_Execute(void)
{
	double					Result, *Values;
	CSG_Formula				Formula;
	CSG_Parameter_Grid_List	*pGrids;
	CSG_Grid				*pResult;

	//-----------------------------------------------------
	pResult		= Parameters("RESULT")	->asGrid();
	pGrids		= Parameters("GRIDS")	->asGridList();

	//-----------------------------------------------------
	if( pGrids->Get_Count() <= 0 )
	{
		Message_Add(_TL("No grid in list"));

		return( false );
	}

	//-----------------------------------------------------
	if( !Formula.Set_Formula(Parameters("FORMULA")->asString()) )
	{
		int			Position;
		CSG_String	Message, s;

		s	+= _TL("Error in formula");
		s	+= SG_T("\n") + Formula.Get_Formula();

		if( Formula.Get_Error(&Position, &Message) )
		{
			s	+= SG_T("\n") + Message;
			s	+= CSG_String::Format(SG_T("\n%s: %d"), _TL("Position") , Position);

			if( Position >= 0 && Position < (int)Formula.Get_Formula().Length() )
			{
				s	+= SG_T("\n")
					+  Formula.Get_Formula().Left(Position - 1) + SG_T("[")
					+  Formula.Get_Formula()[Position] + SG_T("]")
					+  Formula.Get_Formula().Right(Formula.Get_Formula().Length() - (Position + 1));
			}
		}

		Message_Add(s, false);

		return( false );
	}

	//-----------------------------------------------------
	pResult->Set_Name(Formula.Get_Formula());

	Values	= new double[pGrids->Get_Count()];

	for(int y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		for(int x=0; x<Get_NX(); x++)
		{
			bool	bNoData	= false;

			for(int i=0; i<pGrids->Get_Count() && !bNoData; i++)
			{
				if( pGrids->asGrid(i)->is_NoData(x, y) )
				{
					bNoData		= true;
				}
				else
				{
					Values[i]	= pGrids->asGrid(i)->asDouble(x, y);
				}
			}

			if( bNoData || _finite(Result = Formula.Get_Value(Values, pGrids->Get_Count())) == false )
			{
				pResult->Set_NoData(x, y);
			}
			else
			{
				pResult->Set_Value(x, y, Result);
			}
		}
	}

	delete[](Values);

	//-----------------------------------------------------
	return( true );
}
Пример #20
0
bool CStreamNet::On_Execute(void)
{
	// Inputs and Output Strings
	CSG_String InputBasename = CSG_String("input");
	CSG_String OutputBasename = CSG_String("output");
	CSG_String FEL_INPUT_FileName, FEL_INPUT_FilePath;
	CSG_String FLOWD8_INPUT_FileName, FLOWD8_INPUT_FilePath;
	CSG_String AREAD8_INPUT_FileName, AREAD8_INPUT_FilePath;
	CSG_String SRC_INPUT_FileName, SRC_INPUT_FilePath;
	CSG_String ORD_OUTPUT_FileName, ORD_OUTPUT_FilePath, ORD_OUTPUT_Name;
	CSG_String W_OUTPUT_FileName, W_OUTPUT_FilePath, W_OUTPUT_Name;
	CSG_String NET_OUTPUT_FileName, NET_OUTPUT_FilePath, NET_OUTPUT_Name;
	CSG_String TREE_OUTPUT_FileName, TREE_OUTPUT_FilePath, TREE_OUTPUT_Name;
	CSG_String COORD_OUTPUT_FileName, COORD_OUTPUT_FilePath, COORD_OUTPUT_Name;
	CSG_String OUTLET_INPUT_FileName, OUTLET_INPUT_FilePath;

	// Data Objects
	CSG_Grid *FEL_INPUT_Grid, *FLOWD8_INPUT_Grid, *SRC_INPUT_Grid, *AREAD8_INPUT_Grid, *ORD_OUTPUT_Grid, *W_OUTPUT_Grid;
	CSG_Shapes *OUTLET_INPUT_Shapes, *NET_OUTPUT_Shapes;
	CSG_Table *TREE_OUTPUT_Table, *COORD_OUTPUT_Table;

	// Misc
	TSG_Data_Type Type;
	CSG_String GDALDriver, sCmd, TempDirPath, TauDEMBinDir, BinaryName, BinaryPath, LogFile;
	CSG_Projection Projection;
	CSG_GDAL_DataSet DataSet;
	CSG_OGR_DataSource	OGRDataSource;
	CSG_String OGRDriver = CSG_String("ESRI Shapefile");
	bool sw;
	int nproc;
	
	// Grab inputs
	FEL_INPUT_Grid = Parameters("FEL_INPUT")->asGrid();
	FLOWD8_INPUT_Grid = Parameters("FLOWD8_INPUT")->asGrid();
	SRC_INPUT_Grid = Parameters("SRC_INPUT")->asGrid();
	AREAD8_INPUT_Grid = Parameters("AREAD8_INPUT")->asGrid();
	ORD_OUTPUT_Grid = Parameters("ORD_OUTPUT")->asGrid();
	W_OUTPUT_Grid = Parameters("W_OUTPUT")->asGrid();
	nproc = Parameters("NPROC")->asInt();

	OUTLET_INPUT_Shapes = Parameters("OUTLET_INPUT")->asShapes();
	NET_OUTPUT_Shapes = Parameters("NET_OUTPUT")->asShapes();

	TREE_OUTPUT_Table = Parameters("TREE_OUTPUT")->asTable();
	COORD_OUTPUT_Table = Parameters("COORD_OUTPUT")->asTable();

	sw = Parameters("SW")->asBool();

	GDALDriver = CSG_String("GTiff");
	Get_Projection(Projection);
	Type = FEL_INPUT_Grid->Get_Type();
	
	//TempDirPath = SG_File_Get_Path_Absolute(CSG_String("taudem_tmp"));
	TempDirPath = Parameters("TEMP_DIR")->asFilePath()->asString();

	FEL_INPUT_FileName = InputBasename + CSG_String("fel");
	FEL_INPUT_FilePath = SG_File_Make_Path(TempDirPath, FEL_INPUT_FileName, CSG_String("tif")); 

	FLOWD8_INPUT_FileName = InputBasename + CSG_String("p");
	FLOWD8_INPUT_FilePath = SG_File_Make_Path(TempDirPath, FLOWD8_INPUT_FileName, CSG_String("tif"));

	SRC_INPUT_FileName = InputBasename + CSG_String("src");
	SRC_INPUT_FilePath = SG_File_Make_Path(TempDirPath, SRC_INPUT_FileName, CSG_String("tif"));

	AREAD8_INPUT_FileName = InputBasename + CSG_String("ad8");
	AREAD8_INPUT_FilePath = SG_File_Make_Path(TempDirPath, AREAD8_INPUT_FileName, CSG_String("tif"));

	ORD_OUTPUT_FileName = OutputBasename + CSG_String("ord");
	ORD_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, ORD_OUTPUT_FileName, CSG_String("tif"));
	ORD_OUTPUT_Name = CSG_String("NetworkOrder");

	W_OUTPUT_FileName = OutputBasename + CSG_String("w");
	W_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, W_OUTPUT_FileName, CSG_String("tif"));
	W_OUTPUT_Name = CSG_String("WatershedIDs");

	OUTLET_INPUT_FileName = InputBasename + CSG_String("o");
	OUTLET_INPUT_FilePath = SG_File_Make_Path(TempDirPath, OUTLET_INPUT_FileName, CSG_String("shp"));

	NET_OUTPUT_FileName = OutputBasename + CSG_String("net");
	NET_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, NET_OUTPUT_FileName, CSG_String("shp"));
	NET_OUTPUT_Name = CSG_String("Channel Network");

	TREE_OUTPUT_FileName = OutputBasename + CSG_String("tree");
	TREE_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, TREE_OUTPUT_FileName, CSG_String("dat"));
	TREE_OUTPUT_Name = CSG_String("Channel Network Tree");

	COORD_OUTPUT_FileName = OutputBasename + CSG_String("coord");
	COORD_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, COORD_OUTPUT_FileName, CSG_String("dat"));
	COORD_OUTPUT_Name = CSG_String("Channel Network Coords");

	LogFile = SG_File_Make_Path(TempDirPath, CSG_String("taudem_log.txt"));
	LogFile = SG_File_Get_Path_Absolute(LogFile);

	TauDEMBinDir = SG_File_Make_Path(CSG_String("bin"), CSG_String("TauDEM"));
	TauDEMBinDir = SG_File_Get_Path_Absolute(TauDEMBinDir);

	// options
	CSG_String OptionalFlags = CSG_String("");
	if (OUTLET_INPUT_Shapes != NULL)
	{
		OptionalFlags = CSG_String::Format(SG_T("-o \"%s\" "), OUTLET_INPUT_FilePath.c_str());
	}
	if (sw)
	{
		OptionalFlags = OptionalFlags + CSG_String::Format(SG_T("-sw"));
	}

	// exec commnad
	BinaryName = CSG_String("StreamNet"); // D8
	BinaryPath = SG_File_Make_Path(TauDEMBinDir, BinaryName);
	sCmd = CSG_String::Format(SG_T("\"mpiexec -n %d \"%s\" -fel \"%s\" -p \"%s\" -ad8 \"%s\" -src \"%s\" -ord \"%s\" -tree \"%s\" -coord \"%s\" -net \"%s\" -w \"%s\" %s >\"%s\" 2>&1\""), nproc, BinaryPath.c_str(), FEL_INPUT_FilePath.c_str(), FLOWD8_INPUT_FilePath.c_str(), AREAD8_INPUT_FilePath.c_str(), SRC_INPUT_FilePath.c_str(), ORD_OUTPUT_FilePath.c_str(), TREE_OUTPUT_FilePath.c_str(), COORD_OUTPUT_FilePath.c_str(), NET_OUTPUT_FilePath.c_str(), W_OUTPUT_FilePath.c_str(), OptionalFlags.c_str(), LogFile.c_str());

	// make sure temp dir exists
	if (!SG_Dir_Exists(TempDirPath))
	{
		if (!SG_Dir_Create(TempDirPath))
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to create temp directory"), TempDirPath.c_str()));
		}
	}

	CSG_String FilePaths [10] = {FEL_INPUT_FilePath, FLOWD8_INPUT_FilePath, SRC_INPUT_FilePath, AREAD8_INPUT_FilePath, ORD_OUTPUT_FilePath, W_OUTPUT_FilePath, OUTLET_INPUT_FilePath, NET_OUTPUT_FilePath, TREE_OUTPUT_FilePath, COORD_OUTPUT_FilePath};
	for (int i = 0; i < 10; i++)
	{
		CSG_String FilePath = FilePaths[i];
		// Delete old file if exists
		if (SG_File_Exists(FilePath))
		{
			if (!SG_File_Delete(FilePath))
			{
				Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to delete existing file: "), FilePath.c_str()));
				return( false );
			}
		}
	}

	// SAVE TIFFS
	CSG_String TIFF_INPUT_FilePaths [4] = {FEL_INPUT_FilePath, FLOWD8_INPUT_FilePath, SRC_INPUT_FilePath, AREAD8_INPUT_FilePath};
	CSG_Grid* TIFF_INPUT_Grids [4] = {FEL_INPUT_Grid, FLOWD8_INPUT_Grid, SRC_INPUT_Grid, AREAD8_INPUT_Grid};
	for (int i = 0; i < 4; i++)
	{
		CSG_String FilePath = TIFF_INPUT_FilePaths[i];
		CSG_Grid* Grid = TIFF_INPUT_Grids[i];

		if( !DataSet.Open_Write(FilePath, GDALDriver, CSG_String(""), Type, 1, *Get_System(), Projection) )
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open file for writing: "), FilePath.c_str()));
			return( false );
		}
		DataSet.Write(0, Grid);
		if( !DataSet.Close() )
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to close file after writing: "), FilePath.c_str()));
			return( false );
		}
	}

	if (OUTLET_INPUT_Shapes != NULL)
	{
		// save outlet shapefile
		CSG_String OGRDriver = CSG_String("ESRI Shapefile");
		if( !OGRDataSource.Create(OUTLET_INPUT_FilePath, OGRDriver) )
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open file for writing: "), OUTLET_INPUT_FilePath.c_str()));
			return( false );
		}
		OGRDataSource.Write(OUTLET_INPUT_Shapes, OGRDriver);
		OGRDataSource.Destroy();
	}
	

	// Run TauDEM StreamNet
	Message_Add(CSG_String("Executing ") + sCmd);
	if (system(sCmd.b_str()) != 0)	
	{
		Error_Set(CSG_String::Format(SG_T("Error executing '%s' see Execution log for details"), BinaryName.c_str()));
		// read log output
		CSG_File File;
		if (File.Open(LogFile, SG_FILE_R, false))
		{
			CSG_String Line;
			while (! File.is_EOF() && File.Read_Line(Line))
			{
				Message_Add(Line);
			}
			File.Close();
		} else 
		{
			Message_Add(CSG_String("Unable to open " + LogFile + CSG_String(" for reading")));
		}

		return( false );
	}

	// Load output tiffs

	if( !DataSet.Open_Read(ORD_OUTPUT_FilePath))
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open output file: "), ORD_OUTPUT_FilePath.c_str()));
		return( false );
	} 
	else
	{
		ORD_OUTPUT_Grid->Assign(DataSet.Read(0));
		ORD_OUTPUT_Grid->Set_Name(ORD_OUTPUT_Name);
		Parameters("ORD_OUTPUT")->Set_Value(ORD_OUTPUT_Grid);	
	}

	if( !DataSet.Open_Read(W_OUTPUT_FilePath))
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open output file: "), W_OUTPUT_FilePath.c_str()));
		return( false );
	} 
	else
	{
		W_OUTPUT_Grid->Assign(DataSet.Read(0));
		W_OUTPUT_Grid->Set_Name(W_OUTPUT_Name);
		Parameters("W_OUTPUT")->Set_Value(W_OUTPUT_Grid);

		CSG_Colors colors;
		DataObject_Get_Colors(SRC_INPUT_Grid, colors);
		DataObject_Set_Colors(ORD_OUTPUT_Grid, colors);
		DataObject_Update(ORD_OUTPUT_Grid, false);		
	}

	// load output shapefile
	if( !OGRDataSource.Create(NET_OUTPUT_FilePath) )
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open file for reading: "), NET_OUTPUT_FilePath.c_str()));
		return( false );
	} 
	NET_OUTPUT_Shapes->Assign(OGRDataSource.Read(0, 0));
	NET_OUTPUT_Shapes->Set_Name(NET_OUTPUT_Name);
	OGRDataSource.Destroy();
	
	// load table data

	if (!SG_File_Exists(COORD_OUTPUT_FilePath))
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Output file does not exist: "), COORD_OUTPUT_FilePath.c_str()));
		return false;
	} 
	else
	{
		COORD_OUTPUT_Table->Destroy();
		COORD_OUTPUT_Table->Set_Name(COORD_OUTPUT_Name);

		// create table fields
		COORD_OUTPUT_Table->Add_Field(SG_T("X"), SG_DATATYPE_Double);
		COORD_OUTPUT_Table->Add_Field(SG_T("Y"), SG_DATATYPE_Double);
		COORD_OUTPUT_Table->Add_Field(SG_T("Terminal Distance"), SG_DATATYPE_Double);
		COORD_OUTPUT_Table->Add_Field(SG_T("Elevation"), SG_DATATYPE_Double);
		COORD_OUTPUT_Table->Add_Field(SG_T("Contributing Area"), SG_DATATYPE_Double);

		// read table data
		CSG_File File;
		if (File.Open(COORD_OUTPUT_FilePath, SG_FILE_R, false))
		{
			CSG_String Line;
			// determine number of lines
			while (! File.is_EOF() && File.Read_Line(Line))
			{
				Line.Trim();
				if (Line.Length() == 0) 
				{
					break;
				} 
				else
				{
					CSG_Table_Record *Record = COORD_OUTPUT_Table->Add_Record();
					for (int i = 0; i < COORD_OUTPUT_Table->Get_Field_Count(); i++)
					{
						Record->Set_Value(i, Line.asDouble());
						Line = Line.AfterFirst('\t');
						Line.Trim();
					}
				}
			}
			File.Close();
		} else 
		{
			Message_Add(CSG_String("Unable to open " + COORD_OUTPUT_FilePath + CSG_String(" for reading")));
		}
	}

	if (!SG_File_Exists(TREE_OUTPUT_FilePath))
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Output file does not exist: "), TREE_OUTPUT_FilePath.c_str()));
		return false;
	} 
	else
	{
		TREE_OUTPUT_Table->Destroy();
		TREE_OUTPUT_Table->Set_Name(TREE_OUTPUT_Name);

		// create table fields
		TREE_OUTPUT_Table->Add_Field(SG_T("Link"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("Start Point"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("End Point"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("Next (Downstream) Link"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("First Previous (Upstream) Link"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("Second Previous (Upstream) Link"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("Strahler Order"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("Monitoring Point ID"), SG_DATATYPE_Int);
		TREE_OUTPUT_Table->Add_Field(SG_T("Link Network Magnitude"), SG_DATATYPE_Int);

		// read table data
		CSG_File File;
		if (File.Open(TREE_OUTPUT_FilePath, SG_FILE_R, false))
		{
			CSG_String Line;
			// determine number of lines
			while (! File.is_EOF() && File.Read_Line(Line))
			{
				Line.Trim();
				if (Line.Length() == 0) 
				{
					break;
				} 
				else
				{
					CSG_Table_Record *Record = TREE_OUTPUT_Table->Add_Record();
					for (int i = 0; i < TREE_OUTPUT_Table->Get_Field_Count(); i++)
					{
						Record->Set_Value(i, Line.asDouble());
						Line = Line.AfterFirst('\t');
						Line.Trim();
					}
				}
			}
			File.Close();
		} else 
		{
			Message_Add(CSG_String("Unable to open " + TREE_OUTPUT_FilePath + CSG_String(" for reading")));
		}
	}


	return( true );

}
Пример #21
0
//---------------------------------------------------------
bool CGDAL_Export::On_Execute(void)
{
	char					**pOptions	= NULL;
	int						x, y, n;
	double					*zLine;
	CSG_String				File_Name;
	CSG_Parameter_Grid_List	*pGrids;
	CSG_Grid				*pGrid;
	GDALDataType			gdal_Type;
	GDALDriver				*pDriver;
	GDALDataset				*pDataset;
	GDALRasterBand			*pBand;

	//-----------------------------------------------------
	pGrids		= Parameters("GRIDS")	->asGridList();
	File_Name	= Parameters("FILE")	->asString();

	//-----------------------------------------------------
	switch( Parameters("TYPE")->asInt() )
	{
	default:
	case 0:	gdal_Type	= g_GDAL_Driver.Get_GDAL_Type(pGrids);	break;	// match input data
	case 1:	gdal_Type	= GDT_Byte;		break;	// Eight bit unsigned integer
	case 2:	gdal_Type	= GDT_UInt16;	break;	// Sixteen bit unsigned integer
	case 3:	gdal_Type	= GDT_Int16;	break;	// Sixteen bit signed integer
	case 4:	gdal_Type	= GDT_UInt32;	break;	// Thirty two bit unsigned integer
	case 5:	gdal_Type	= GDT_Int32;	break;	// Thirty two bit signed integer
	case 6:	gdal_Type	= GDT_Float32;	break;	// Thirty two bit floating point
	case 7:	gdal_Type	= GDT_Float64;	break;	// Sixty four bit floating point
	}

	//-----------------------------------------------------
	if( (pDriver = g_GDAL_Driver.Get_Driver(SG_STR_SGTOMB(m_DriverNames[Parameters("FORMAT")->asInt()]))) == NULL )
	{
		Message_Add(_TL("Driver not found."));
	}
	else if( CSLFetchBoolean(pDriver->GetMetadata(), GDAL_DCAP_CREATE, false) == false )
	{
		Message_Add(_TL("Driver does not support file creation."));
	}
	else if( (pDataset = pDriver->Create(File_Name.b_str(), Get_NX(), Get_NY(), pGrids->Get_Count(), gdal_Type, pOptions)) == NULL )
	{
		Message_Add(_TL("Could not create dataset."));
	}
	else
	{
		g_GDAL_Driver.Set_Transform(pDataset, Get_System());

		if( pGrids->asGrid(0)->Get_Projection().Get_Type() != SG_PROJ_TYPE_CS_Undefined )
		{
			pDataset->SetProjection(SG_STR_SGTOMB(pGrids->asGrid(0)->Get_Projection().Get_WKT()));
		}

		zLine	= (double *)SG_Malloc(Get_NX() * sizeof(double));

		for(n=0; n<pGrids->Get_Count(); n++)
		{
			Process_Set_Text(CSG_String::Format(SG_T("%s %d"), _TL("Band"), n + 1));

			pGrid	= pGrids->asGrid(n);
			pBand	= pDataset->GetRasterBand(n + 1);

			for(y=0; y<Get_NY() && Set_Progress(y, Get_NY()); y++)
			{
				for(x=0; x<Get_NX(); x++)
				{
					zLine[x]	= pGrid->asDouble(x, Get_NY() - 1 - y);
				}

				pBand->RasterIO(GF_Write, 0, y, Get_NX(), 1, zLine, Get_NX(), 1, GDT_Float64, 0, 0);
			}
		}

		//-------------------------------------------------
		SG_Free(zLine);

		GDALClose(pDataset);

		return( true );
	}

	//-----------------------------------------------------
	return( false );
}
//---------------------------------------------------------
bool CPointCloud_From_Text_File::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_File	Stream;

	if( !Stream.Open(Parameters("FILE")->asString(), SG_FILE_R, false) )
	{
		Error_Set(_TL("Unable to open input file!"));

		return( false );
	}

	//-----------------------------------------------------
	int	xField	= Parameters("XFIELD")->asInt() - 1;
	int	yField	= Parameters("YFIELD")->asInt() - 1;
	int	zField	= Parameters("ZFIELD")->asInt() - 1;

	char	Separator;

	switch( Parameters("SEPARATOR")->asInt() )
    {
	default:	Separator	= '\t';	break;
    case  1:	Separator	=  ' ';	break;
    case  2:	Separator	=  ',';	break;
    }

    //-----------------------------------------------------
	CSG_String	sLine;
	CSG_Strings	Values;

	if( !Stream.Read_Line(sLine) )
	{
		Error_Set(_TL("Empty file!"));

		return( false );
	}

	if( Parameters("SKIP_HEADER")->asBool() )	// header contains field names
	{
		CSG_String_Tokenizer	tokValues(sLine, Separator);	// read each field name for later use

		while( tokValues.Has_More_Tokens() )
		{
			Values	+= tokValues.Get_Next_Token();
		}
	}
	else
    {
		Stream.Seek_Start();
    }

    //-----------------------------------------------------
    CSG_PointCloud	*pPoints	= SG_Create_PointCloud();
    pPoints->Set_Name(SG_File_Get_Name(Parameters("FILE")->asString(), false));
    Parameters("POINTS")->Set_Value(pPoints);

	CSG_Array_Int	Fields;

    //-----------------------------------------------------
    if( SG_UI_Get_Window_Main() )
    {
		CSG_Parameters	&Fields	= *Parameters("FIELDSPECS")->asParameters();

		int	nFields	= Fields.Get_Count() / 2;

		CSG_String	Names, Types;

		for(int iField=0; iField<nFields; iField++)
		{
			Names	+= CSG_String::Format("%s;", Fields(CSG_String::Format("NAME%03d", iField))->asString());
			Types	+= CSG_String::Format("%d;", Fields(CSG_String::Format("TYPE%03d", iField))->asInt   ());
		}

		Parameters("FIELDNAMES")->Set_Value(Names);
		Parameters("FIELDTYPES")->Set_Value(Types);
	}

	{
		TSG_Data_Type	Type	= SG_DATATYPE_Float;	// default

		CSG_String_Tokenizer	tokFields(Parameters("FIELDS"    )->asString(), ";");
		CSG_String_Tokenizer	tokTypes (Parameters("FIELDTYPES")->asString(), ";");
		CSG_String_Tokenizer	tokNames (Parameters("FIELDNAMES")->asString(), ";");

		while( tokFields.Has_More_Tokens() )
		{
			int	iField;

			if( !tokFields.Get_Next_Token().asInt(iField) || iField < 1 )
			{
				Error_Set(_TL("Error parsing attribute field index"));

				return( false );
			}

			Fields	+= iField - 1;

			CSG_String	Name;

			if( tokNames.Has_More_Tokens() )
			{
				Name	= tokNames.Get_Next_Token(); Name.Trim(true); Name.Trim(false);
			}

			if( Name.is_Empty() )
			{
				if( iField - 1 < Values.Get_Count() )
				{
					Name	= Values[iField - 1];
				}
				else
				{
					Name.Printf("FIELD%02d", iField);
				}
			}

			if( tokTypes.Has_More_Tokens() )
			{
				Get_Data_Type(Type, tokTypes.Get_Next_Token());
			}

			pPoints->Add_Field(Name, Type);
		}
	}

    //-----------------------------------------------------
	Process_Set_Text(_TL("Importing data ..."));

	int		nLines	= 0;
	sLong	Length	= Stream.Length();

	while( Stream.Read_Line(sLine) )
    {
		nLines++;

		if( pPoints->Get_Count() % 10000 == 0 && !Set_Progress((double)Stream.Tell(), (double)Length) )
		{
			return( true );	// user break
		}

	    //-------------------------------------------------
		CSG_String_Tokenizer	tokValues(sLine, Separator);

		Values.Clear();

		while( tokValues.Has_More_Tokens() )	// read every column in this line and fill vector
        {
			Values	+= tokValues.Get_Next_Token();
        }

	    //-------------------------------------------------
		double	x, y, z;

		if( xField >= Values.Get_Count() || !Values[xField].asDouble(x)
		||  yField >= Values.Get_Count() || !Values[yField].asDouble(y)
		||  zField >= Values.Get_Count() || !Values[zField].asDouble(z) )
		{
			Message_Fmt("\n%s: %s [%d]", _TL("Warning"), _TL("Skipping misformatted line"), nLines);

			continue;
		}

        pPoints->Add_Point(x, y, z);

	    //-------------------------------------------------
		for(int iAttribute=0; iAttribute<pPoints->Get_Attribute_Count(); iAttribute++)
		{
			if( Fields[iAttribute] >= Values.Get_Count() )
			{
				pPoints->Set_NoData(3 + iAttribute);
			}
			else switch( pPoints->Get_Attribute_Type(iAttribute) )
			{
			case SG_DATATYPE_String:
				pPoints->Set_Attribute(iAttribute, Values[Fields[iAttribute]]);
				break;

			default:
				{
					double	Value;

					if( Values[Fields[iAttribute]].asDouble(Value) )
					{
						pPoints->Set_Attribute(iAttribute, Value);
					}
					else
					{
						pPoints->Set_NoData(3 + iAttribute);
					}
				}
				break;
			}
		}
    }

    //-----------------------------------------------------
	DataObject_Set_Parameter(pPoints, "DISPLAY_VALUE_AGGREGATE", 3);	// highest z
	DataObject_Set_Parameter(pPoints, "COLORS_TYPE"            , 3);	// graduated colors
	DataObject_Set_Parameter(pPoints, "METRIC_ATTRIB"          , 2);	// z attrib
	DataObject_Set_Parameter(pPoints, "METRIC_ZRANGE", pPoints->Get_Minimum(2), pPoints->Get_Maximum(2));

	DataObject_Update(pPoints);

    //-----------------------------------------------------
	if( nLines > pPoints->Get_Count() )
	{
		Message_Add(" ", true);
		Message_Fmt("%s: %d %s", _TL("Warning"), nLines - pPoints->Get_Count(), _TL("invalid points have been skipped"));
	}

	Message_Add(" ", true);
	Message_Fmt("%d %s", pPoints->Get_Count(), _TL("points have been imported with success"));

	return( true );
}
Пример #23
0
//---------------------------------------------------------
bool CExercise_01::On_Execute(void)
{
	int		x, y, Method;
	double	Factor, Value_Input, Value_Output;
	CSG_Grid	*pInput, *pOutput;

	//-----------------------------------------------------
	// Get parameter settings...

	pInput		= Parameters("INPUT" )->asGrid();
	pOutput		= Parameters("OUTPUT")->asGrid();
	Factor		= Parameters("FACTOR")->asDouble();
	Method		= Parameters("METHOD")->asInt();


	//-----------------------------------------------------
	// Check for valid parameter settings...

	if( Method == 3 && Factor == 0.0 )
	{
		Message_Add(_TL("Division by zero is not allowed !!!"));
		Message_Dlg(_TL("Division by zero is not allowed !!!"));

		return( false );	// prevent a division by zero!!!
	}


	//-----------------------------------------------------
	// Execute calculation...

	for(y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		for(x=0; x<Get_NX(); x++)
		{
			Value_Input	= pInput->asDouble(x, y);

			switch( Method )
			{
			case 0:	// Addition...
				Value_Output	= Value_Input + Factor;
				break;

			case 1:	// Subtraction...
				Value_Output	= Value_Input - Factor;
				break;

			case 2:	// Multiplication...
				Value_Output	= Value_Input * Factor;
				break;

			case 3:	// Division...
				Value_Output	= Value_Input / Factor;
				break;
			}

			pOutput->Set_Value(x, y, Value_Output);
		}
	}


	//-----------------------------------------------------
	// Return 'true' if everything went okay...

	return( true );
}
Пример #24
0
//---------------------------------------------------------
bool CGrid_Cluster_Analysis::_On_Execute(void)
{
	int						i, j, *nMembers, nCluster, nElements;
	double					*Variances, **Centroids, SP;
	CSG_Grid				**Grids, *pCluster;
	CSG_Parameter_Grid_List	*pGrids;

	//-----------------------------------------------------
	pGrids		= Parameters("GRIDS")	->asGridList();
	pCluster	= Parameters("CLUSTER")	->asGrid();
	nCluster	= Parameters("NCLUSTER")->asInt();

	if( pGrids->Get_Count() < 1 )
	{
		return( false );
	}

	//-----------------------------------------------------
	Grids		= (CSG_Grid **)SG_Malloc(pGrids->Get_Count() * sizeof(CSG_Grid *));

	if( Parameters("NORMALISE")->asBool() )
	{
		for(i=0; i<pGrids->Get_Count(); i++)
		{
			Grids[i]	= SG_Create_Grid(pGrids->asGrid(i), SG_DATATYPE_Float);
			Grids[i]	->Assign(pGrids->asGrid(i));
			Grids[i]	->Standardise();
		}
	}
	else
	{
		for(i=0; i<pGrids->Get_Count(); i++)
		{
			Grids[i]	= pGrids->asGrid(i);
		}
	}

	pCluster->Set_NoData_Value(-1.0);
	pCluster->Assign_NoData();

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

	for(i=0; i<nCluster; i++)
	{
		Centroids[i]	= (double  *)SG_Malloc(pGrids->Get_Count() * sizeof(double));
	}

	//-------------------------------------------------
	switch( Parameters("METHOD")->asInt() )
	{
	case 0:		SP	= _MinimumDistance	(Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells());	break;
	case 1:		SP	= _HillClimbing		(Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells());	break;
	case 2:		SP	= _MinimumDistance	(Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells());
				SP	= _HillClimbing		(Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells());	break;
	}

	//-------------------------------------------------
	if( Parameters("NORMALISE")->asBool() )
	{
		for(i=0; i<pGrids->Get_Count(); i++)
		{
			delete(Grids[i]);

			for(j=0; j<nCluster; j++)
			{
				Centroids[j][i]	= pGrids->asGrid(i)->Get_StdDev() * Centroids[j][i] + pGrids->asGrid(i)->Get_Mean();
			}
		}
	}

	//-------------------------------------------------
	Save_LUT(pCluster);

	//-------------------------------------------------
	int					iCluster, iFeature;
	CSG_String			s;
	CSG_Table_Record	*pRecord;
	CSG_Table			*pTable;

	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%ld \n%s:\t%d \n%s:\t%d \n%s:\t%f\n\n%s\t%s\t%s"),
		_TL("Number of Elements")	, nElements,
		_TL("Number of Variables")	, pGrids->Get_Count(),
		_TL("Number of Clusters")	, nCluster,
		_TL("Standard Deviation")	, sqrt(SP),
		_TL("Cluster"), _TL("Elements"), _TL("Std.Dev.")
	);

	for(iFeature=0; iFeature<pGrids->Get_Count(); 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<nCluster; iCluster++)
	{
		Variances[iCluster]	= nMembers[iCluster] ? Variances[iCluster] / nMembers[iCluster] : 0.0;

		s.Printf(SG_T("\n%d\t%d\t%f"), iCluster, nMembers[iCluster], sqrt(Variances[iCluster]));

		pRecord	= pTable->Add_Record();
		pRecord->Set_Value(0, iCluster);
		pRecord->Set_Value(1, nMembers[iCluster]);
		pRecord->Set_Value(2, sqrt(Variances[iCluster]));

		for(iFeature=0; iFeature<pGrids->Get_Count(); iFeature++)
		{
			double	Centroid	= Centroids[iCluster][iFeature];

			if( Parameters("NORMALISE")->asBool() )
			{
				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);
	}

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

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

	return( true );
}
Пример #25
0
//---------------------------------------------------------
bool CWMS_Import::Get_Map(wxHTTP *pServer, const CSG_String &Directory, CWMS_Capabilities &Cap)
{
	bool	bResult	= false;

	int				i, n;
	CSG_Rect		r(Cap.m_Extent);
	CSG_Parameters	p;

	//-----------------------------------------------------
//	if( Cap.m_MaxWidth  > 2 && NX > Cap.m_MaxWidth  )	NX	= Cap.m_MaxWidth;
//	if( Cap.m_MaxHeight > 2 && NY > Cap.m_MaxHeight )	NY	= Cap.m_MaxHeight;

	p.Add_Range	(NULL	, "X_RANGE"	, _TL("X Range")	, _TL(""), r.Get_XMin(), r.Get_XMax(), r.Get_XMin(), r.Get_XRange() > 0.0, r.Get_XMax(), r.Get_XRange() > 0.0);
	p.Add_Range	(NULL	, "Y_RANGE"	, _TL("Y Range")	, _TL(""), r.Get_YMin(), r.Get_YMax(), r.Get_YMin(), r.Get_YRange() > 0.0, r.Get_YMax(), r.Get_YRange() > 0.0);

	p.Add_Value	(NULL	, "CELLSIZE", _TL("Cellsize")	, _TL(""), PARAMETER_TYPE_Double, r.Get_XRange() / 2001.0, 0.0, true);

	p.Add_Choice(NULL	, "FORMAT"	, _TL("Format")		, _TL(""), Cap.m_Formats);
	p.Add_Choice(NULL	, "PROJ"	, _TL("Projections"), _TL(""), Cap.m_Projections);

	CSG_Parameter	*pNode	= p("FORMAT");
	for(i=0; i<pNode->asChoice()->Get_Count(); i++)
	{
		CSG_String	s(pNode->asChoice()->Get_Item(i));
		if( !s.CmpNoCase(SG_T("image/png")) )
			pNode->Set_Value(i);
	}

	for(i=0; i<Cap.m_Layers_Name.Get_Count(); i++)
	{
		p.Add_Value(NULL, Cap.m_Layers_Name[i], Cap.m_Layers_Title[i], "", PARAMETER_TYPE_Bool, false);
	}

	//-----------------------------------------------------
	if( pServer && Dlg_Parameters(&p, _TL("WMS Import")) )
	{
		int			NX, NY;
		double		Cellsize;
		CSG_String	Layers, Format;

		//-------------------------------------------------
		r.Assign(
			p("X_RANGE")->asRange()->Get_LoVal(),
			p("Y_RANGE")->asRange()->Get_LoVal(),
			p("X_RANGE")->asRange()->Get_HiVal(),
			p("Y_RANGE")->asRange()->Get_HiVal()
		);

		Cellsize	= p("CELLSIZE")	->asDouble();

		NX			= 1 + (int)(r.Get_XRange() / Cellsize);
		NY			= 1 + (int)(r.Get_YRange() / Cellsize);

		//-------------------------------------------------
		Layers.Clear();

		for(i=0, n=0; i<Cap.m_Layers_Name.Get_Count(); i++)
		{
			if( p(Cap.m_Layers_Name[i])->asBool() )
			{
				if( n++ > 0 )	Layers	+= ",";

				Layers	+= Cap.m_Layers_Name[i];
			}
		}

		if( n == 0 )
		{
			return( false );
		}

		//-------------------------------------------------
		wxBitmapType	tFormat;

		Format	= p("FORMAT")->asString();

		if(      Format.Contains(SG_T("image/gif" )) )	tFormat	= wxBITMAP_TYPE_GIF ;
		else if( Format.Contains(SG_T("image/jpeg")) )	tFormat	= wxBITMAP_TYPE_JPEG;
		else if( Format.Contains(SG_T("image/png" )) )	tFormat	= wxBITMAP_TYPE_PNG ;
		else if( Format.Contains(SG_T("image/wbmp")) )	tFormat	= wxBITMAP_TYPE_BMP ;
		else if( Format.Contains(SG_T("image/bmp" )) )	tFormat	= wxBITMAP_TYPE_BMP ;
		else if( Format.Contains(SG_T("image/tiff")) )	tFormat	= wxBITMAP_TYPE_TIF ;
		else if( Format.Contains(SG_T("GIF"       )) )	tFormat	= wxBITMAP_TYPE_GIF ;
		else if( Format.Contains(SG_T("JPEG"      )) )	tFormat	= wxBITMAP_TYPE_JPEG;
		else if( Format.Contains(SG_T("PNG"       )) )	tFormat	= wxBITMAP_TYPE_PNG ;
		else
		{
			return( false );
		}

		//-------------------------------------------------
		CSG_String	sRequest(Directory);

		sRequest	+= SG_T("?SERVICE=WMS");
		sRequest	+= SG_T("&VERSION=")	+ Cap.m_Version;
		sRequest	+= SG_T("&REQUEST=GetMap");

		sRequest	+= SG_T("&LAYERS=")		+ Layers;

		if( Cap.m_Projections.Length() > 0 )
			sRequest	+= CSG_String(S_SRS(Cap.m_Version)) + p("PROJ")->asString();

		sRequest	+= SG_T("&FORMAT=")		+ Format;

		sRequest	+= CSG_String::Format(SG_T("&WIDTH=%d&HEIGHT=%d"), NX, NY);
		sRequest	+= CSG_String::Format(SG_T("&BBOX=%f,%f,%f,%f"), r.m_rect.xMin, r.m_rect.yMin, r.m_rect.xMax, r.m_rect.yMax);

		Message_Add(sRequest, true);

		//-------------------------------------------------
		wxInputStream	*pStream;

		if( (pStream = pServer->GetInputStream(sRequest.c_str())) == NULL )
		{
			Message_Add(_TL("could not open GetMap stream"));
		}
		else
		{
			wxImage	Image;

			if( Image.LoadFile(*pStream, tFormat) == false )
			{
				Message_Add(_TL("could not read image"));

				CSG_String	s	= SG_T("\n");

				pStream->SeekI(0, wxFromStart);

				while( !pStream->Eof() )
				{
					s	+= (char)pStream->GetC();
				}

				Message_Add(s);
			}
			else
			{
				CSG_Grid	*pGrid	= SG_Create_Grid(SG_DATATYPE_Int, Image.GetWidth(), Image.GetHeight(), Cellsize, r.m_rect.xMin, r.m_rect.yMin);

				for(int y=0, yy=pGrid->Get_NY()-1; y<pGrid->Get_NY() && Set_Progress(y, pGrid->Get_NY()); y++, yy--)
				{
					for(int x=0; x<pGrid->Get_NX(); x++)
					{
						pGrid->Set_Value(x, y, SG_GET_RGB(Image.GetRed(x, yy), Image.GetGreen(x, yy), Image.GetBlue(x, yy)));
					}
				}

				//-----------------------------------------
				pGrid->Set_Name(Cap.m_Title);
				Parameters("MAP")->Set_Value(pGrid);
				DataObject_Set_Colors(pGrid, 100, SG_COLORS_BLACK_WHITE);

				CSG_Parameters	Parms;

				if( DataObject_Get_Parameters(pGrid, Parms) && Parms("COLORS_TYPE") )
				{
					Parms("COLORS_TYPE")->Set_Value(3);	// Color Classification Type: RGB

					DataObject_Set_Parameters(pGrid, Parms);
				}

				bResult	= true;
			}

			delete(pStream);
		}
	}

	return( bResult );
}
Пример #26
0
bool CGridNet::On_Execute(void)
{
	TSG_Data_Type Type;
	CSG_String InputBasename = CSG_String("input");
	CSG_String OutputBasename = CSG_String("output");
	CSG_String FLOWD8_INPUT_FileName, FLOWD8_INPUT_FilePath;
	CSG_String LONGEST_OUTPUT_FileName, LONGEST_OUTPUT_FilePath;
	CSG_String TOTAL_LENGTH_OUTPUT_FileName, TOTAL_LENGTH_OUTPUT_FilePath;
	CSG_String ORDER_OUTPUT_FileName, ORDER_OUTPUT_FilePath;
	CSG_String OUTLET_INPUT_FileName, OUTLET_INPUT_FilePath, MASK_INPUT_FileName, MASK_INPUT_FilePath;
	CSG_String GDALDriver, sCmd, TempDirPath, TauDEMBinDir, BinaryName, BinaryPath, LogFile;
	CSG_String LONGESTName, LENGTHName, ORDERName;
	CSG_Projection Projection;
	CSG_GDAL_DataSet DataSet;
	CSG_Grid *FLOWD8_INPUT_Grid, *LONGEST_OUTPUT_Grid, *TOTAL_LENGTH_OUTPUT_Grid, *ORDER_OUTPUT_Grid, *MASK_INPUT_Grid;
	CSG_Shapes *OUTLET_INPUT_Grid;
	int Threshold, nproc;

	FLOWD8_INPUT_Grid = Parameters("FLOWD8_INPUT")->asGrid();
	LONGEST_OUTPUT_Grid = Parameters("LONGEST_OUTPUT")->asGrid();
	TOTAL_LENGTH_OUTPUT_Grid = Parameters("TOTAL_LENGTH_OUTPUT")->asGrid();
	ORDER_OUTPUT_Grid = Parameters("ORDER_OUTPUT")->asGrid();
	MASK_INPUT_Grid = Parameters("MASK_INPUT")->asGrid();
	OUTLET_INPUT_Grid = Parameters("OUTLET_INPUT")->asShapes();
	Threshold = Parameters("THRESHOLD")->asInt();
	nproc = Parameters("NPROC")->asInt();

	GDALDriver = CSG_String("GTiff");
	Get_Projection(Projection);
	Type = FLOWD8_INPUT_Grid->Get_Type();

	//TempDirPath = SG_File_Get_Path_Absolute(CSG_String("taudem_tmp"));
	TempDirPath = Parameters("TEMP_DIR")->asFilePath()->asString();

	FLOWD8_INPUT_FileName = InputBasename + CSG_String("p");
	FLOWD8_INPUT_FilePath = SG_File_Make_Path(TempDirPath, FLOWD8_INPUT_FileName, CSG_String("tif")); 

	LONGEST_OUTPUT_FileName = OutputBasename + CSG_String("plen");
	LONGEST_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, LONGEST_OUTPUT_FileName, CSG_String("tif"));

	TOTAL_LENGTH_OUTPUT_FileName = OutputBasename + CSG_String("tlen");
	TOTAL_LENGTH_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, TOTAL_LENGTH_OUTPUT_FileName, CSG_String("tif"));

	ORDER_OUTPUT_FileName = OutputBasename + CSG_String("gord");
	ORDER_OUTPUT_FilePath = SG_File_Make_Path(TempDirPath, ORDER_OUTPUT_FileName, CSG_String("tif"));

	OUTLET_INPUT_FileName = InputBasename + CSG_String("o");
	OUTLET_INPUT_FilePath = SG_File_Make_Path(TempDirPath, OUTLET_INPUT_FileName, CSG_String("shp")); 

	MASK_INPUT_FileName = InputBasename + CSG_String("wg");
	MASK_INPUT_FilePath = SG_File_Make_Path(TempDirPath, MASK_INPUT_FileName, CSG_String("tif")); 

	LogFile = SG_File_Make_Path(TempDirPath, CSG_String("taudem_log.txt"));
	LogFile = SG_File_Get_Path_Absolute(LogFile);

	TauDEMBinDir = SG_File_Make_Path(CSG_String("bin"), CSG_String("TauDEM"));
	TauDEMBinDir = SG_File_Get_Path_Absolute(TauDEMBinDir);

	// optional flags
	CSG_String OptionalFlags = CSG_String("");
	if (OUTLET_INPUT_Grid != NULL)
	{
		OptionalFlags = CSG_String::Format(SG_T(" -o \"%s\""), OUTLET_INPUT_FilePath.c_str());
	}
	if (MASK_INPUT_Grid != NULL)
	{
		OptionalFlags = OptionalFlags + CSG_String::Format(SG_T(" -mask \"%s\" -thresh %d"), MASK_INPUT_FilePath.c_str(), Threshold);
	}
		
	BinaryName = CSG_String("GridNet"); 
	BinaryPath = SG_File_Make_Path(TauDEMBinDir, BinaryName);
	sCmd = CSG_String::Format(SG_T("\"mpiexec -n %d \"%s\" -p \"%s\" -plen \"%s\" -tlen \"%s\" -gord \"%s\" %s > \"%s\" 2>&1\""), nproc, BinaryPath.c_str(), FLOWD8_INPUT_FilePath.c_str(), LONGEST_OUTPUT_FilePath.c_str(), TOTAL_LENGTH_OUTPUT_FilePath.c_str(), ORDER_OUTPUT_FilePath.c_str(), OptionalFlags.c_str(), LogFile.c_str());
	LONGESTName = CSG_String("D8 LongestPath");
	LENGTHName = CSG_String("D8 TotalLength");
	ORDERName = CSG_String("D8 GridOrder");

	// make sure temp dir exists
	if (!SG_Dir_Exists(TempDirPath))
	{
		if (!SG_Dir_Create(TempDirPath))
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to create temp directory"), TempDirPath.c_str()));
		}
	}

	// Delete old input file if exists
	if (SG_File_Exists(FLOWD8_INPUT_FilePath))
	{
		if (!SG_File_Delete(FLOWD8_INPUT_FilePath))
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to delete previous input file: "), FLOWD8_INPUT_FilePath.c_str()));
			return( false );
		}
	}

	if (OUTLET_INPUT_Grid != NULL)
	{
		// Delete old input file if exists
		if (SG_File_Exists(OUTLET_INPUT_FilePath))
		{
			if (!SG_File_Delete(OUTLET_INPUT_FilePath))
			{
				Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to delete previous input file: "), OUTLET_INPUT_FilePath.c_str()));
				return( false );
			}
		}
	}

	if (MASK_INPUT_Grid != NULL)
	{
		// Delete old input file if exists
		if (SG_File_Exists(MASK_INPUT_FilePath))
		{
			if (!SG_File_Delete(MASK_INPUT_FilePath))
			{
				Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to delete previous input file: "), MASK_INPUT_FilePath.c_str()));
				return( false );
			}
		}
	}

	// Delete old output files
	if (SG_File_Exists(LONGEST_OUTPUT_FilePath))
	{
		if (!SG_File_Delete(LONGEST_OUTPUT_FilePath))
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to delete previous output file: "), LONGEST_OUTPUT_FilePath.c_str()));
			return( false );
		}
	}

	// Delete old output files
	if (SG_File_Exists(TOTAL_LENGTH_OUTPUT_FilePath))
	{
		if (!SG_File_Delete(TOTAL_LENGTH_OUTPUT_FilePath))
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to delete previous output file: "), TOTAL_LENGTH_OUTPUT_FilePath.c_str()));
			return( false );
		}
	}

	// Delete old output files
	if (SG_File_Exists(ORDER_OUTPUT_FilePath))
	{
		if (!SG_File_Delete(ORDER_OUTPUT_FilePath))
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to delete previous output file: "), ORDER_OUTPUT_FilePath.c_str()));
			return( false );
		}
	}

	// save input file
	if( !DataSet.Open_Write(FLOWD8_INPUT_FilePath, GDALDriver, CSG_String(""), Type, 1, *Get_System(), Projection) )
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open file for writing: "), FLOWD8_INPUT_FilePath.c_str()));
		return( false );
	}
	DataSet.Write(0, FLOWD8_INPUT_Grid);
	
	if( !DataSet.Close() )
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to close file after writing: "), FLOWD8_INPUT_FilePath.c_str()));
		return( false );
	}

	// save mask grid
	if (MASK_INPUT_Grid != NULL)
	{
		if( !DataSet.Open_Write(MASK_INPUT_FilePath, GDALDriver, CSG_String(""), Type, 1, *Get_System(), Projection) )
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open file for writing: "), MASK_INPUT_FilePath.c_str()));
			return( false );
		}
		DataSet.Write(0, MASK_INPUT_Grid);
	
		if( !DataSet.Close() )
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to close file after writing: "), MASK_INPUT_FilePath.c_str()));
			return( false );
		}
	}

	// save outlet shapefile
	if (OUTLET_INPUT_Grid != NULL)
	{
		CSG_OGR_DataSource	DataSource;
		CSG_String OGRDriver = CSG_String("ESRI Shapefile");
		if( !DataSource.Create(OUTLET_INPUT_FilePath, OGRDriver) )
		{
			Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open file for writing: "), OUTLET_INPUT_FilePath.c_str()));
			return( false );
		}
		DataSource.Write(OUTLET_INPUT_Grid, OGRDriver);
	}


	// Run TauDEM GridNet

	Message_Add(CSG_String("Executing ") + sCmd);

	// run process
	if (system(sCmd.b_str()) != 0)
	{
		Error_Set(CSG_String::Format(SG_T("Error executing '%s' see Execution log for details"), BinaryName.c_str()));
		// read log output
		CSG_File File;
		if (File.Open(LogFile, SG_FILE_R, false))
		{
			CSG_String Line;
			while (! File.is_EOF() && File.Read_Line(Line))
			{
				Message_Add(Line);
			}
			File.Close();
		} else 
		{
			Message_Add(CSG_String("Unable to open " + LogFile + CSG_String(" for reading")));
		}

		return( false );
	}

	// Open new output tif file
	if( !DataSet.Open_Read(LONGEST_OUTPUT_FilePath))
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open generated file: "), LONGEST_OUTPUT_FilePath.c_str()));
		return( false );
	} 
	else 
	{
		LONGEST_OUTPUT_Grid->Assign(DataSet.Read(0));
		LONGEST_OUTPUT_Grid->Set_Name(LONGESTName);
		Parameters("LONGEST_OUTPUT")->Set_Value(LONGEST_OUTPUT_Grid);

		CSG_Colors colors;
		DataObject_Get_Colors(FLOWD8_INPUT_Grid, colors);
		DataObject_Set_Colors(LONGEST_OUTPUT_Grid, colors);
		DataObject_Update(LONGEST_OUTPUT_Grid, false);		
	}

	// Open new output tif file
	if( !DataSet.Open_Read(TOTAL_LENGTH_OUTPUT_FilePath))
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open generated file: "), TOTAL_LENGTH_OUTPUT_FilePath.c_str()));
		return( false );
	} 
	else 
	{
		TOTAL_LENGTH_OUTPUT_Grid->Assign(DataSet.Read(0));
		TOTAL_LENGTH_OUTPUT_Grid->Set_Name(LENGTHName);
		Parameters("TOTAL_LENGTH_OUTPUT")->Set_Value(TOTAL_LENGTH_OUTPUT_Grid);

		CSG_Colors colors;
		DataObject_Get_Colors(FLOWD8_INPUT_Grid, colors);
		DataObject_Set_Colors(TOTAL_LENGTH_OUTPUT_Grid, colors);
		DataObject_Update(TOTAL_LENGTH_OUTPUT_Grid, false);		
	}

	// Open new output tif
	if( !DataSet.Open_Read(ORDER_OUTPUT_FilePath))
	{
		Error_Set(CSG_String::Format(SG_T("%s: '%s' "), _TL("Failed to open generated file: "), ORDER_OUTPUT_FilePath.c_str()));
		return( false );
	} 
	else 
	{
		ORDER_OUTPUT_Grid->Assign(DataSet.Read(0));
		ORDER_OUTPUT_Grid->Set_Name(ORDERName);
		Parameters("ORDER_OUTPUT")->Set_Value(ORDER_OUTPUT_Grid);

		CSG_Colors colors;
		DataObject_Get_Colors(FLOWD8_INPUT_Grid, colors);
		DataObject_Set_Colors(ORDER_OUTPUT_Grid, colors);
		DataObject_Update(ORDER_OUTPUT_Grid, false);		
	}

	return( true );
}
Пример #27
0
//---------------------------------------------------------
bool Cdodproperror::On_Execute(void)
{

	if (!GetParameterValues())
	{
		return false;
	}
	CSG_String TempDirPath = Parameters("TEMP_DIR")->asFilePath()->asString();

	LogOutput = SG_File_Make_Path(TempDirPath, CSG_String("out"), CSG_String("txt"));
	LogError = SG_File_Make_Path(TempDirPath, CSG_String("error"), CSG_String("txt"));;

	NewDEM_InputPath = SG_File_Make_Path(TempDirPath, CSG_String("newdem"), CSG_String("tif"));
	OldDEM_InputPath = SG_File_Make_Path(TempDirPath, CSG_String("olddem"), CSG_String("tif"));
	PropError_InputPath = SG_File_Make_Path(TempDirPath, CSG_String("properror"), CSG_String("tif"));
	RawDoD_OutputPath = SG_File_Make_Path(TempDirPath, CSG_String("rawdodoutput"), CSG_String("tif"));
	ThresholdedDoD_OutputPath = SG_File_Make_Path(TempDirPath, CSG_String("threshdodoutput"), CSG_String("tif"));


	// convert grids to tiffs for command input
	CSG_Grid* InputGrids [3] = {NewDEM, OldDEM, PropError};

	CSG_Strings InputGridPaths = CSG_Strings();
	InputGridPaths.Add(NewDEM_InputPath);
	InputGridPaths.Add(OldDEM_InputPath);
	InputGridPaths.Add(PropError_InputPath);

	if (!SaveGridsAsTIFF(InputGrids, InputGridPaths))
	{
		return false;
	}

	CSG_Strings OutputGridPaths = CSG_Strings();
	OutputGridPaths.Add(RawDoD_OutputPath);
	OutputGridPaths.Add(ThresholdedDoD_OutputPath);

	CSG_Strings OutputGridNames = CSG_Strings();
	OutputGridNames.Add("Raw DoD");
	OutputGridNames.Add("Thresholded DoD");

	// delete old output files (GCD throws an error if a file already exists)
	if (!DeleteFiles(OutputGridPaths))
	{
		return false;
	}

	CSG_String CMD = CSG_String::Format(SG_T("\"\"%s\" %s \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" >\"%s\" 2>\"%s\"\""), GCD.c_str(), GCD_CMD.c_str(), NewDEM_InputPath.c_str(), OldDEM_InputPath.c_str(), PropError_InputPath.c_str(), RawDoD_OutputPath.c_str(), ThresholdedDoD_OutputPath.c_str(), LogOutput.c_str(), LogError.c_str());
	Message_Add(CSG_String("Executing: ") + CMD);			
	if (system(CMD.b_str()) != 0)
	{
		Message_Dlg(CSG_String::Format(SG_T("Error while executing %s, see Execution Log for details"), GCD_CMD.c_str()));
		DisplayLogs();
		return false;
	}	

	CSG_Grid* OutputGrids [3] = {RawDoD, ThresholdedDoD};
	if (!LoadTIFFsAsGrids(OutputGridPaths, OutputGrids, OutputGridNames))
	{
		return false;
	}
	Parameters("RAW_DOD")->Set_Value(RawDoD);
	Parameters("THRESHOLDED_DOD")->Set_Value(ThresholdedDoD);

	ApplyColors(NewDEM, RawDoD);
	ApplyColors(NewDEM, ThresholdedDoD);

	DisplayFile(LogOutput);
	return true;
}
Пример #28
0
//---------------------------------------------------------
bool CPGIS_Shapes_Save::On_Execute(void)
{
	int			SRID;
	CSG_Shapes	*pShapes;
	CSG_String	SQL, Geo_Table, Geo_Type, Geo_Field, sSRID;

	pShapes		= Parameters("SHAPES")	->asShapes();
	Geo_Table	= Parameters("NAME")	->asString();	if( Geo_Table.Length() == 0 )	Geo_Table	= pShapes->Get_Name();
	SRID		= Parameters("SRID")	->asInt();
	SRID		= SG_Get_Projections().Get_SRID_byNamesIndex(SRID);

	sSRID.Printf(SG_T("%d"), SRID);

	//-----------------------------------------------------
	switch( pShapes->Get_Vertex_Type() )
	{
	case SG_VERTEX_TYPE_XY:
		switch( pShapes->Get_Type() )
		{	default:	return( false );
		case SHAPE_TYPE_Point:		Geo_Type	= SG_OGIS_TYPE_STR_Point;			Geo_Field	= SG_T("geo_point");		break;
		case SHAPE_TYPE_Points:		Geo_Type	= SG_OGIS_TYPE_STR_MultiPoint;		Geo_Field	= SG_T("geo_points");		break;
		case SHAPE_TYPE_Line:		Geo_Type	= SG_OGIS_TYPE_STR_MultiLine;		Geo_Field	= SG_T("geo_line");			break;
		case SHAPE_TYPE_Polygon:	Geo_Type	= SG_OGIS_TYPE_STR_MultiPolygon;	Geo_Field	= SG_T("geo_polygon");		break;
		}
		break;

	case SG_VERTEX_TYPE_XYZ:
		switch( pShapes->Get_Type() )
		{	default:	return( false );
		case SHAPE_TYPE_Point:		Geo_Type	= SG_OGIS_TYPE_STR_Point_Z;			Geo_Field	= SG_T("geo_point_z");		break;
		case SHAPE_TYPE_Points:		Geo_Type	= SG_OGIS_TYPE_STR_MultiPoint_Z;	Geo_Field	= SG_T("geo_points_z");		break;
		case SHAPE_TYPE_Line:		Geo_Type	= SG_OGIS_TYPE_STR_MultiLine_Z;		Geo_Field	= SG_T("geo_line_z");		break;
		case SHAPE_TYPE_Polygon:	Geo_Type	= SG_OGIS_TYPE_STR_MultiPolygon_Z;	Geo_Field	= SG_T("geo_polygon_z");	break;
		}
		break;

	case SG_VERTEX_TYPE_XYZM:
		switch( pShapes->Get_Type() )
		{	default:	return( false );
		case SHAPE_TYPE_Point:		Geo_Type	= SG_OGIS_TYPE_STR_Point_ZM;		Geo_Field	= SG_T("geo_point_zm");		break;
		case SHAPE_TYPE_Points:		Geo_Type	= SG_OGIS_TYPE_STR_MultiPoint_ZM;	Geo_Field	= SG_T("geo_points_zm");	break;
		case SHAPE_TYPE_Line:		Geo_Type	= SG_OGIS_TYPE_STR_MultiLine_ZM;	Geo_Field	= SG_T("geo_line_zm");		break;
		case SHAPE_TYPE_Polygon:	Geo_Type	= SG_OGIS_TYPE_STR_MultiPolygon_ZM;	Geo_Field	= SG_T("geo_polygon_zm");	break;
		}
		break;
	}

	//-----------------------------------------------------
	if( Get_Connection()->Table_Exists(Geo_Table) )
	{
		Message_Add(CSG_String::Format(SG_T("%s: %s"), _TL("table already exists"), Geo_Table.c_str()));

		switch( Parameters("EXISTS")->asInt() )
		{
		case 0:	// abort export
			return( false );

		case 1:	// replace existing table
			Message_Add(CSG_String::Format(SG_T("%s: %s"), _TL("trying to drop table"), Geo_Table.c_str()));

			if( !Get_Connection()->Table_Drop(Geo_Table, false) )
			{
				Message_Add(CSG_String::Format(SG_T(" ...%s!"), _TL("failed")));

				return( false );
			}

			break;

		case 2:	// append records, if table structure allows
			break;
		}
	}

	//-----------------------------------------------------
	if( !Get_Connection()->Table_Exists(Geo_Table) && !Get_Connection()->Table_Create(Geo_Table, *pShapes, Get_Constraints(Parameters("FLAGS")->asParameters(), pShapes), false) )
	{
		Get_Connection()->Rollback();

		return( false );
	}

	//-----------------------------------------------------
	SQL.Printf(SG_T("SELECT AddGeometryColumn('%s', '%s', %d, '%s', %d)"),
		Geo_Table.c_str(),				// <table_name>
		Geo_Field.c_str(),				// <column_name>
		SRID,							// <srid>
		Geo_Type.Make_Upper().c_str(),	// <type>
		2								// <dimension>
	);

	if( !Get_Connection()->Execute(SQL) )
	{
		Get_Connection()->Rollback();

		Message_Add(_TL("could not create geometry field"));

		return( false );
	}

	//-----------------------------------------------------
	int			iShape, iField, nAdded;
	CSG_String	Insert, Fields, sWKT;

	Fields	= Geo_Field;

	for(iField=0; iField<pShapes->Get_Field_Count(); iField++)
	{
		Fields	+= CSG_String(", ") + pShapes->Get_Field_Name(iField);
	}

	Insert.Printf(SG_T("INSERT INTO %s (%s) VALUES ("), Geo_Table.c_str(), Fields.c_str());

	for(iShape=0, nAdded=0; iShape<pShapes->Get_Count() && Set_Progress(iShape, pShapes->Get_Count()); iShape++)
	{
		CSG_Shape	*pShape	= pShapes->Get_Shape(iShape);

		if( pShape->is_Valid() )
		{
			SQL	= Insert;

			CSG_Shapes_OGIS_Converter::to_WKText(pShape, sWKT);

			SQL	+= SG_T("GeomFromText('") + sWKT + SG_T("', ") + sSRID + SG_T(")");

			for(iField=0; iField<pShapes->Get_Field_Count(); iField++)
			{
				CSG_String	s = pShape->asString(iField);

				if( pShapes->Get_Field_Type(iField) == SG_DATATYPE_String )
				{
					s.Replace(SG_T("'"), SG_T("\""));
					s	= SG_T("'") + s + SG_T("'");
				}

				SQL	+= SG_T(", ")  + s;
			}

			SQL	+= SG_T(")");

			if( Get_Connection()->Execute(SQL) )
			{
				nAdded++;
			}
			else
			{
				Message_Add(CSG_String::Format(SG_T("dropped %d. shape"), iShape));
			}
		}
	}

	//-----------------------------------------------------
	if( nAdded == 0 )
	{
		Get_Connection()->Rollback();

		Get_Connection()->Table_Drop(Geo_Table);

		return( false );
	}

	return( Get_Connection()->Commit() );
}
Пример #29
0
bool CCropToData::On_Execute(void) {

    //CSG_Grid* pGrid = Parameters("GRID")->asGrid();
    CSG_Grid* pCroppedGrid;
    CSG_Grid** pGrids;
    int iGrids;
    int iMinX = 1000000;
    int iMaxX = 0;
    int iMinY = 1000000;
    int iMaxY = 0;
    double dMinX, dMinY;
    int iNX;
    int iNY;
    int i;
    int x,y;

    if (Parameters("INPUT")->asInt() <= 0) {
        Message_Add(_TL("No grids selected"));
        return (false);
    }//if

    iGrids		= Parameters("INPUT")->asInt();
    pGrids		=(CSG_Grid **)Parameters("INPUT")->asPointer();

    for (i = 0 ; i < iGrids ; i++) {
        if (pGrids[i]->is_Compatible(pGrids[0]->Get_System())) {
            for(y=0; y<Get_NY() && Set_Progress(y); y++) {
                for(x=0; x<Get_NX(); x++) {
                    if (!pGrids[i]->is_NoData(x,y)) {
                        if (x<iMinX) {
                            iMinX = x;
                        }//if
                        if (x>iMaxX) {
                            iMaxX = x;
                        }//if
                        if (y<iMinY) {
                            iMinY = y;
                        }//if
                        if (y>iMaxY) {
                            iMaxY = y;
                        }//if
                    }//if
                }//for
            }//for
        }//if
    }//for
    iNX = iMaxX-iMinX+1;
    iNY = iMaxY-iMinY+1;
    dMinX = pGrids[0]->Get_XMin() + iMinX * pGrids[0]->Get_Cellsize();
    dMinY = pGrids[0]->Get_YMin() + iMinY * pGrids[0]->Get_Cellsize();

    if (iNX != pGrids[0]->Get_NX() || iNY != pGrids[0]->Get_NY()) {
        for (i = 0 ; i < iGrids ; i++) {
            if (pGrids[i]->is_Compatible(pGrids[0]->Get_System())) {
                pCroppedGrid = new CSG_Grid(pGrids[i]->Get_Type(), iNX, iNY, pGrids[i]->Get_Cellsize(), dMinX, dMinY);
                pCroppedGrid->Assign(pGrids[i], GRID_INTERPOLATION_BSpline);
                DataObject_Add(pCroppedGrid);
            }//if
        }//for
    }//if

    return true;

}//method
Пример #30
0
//---------------------------------------------------------
bool CSearchInTable::On_Execute(void)
{
	bool		*WasSelected;
	int			i, iMethod;
	CSG_String	sExpression;
	CSG_Shapes	*pShapes;

	pShapes		= Parameters("SHAPES")		->asShapes();
	sExpression	= Parameters("EXPRESSION")	->asString();
	iMethod		= Parameters("METHOD")		->asInt();

	//-----------------------------------------------------
	if( iMethod == METHOD_SELECT_FROM_SEL )
	{
		WasSelected	= new bool[pShapes->Get_Count()];

		for(i=0; i<pShapes->Get_Count() && Set_Progress(i, pShapes->Get_Count()); i++)
		{
			WasSelected[i]	= pShapes->Get_Record(i)->is_Selected();
		}
	}

	if( iMethod != METHOD_ADD_TO_SEL )
	{
		pShapes->Select();
	}

	//-----------------------------------------------------
	std::vector <int> m_Selection;

	for(i=0; i<pShapes->Get_Count() && Set_Progress(i, pShapes->Get_Count()); i++)
	{
		CSG_Shape	*pShape	= pShapes->Get_Shape(i);

		for(int j=0; j<pShapes->Get_Field_Count(); j++)
		{
			CSG_String	sValue	= pShape->asString(j);

			if( sValue.Find(sExpression) != -1 )
			{
				m_Selection.push_back(i);
				break;
			}
		}
	}

	//-----------------------------------------------------
	for(i=0; i<m_Selection.size() && Set_Progress(i, m_Selection.size()); i++)
	{
		int	iSelection = m_Selection[i];

		if( !pShapes->Get_Record(iSelection)->is_Selected() )
		{
			if( iMethod != METHOD_SELECT_FROM_SEL || WasSelected[iSelection] )
			{
				((CSG_Table *)pShapes)->Select(iSelection, true);
			}
		}
	}

	//-----------------------------------------------------
	if( iMethod == METHOD_SELECT_FROM_SEL )
	{
		delete(WasSelected);
	}

	Message_Add(CSG_String::Format(SG_T("%s: %d"), _TL("selected shapes"), m_Selection.size()));

	DataObject_Update(pShapes);

	return( true );
}