Ejemplo n.º 1
0
//---------------------------------------------------------
bool CWKSP_Project::_Compatibility_Load_Map(CSG_File &Stream, const wxString &ProjectDir)
{
	TSG_Rect		r;
	CSG_String		sLine, sName;
	CWKSP_Base_Item	*pItem;
	CWKSP_Map		*pMap;

	while( Stream.Read_Line(sLine) && sLine.Cmp(MAP_ENTRY_BEGIN) && sLine.Cmp(MAP_ENTRIES_END) );

	if( !sLine.Cmp(MAP_ENTRY_BEGIN) && Stream.Read_Line(sLine) )
	{
		if(	SG_SSCANF(sLine, SG_T("%lf %lf %lf %lf"), &r.xMin, &r.xMax, &r.yMin, &r.yMax) == 4 )
		{
			pMap	= NULL;

			while( Stream.Read_Line(sLine) && sLine.Cmp(MAP_ENTRY_END) )
			{
				if( !sLine.Cmp(MAP_ENTRY_NAME) )
				{
					Stream.Read_Line(sName);
				}
				else
				{
					sLine	= Get_FilePath_Absolute(ProjectDir, sLine.w_str()).wc_str();

					if(	(pItem = _Get_byFileName(sLine.c_str())) != NULL
					&&	(	pItem->Get_Type()	== WKSP_ITEM_Grid
						||	pItem->Get_Type()	== WKSP_ITEM_Grids
						||	pItem->Get_Type()	== WKSP_ITEM_TIN
						||	pItem->Get_Type()	== WKSP_ITEM_PointCloud
						||	pItem->Get_Type()	== WKSP_ITEM_Shapes) )
					{
						if( pMap == NULL )
						{
							pMap	= new CWKSP_Map;
						}

						g_pMaps->Add((CWKSP_Layer *)pItem, pMap);
					}
				}
			}

			if( pMap )
			{
				if( sName.Length() > 0 )
				{
					pMap->Get_Parameter("NAME")->Set_Value(sName);
					pMap->Parameters_Changed();
				}

				pMap->Set_Extent(r, true);
				pMap->View_Show(true);
			}
		}

		return( true );
	}

	return( false );
}
Ejemplo n.º 2
0
//---------------------------------------------------------
bool CWKSP_Project::_Compatibility_Load_Data(CSG_File &Stream, const wxString &ProjectDir)
{
	int				Type;
	CSG_String		sLine, sPath;
	CWKSP_Base_Item	*pItem;

	while( Stream.Read_Line(sLine) && sLine.Cmp(DATA_ENTRY_BEGIN) && sLine.Cmp(DATA_ENTRIES_END) );

	if( !sLine.Cmp(DATA_ENTRY_BEGIN) )
	{
		if(	Stream.Read_Line(sPath) && Stream.Read_Line(sLine) && sLine.asInt(Type) )
		{
			if( SG_File_Exists(sPath = Get_FilePath_Absolute(ProjectDir, sPath.w_str()).wc_str()) )
			{
				if(	(pItem = g_pData->Open(sPath.w_str(), Type)) != NULL )
				{
					if( pItem->Get_Parameters() )
					{
						pItem->Get_Parameters()->Serialize_Compatibility(Stream);
						_Compatibility_Data((TSG_Data_Type)Type, pItem->Get_Parameters(), "");
						pItem->Parameters_Changed();
					}
				}
			}
		}

		return( true );
	}

	return( false );
}
Ejemplo n.º 3
0
void Cdodproperror::DisplayFile(CSG_String path)
{

	if (SG_File_Exists(path))
	{
		CSG_File File;
		if (File.Open(path, 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 " + path + CSG_String(" for reading")));
		}
	}
	else
	{
		Message_Add(CSG_String("File '" + path + CSG_String("' does not exist")));
	}

}
Ejemplo n.º 4
0
//---------------------------------------------------------
int CSG_Grid::_Load_Native_Get_Key(CSG_File &Stream, CSG_String &Value)
{
	int			i;
	CSG_String	sLine;

	if( Stream.Read_Line(sLine) && (i = sLine.Find('=')) > 0 )
	{
		Value	= sLine.AfterFirst('=');
		Value.Trim();

		sLine.Remove(i);

		for(i=0; i<GRID_FILE_KEY_Count; i++)
		{
			CSG_String	s(gSG_Grid_File_Key_Names[i]);

			if( s.Find(sLine.Left(s.Length())) >= 0 )
			{
				return( i );
			}
		}
	}

	return( -1 );
}
Ejemplo n.º 5
0
//---------------------------------------------------------
inline bool CXYZ_Import::Read_Values(CSG_File &Stream, double &x, double &y, double &z)
{
	CSG_String	sLine;

	if( Stream.Read_Line(sLine) )
	{
		sLine.Trim();

		if( sLine.asDouble(x) )
		{
			sLine	= sLine.AfterFirst(m_Separator);

			sLine.Trim();

			if( sLine.asDouble(y) )
			{
				sLine	= sLine.AfterFirst(m_Separator);

				if( sLine.asDouble(z) )
				{
					return( true );
				}
			}
		}
	}

	return( false );
}
Ejemplo n.º 6
0
//---------------------------------------------------------
bool CWKSP_Project::_Compatibility_Load_Data(const wxString &FileName)
{
	CSG_String	sLine;
	CSG_File	Stream;

	if( !Stream.Open(&FileName, SG_FILE_R, true) )
	{
		return( false );
	}

	//-------------------------------------------------
	while( Stream.Read_Line(sLine) && sLine.Cmp(DATA_ENTRIES_BEGIN) );

	if( sLine.Cmp(DATA_ENTRIES_BEGIN) )
	{
		return( false );
	}

	g_pSAGA_Frame->Freeze();

	g_pData->Get_Menu_Files()->Set_Update(false);
	while( _Compatibility_Load_Data(Stream, SG_File_Get_Path(&FileName).w_str()) );
	g_pData->Get_Menu_Files()->Set_Update(true);

	//-------------------------------------------------
	while( Stream.Read_Line(sLine) && sLine.Cmp(MAP_ENTRIES_BEGIN) );

	if( !sLine.Cmp(MAP_ENTRIES_BEGIN) )
	{
		while( _Compatibility_Load_Map(Stream, SG_File_Get_Path(&FileName).w_str()) );
	}

	switch( g_pData->Get_Parameter("PROJECT_MAP_ARRANGE")->asInt() )
	{
	case 1:	g_pSAGA_Frame->Tile(wxHORIZONTAL);	break;
	case 2:	g_pSAGA_Frame->Tile(wxVERTICAL  );	break;
	}

	g_pSAGA_Frame->Thaw();

	return( true );
}
Ejemplo n.º 7
0
//---------------------------------------------------------
bool CXYZ_Import::On_Execute(void)
{
	CSG_File	Stream;

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

		return( false );
	}

	//-----------------------------------------------------
	CSG_Shapes	*pPoints	= Parameters("POINTS")->asShapes();

	pPoints->Create(SHAPE_TYPE_Point, SG_File_Get_Name(Parameters("FILENAME")->asString(), false));

	pPoints->Add_Field("Z", SG_DATATYPE_Double);

	//-----------------------------------------------------
	if( Parameters("HEADLINE")->asBool() )
	{
		CSG_String	sLine;

		if( !Stream.Read_Line(sLine) )
		{
			Error_Set(_TL("could not read headline"));

			return( false );
		}
	}

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

	double	x, y, z;

	while( Stream.Scan(x) && Stream.Scan(y) && Stream.Scan(z) && Set_Progress((double)Stream.Tell(), (double)Length) )
	{
		CSG_Shape	*pPoint	= pPoints->Add_Shape();

		pPoint->Add_Point(x, y);

		pPoint->Set_Value(0, z);
	}

	return( pPoints->Get_Count() > 0 );
}
Ejemplo n.º 8
0
//---------------------------------------------------------
bool CSG_Table::Serialize(CSG_File &Stream, bool bSave)
{
	SG_Char				Separator	= SG_T('\t');
	int					iField, nFields, iRecord, nRecords, FieldType;
	CSG_Table_Record	*pRecord;
	CSG_String			s, sLine;

	//-----------------------------------------------------
	if( bSave )
	{
		Stream.Printf(SG_T("%d %d\n"), m_nFields, m_nRecords);

		for(iField=0; iField<m_nFields; iField++)
		{
			Stream.Printf(SG_T("%d \"%s\"\n"), Get_Field_Type(iField), Get_Field_Name(iField));
		}

		for(iRecord=0; iRecord<m_nRecords; iRecord++)
		{
			for(iField=0; iField<m_nFields; iField++)
			{
				Stream.Printf(SG_T("%s%c"), Get_Record(iRecord)->asString(iField), iField < m_nFields - 1 ? Separator : '\n');
			}
		}

		return( true );
	}

	//-----------------------------------------------------
	else if( Stream.Read_Line(sLine) && SG_SSCANF(sLine, SG_T("%d %d"), &nFields, &nRecords) == 2 && nFields > 0 )
	{
		_Destroy();

		for(iField=0; iField<nFields; iField++)
		{
			if( Stream.Read_Line(sLine) && SG_SSCANF(sLine, SG_T("%d"), &FieldType) == 1 )
			{
				Add_Field(sLine.AfterFirst(SG_T('\"')).BeforeFirst(SG_T('\"')), (TSG_Data_Type)FieldType);
			}
		}

		for(iRecord=0; iRecord<nRecords; iRecord++)
		{
			if( Stream.Read_Line(sLine) )
			{
				pRecord	= _Add_Record();

				for(iField=0; iField<m_nFields; iField++)
				{
					pRecord->Set_Value(iField, sLine.BeforeFirst(Separator));

					sLine	= sLine.AfterFirst(Separator);
				}
			}
		}

		return( true );
	}

	//-----------------------------------------------------
	return( false );
}
Ejemplo n.º 9
0
//---------------------------------------------------------
bool CSG_Table::_Load_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator)
{
	int			i, iField, fLength;
	CSG_String	sLine, sField;
	CSG_File	Stream;
	CSG_Table	Table;

	//-----------------------------------------------------
	if( Stream.Open(File_Name, SG_FILE_R, false) == false )
	{
		return( false );
	}

	if( !Stream.Read_Line(sLine) )
	{
		return( false );
	}

	//-----------------------------------------------------
	sLine	+= Separator;

	while( (i = sLine.Find(Separator)) >= 0 )
	{
		sField	= bHeadline ? sLine.Left(i) : CSG_String::Format(SG_T("FIELD_%02d"), Table.Get_Field_Count() + 1);

		if( sField[0] == SG_T('\"') && sField[(int)(sField.Length() - 1)] == SG_T('\"') )	// remove quota
		{
			sField	= sField.AfterFirst('\"').BeforeLast('\"');
		}

		Table.Add_Field(sField, SG_DATATYPE_String);

		sLine.Remove(0, i + 1);
	}

	//-----------------------------------------------------
	TSG_Data_Type	*Type	= new TSG_Data_Type[Table.Get_Field_Count()];

	for(iField=0; iField<Table.Get_Field_Count(); iField++)
	{
		Type[iField]	= SG_DATATYPE_Int;
	}

	if( !bHeadline )
	{
		Stream.Seek_Start();
	}

	fLength	= Stream.Length();

	while( Stream.Read_Line(sLine) && sLine.Length() > 0 && SG_UI_Process_Set_Progress(Stream.Tell(), fLength) )
	{
		CSG_Table_Record	*pRecord	= Table._Add_Record();

		sLine	+= Separator;

		for(iField=0; iField<Table.Get_Field_Count(); iField++)
		{
			if( (i = sLine.Find(Separator)) >= 0 )
			{
				sField	= sLine.Left(i);

				if( sField[0] == SG_T('\"') && sField[(int)(sField.Length() - 1)] == SG_T('\"') )	// remove quota
				{
					sField	= sField.AfterFirst('\"').BeforeLast('\"');
				}

				if( Type[iField] != SG_DATATYPE_String )
				{
					double	Value;

					if( SG_SSCANF(sField, SG_T("%lf"), &Value) != 1 )
					{
						Type[iField]	= SG_DATATYPE_String;
					}
					else if( Type[iField] != SG_DATATYPE_Double && Value - (int)Value != 0.0 )
					{
						Type[iField]	= SG_DATATYPE_Double;
					}
				}

				pRecord->Set_Value(iField, sField);

				sLine.Remove(0, i + 1);
			}
			else
			{
				break;
			}
		}
	}

	//-----------------------------------------------------
	if( Table.Get_Count() > 0 )
	{
		for(iField=0; iField<Table.Get_Field_Count(); iField++)
		{
			Add_Field(Table.Get_Field_Name(iField), Type[iField]);
		}

		for(int iRecord=0; iRecord<Table.Get_Count() && SG_UI_Process_Set_Progress(iRecord, Table.Get_Count()); iRecord++)
		{
			CSG_Table_Record	*pRecord	= _Add_Record();

			for(iField=0; iField<Get_Field_Count(); iField++)
			{
				switch( Get_Field_Type(iField) )
				{
				default:						pRecord->Set_Value(iField, Table[iRecord].asString(iField));	break;
				case SG_DATATYPE_Int:		pRecord->Set_Value(iField, Table[iRecord].asInt   (iField));	break;
				case SG_DATATYPE_Double:	pRecord->Set_Value(iField, Table[iRecord].asDouble(iField));	break;
				}
			}
		}
	}

	delete[](Type);

	SG_UI_Process_Set_Ready();

	return( Get_Field_Count() > 0 );
}
Ejemplo n.º 10
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 );
}
Ejemplo n.º 11
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 );
}
//---------------------------------------------------------
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 );
}
Ejemplo n.º 13
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 );

}
Ejemplo n.º 14
0
//---------------------------------------------------------
bool CWRF_Index::Load(const CSG_String &File)
{
	Reset();

	CSG_File	Stream;

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

	CSG_String	sLine, sKey, sValue;

	while( Stream.Read_Line(sLine) )
	{
		sKey	= sLine.BeforeFirst(SG_T('=')).Make_Upper();	sKey  .Trim();	sKey  .Trim(true);
		sValue	= sLine.AfterFirst (SG_T('=')).Make_Upper();	sValue.Trim();	sValue.Trim(true);

		if( !sKey.Cmp(SG_T("PROJECTION")) )
		{
			m_PROJECTION	= sValue;
		}
		else if( !sKey.Cmp(SG_T("TYPE")) )
		{
			m_TYPE			= sValue.Contains(SG_T("CATEGORICAL")) ? VAL_CATEGORICAL : VAL_CONTINUOUS;
		}
		else if( !sKey.Cmp(SG_T("SIGNED")) )
		{
			m_SIGNED		= sValue.Contains(SG_T("YES"));
		}
		else if( !sKey.Cmp(SG_T("UNITS")) )
		{
			m_UNITS			= sValue;
		}
		else if( !sKey.Cmp(SG_T("DESCRIPTION")) )
		{
			m_DESCRIPTION	= sValue;
		}
		else if( !sKey.Cmp(SG_T("DX")) )
		{
			m_DX			= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("DY")) )
		{
			m_DY			= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("KNOWN_X")) )
		{
			m_KNOWN_X		= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("KNOWN_Y")) )
		{
			m_KNOWN_Y		= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("KNOWN_LAT")) )
		{
			m_KNOWN_LAT		= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("KNOWN_LON")) )
		{
			m_KNOWN_LON		= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("STDLON")) )
		{
			m_STDLON		= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("TRUELAT1")) )
		{
			m_TRUELAT1		= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("TRUELAT2")) )
		{
			m_TRUELAT2		= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("WORDSIZE")) )
		{
			m_WORDSIZE		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("TILE_X")) )
		{
			m_TILE_X		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("TILE_Y")) )
		{
			m_TILE_Y		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("TILE_Z")) )
		{
			m_TILE_Z		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("TILE_Z_START")) )
		{
			m_TILE_Z_START	= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("TILE_Z_END")) )
		{
			m_TILE_Z_END	= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("CATEGORY_MIN")) )
		{
			m_CATEGORY_MIN	= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("CATEGORY_MAX")) )
		{
			m_CATEGORY_MAX	= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("TILE_BDR")) )
		{
			m_TILE_BDR		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("MISSING_VALUE")) )
		{
			m_MISSING_VALUE	= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("SCALE_FACTOR")) )
		{
			m_SCALE_FACTOR	= sValue.asDouble();
		}
		else if( !sKey.Cmp(SG_T("ROW_ORDER")) )
		{
			m_ROW_ORDER		= sValue.Contains(SG_T("BOTTOM_TOP")) ? VAL_BOTTOM_TOP : VAL_TOP_BOTTOM;
		}
		else if( !sKey.Cmp(SG_T("ENDIAN")) )
		{
			m_ENDIAN		= sValue.Contains(SG_T("BIG")) ? VAL_ENDIAN_BIG : VAL_ENDIAN_LITTLE;
		}
		else if( !sKey.Cmp(SG_T("ISWATER")) )
		{
			m_ISWATER		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("ISLAKE")) )
		{
			m_ISLAKE		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("ISICE")) )
		{
			m_ISICE			= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("ISURBAN")) )
		{
			m_ISURBAN		= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("ISOILWATER")) )
		{
			m_ISOILWATER	= sValue.asInt();
		}
		else if( !sKey.Cmp(SG_T("MMINLU")) )
		{
			m_MMINLU		= sValue;
		}
	}

	return( true );
}
Ejemplo n.º 15
0
//---------------------------------------------------------
bool CWASP_MAP_Import::On_Execute(void)
{
	int			n, Method, nLength;
	double		z, dz, zMin, rLeft, rRight;
	CSG_File	Stream;
	TSG_Point	p, pu[2], pm[2];
	CSG_String	fName, sLine;
	CSG_Shape	*pLine;
	CSG_Shapes	*pLines;

	//-----------------------------------------------------
	pLines	= Parameters("SHAPES")->asShapes();
	fName	= Parameters("FILE"  )->asString();
	Method	= Parameters("METHOD")->asInt();

	//-----------------------------------------------------
	if( Stream.Open(fName, SG_FILE_R) )
	{
		nLength	= Stream.Length();

		pLines->Create(SHAPE_TYPE_Line, SG_File_Get_Name(fName, false));

		switch( Method )
		{
		case 0:	// elevation
			pLines->Add_Field("Z"		, SG_DATATYPE_Double);
			break;

		case 1:	// roughness
			pLines->Add_Field("RLEFT"	, SG_DATATYPE_Double);
			pLines->Add_Field("RRIGHT"	, SG_DATATYPE_Double);
			break;

		case 2:	// elevation and roughness
			pLines->Add_Field("Z"		, SG_DATATYPE_Double);
			pLines->Add_Field("RLEFT"	, SG_DATATYPE_Double);
			pLines->Add_Field("RRIGHT"	, SG_DATATYPE_Double);
			break;
		}


		// 1)	Text string identifying the terrain map: + ...

		Stream.Read_Line(sLine);


		// 2)	Fixed point #1 in user and metric [m] coordinates:
		//			X1(user) Y1(user) X1(metric) Y1(metric)

	//	fscanf(Stream, "%lf %lf %lf %lf", &pu[0].x, &pu[0].y, &pm[0].x, &pm[0].y);
		pu[0].x	= Stream.Scan_Double();
		pu[0].y	= Stream.Scan_Double();
		pm[0].x	= Stream.Scan_Double();
		pm[0].y	= Stream.Scan_Double();


		// 3)	Fixed point #2 in user and metric [m] coordinates:
		//			X2(user) Y2(user) X2(metric) Y2(metric)

	//	fscanf(Stream, "%lf %lf %lf %lf", &pu[1].x, &pu[1].y, &pm[1].x, &pm[1].y);
		pu[1].x	= Stream.Scan_Double();
		pu[1].y	= Stream.Scan_Double();
		pm[1].x	= Stream.Scan_Double();
		pm[1].y	= Stream.Scan_Double();


		// 4)	Scaling factor and offset for height scale (Z):
		//			Zmetric = {scaling factor}(Zuser + {offset})

	//	fscanf(Stream, "%lf %lf", &dz, &zMin);
		dz		= Stream.Scan_Double();
		zMin	= Stream.Scan_Double();


		while( !Stream.is_EOF() && Set_Progress((int)Stream.Tell(), nLength) )
		{
			pLine	= NULL;

			switch( Method )
			{
			case 0:	// elevation
				// 5a)	Height contour: elevation (Z) and number of points (n) in line:
				//			Z n

			//	fscanf(Stream, "%lf %d", &z, &n);
				z		= Stream.Scan_Double();
				n		= Stream.Scan_Int   ();

				if( !Stream.is_EOF() && n > 1 )
				{
					pLine	= pLines->Add_Shape();
					pLine->Set_Value(0, zMin + dz * z);
				}
				break;

			case 1:	// roughness
				// 5b)	Roughness change line:
				//			roughness lengths to the left (z0l) and right (z0r) side of the line,
				//			respectively, and number of points:
				//				z0l z0r n

			//	fscanf(Stream, "%lf %lf %d", &rLeft, &rRight, &n);
				rLeft	= Stream.Scan_Double();
				rRight	= Stream.Scan_Double();
				n		= Stream.Scan_Int   ();

				if( !Stream.is_EOF() && n > 1 )
				{
					pLine	= pLines->Add_Shape();
					pLine->Set_Value(0, rLeft);
					pLine->Set_Value(1, rRight);
				}
				break;

			case 2:	// elevation and roughness
				// 5c)	Roughness and contour line:
				//			roughness lengths to the left and right of the line,
				//			respectively, elevation and number of points:
				//				z0l z0r Z n

			//	fscanf(Stream, "%lf %lf %lf %d", &rLeft, &rRight, &z, &n);
				rLeft	= Stream.Scan_Double();
				rRight	= Stream.Scan_Double();
				z		= Stream.Scan_Double();
				n		= Stream.Scan_Int   ();

				if( !Stream.is_EOF() && n > 1 )
				{
					pLine	= pLines->Add_Shape();
					pLine->Set_Value(0, zMin + dz * z);
					pLine->Set_Value(1, rLeft);
					pLine->Set_Value(2, rRight);
				}
				break;
			}


			// 6–)	Cartesian coordinates (X, Y) of line described in 5a, 5b or 5c:
			//			X1 Y1 [... Xn Yn]
			//			Xn+1 Yn+1
			//			... where [] embrace optional numbers and n is > 0

			for(int i=0; i<n && !Stream.is_EOF() && Process_Get_Okay(false); i++)
			{
			//	fscanf(Stream, "%lf %lf", &p.x, &p.y);
				p.x	= Stream.Scan_Double();
				p.y	= Stream.Scan_Double();

				pLine->Add_Point(p);
			}
		}

		return( true );
	}

	return( false );
}
Ejemplo n.º 16
0
//---------------------------------------------------------
bool CXYZ_Import::On_Execute(void)
{
	int			nx, ny, nValues, fLength;
	double		x, y, z, xMin, yMin, xMax, yMax, Cellsize;
	CSG_File	Stream;
	CSG_String	FileName, sLine;
	CSG_Grid	*pGrid, *pCount;

	FileName	= Parameters("FILENAME")->asString();
	Cellsize	= Parameters("CELLSIZE")->asDouble();

	switch( Parameters("SEPARATOR")->asInt() )
	{
	case 0:	m_Separator	= SG_T(' ');	break;
	case 1:	m_Separator	= SG_T('\t');	break;
	case 2:	m_Separator	= SG_T(',');	break;
	case 3:	m_Separator	= SG_T(';');	break;
	}

	if( Cellsize > 0.0 && Stream.Open(FileName, SG_FILE_R, false) )
	{
		if( Parameters("CAPTION")->asBool() )
		{
			Stream.Read_Line(sLine);
		}

		fLength	= Stream.Length();
		nValues	= 0;
		xMin	= xMax	= 0;
		yMin	= yMax	= 0;

		while( Read_Values(Stream, x, y, z) && Set_Progress(Stream.Tell(), fLength) )
		{
			if( nValues == 0 )
			{
				xMin	= xMax	= x;
				yMin	= yMax	= y;
			}
			else
			{
				if( xMin > x )	xMin	= x;	else if( xMax < x )	xMax	= x;
				if( yMin > y )	yMin	= y;	else if( yMax < y )	yMax	= y;
			}

			nValues++;
		}

		//-------------------------------------------------
		if( Process_Get_Okay() && xMin < xMax && yMin < yMax )
		{
			nx		= 1 + (int)((xMax - xMin) / Cellsize);
			ny		= 1 + (int)((yMax - yMin) / Cellsize);

			Parameters("GRID" )->Set_Value(pGrid  = SG_Create_Grid(SG_DATATYPE_Float, nx, ny, Cellsize, xMin, yMin));
			Parameters("COUNT")->Set_Value(pCount = SG_Create_Grid(SG_DATATYPE_Byte , nx, ny, Cellsize, xMin, yMin));

			if( pGrid && pCount )
			{
				pGrid	->Set_Name(FileName = SG_File_Get_Name(FileName, false));
				pCount	->Set_Name(CSG_String::Format(SG_T("%s [%s]"), FileName.c_str(), _TL("Count")));

				Stream.Seek_Start();

				if( Parameters("CAPTION")->asBool() )
				{
					Stream.Read_Line(sLine);
				}

				while( Read_Values(Stream, x, y, z) && Set_Progress(Stream.Tell(), fLength) )
				{
					if( pGrid->Get_System().Get_World_to_Grid(nx, ny, x, y) )
					{
						pGrid ->Add_Value(nx, ny, z);
						pCount->Add_Value(nx, ny, 1.0);
					}
				}

				for(ny=0; ny<pGrid->Get_NY() && Set_Progress(ny, pGrid->Get_NY()); ny++)
				{
					for(nx=0; nx<pGrid->Get_NX(); nx++)
					{
						nValues	= pCount->asInt(nx, ny);

						if( nValues == 0 )
						{
							pGrid->Set_NoData(nx, ny);
						}
						else if( nValues > 1 )
						{
							pGrid->Mul_Value(nx, ny, 1.0 / nValues);
						}
					}
				}

				return( true );
			}
		}
	}

	return( false );
}
Ejemplo n.º 17
0
//---------------------------------------------------------
bool CCRU_Table_Import::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_File	File;

	if( !File.Open(Parameters("FILE")->asString(), SG_FILE_R, false) )
	{
		Error_Fmt("%s [%s]", _TL("could not open file"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	CSG_String	sLine;

	if( !File.Read_Line(sLine) )
	{
		Error_Fmt("%s [%s]", _TL("failed to read header"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	int		nx, ny, nMonths;
	double	Cellsize, xMin, yMin, xMax, yMax;

	if( !File.Scan(Cellsize)
	||  !File.Scan(xMin    ) || !File.Scan(yMin    )
	||  !File.Scan(xMax    ) || !File.Scan(yMax    )
	||  !File.Scan(nx      ) || !File.Scan(ny      )
	||  !File.Scan(nMonths ) )
	{
		Error_Fmt("%s [%s]", _TL("failed to read header"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	CSG_Grid_System	System(Cellsize, xMin, yMin, nx, ny);

	if( !System.is_Valid() || System.Get_XMax() != xMax || System.Get_YMax() != yMax )
	{
		Error_Fmt("%s [%s]", _TL("failed to read header"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	bool	bShift	= Parameters("SHIFT")->asBool();

	if( bShift )
	{
		System.Assign(Cellsize, xMin - 180.0, yMin, nx, ny);
	}

	//-----------------------------------------------------
	CSG_String	Name	= SG_File_Get_Name(Parameters("FILE")->asString(), false);

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

	for(int iMonth=0; iMonth<nMonths && !File.is_EOF() && Process_Get_Okay(); iMonth++)
	{
		Process_Set_Text("%s %d", _TL("Band"), 1 + iMonth);

		CSG_Grid	*pGrid	= SG_Create_Grid(System, SG_DATATYPE_Short);

		pGrid->Fmt_Name("%s_%02d", Name.c_str(), 1 + iMonth);
		pGrid->Set_NoData_Value(-9999);
		pGrid->Get_Projection().Set_GCS_WGS84();

		Parameters("GRIDS")->asGridList()->Add_Item(pGrid);

		//-------------------------------------------------
		for(int y=0; y<ny && !File.is_EOF() && Set_Progress(y, ny); y++)
		{
			if( File.Read_Line(sLine) && sLine.Length() >= 5. * nx )
			{
				for(int x=0, xx=bShift?nx/2:x, yy=ny-1-y; x<nx; x++, xx++)
				{
					double	z;

					CSG_String	s	= sLine.Mid(x * 5, 5);

					if( s.asDouble(z) )
					{
						pGrid->Set_Value(xx % nx, yy, z);
					}
					else
					{
						pGrid->Set_NoData(xx % nx, yy);
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	return( true );
}
Ejemplo n.º 18
0
//---------------------------------------------------------
bool CTable_Text_Import_Numbers::On_Execute(void)
{
    CSG_String	sHead, sLine, Separator;
    CSG_File	Stream;

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

        return( false );
    }

    if( Parameters("SKIP")->asInt() > 0 )
    {
        int	i	= Parameters("SKIP")->asInt();

        while( i > 0 && Stream.Read_Line(sLine) )	{
            i--;
        }
    }

    if( !Stream.Read_Line(sHead) || sHead.Length() == 0 )
    {
        Error_Set(_TL("empty or corrupted file"));

        return( false );
    }

    if( !Parameters("HEADLINE")->asBool() )
    {
        sLine	= sHead;
    }
    else if( !Stream.Read_Line(sLine) || sLine.Length() == 0 )
    {
        Error_Set(_TL("empty or corrupted file"));

        return( false );
    }

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

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

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

    sHead.Trim(true);
    sHead.Replace(Separator, "\t");

    while( sHead.Length() > 0 )
    {
        sHead.Trim();

        if( Parameters("HEADLINE")->asBool() )
        {
            pTable->Add_Field(sHead.BeforeFirst('\t'), SG_DATATYPE_Double);
        }
        else
        {
            pTable->Add_Field(CSG_String::Format("FIELD%02d", 1 + pTable->Get_Field_Count()), SG_DATATYPE_Double);
        }

        sHead	= sHead.AfterFirst('\t');
    }

    if( pTable->Get_Field_Count() <= 0 )
    {
        Error_Set(_TL("empty or corrupted file"));

        return( false );
    }

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

    bool	bOkay	= true;

    do
    {
        sLine.Replace(Separator, "\t");

        CSG_Table_Record	*pRecord	= pTable->Add_Record();

        for(int i=0; bOkay && i<pTable->Get_Field_Count(); i++)
        {
            double	Value;

            sLine.Trim();

            if( (bOkay = sLine.asDouble(Value)) == true )
            {
                pRecord->Set_Value(i, Value);

                sLine	= sLine.AfterFirst('\t');
            }
            else
            {
                pTable->Del_Record(pTable->Get_Count() - 1);
            }
        }
    }
    while( bOkay && Stream.Read_Line(sLine) && Set_Progress(Stream.Tell(), fLength) );

    return( pTable->Get_Count() > 0 );
}