Ejemplo n.º 1
0
//---------------------------------------------------------
bool CSG_MetaData::Load(const CSG_String &File, const SG_Char *Extension)
{
	Destroy();

	//-----------------------------------------------------
	if( File.Find("http://") == 0 )
	{
		CSG_String	s(File.Right(File.Length() - CSG_String("http://").Length()));

		return( Load_HTTP(s.BeforeFirst('/'), s.AfterFirst('/')) );
	}

	//-----------------------------------------------------
	wxXmlDocument	XML;

	if( SG_File_Exists(SG_File_Make_Path(NULL, File, Extension)) && XML.Load(SG_File_Make_Path(NULL, File, Extension).c_str()) )
	{
		_Load(XML.GetRoot());

		return( true );
	}

	//-----------------------------------------------------
	return( false );
}
Ejemplo n.º 2
0
//---------------------------------------------------------
int CWKSP_Module_Manager::_Open_Directory(const wxChar *sDirectory, bool bOnlySubDirectories)
{
    int			nOpened	= 0;
    wxDir		Dir;
    wxString	FileName;

    if( Dir.Open(sDirectory) )
    {
        if( !bOnlySubDirectories && Dir.GetFirst(&FileName, wxEmptyString, wxDIR_FILES) )
        {
            do
            {   if( FileName.Find(wxT("saga_api")) < 0 && FileName.Find(wxT("saga_gdi")) < 0 && FileName.Find(wxT("wx")) < 0 && FileName.Find(wxT("mingw")) < 0 )
                    if( Open(SG_File_Make_Path(Dir.GetName(), FileName, NULL)) )
                    {
                        nOpened++;
                    }
            }
            while( Dir.GetNext(&FileName) );
        }

        if( Dir.GetFirst(&FileName, wxEmptyString, wxDIR_DIRS) )
        {
            do
            {
                if( FileName.CmpNoCase(wxT("dll")) )
                {
                    nOpened	+= _Open_Directory(SG_File_Make_Path(Dir.GetName(), FileName, NULL));
                }
            }
            while( Dir.GetNext(&FileName) );
        }
    }

    return( nOpened );
}
Ejemplo n.º 3
0
//---------------------------------------------------------
bool CSG_PointCloud::_Save(const CSG_String &File_Name)
{
    CSG_File	Stream;

    SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Save point cloud"), File_Name.c_str()), true);

    CSG_String	sFile_Name = SG_File_Make_Path(NULL, File_Name, SG_T("spc"));

    if( Stream.Open(sFile_Name, SG_FILE_W, true) == false )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("unable to create file."));

        return( false );
    }

    int		i, iBuffer, nPointBytes	= m_nPointBytes - 1;

    Stream.Write((void *)PC_FILE_VERSION, 6);
    Stream.Write(&nPointBytes	, sizeof(int));
    Stream.Write(&m_nFields		, sizeof(int));

    for(i=0; i<m_nFields; i++)
    {
        Stream.Write(&m_Field_Type[i], sizeof(TSG_Data_Type));

        iBuffer	= (int)m_Field_Name[i]->Length();
        if( iBuffer >= 1024 - 1 )	iBuffer	= 1024 - 1;
        Stream.Write(&iBuffer, sizeof(int));
        Stream.Write((void *)m_Field_Name[i]->b_str(), sizeof(char), iBuffer);
    }

    _Set_Shape(m_Shapes_Index);

    for(i=0; i<Get_Count() && SG_UI_Process_Set_Progress(i, Get_Count()); i++)
    {
        Stream.Write(m_Points[i] + 1, nPointBytes);
    }

    Set_Modified(false);

    Set_File_Name(sFile_Name, true);

    Save_MetaData(File_Name);

    Get_Projection().Save(SG_File_Make_Path(NULL, File_Name, SG_T("prj")), SG_PROJ_FMT_WKT);

    SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);

    SG_UI_Process_Set_Ready();

    return( true );
}
Ejemplo n.º 4
0
//---------------------------------------------------------
bool CSG_MetaData::Load(const CSG_String &File, const SG_Char *Extension)
{
	Destroy();

	wxXmlDocument	XML;

	if( SG_File_Exists(SG_File_Make_Path(NULL, File, Extension)) && XML.Load(SG_File_Make_Path(NULL, File, Extension).c_str()) )
	{
		_Load(XML.GetRoot());

		return( true );
	}

	return( false );
}
Ejemplo n.º 5
0
CGridNet::CGridNet(void)
{
	#ifdef _WIN32
		CSG_String UserHomeDir = CSG_String(getenv("USERPROFILE"));
	#else
		CSG_String UserHomeDir = CSG_String(getenv("HOME"));
	#endif

	CSG_String DefaultTempDir = SG_File_Make_Path(UserHomeDir, CSG_String("Saga_GIS_tmp"));

	// INFO
	Set_Name(_TL("Grid Network"));
	Set_Author(SG_T("S. Masoud-Ansari, J. Tunnicliffe, D. Tarboton"));
	Set_Description	(_TW("Creates 3 grids that contain for each grid cell: 1) the longest path, 2) the total path, and 3) the Strahler order number. These values are derived from the network defined by the D8 flow model.\n\nThe longest upslope length is the length of the flow path from the furthest cell that drains to each cell. The total upslope path length is the length of the entire grid network upslope of each grid cell. Lengths are measured between cell centers taking into account cell size and whether the direction is adjacent or diagonal.\n\nStrahler order is defined as follows: A network of flow paths is defined by the D8 Flow Direction grid. Source flow paths have a Strahler order number of one. When two flow paths of different order join the order of the downstream flow path is the order of the highest incoming flow path. When two flow paths of equal order join the downstream flow path order is increased by 1. When more than two flow paths join the downstream flow path order is calculated as the maximum of the highest incoming flow path order or the second highest incoming flow path order + 1. This generalizes the common definition to cases where more than two flow paths join at a point.\n\nWhere the optional mask grid and threshold value are input, the function is evaluated only considering grid cells that lie in the domain with mask grid value greater than or equal to the threshold value. Source (first order) grid cells are taken as those that do not have any other grid cells from inside the domain draining in to them, and only when two of these flow paths join is order propagated according to the ordering rules. Lengths are also only evaluated counting paths within the domain greater than or equal to the threshold.\n\nIf the optional outlet point shapefile is used, only the outlet cells and the cells upslope (by the D8 flow model) of them are in the domain to be evaluated."));

	// GRIDS
	Parameters.Add_Grid(NULL, "FLOWD8_INPUT"	, _TL("Input D8 Flow Direction"), _TL("A grid of D8 flow directions which are defined, for each cell, as the direction of the one of its eight adjacent or diagonal neighbors with the steepest downward slope."), PARAMETER_INPUT);
	Parameters.Add_Grid(NULL, "MASK_INPUT", _TL("Input Mask (Optional)"), _TL("A grid that is used to determine the domain do be analyzed. If the mask grid value >= mask threshold, then the cell will be included in the domain. While this tool does not have an edge contamination flag, if edge contamination analysis is needed, then a mask grid from a function like AreaD8 that does support edge contamination can be used to achieve the same result."), PARAMETER_INPUT_OPTIONAL);
	Parameters.Add_Grid(NULL, "ORDER_OUTPUT", _TL("Output Strahler Network Order"), _TL("A grid giving the Strahler order number for each cell. A network of flow paths is defined by the D8 Flow Direction grid. Source flow paths have a Strahler order number of one. When two flow paths of different order join the order of the downstream flow path is the order of the highest incoming flow path. When two flow paths of equal order join the downstream flow path order is increased by 1. When more than two flow paths join the downstream flow path order is calculated as the maximum of the highest incoming flow path order or the second highest incoming flow path order + 1. This generalizes the common definition to cases where more than two flow paths join at a point."), PARAMETER_OUTPUT);
	Parameters.Add_Grid(NULL, "LONGEST_OUTPUT", _TL("Output Longest Upslope Length"), _TL("A grid that gives the length of the longest upslope D8 flow path terminating at each grid cell. Lengths are measured between cell centers taking into account cell size and whether the direction is adjacent or diagonal."), PARAMETER_OUTPUT);
	Parameters.Add_Grid(NULL, "TOTAL_LENGTH_OUTPUT", _TL("Output Total Upslope Length"), _TL("The total upslope path length is the length of the entire D8 flow grid network upslope of each grid cell. Lengths are measured between cell centers taking into account cell size and whether the direction is adjacent or diagonal."), PARAMETER_OUTPUT);

	// SHAPES
	Parameters.Add_Shapes(NULL, "OUTLET_INPUT"	, _TL("Input Outlet Points (Optional)"), _TL("Point shapes defining the outlets of interest. If this input is used, only the cells upslope of these outlet cells are considered to be within the domain being evaluated."), PARAMETER_INPUT_OPTIONAL);

	//Values
	Parameters.Add_Value(NULL, "NPROC"	, _TL("Number of Processes"), _TL("The number of stripes that the domain will be divided into and the number of MPI parallel processes that will be spawned to evaluate each of the stripes"), PARAMETER_TYPE_Int, SG_Get_Max_Num_Procs_Omp(), 1, true, SG_Get_Max_Num_Procs_Omp(), true);
	Parameters.Add_Value(NULL, "THRESHOLD"	, _TL("Mask Threshold"), _TL("This input parameter is used in the calculation mask grid value >= mask threshold to determine if the grid cell is in the domain to be analyzed."), PARAMETER_TYPE_Int, 0);

	// Other
	Parameters.Add_FilePath(NULL, "TEMP_DIR", _TL("Temp File Directory"), _TL("Directory used for storing temporary files during processing."), NULL, DefaultTempDir, false, true, false); 
	

}
Ejemplo n.º 6
0
//---------------------------------------------------------
bool CWRF_Import::On_Execute(void)
{
	CSG_String		File;

	//-----------------------------------------------------
	File		= Parameters("FILE")	->asString();

	Parameters("GRIDS")->asGridList()->Del_Items();

	//-----------------------------------------------------
	if( !m_Index.Load(SG_File_Make_Path(SG_File_Get_Path(File), SG_T("index"))) )
	{
		Error_Set(_TL("error reading index file"));

		return( false );
	}

	//-----------------------------------------------------
	if( !Load(File) )
	{
		Error_Set(_TL("error loading data file"));

		return( false );
	}

	//-----------------------------------------------------
	return( true );
}
Ejemplo n.º 7
0
//---------------------------------------------------------
CSG_String		SG_File_Get_TmpName(const SG_Char *Prefix, const SG_Char *Directory)
{
	if( !SG_Dir_Exists(Directory) )
	{
		return( wxFileName::CreateTempFileName(Prefix).c_str() );
	}

	return( wxFileName::CreateTempFileName(SG_File_Make_Path(Directory, Prefix).c_str()).c_str() );
}
Ejemplo n.º 8
0
//---------------------------------------------------------
int CSurfer_Export::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
{
	if( pParameter->Cmp_Identifier("GRID") && pParameter->asGrid() )
	{
		CSG_String	Path(SG_File_Get_Path((*pParameters)["FILE"].asString()));

		pParameters->Set_Parameter("FILE", SG_File_Make_Path(Path, pParameter->asGrid()->Get_Name(), "grd"));
	}

	return( CSG_Tool_Grid::On_Parameter_Changed(pParameters, pParameter) );
}
Ejemplo n.º 9
0
//---------------------------------------------------------
Cdodproperror::Cdodproperror(void)
{
	#ifdef _WIN32
		CSG_String UserHomeDir = CSG_String(getenv("USERPROFILE"));
	#else
		CSG_String UserHomeDir = CSG_String(getenv("HOME"));
	#endif
	CSG_String DefaultTempDir = SG_File_Make_Path(UserHomeDir, CSG_String("Saga_GIS_tmp"));

	// Module info
	Set_Name		(_TL("Propogated Error DoD"));
	Set_Author		(SG_T("Sina Masoud-Ansari"));
	Set_Description	(_TW("Calculate a raw DEM and threshold it using propagated error"));

	// GCD setup
	GCDBinDir = SG_File_Make_Path(CSG_String("bin"), CSG_String("GCD"));
	GCDBinDir = SG_File_Get_Path_Absolute(GCDBinDir);
	GCD = SG_File_Make_Path(GCDBinDir, CSG_String("gcd"), CSG_String("exe"));
	GCD_CMD = CSG_String("dodproperror");

	// Grids
	Parameters.Add_Grid(NULL, "NEW_DEM"	, _TL("New DEM"), _TL("New DEM raster"), PARAMETER_INPUT);
	Parameters.Add_Grid(NULL, "OLD_DEM"	, _TL("Old DEM"), _TL("Old DEM raster"), PARAMETER_INPUT);
	Parameters.Add_Grid(NULL, "PROP_ERROR", _TL("Propagated Error"), _TL("Propagated Error"), PARAMETER_INPUT);
	Parameters.Add_Grid(NULL, "RAW_DOD", _TL("Raw DoD"), _TL("Raw DEM of difference"), PARAMETER_OUTPUT);
	Parameters.Add_Grid(NULL, "THRESHOLDED_DOD", _TL("Thresholded DoD"), _TL("Thresholded DEM of difference"), PARAMETER_OUTPUT);

	//Other
	Parameters.Add_FilePath(NULL, "TEMP_DIR", _TL("Temp File Directory"), _TL("Directory used for storing temporary files during processing."), NULL, DefaultTempDir, false, true, false); 

	//GDAL
	GDALDriver = CSG_String("GTiff");
	GDALOptions = CSG_String(""); 
	Get_Projection(Projection);

}
Ejemplo n.º 10
0
CStreamNet::CStreamNet(void)
{

	#ifdef _WIN32
		CSG_String UserHomeDir = CSG_String(getenv("USERPROFILE"));
	#else
		CSG_String UserHomeDir = CSG_String(getenv("HOME"));
	#endif

	CSG_String DefaultTempDir = SG_File_Make_Path(UserHomeDir, CSG_String("Saga_GIS_tmp"));

	// INFO
	Set_Name(_TL("Stream Reach and Watershed"));
	Set_Author(SG_T("S. Masoud-Ansari, J. Tunnicliffe, D. Tarboton"));
	Set_Description	(CSG_String("This tool produces a vector network and shapefile from the stream raster grid. The flow direction grid is used to connect flow paths along the stream raster. The Strahler order of each stream segment is computed. The subwatershed draining to each stream segment (reach) is also delineated and labeled with the value identifier that corresponds to the WSNO (watershed number) attribute in the Stream Reach Shapefile.\n\nThis tool orders the stream network according to the Strahler ordering system. Streams that don't have any other streams draining in to them are order 1. When two stream reaches of different order join the order of the downstream reach is the order of the highest incoming reach. When two reaches of equal order join the downstream reach order is increased by 1. When more than two reaches join the downstream reach order is calculated as the maximum of the highest incoming reach order or the second highest incoming reach order + 1. This generalizes the common definition to cases where more than two reaches join at a point. The network topological connectivity is stored in the Stream Network Tree file, and coordinates and attributes from each grid cell along the network are stored in the Network Coordinates file.\n\nThe stream raster grid is used as the source for the stream network, and the flow direction grid is used to trace connections within the stream network. Elevations and contributing area are used to determine the elevation and contributing area attributes in the network coordinate file. Points in the outlets shapefile are used to logically split stream reaches to facilitate representing watersheds upstream and downstream of monitoring points. The program uses the attribute field \"id\" in the outlets shapefile as identifiers in the Network Tree file. This tool then translates the text file vector network representation in the Network Tree and Coordinates files into a shapefile. Further attributes are also evaluated. The program has an option to delineate a single watershed by representing the entire area draining to the Stream Network as a single value in the output watershed grid."));

	// GRIDS
	Parameters.Add_Grid(NULL, "FEL_INPUT"	, _TL("Input Pit Filled Elevation"), _TL("This input is a grid of elevation values. This is usually the output of the \"Pit Remove\" tool, in which case it is elevations with pits removed. Pits are low elevation areas in digital elevation models (DEMs) that are completely surrounded by higher terrain. They are generally taken to be artifacts that interfere with the processing of flow across DEMs, so are removed by raising their elevation to the point where they just drain. This step is not essential if you have reason to believe that the pits in your DEM are real. Elevation values are used in this function to compute the slope of stream segments. Not removing pits can result in negative (i.e. uphill) stream segment slopes."), PARAMETER_INPUT);
	Parameters.Add_Grid(NULL, "FLOWD8_INPUT"	, _TL("Input D8 Flow Direction"), _TL("This input is a grid of flow directions that are encoded using the D8 method where all flow from a cells goes to a single neighboring cell in the direction of steepest descent."), PARAMETER_INPUT);
	Parameters.Add_Grid(NULL, "AREAD8_INPUT"	, _TL("Input D8 Drainage Area"), _TL("A grid giving the contributing area value in terms of the number of grid cells (or the summation of weights) for each cell taken as its own contribution plus the contribution from upslope neighbors that drain in to it using the D8 algorithm. This is usually the output of the \"D8 Contributing Area\" tool and is used to determine the contributing area attribute in the Network Coordinate file."), PARAMETER_INPUT);
	Parameters.Add_Grid(NULL, "SRC_INPUT"	, _TL("Input Stream Raster"), _TL("An indicator grid indicating streams, by using a grid cell value of 1 on streams and 0 off streams. Several of the \"Stream Network Analysis\" tools produce this type of grid. The Stream Raster Grid is used as the source for the stream network."), PARAMETER_INPUT);

	Parameters.Add_Grid(NULL, "ORD_OUTPUT"	, _TL("Output Stream Order"), _TL("The Stream Order Grid has cells values of streams ordered according to the Strahler order system. The Strahler ordering system defines order 1 streams as stream reaches that don't have any other reaches draining in to them. When two stream reaches of different order join the order of the downstream reach is the order of the highest incoming reach. When two reaches of equal order join the downstream reach order is increased by 1. When more than two reaches join the downstream reach order is calculated as the maximum of the highest incoming reach order or the second highest incoming reach order + 1. This generalizes the common definition to cases where more than two reaches join at a point. This generalizes the common definition to cases where more than two flow paths join at a point."), PARAMETER_OUTPUT);
	Parameters.Add_Grid(NULL, "W_OUTPUT"	, _TL("Output Watershed"), _TL("This output grid identified each reach watershed with a unique ID number, or in the case where the delineate single watershed option was checked, the entire area draining to the stream network is identified with a single ID."), PARAMETER_OUTPUT);

	// SHAPES
	Parameters.Add_Shapes(NULL, "OUTLET_INPUT"	, _TL("Input Outlet Points (Optional)"), CSG_String("Point shapes defining points of interest. If this is used, the tool will only deliiniate the stream network upstream of these outlets. Additionally, the points are used to logically split stream reaches to facilitate representing watersheds upstream and downstream of monitoring points. Points must have an integer attribute field \"id\" as it is for identifiers in the Network Tree file."), PARAMETER_INPUT_OPTIONAL);
	Parameters.Add_Shapes(NULL, "NET_OUTPUT"	, _TL("Output Stream Reach"), _TL("This output is a polyline shapefile giving the links in a stream network. The columns in the attribute table are:\n\nLINKNO- Link Number. A unique number associated with each link (segment of channel between junctions). This is arbitrary and will vary depending on number of processes used.\n\nDSLINKNO - Link Number of the downstream link. -1 indicates that this does not exist.\n\nUSLINKNO1 - Link Number of first upstream link. (-1 indicates no link upstream, i.e. for a source link)\n\nUSLINKNO2 - Link Number of second upstream link. (-1 indicates no second link upstream, i.e. for a source link or an internal monitoring point where the reach is logically split but the network does not bifurcate.)\n\nDSNODEID - Node identifier for node at downstream end of stream reach. This identifier corresponds to the \"id\" attribute from the Outlets shapefile used to designate nodes.\n\nOrder - Strahler Stream Order\n\nLength - Length of the link. The units are the horizontal map units of the underlying DEM grid.\n\nMagnitude - Shreve Magnitude of the link. This is the total number of sources upstream\n\nDS_Cont_Ar - Drainage area at the downstream end of the link. Generally this is one grid cell upstream of the downstream end because the drainage area at the downstream end grid cell includes the area of the stream being joined.\n\nDrop - Drop in elevation from the start to the end of the link\n\nSlope - Average slope of the link (computed as drop/length)\n\nStraight_L - Straight line distance from the start to the end of the link\n\nUS_Cont_Ar - Drainage area at the upstream end of the link\n\nWSNO - Watershed number. Cross reference to the *w.shp and *w grid files giving the identification number of the watershed draining directly to the link.\n\nDOUT_END - Distance to the eventual outlet (i.e. the most downstream point in the stream network) from the downstream end of the link.\n\nDOUT_START - Distance to the eventual outlet from the upstream end of the link\n\nDOUT_MID - Distance to the eventual outlet from the midpoint of the link"), PARAMETER_OUTPUT);
	
	// TABLES
	Parameters.Add_Table(NULL, "TREE_OUTPUT", _TL("Output Network Connectivity Tree"), _TL("This output is a text file that details the network topological connectivity is stored in the Stream Network Tree file. Columns are as follows:\n\nLink Number (Arbitrary - will vary depending on number of processes used)\n\nStart Point Number in Network coordinates (*coord.dat) file (Indexed from 0)\n\nEnd Point Number in Network coordinates (*coord.dat) file (Indexed from 0)\n\nNext (Downstream) Link Number. Points to Link Number. -1 indicates no links downstream, i.e. a terminal link\n\nFirst Previous (Upstream) Link Number. Points to Link Number. -1 indicates no upstream links.\n\nSecond Previous (Upstream) Link Numbers. Points to Link Number. -1 indicates no upstream links. Where only one previous link is -1, it indicates an internal monitoring point where the reach is logically split, but the network does not bifurcate.\n\nStrahler Order of Link\n\nMonitoring point identifier at downstream end of link. -1 indicates downstream end is not a monitoring point.\n\nNetwork magnitude of the link, calculated as the number of upstream sources (following Shreve)."), PARAMETER_OUTPUT); 
	Parameters.Add_Table(NULL, "COORD_OUTPUT", _TL("Output Network Coordinates"), _TL("This output is a text file that contains the coordinates and attributes of points along the stream network. Columns are as follows:\n\nX coordinate\n\nY Coordinate\n\nDistance along channels to the downstream end of a terminal link\n\nElevation\n\nContributing area"), PARAMETER_OUTPUT); 

	// Booleans
	Parameters.Add_Value(
		NULL, "SW"		, _TL("Delineate Single Watershed"),
		_TL("This option causes the tool to delineate a single watershed by representing the entire area draining to the Stream Network as a single value in the output watershed grid. Otherwise a seperate watershed is delineated for each stream reach."),
		PARAMETER_TYPE_Bool, false
	);

	// VALUES
	Parameters.Add_Value(NULL, "NPROC"	, _TL("Number of Processes"), _TL("The number of stripes that the domain will be divided into and the number of MPI parallel processes that will be spawned to evaluate each of the stripes"), PARAMETER_TYPE_Int, SG_Get_Max_Num_Procs_Omp(), 1, true, SG_Get_Max_Num_Procs_Omp(), true);

	// Other
	Parameters.Add_FilePath(NULL, "TEMP_DIR", _TL("Temp File Directory"), _TL("Directory used for storing temporary files during processing."), NULL, DefaultTempDir, false, true, false); 
	

}
Ejemplo n.º 11
0
//---------------------------------------------------------
bool CSG_MetaData::Save(const CSG_String &File, const SG_Char *Extension) const
{
	wxXmlDocument	XML;

	wxXmlNode	*pRoot	= new wxXmlNode(NULL, wxXML_ELEMENT_NODE, Get_Name().c_str());

	XML.SetRoot(pRoot);

	_Save(pRoot);

	if( XML.Save(SG_File_Make_Path(NULL, File, Extension).c_str()) )
	{
		return( true );
	}

	return( false );
}
Ejemplo n.º 12
0
//---------------------------------------------------------
bool CSG_Translator::Create(const CSG_String &File_Name, bool bSetExtension, int iText, int iTranslation, bool bCmpNoCase)
{
	CSG_Table	Translations;
	CSG_String	fName(bSetExtension ? SG_File_Make_Path(NULL, File_Name, SG_T("lng")) : File_Name);

	SG_UI_Msg_Lock(true);

	Destroy();

	if( SG_File_Exists(fName) && Translations.Create(fName) )
	{
		Create(&Translations, iText, iTranslation, bCmpNoCase);
	}

	SG_UI_Msg_Lock(false);

	return( m_nTranslations > 0 );
}
Ejemplo n.º 13
0
//---------------------------------------------------------
bool CSG_Grid::_Save_Native(const CSG_String &File_Name, int xA, int yA, int xN, int yN, bool bBinary)
{
	bool		bResult		= false;
	CSG_File	Stream;

	if(	Stream.Open(File_Name, SG_FILE_W, false) )
	{
		//-------------------------------------------------
		// Header...

		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_NAME			], Get_Name() );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_DESCRIPTION	], Get_Description() );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_UNITNAME		], Get_Unit() );
		Stream.Printf(SG_T("%s\t= %d\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_DATAFILE_OFFSET], 0 );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_DATAFORMAT		], bBinary ? gSG_Data_Type_Identifier[Get_Type()] : SG_T("ASCII") );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_BYTEORDER_BIG	], GRID_FILE_KEY_FALSE );
		Stream.Printf(SG_T("%s\t= %.10f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_POSITION_XMIN	], Get_XMin() + Get_Cellsize() * xA );
		Stream.Printf(SG_T("%s\t= %.10f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_POSITION_YMIN	], Get_YMin() + Get_Cellsize() * yA );
		Stream.Printf(SG_T("%s\t= %d\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_CELLCOUNT_X	], xN );
		Stream.Printf(SG_T("%s\t= %d\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_CELLCOUNT_Y	], yN );
		Stream.Printf(SG_T("%s\t= %.10f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_CELLSIZE		], Get_Cellsize() );
		Stream.Printf(SG_T("%s\t= %f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_Z_FACTOR		], m_zFactor );
		Stream.Printf(SG_T("%s\t= %f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_NODATA_VALUE	], Get_NoData_Value() );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_TOPTOBOTTOM	], GRID_FILE_KEY_FALSE );


		//-------------------------------------------------
		// Data...

		if( Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T("sdat")), SG_FILE_W, true) )
		{
			if( bBinary )
			{
				bResult		= _Save_Binary	(Stream, xA, yA, xN, yN, Get_Type(), false, false);
			}
			else
			{
				bResult		= _Save_ASCII	(Stream, xA, yA, xN, yN);
			}
		}
	}

	return( bResult );
}
//---------------------------------------------------------
bool CWKSP_Module_Manager::Initialise(void)
{
	CONFIG_Read("/MODULES", &m_Parameters);

	CONFIG_Do_Save(m_Parameters("SAVE_CONFIG")->asBool());

	g_pSAGA->Process_Set_Frequency(m_Parameters("PROCESS_UPDATE")->asInt());

#ifdef _OPENMP
	SG_OMP_Set_Max_Num_Threads(m_Parameters("OMP_THREADS_MAX")->asInt());
#endif

	//-----------------------------------------------------
	wxString	Library;

	for(int i=0; CONFIG_Read(CFG_LIBS, wxString::Format(CFG_LIBF, i), Library); i++)
	{
		if( !wxFileExists(Library) )
		{
			wxFileName	fn(Library);	fn.MakeAbsolute(g_pSAGA->Get_App_Path());

			Library	= fn.GetFullPath();
		}

		SG_Get_Module_Library_Manager().Add_Library(Library);
	}

	if( SG_Get_Module_Library_Manager().Get_Count() == 0 )
	{
#if defined(_SAGA_LINUX)
	if( (SG_Get_Module_Library_Manager().Add_Directory(CSG_String(MODULE_LIBRARY_PATH), false)
	   + SG_Get_Module_Library_Manager().Add_Directory(SG_File_Make_Path(CSG_String(SHARE_PATH), SG_T("toolchains")), false)) == 0 )
#endif
		SG_Get_Module_Library_Manager().Add_Directory(g_pSAGA->Get_App_Path(), true);
	}

	_Update(false);

	return( true );
}
Ejemplo n.º 15
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;
}
Ejemplo n.º 16
0
//---------------------------------------------------------
bool	SG_FTP_Download(const CSG_String &Target_Directory, const CSG_String &Source, const SG_Char *Username, const SG_Char *Password, unsigned short Port, bool bBinary, bool bVerbose)
{
	CSG_String	_Source(Source); _Source.Trim();

	if( _Source.Find("ftp://") == 0 )
	{
		_Source	= _Source.Right(_Source.Length() - CSG_String("ftp://").Length());
	}

	CSG_String	ftpHost	= _Source.BeforeFirst('/');
	CSG_String	ftpDir	= _Source.AfterFirst ('/').BeforeLast('/'); // ftpDir.Prepend("/");
	CSG_String	ftpFile	= _Source.AfterLast  ('/');

	//-----------------------------------------------------
	wxFTP ftp;

	if( Username && *Username )	{	ftp.SetUser    (Username);	}
	if( Password && *Password )	{	ftp.SetPassword(Password);	}

	if( !ftp.Connect(ftpHost.c_str(), Port) )
	{
		if( bVerbose )
		{
			SG_UI_Msg_Add_Error(_TL("Couldn't connect"));
		}

		return( false );
	}

	//-----------------------------------------------------
	if( !ftpDir.is_Empty() && !ftp.ChDir(ftpDir.c_str()) )
	{
		if( bVerbose )
		{
			SG_UI_Msg_Add_Error(CSG_String::Format("%s [%s]", _TL("Couldn't change to directory"), ftpDir.c_str()));
		}

		return( false );
	}

	if( ftp.GetFileSize(ftpFile.c_str()) == -1 )
	{
		if( bVerbose )
		{
			SG_UI_Msg_Add_Error(CSG_String::Format("%s [%s]", _TL("Couldn't get the file size"), ftpFile.c_str()));
		}
	}

	//-----------------------------------------------------
	wxInputStream	*pStream	= ftp.GetInputStream(ftpFile.c_str());

	if( !pStream )
	{
		if( bVerbose )
		{
			SG_UI_Msg_Add_Error(CSG_String::Format("%s [%s]", _TL("Couldn't get the file"), ftpFile.c_str()));
		}

		return( false );
	}

	//-----------------------------------------------------
	wxFileOutputStream	*pFile	= new wxFileOutputStream(SG_File_Make_Path(Target_Directory, ftpFile).c_str());

	if( !pFile )
	{
		if( bVerbose )
		{
			SG_UI_Msg_Add_Error(CSG_String::Format("%s [%s]", _TL("Couldn't create target file"), SG_File_Make_Path(Target_Directory, ftpFile).c_str()));
		}

		delete(pStream);

		return( false );
	}

	//-----------------------------------------------------
	pFile->Write(*pStream);

	delete(pFile);
	delete(pStream);

	return( true );
}
Ejemplo n.º 17
0
bool CSG_Grid::Save(const CSG_String &File_Name, int Format, int xA, int yA, int xN, int yN)
{
	bool		bResult;
	CSG_String	sFile_Name	= SG_File_Make_Path(NULL, File_Name, SG_T("sgrd"));

	//-----------------------------------------------------
	if( xA	< 0 || xA >= Get_NX() - 1 )
	{
		xA	= 0;
	}

	if( yA	< 0 || yA >= Get_NY() - 1 )
	{
		yA	= 0;
	}

	if( xN	> Get_NX() - xA )
	{
		xN	= Get_NX() - xA;
	}

	if( yN	> Get_NY() - yA )
	{
		yN	= Get_NY() - yA;
	}

	//-----------------------------------------------------
	SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), LNG("[MSG] Save grid"), File_Name.c_str()), true);

	switch( Format )
	{
	default:
	case GRID_FILE_FORMAT_Binary:	// 1 - Binary
		bResult	= _Save_Native(sFile_Name, xA, yA, xN, yN, true);
		break;

	case GRID_FILE_FORMAT_ASCII:	// 2 - ASCII
		bResult	= _Save_Native(sFile_Name, xA, yA, xN, yN, false);
		break;
	}

	//-----------------------------------------------------
	if( bResult )
	{
		Set_Modified(false);

		Set_File_Name(sFile_Name);

		Save_MetaData(File_Name);

		SG_UI_Msg_Add(LNG("[MSG] okay"), false, SG_UI_MSG_STYLE_SUCCESS);
	}
	else
	{
		SG_UI_Msg_Add(LNG("[MSG] failed"), false, SG_UI_MSG_STYLE_FAILURE);

		SG_UI_Msg_Add_Error(LNG("[ERR] Grid file could not be saved."));
	}

	return( bResult );
}
Ejemplo n.º 18
0
bool CGPX2SHP::On_Execute(void) {

    CSG_String sCmd;
    CSG_String sFile = Parameters("FILE")->asString();
    CSG_String sBasePath = Parameters("BASEPATH")->asString();
    CSG_String sShapefile;
    bool bWaypoints = Parameters("WAYPOINTS")->asBool();
    bool bTrackpoints = Parameters("TRACKPOINTS")->asBool();
    bool bRoutes = Parameters("ROUTES")->asBool();
    bool bAdd = Parameters("ADD")->asBool();
    CSG_Shapes *pShapes;

    sCmd = sBasePath + SG_T("\\gpx2shp ");

    if (bWaypoints) {
        sCmd += SG_T("-w ");
    }//if
    if (bTrackpoints) {
        sCmd += SG_T("-t ");
    }//if
    if (bRoutes) {
        sCmd += SG_T("-r ");
    }//if

    sCmd += sFile;

    system(sCmd.b_str());

    if( bAdd )
    {
        CSG_String	sDir(SG_File_Get_Path(sFile)), sName(SG_File_Get_Name(sFile, false));

        //-------------------------------------------------
        sFile	= SG_File_Make_Path(sDir, sName + SG_T("_wpt"), SG_T("shp"));
        pShapes	= SG_Create_Shapes(sFile);

        if( pShapes->is_Valid() )
            DataObject_Add(pShapes, false);
        else
            delete(pShapes);

        //-------------------------------------------------
        sFile	= SG_File_Make_Path(sDir, sName + SG_T("_trk"), SG_T("shp"));
        pShapes	= SG_Create_Shapes(sFile);

        if( pShapes->is_Valid() )
            DataObject_Add(pShapes, false);
        else
            delete(pShapes);

        //-------------------------------------------------
        sFile	= SG_File_Make_Path(sDir, sName + SG_T("_rte"), SG_T("shp"));
        pShapes	= SG_Create_Shapes(sFile);

        if( pShapes->is_Valid() )
            DataObject_Add(pShapes, false);
        else
            delete(pShapes);
    }//if

    return true;

}//method
Ejemplo n.º 19
0
//---------------------------------------------------------
bool CSG_PointCloud::_Load(const CSG_String &File_Name)
{
    TSG_Data_Type	Type;

    char		ID[6];
    int			i, iBuffer, nPointBytes, nFields;
    char		Name[1024];
    CSG_File	Stream;

    SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Load point cloud"), File_Name.c_str()), true);

    //-----------------------------------------------------
    if( !Stream.Open(File_Name, SG_FILE_R, true) )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("file could not be opened."));

        return( false );
    }

    if( !Stream.Read(ID, 6) || strncmp(ID, PC_FILE_VERSION, 5) != 0 )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

    if( !Stream.Read(&nPointBytes, sizeof(int)) || nPointBytes < (int)(3 * sizeof(float)) )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

    if( !Stream.Read(&nFields, sizeof(int)) || nFields < 3 )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

    //-----------------------------------------------------
    Destroy();

    for(i=0; i<nFields; i++)
    {
        if( !Stream.Read(&Type		, sizeof(TSG_Data_Type))
                ||	!Stream.Read(&iBuffer	, sizeof(int)) || !(iBuffer > 0 && iBuffer < 1024)
                ||	!Stream.Read(Name		, iBuffer) )
        {
            SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
            SG_UI_Msg_Add_Error(_TL("incompatible file."));

            return( false );
        }

        if( ID[5] == '0' )	// Data Type Definition changed!!!
        {
            switch( Type )
            {
            default:
                Type	= SG_DATATYPE_Undefined;
                break;
            case 1:
                Type	= SG_DATATYPE_Char;
                break;
            case 2:
                Type	= SG_DATATYPE_Short;
                break;
            case 3:
                Type	= SG_DATATYPE_Int;
                break;
            case 4:
                Type	= SG_DATATYPE_Long;
                break;
            case 5:
                Type	= SG_DATATYPE_Float;
                break;
            case 6:
                Type	= SG_DATATYPE_Double;
                break;
            }
        }

        Name[iBuffer]	= '\0';

        if( !_Add_Field(CSG_String((const char *)Name), Type) )
        {
            SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
            SG_UI_Msg_Add_Error(_TL("incompatible file."));

            return( false );
        }
    }

    if( m_nPointBytes != nPointBytes + 1 )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

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

    while( _Inc_Array() && Stream.Read(m_Cursor + 1, nPointBytes) && SG_UI_Process_Set_Progress((double)Stream.Tell(), (double)fLength) )
    {}

    _Dec_Array();

    Set_File_Name(File_Name, true);

    Load_MetaData(File_Name);

    if( 0 > Get_Count() )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("no records in file."));

        return( false );
    }

    //-----------------------------------------------------
    SG_UI_Process_Set_Ready();

    Get_Projection().Load(SG_File_Make_Path(NULL, File_Name, SG_T("prj")), SG_PROJ_FMT_WKT);

    SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);

    return( true );
}
Ejemplo n.º 20
0
//---------------------------------------------------------
bool CWRF_Export::On_Execute(void)
{
	CSG_String				Directory;
	CSG_Parameter_Grid_List	*pGrids;

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

	//-----------------------------------------------------
	m_Index.Reset();

	switch( Parameters("DATATYPE")->asInt() )
	{
	case 0:	default:	m_Index.m_WORDSIZE	= 1;	m_Index.m_SIGNED	= false;	break;
	case 1:				m_Index.m_WORDSIZE	= 1;	m_Index.m_SIGNED	=  true;	break;
	case 2:				m_Index.m_WORDSIZE	= 2;	m_Index.m_SIGNED	= false;	break;
	case 3:				m_Index.m_WORDSIZE	= 2;	m_Index.m_SIGNED	=  true;	break;
	case 4:				m_Index.m_WORDSIZE	= 4;	m_Index.m_SIGNED	= false;	break;
	case 5:				m_Index.m_WORDSIZE	= 4;	m_Index.m_SIGNED	=  true;	break;
	}

	m_Index.m_TYPE			= Parameters("TYPE")		->asInt();
	m_Index.m_MISSING_VALUE	= Parameters("MISSING")		->asDouble();
	m_Index.m_SCALE_FACTOR	= Parameters("SCALE")		->asDouble();
	m_Index.m_UNITS			= Parameters("UNITS")		->asString();
	m_Index.m_DESCRIPTION	= Parameters("DESCRIPTION")	->asString();
	m_Index.m_MMINLU		= Parameters("MMINLU")		->asString();

	m_Index.m_TILE_BDR		= Parameters("TILE_BDR")	->asInt();
	m_Index.m_TILE_X		= Get_NX() - 2 * m_Index.m_TILE_BDR;
	m_Index.m_TILE_Y		= Get_NY() - 2 * m_Index.m_TILE_BDR;
	m_Index.m_TILE_Z		= pGrids->Get_Count();
	m_Index.m_TILE_Z_START	= 1;
	m_Index.m_TILE_Z_END	= pGrids->Get_Count();
	m_Index.m_DX			= Get_Cellsize();
	m_Index.m_DY			= Get_Cellsize();
	m_Index.m_ENDIAN		= VAL_ENDIAN_LITTLE;
	m_Index.m_ROW_ORDER		= VAL_BOTTOM_TOP;

	m_Index.m_PROJECTION	= Parameters("PROJECTION")	->asString();
	m_Index.m_STDLON		= Parameters("SDTLON")		->asDouble();
	m_Index.m_TRUELAT1		= Parameters("TRUELAT1")	->asDouble();
	m_Index.m_TRUELAT2		= Parameters("TRUELAT2")	->asDouble();

	m_Index.m_KNOWN_LAT		= - 90.0 + 0.5 * m_Index.m_DY;
	m_Index.m_KNOWN_LON		= -180.0 + 0.5 * m_Index.m_DX;

//	m_Index.m_KNOWN_X		= Parameters("KNOWN_X")		->asDouble();
//	m_Index.m_KNOWN_Y		= Parameters("KNOWN_Y")		->asDouble();
//	m_Index.m_KNOWN_LAT		= Parameters("KNOWN_LAT")	->asDouble();
//	m_Index.m_KNOWN_LON		= Parameters("KNOWN_LON")	->asDouble();

	if( m_Index.m_TILE_Z == 1 )
	{
		m_Index.m_CATEGORY_MIN	= m_Index.m_TYPE == VAL_CATEGORICAL ? (int)pGrids->asGrid(0)->Get_ZMin() : 0;
		m_Index.m_CATEGORY_MAX	= m_Index.m_TYPE == VAL_CATEGORICAL ? (int)pGrids->asGrid(0)->Get_ZMax() : 0;
	}
	else
	{
		m_Index.m_CATEGORY_MIN	= m_Index.m_TILE_Z_START;
		m_Index.m_CATEGORY_MAX	= m_Index.m_TILE_Z_END;
	}

	m_Index.m_ISWATER		= Parameters("ISWATER")		->asInt();
	m_Index.m_ISLAKE		= Parameters("ISLAKE")		->asInt();
	m_Index.m_ISICE			= Parameters("ISICE")		->asInt();
	m_Index.m_ISURBAN		= Parameters("ISURBAN")		->asInt();
	m_Index.m_ISOILWATER	= Parameters("ISOILWATER")	->asInt();

	//-----------------------------------------------------
	if( !m_Index.Save(SG_File_Make_Path(Directory, SG_T("index"))) )
	{
		Error_Set(_TL("error saving index file"));

		return( false );
	}

	//-----------------------------------------------------
	if( !Save(Directory, pGrids) )
	{
		Error_Set(_TL("error saving data file"));

		return( false );
	}

	//-----------------------------------------------------
	return( true );
}
Ejemplo n.º 21
0
//---------------------------------------------------------
bool CGrid_Export::On_Execute(void)
{
	//-----------------------------------------------------
	int			y, iy, Method;
	double		dTrans;
	CSG_Grid	*pGrid, *pShade, Grid, Shade;

	//-----------------------------------------------------
	pGrid		= Parameters("GRID"			)->asGrid();
	pShade		= Parameters("SHADE"		)->asGrid();
	Method		= Parameters("COLOURING"	)->asInt ();
	dTrans		= Parameters("SHADE_TRANS"	)->asDouble() / 100.0;

	if( !pGrid )
	{
		return( false );
	}

	//-----------------------------------------------------
	if( Method == 5 )	// same as in graphical user interface
	{
		if( !SG_UI_DataObject_asImage(pGrid, &Grid) )
		{
			Error_Set("could not retrieve colour coding from graphical user interface.");

			return( false );
		}
	}
	else
	{
		double		zMin, zScale;
		CSG_Colors	Colors;
		CSG_Table	LUT;

		if( SG_UI_Get_Window_Main() )
		{
			Colors.Assign(Parameters("COL_PALETTE")->asColors());
		}
		else
		{
			Colors.Set_Palette(
				Parameters("COL_PALETTE")->asInt (),
				Parameters("COL_REVERT" )->asBool(),
				Parameters("COL_COUNT"  )->asInt ()
			);
		}

		switch( Method )
		{
		case 0:	// stretch to grid's standard deviation
			zMin	= pGrid->Get_Mean() -  Parameters("STDDEV")->asDouble() * pGrid->Get_StdDev();
			zScale	= Colors.Get_Count() / (2 * Parameters("STDDEV")->asDouble() * pGrid->Get_StdDev());
			break;

		case 1:	// stretch to grid's value range
			zMin	= pGrid->Get_ZMin();
			zScale	= Colors.Get_Count() / pGrid->Get_ZRange();
			break;

		case 2:	// stretch to specified value range
			zMin	= Parameters("STRETCH")->asRange()->Get_LoVal();
			if( zMin >= (zScale = Parameters("STRETCH")->asRange()->Get_HiVal()) )
			{
				Error_Set(_TL("invalid user specified value range."));

				return( false );
			}
			zScale	= Colors.Get_Count() / (zScale - zMin);
			break;

		case 3:	// lookup table
			if( !Parameters("LUT")->asTable() || Parameters("LUT")->asTable()->Get_Field_Count() < 5 )
			{
				Error_Set(_TL("invalid lookup table."));

				return( false );
			}

			LUT.Create(*Parameters("LUT")->asTable());
			break;

		case 4:	// rgb coded values
			break;
		}

		//-------------------------------------------------
		Grid.Create(*Get_System(), SG_DATATYPE_Int);

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

				if( Method == 3 )	// lookup table
				{
					int	i, iColor	= -1;

					for(i=0; iColor<0 && i<LUT.Get_Count(); i++)
					{
						if( z == LUT[i][3] )
						{
							Grid.Set_Value(x, iy, LUT[iColor = i].asInt(0));
						}
					}

					for(i=0; iColor<0 && i<LUT.Get_Count(); i++)
					{
						if( z >= LUT[i][3] && z <= LUT[i][4] )
						{
							Grid.Set_Value(x, iy, LUT[iColor = i].asInt(0));
						}
					}

					if( iColor < 0 )
					{
						Grid.Set_NoData(x, iy);
					}
				}
				else if( pGrid->is_NoData(x, y) )
				{
					Grid.Set_NoData(x, iy);
				}
				else if( Method == 4 )	// rgb coded values
				{
					Grid.Set_Value(x, iy, z);
				}
				else
				{
					int	i	= (int)(zScale * (z - zMin));

					Grid.Set_Value(x, iy, Colors[i < 0 ? 0 : i >= Colors.Get_Count() ? Colors.Get_Count() - 1 : i]);
				}
			}
		}
	}

	//-----------------------------------------------------
	if( !pShade || pShade->Get_ZRange() <= 0.0 )
	{
		pShade	= NULL;
	}
	else
	{
		double	dMinBright, dMaxBright;

		dMinBright	= Parameters("SHADE_BRIGHT")->asRange()->Get_LoVal() / 100.0;
		dMaxBright	= Parameters("SHADE_BRIGHT")->asRange()->Get_HiVal() / 100.0;

		if( dMinBright >= dMaxBright )
		{
			SG_UI_Msg_Add_Error(_TL("Minimum shade brightness must be lower than maximum shade brightness!"));

			return( false );
		}

		int			nColors	= 100;
		CSG_Colors	Colors(nColors, SG_COLORS_BLACK_WHITE, true);

	    //-------------------------------------------------
		Shade.Create(*Get_System(), SG_DATATYPE_Int);

		for(y=0, iy=Get_NY()-1; y<Get_NY() && Set_Progress(y); y++, iy--)
		{
			#pragma omp parallel for
			for(int x=0; x<Get_NX(); x++)
			{
				if( pShade->is_NoData(x, y) )
				{
					Shade.Set_NoData(x, iy);
				}
				else
				{
					Shade.Set_Value (x, iy, Colors[(int)(nColors * (dMaxBright - dMinBright) * (pShade->asDouble(x, y) - pShade->Get_ZMin()) / pShade->Get_ZRange() + dMinBright)]);
				}
			}
		}
	}

	//-----------------------------------------------------
	wxImage	Image(Get_NX(), Get_NY());

	if( Grid.Get_NoData_Count() > 0 )
	{
		Image.SetAlpha();
	}

	for(y=0; y<Get_NY() && Set_Progress(y); y++)
	{
		#pragma omp parallel for
		for(int x=0; x<Get_NX(); x++)
		{
			if( Grid.is_NoData(x, y) || (pShade != NULL && Shade.is_NoData(x, y)) )
			{
				if( Image.HasAlpha() )
				{
					Image.SetAlpha(x, y, wxIMAGE_ALPHA_TRANSPARENT);
				}

				Image.SetRGB(x, y, 255, 255, 255);
			}
			else
			{
				if( Image.HasAlpha() )
				{
					Image.SetAlpha(x, y, wxIMAGE_ALPHA_OPAQUE);
				}

				int	r, g, b, c	= Grid.asInt(x, y);

				r	= SG_GET_R(c);
				g	= SG_GET_G(c);
				b	= SG_GET_B(c);

				if( pShade )
				{
					c	= Shade.asInt(x, y);

					r	= dTrans * r + SG_GET_R(c) * (1.0 - dTrans);
					g	= dTrans * g + SG_GET_G(c) * (1.0 - dTrans);
					b	= dTrans * b + SG_GET_B(c) * (1.0 - dTrans);
				}

				Image.SetRGB(x, y, r, g, b);
			}
		}
	}

	//-------------------------------------------------
	CSG_String	fName(Parameters("FILE")->asString());

	if( !SG_File_Cmp_Extension(fName, SG_T("bmp"))
	&&  !SG_File_Cmp_Extension(fName, SG_T("jpg"))
	&&  !SG_File_Cmp_Extension(fName, SG_T("pcx"))
	&&  !SG_File_Cmp_Extension(fName, SG_T("png"))
	&&  !SG_File_Cmp_Extension(fName, SG_T("tif")) )
	{
		fName	= SG_File_Make_Path(NULL, fName, SG_T("png"));

		Parameters("FILE")->Set_Value(fName);
	}

	//-----------------------------------------------------
	wxImageHandler	*pImgHandler = NULL;

	if( !SG_UI_Get_Window_Main() )
	{
		if(      SG_File_Cmp_Extension(fName, SG_T("jpg")) )
			pImgHandler = new wxJPEGHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("pcx")) )
			pImgHandler = new wxPCXHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("tif")) )
			pImgHandler = new wxTIFFHandler;
#ifdef _SAGA_MSW
		else if( SG_File_Cmp_Extension(fName, SG_T("bmp")) )
			pImgHandler = new wxBMPHandler;
#endif
		else // if( SG_File_Cmp_Extension(fName, SG_T("png")) )
			pImgHandler = new wxPNGHandler;

		wxImage::AddHandler(pImgHandler);
	}

	if( !Image.SaveFile(fName.c_str()) )
	{
		Error_Set(CSG_String::Format(SG_T("%s [%s]"), _TL("could not save image file"), fName.c_str()));

		return( false );
	}

	pGrid->Get_Projection().Save(SG_File_Make_Path(NULL, fName, SG_T("prj")), SG_PROJ_FMT_WKT);

	//-----------------------------------------------------
	CSG_File	Stream;

	if(      SG_File_Cmp_Extension(fName, SG_T("bmp")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("bpw")), SG_FILE_W, false);
	else if( SG_File_Cmp_Extension(fName, SG_T("jpg")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("jgw")), SG_FILE_W, false);
	else if( SG_File_Cmp_Extension(fName, SG_T("pcx")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("pxw")), SG_FILE_W, false);
	else if( SG_File_Cmp_Extension(fName, SG_T("png")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("pgw")), SG_FILE_W, false);
	else if( SG_File_Cmp_Extension(fName, SG_T("tif")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("tfw")), SG_FILE_W, false);

	if( Stream.is_Open() )
	{
		Stream.Printf(SG_T("%.10f\n%f\n%f\n%.10f\n%.10f\n%.10f\n"),
			 pGrid->Get_Cellsize(),
			 0.0, 0.0,
			-pGrid->Get_Cellsize(),
			 pGrid->Get_XMin(),
			 pGrid->Get_YMax()
		);
	}

	//-----------------------------------------------------
	if( Parameters("FILE_KML")->asBool() )
	{
		CSG_MetaData	KML;	KML.Set_Name("kml");	KML.Add_Property("xmlns", "http://www.opengis.net/kml/2.2");

	//	CSG_MetaData	*pFolder	= KML.Add_Child("Folder");
	//	pFolder->Add_Child("name"       , "Raster exported from SAGA");
	//	pFolder->Add_Child("description", "System for Automated Geoscientific Analyses - www.saga-gis.org");
	//	CSG_MetaData	*pOverlay	= pFolder->Add_Child("GroundOverlay");

		CSG_MetaData	*pOverlay	= KML.Add_Child("GroundOverlay");
		pOverlay->Add_Child("name"       , pGrid->Get_Name());
		pOverlay->Add_Child("description", pGrid->Get_Description());
		pOverlay->Add_Child("Icon"       )->Add_Child("href", SG_File_Get_Name(fName, true));
		pOverlay->Add_Child("LatLonBox"  );
		pOverlay->Get_Child("LatLonBox"  )->Add_Child("north", pGrid->Get_YMax());
		pOverlay->Get_Child("LatLonBox"  )->Add_Child("south", pGrid->Get_YMin());
		pOverlay->Get_Child("LatLonBox"  )->Add_Child("east" , pGrid->Get_XMax());
		pOverlay->Get_Child("LatLonBox"  )->Add_Child("west" , pGrid->Get_XMin());

		KML.Save(fName, SG_T("kml"));
	}

	//-----------------------------------------------------
	if( !SG_UI_Get_Window_Main() && pImgHandler != NULL)
	{
		wxImage::RemoveHandler(pImgHandler->GetName());
	}

	//-----------------------------------------------------
	return( true );
}
Ejemplo n.º 22
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 );
}
Ejemplo n.º 23
0
//---------------------------------------------------------
bool CWRF_Export::Save(const CSG_String &Directory, CSG_Parameter_Grid_List *pGrids)
{
	//-----------------------------------------------------
	// 00001-00600.00001-00600
	// 01234567890123456789012

	int	xOffset	= m_Index.m_TILE_BDR + (int)(0.5 + (Get_XMin() - m_Index.m_KNOWN_LON) / Get_Cellsize());
	int	yOffset	= m_Index.m_TILE_BDR + (int)(0.5 + (Get_YMin() - m_Index.m_KNOWN_LAT) / Get_Cellsize());

	CSG_String	Name	= SG_File_Get_Name(Directory, true);

	Name.Printf(SG_T("%05d-%05d.%05d-%05d"), xOffset + 1, xOffset + m_Index.m_TILE_X, yOffset + 1, yOffset + m_Index.m_TILE_Y);

	//-----------------------------------------------------
	CSG_File	Stream;

	if( !Stream.Open(SG_File_Make_Path(Directory, Name), SG_FILE_W) )
	{
		Error_Set(_TL("data file could not be openend"));

		return( false );
	}

	//-----------------------------------------------------
	char	*pLine, *pValue;
	int		x, y, nBytes_Line;

	nBytes_Line	= Get_NX() * m_Index.m_WORDSIZE;
	pLine		= (char *)SG_Malloc(nBytes_Line);

	//-----------------------------------------------------
	for(int z=0; z<pGrids->Get_Count() && Process_Get_Okay(); z++)
	{
		CSG_Grid	*pGrid	= pGrids->asGrid(z);

		//-------------------------------------------------
		for(y=0; y<pGrid->Get_NY() && !Stream.is_EOF() && Set_Progress(y, pGrid->Get_NY()); y++)
		{
			int	yy	= m_Index.m_ROW_ORDER == VAL_TOP_BOTTOM ? pGrid->Get_NY() - 1 - y : y;

			for(x=0, pValue=pLine; x<pGrid->Get_NX(); x++, pValue+=m_Index.m_WORDSIZE)
			{
				if( m_Index.m_SIGNED )
				{
					switch( m_Index.m_WORDSIZE )
					{
					case 1:	*((signed char    *)pValue)	= (signed char   )pGrid->asInt(x, yy);	break;
					case 2:	*((signed short   *)pValue)	= (signed short  )pGrid->asInt(x, yy);	break;
					case 4:	*((signed int     *)pValue)	= (signed int    )pGrid->asInt(x, yy);	break;
					}
				}
				else
				{
					switch( m_Index.m_WORDSIZE )
					{
					case 1:	*((unsigned char  *)pValue)	= (unsigned char )pGrid->asInt(x, yy);	break;
					case 2:	*((unsigned short *)pValue)	= (unsigned short)pGrid->asInt(x, yy);	break;
					case 4:	*((unsigned int   *)pValue)	= (unsigned int  )pGrid->asInt(x, yy);	break;
					}
				}

				if( m_Index.m_ENDIAN == VAL_ENDIAN_BIG )
				{
					SG_Swap_Bytes(pValue, m_Index.m_WORDSIZE);
				}
			}

			Stream.Write(pLine, sizeof(char), nBytes_Line);
		}
	}

	//-----------------------------------------------------
	SG_Free(pLine);

	return( true );
}
Ejemplo n.º 24
0
//---------------------------------------------------------
bool CSG_Grid::_Load_Native(const CSG_String &File_Name, TSG_Grid_Memory_Type Memory_Type)
{
	bool			bResult, hdr_bFlip, hdr_bSwapBytes;
	int				iType, hdr_Offset, NX, NY;
	double			Cellsize, xMin, yMin;
	CSG_File		Stream;
	TSG_Data_Type	hdr_Type;
	CSG_Grid_System	System;
	CSG_String		File_Data, Value;

	//-----------------------------------------------------
	bResult	= false;

	if( Stream.Open(File_Name, SG_FILE_R, false) )
	{
		//-------------------------------------------------
		// Load Header...

		hdr_Type		= SG_DATATYPE_Undefined;
		hdr_Offset		= 0;
		hdr_bFlip		= false;
		hdr_bSwapBytes	= false;

		NX	= NY		= 0;
		Cellsize		= 0.0;
		xMin			= 0.0;
		yMin			= 0.0;

		//-------------------------------------------------
		do
		{
			switch( _Load_Native_Get_Key(Stream, Value) )
			{
			case GRID_FILE_KEY_NAME:			Set_Name		(Value);			break;
			case GRID_FILE_KEY_DESCRIPTION:		Set_Description	(Value);			break;
			case GRID_FILE_KEY_UNITNAME:		Set_Unit		(Value);			break;

			case GRID_FILE_KEY_CELLCOUNT_X:		NX				= Value.asInt();	break;
			case GRID_FILE_KEY_CELLCOUNT_Y:		NY				= Value.asInt();	break;
			case GRID_FILE_KEY_POSITION_XMIN:	xMin			= Value.asDouble();	break;
			case GRID_FILE_KEY_POSITION_YMIN:	yMin			= Value.asDouble();	break;
			case GRID_FILE_KEY_CELLSIZE:		Cellsize		= Value.asDouble();	break;
			case GRID_FILE_KEY_Z_FACTOR:		m_zFactor		= Value.asDouble();	break;
			case GRID_FILE_KEY_NODATA_VALUE:	Set_NoData_Value(Value.asDouble());	break;

			case GRID_FILE_KEY_DATAFILE_OFFSET:	hdr_Offset		= Value.asInt();	break;
			case GRID_FILE_KEY_BYTEORDER_BIG:	hdr_bSwapBytes	= Value.Find(GRID_FILE_KEY_TRUE) >= 0;	break;
			case GRID_FILE_KEY_TOPTOBOTTOM:		hdr_bFlip		= Value.Find(GRID_FILE_KEY_TRUE) >= 0;	break;

			case GRID_FILE_KEY_DATAFILE_NAME:
				if( SG_File_Get_Path(Value).Length() > 0 )
				{
					File_Data	= Value;
				}
				else
				{
					File_Data	= SG_File_Make_Path(SG_File_Get_Path(File_Name), Value);
				}
				break;

			case GRID_FILE_KEY_DATAFORMAT:
				for(iType=0; iType<SG_DATATYPE_Undefined && hdr_Type == SG_DATATYPE_Undefined; iType++)
				{
					if( Value.Find(gSG_Data_Type_Identifier[iType]) >= 0 )
					{
						hdr_Type	= (TSG_Data_Type)iType;
					}
				}
				break;
			}
		}
		while( !Stream.is_EOF() );


		//-------------------------------------------------
		// Load Data...

		if( m_System.Assign(Cellsize, xMin, yMin, NX, NY) )
		{
			//---------------------------------------------
			// ASCII...

			if( !SG_Data_Type_is_Numeric(hdr_Type) )
			{
				if( m_Type >= SG_DATATYPE_Undefined )
				{
					m_Type	= SG_DATATYPE_Float;
				}

				if(	Stream.Open(File_Data											, SG_FILE_R, false)
				||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T( "dat"))	, SG_FILE_R, false)
				||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T("sdat"))	, SG_FILE_R, false) )
				{
					Stream.Seek(hdr_Offset);
					bResult	= _Load_ASCII(Stream, Memory_Type, hdr_bFlip);
				}
			}

			//---------------------------------------------
			// Binary...

			else
			{
				if( m_Type >= SG_DATATYPE_Undefined )
				{
					m_Type	= hdr_Type;
				}

				if( (NX = SG_Grid_Cache_Check(m_System, Get_nValueBytes())) > 0 )
				{
					Set_Buffer_Size(NX);

					if( _Cache_Create(File_Data											, hdr_Type, hdr_Offset, hdr_bSwapBytes, hdr_bFlip)
					||	_Cache_Create(SG_File_Make_Path(NULL, File_Name, SG_T( "dat"))	, hdr_Type, hdr_Offset, hdr_bSwapBytes, hdr_bFlip)
					||	_Cache_Create(SG_File_Make_Path(NULL, File_Name, SG_T("sdat"))	, hdr_Type, hdr_Offset, hdr_bSwapBytes, hdr_bFlip) )
					{
						return( true );
					}

					Memory_Type	= GRID_MEMORY_Cache;
				}

				if( _Memory_Create(Memory_Type) )
				{
					if(	Stream.Open(File_Data											, SG_FILE_R, true)
					||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T( "dat"))	, SG_FILE_R, true)
					||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T("sdat"))	, SG_FILE_R, true) )
					{
						Stream.Seek(hdr_Offset);
						bResult	= _Load_Binary(Stream, hdr_Type, hdr_bFlip, hdr_bSwapBytes);
					}
				}
			}
		}
	}

	return( bResult );
}
Ejemplo n.º 25
0
//---------------------------------------------------------
bool CGrid_Import::On_Execute(void)
{
	bool				bTransform;
	int					x, y, yy, Method;
	double				ax, ay, dx, dy, rx, ry, xMin, yMin, Cellsize;
	CSG_Colors			Colors;
	CSG_String			fImage, fWorld, Name;
	CSG_Grid			*pImage;
	CSG_File			Stream;
	wxImage				Image;
	wxImageHistogram	Histogram;

	//-----------------------------------------------------
	fImage	= Parameters("FILE")	->asString();
	Method	= Parameters("METHOD")	->asInt();

	Name	= SG_File_Get_Name(fImage, false);

	//-----------------------------------------------------
	wxImageHandler	*pImgHandler = NULL;

	if( !SG_UI_Get_Window_Main() )
	{
		CSG_String	fName = SG_File_Get_Name(fImage, true);

		if( SG_File_Cmp_Extension(fName, SG_T("jpg")) )
			pImgHandler = new wxJPEGHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("pcx")) )
			pImgHandler = new wxPCXHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("tif")) )
			pImgHandler = new wxTIFFHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("gif")) )
			pImgHandler = new wxGIFHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("pnm")) )
			pImgHandler = new wxPNMHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("xpm")) )
			pImgHandler = new wxXPMHandler;
#ifdef _SAGA_MSW
		else if( SG_File_Cmp_Extension(fName, SG_T("bmp")) )
			pImgHandler = new wxBMPHandler;
#endif
		else // if( SG_File_Cmp_Extension(fName, SG_T("png")) )
			pImgHandler = new wxPNGHandler;

		wxImage::AddHandler(pImgHandler);
	}

	if( !Image.LoadFile(fImage.c_str()) )
	{
		return( false );
	}

	//-----------------------------------------------------
	     if( SG_File_Cmp_Extension(fImage, SG_T("bmp")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("bpw"));
	}
	else if( SG_File_Cmp_Extension(fImage, SG_T("jpg")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("jgw"));
	}
	else if( SG_File_Cmp_Extension(fImage, SG_T("png")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("pgw"));
	}
	else if( SG_File_Cmp_Extension(fImage, SG_T("tif")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("tfw"));
	}
	else
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("world"));
	}

	bTransform	= false;
	xMin		= 0.0;
	yMin		= 0.0;
	Cellsize	= 1.0;

	if(	Stream.Open(fWorld, SG_FILE_R, false) && fscanf(Stream.Get_Stream(), "%lf %lf %lf %lf %lf %lf ", &dx, &ry, &rx, &dy, &ax, &ay) == 6 )
	{
		if( dx != -dy || rx != 0.0 || ry != 0.0 )
		{
			bTransform	= true;
		}
		else
		{
			xMin		= ax;
			yMin		= ay + dy * (Image.GetHeight() - 1);
			Cellsize	= dx;
		}
	}


	//-----------------------------------------------------
	// color look-up table...

	if( Method == 0 && (yy = Image.ComputeHistogram(Histogram)) <= 256 )
	{
		Colors.Set_Count(yy);

		for(wxImageHistogram::iterator i=Histogram.begin(); i!=Histogram.end(); ++i)
		{
			Colors.Set_Color(i->second.index, SG_GET_R(i->first), SG_GET_G(i->first), SG_GET_B(i->first));
		}

		pImage	= SG_Create_Grid(yy <= 2 ? SG_DATATYPE_Bit : SG_DATATYPE_Byte, Image.GetWidth(), Image.GetHeight(), Cellsize, xMin, yMin);

		for(y=0; y<pImage->Get_NY() && Set_Progress(y, pImage->Get_NY()); y++)
		{
			yy	= bTransform ? y : pImage->Get_NY() - 1 - y;

			for(x=0; x<pImage->Get_NX(); x++)
			{
				pImage->Set_Value(x, y, Histogram[SG_GET_RGB(Image.GetRed(x, yy), Image.GetGreen(x, yy), Image.GetBlue(x, yy))].index);
			}
		}

		if( bTransform )
		{
			Set_Transformation(&pImage, ax, ay, dx, dy, rx, ry);
		}

		pImage->Set_Name(Name);
		pImage->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
		Parameters("OUT_GRID")->Set_Value(pImage);
		DataObject_Set_Colors(pImage, Colors);
		DataObject_Update(pImage, 0, Colors.Get_Count() - 1);
	}

	//-----------------------------------------------------
	else	// true color...
	{
		pImage	= SG_Create_Grid(SG_DATATYPE_Int, Image.GetWidth(), Image.GetHeight(), Cellsize, xMin, yMin);
		pImage	->Set_Name(Name);

		for(y=0; y<pImage->Get_NY() && Set_Progress(y, pImage->Get_NY()); y++)
		{
			yy	= bTransform ? y : pImage->Get_NY() - 1 - y;

			for(x=0; x<pImage->Get_NX(); x++)
			{
				pImage->Set_Value(x, y, SG_GET_RGB(Image.GetRed(x, yy), Image.GetGreen(x, yy), Image.GetBlue(x, yy)));
			}
		}

		if( bTransform )
		{
			Set_Transformation(&pImage, ax, ay, dx, dy, rx, ry);
		}

		//-------------------------------------------------
		if( Method != 1 )	// true color...
		{
			pImage->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);
			pImage->Set_Name(Name);
			pImage->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
			Parameters("OUT_GRID")->Set_Value(pImage);
			DataObject_Set_Colors(pImage, 100, SG_COLORS_BLACK_WHITE);
			DataObject_Set_Parameter(pImage, "COLORS_TYPE", 6);	// Color Classification Type: RGB
		}

		//-------------------------------------------------
		else				// split channels...
		{
			CSG_Grid	*pR, *pG, *pB;

			pR	= SG_Create_Grid(pImage->Get_System(), SG_DATATYPE_Byte);
			pG	= SG_Create_Grid(pImage->Get_System(), SG_DATATYPE_Byte);
			pB	= SG_Create_Grid(pImage->Get_System(), SG_DATATYPE_Byte);

			for(y=0; y<pImage->Get_NY() && Set_Progress(y, pImage->Get_NY()); y++)
			{
				for(x=0; x<pImage->Get_NX(); x++)
				{
					pR->Set_Value(x, y, SG_GET_R(pImage->asInt(x, y)));
					pG->Set_Value(x, y, SG_GET_G(pImage->asInt(x, y)));
					pB->Set_Value(x, y, SG_GET_B(pImage->asInt(x, y)));
				}
			}

			pR->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);
			pG->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);
			pB->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);

			pR->Set_Name(CSG_String::Format(SG_T("%s [R]"), Name.c_str()));
			pG->Set_Name(CSG_String::Format(SG_T("%s [G]"), Name.c_str()));
			pB->Set_Name(CSG_String::Format(SG_T("%s [B]"), Name.c_str()));

			pR->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
			pG->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
			pB->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));

			Parameters("OUT_RED")	->Set_Value(pR);
			Parameters("OUT_GREEN")	->Set_Value(pG);
			Parameters("OUT_BLUE")	->Set_Value(pB);

			DataObject_Set_Colors(pR, 100, SG_COLORS_BLACK_RED);
			DataObject_Set_Colors(pG, 100, SG_COLORS_BLACK_GREEN);
			DataObject_Set_Colors(pB, 100, SG_COLORS_BLACK_BLUE);
		}
	}

	//-----------------------------------------------------
	if( !SG_UI_Get_Window_Main() && pImgHandler != NULL)
	{
		wxImage::RemoveHandler(pImgHandler->GetName());
	}

	//-----------------------------------------------------
	return( true );
}
Ejemplo n.º 26
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 );

}