//--------------------------------------------------------- double CExercise_14::Vectorise(int x, int y, CSG_Shape *pSegment) { int Dir, ix, iy; double Length; Length = 0.0; pSegment->Add_Point(Get_XMin() + x * Get_Cellsize(), Get_YMin() + y * Get_Cellsize()); if( (Dir = m_pDir->asInt(x, y)) >= 0 ) { Length = Get_Length(Dir); ix = Get_xTo(Dir, x); iy = Get_yTo(Dir, y); switch( m_pChnl->asInt(ix, iy) ) { case CHANNEL: Length += Vectorise(ix, iy, pSegment); // recursive function call... break; case MOUTH: Length += Get_Length(Dir); pSegment->Add_Point(Get_XMin() + ix * Get_Cellsize(), Get_YMin() + iy * Get_Cellsize()); break; } } return( Length ); }
//--------------------------------------------------------- bool CFilter_Resample::On_Execute(void) { double Cellsize; CSG_Grid *pGrid, *pLoPass, *pHiPass; //----------------------------------------------------- pGrid = Parameters("GRID" )->asGrid(); pLoPass = Parameters("LOPASS")->asGrid(); pHiPass = Parameters("HIPASS")->asGrid(); Cellsize = Parameters("SCALE" )->asDouble() * Get_Cellsize(); //----------------------------------------------------- if( Cellsize > 0.5 * SG_Get_Length(Get_System()->Get_XRange(), Get_System()->Get_YRange()) ) { Error_Set(_TL("resampling cell size is too large")); return( false ); } //----------------------------------------------------- CSG_Grid Grid(CSG_Grid_System(Cellsize, Get_XMin(), Get_YMin(), Get_XMax(), Get_YMax()), SG_DATATYPE_Float); Grid.Assign(pGrid, GRID_RESAMPLING_Mean_Cells); //----------------------------------------------------- pLoPass->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pGrid->Get_Name(), _TL("Low Pass"))); pHiPass->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pGrid->Get_Name(), _TL("High Pass"))); CSG_Colors Colors; DataObject_Get_Colors(pGrid , Colors); DataObject_Set_Colors(pLoPass, Colors); DataObject_Set_Colors(pHiPass, 11, SG_COLORS_RED_GREY_BLUE); //----------------------------------------------------- for(int y=0; y<Get_NY() && Set_Progress(y); y++) { double py = Get_YMin() + y * Get_Cellsize(); #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { double z, px = Get_XMin() + x * Get_Cellsize(); if( !pGrid->is_NoData(x, y) && Grid.Get_Value(px, py, z) ) { pLoPass->Set_Value(x, y, z); pHiPass->Set_Value(x, y, pGrid->asDouble(x, y) - z); } else { pLoPass->Set_NoData(x, y); pHiPass->Set_NoData(x, y); } } } //----------------------------------------------------- return( true ); }
//--------------------------------------------------------- TSG_Intersection CSG_Rect::Intersects(const CSG_Rect &Rect) const { if( m_rect.xMax < Rect.Get_XMin() || Rect.Get_XMax() < m_rect.xMin || m_rect.yMax < Rect.Get_YMin() || Rect.Get_YMax() < m_rect.yMin ) { return( INTERSECTION_None ); } if( is_Equal(Rect) ) { return( INTERSECTION_Identical ); } if( Contains(Rect.Get_XMin(), Rect.Get_YMin()) && Contains(Rect.Get_XMax(), Rect.Get_YMax()) ) { return( INTERSECTION_Contains ); } if( Rect.Contains(Get_XMin(), Get_YMin()) && Rect.Contains(Get_XMax(), Get_YMax()) ) { return( INTERSECTION_Contained ); } return( INTERSECTION_Overlaps ); }
//--------------------------------------------------------- bool CSG_Grid::_Assign_Interpolated(CSG_Grid *pGrid, TSG_Grid_Interpolation Interpolation) { int x, y; double xPosition, yPosition, z; Set_NoData_Value_Range(pGrid->Get_NoData_Value(), pGrid->Get_NoData_hiValue()); for(y=0, yPosition=Get_YMin(); y<Get_NY() && SG_UI_Process_Set_Progress(y, Get_NY()); y++, yPosition+=Get_Cellsize()) { for(x=0, xPosition=Get_XMin(); x<Get_NX(); x++, xPosition+=Get_Cellsize()) { if( pGrid->Get_Value(xPosition, yPosition, z, Interpolation) ) { Set_Value (x, y, z); } else { Set_NoData(x, y); } } } Get_History() = pGrid->Get_History(); Get_History().Add_Child(SG_T("GRID_OPERATION"), CSG_String::Format(SG_T("%f -> %f"), pGrid->Get_Cellsize(), Get_Cellsize()))->Add_Property(SG_T("NAME"), LNG("Resampling")); SG_UI_Process_Set_Ready(); return( true ); }
bool CSG_Grid::Assign(CSG_Grid *pGrid, TSG_Grid_Interpolation Interpolation) { bool bResult = false; //----------------------------------------------------- if( is_Valid() && pGrid && pGrid->is_Valid() && is_Intersecting(pGrid->Get_Extent()) != INTERSECTION_None ) { if( Get_Cellsize() == pGrid->Get_Cellsize() // No-Scaling... && fmod(Get_XMin() - pGrid->Get_XMin(), Get_Cellsize()) == 0.0 && fmod(Get_YMin() - pGrid->Get_YMin(), Get_Cellsize()) == 0.0 ) { bResult = _Assign_Interpolated (pGrid, GRID_INTERPOLATION_NearestNeighbour); } else switch( Interpolation ) { case GRID_INTERPOLATION_NearestNeighbour: case GRID_INTERPOLATION_Bilinear: case GRID_INTERPOLATION_InverseDistance: case GRID_INTERPOLATION_BicubicSpline: case GRID_INTERPOLATION_BSpline: bResult = _Assign_Interpolated (pGrid, Interpolation); break; case GRID_INTERPOLATION_Mean_Nodes: case GRID_INTERPOLATION_Mean_Cells: bResult = _Assign_MeanValue (pGrid, Interpolation != GRID_INTERPOLATION_Mean_Nodes); break; case GRID_INTERPOLATION_Minimum: case GRID_INTERPOLATION_Maximum: bResult = _Assign_ExtremeValue (pGrid, Interpolation == GRID_INTERPOLATION_Maximum); break; default: if( Get_Cellsize() < pGrid->Get_Cellsize() ) // Down-Scaling... { bResult = _Assign_Interpolated (pGrid, GRID_INTERPOLATION_BSpline); } else // Up-Scaling... { bResult = _Assign_MeanValue (pGrid, Interpolation != GRID_INTERPOLATION_Mean_Nodes); } break; } //------------------------------------------------- if( bResult ) { // Set_Name (pGrid->Get_Name()); Set_Description (pGrid->Get_Description()); Set_Unit (pGrid->Get_Unit()); Set_ZFactor (pGrid->Get_ZFactor()); Set_NoData_Value_Range (pGrid->Get_NoData_Value(), pGrid->Get_NoData_hiValue()); } } //----------------------------------------------------- return( bResult ); }
//--------------------------------------------------------- bool CSG_Grid::_Assign_ExtremeValue(CSG_Grid *pGrid, bool bMaximum) { if( Get_Cellsize() < pGrid->Get_Cellsize() || is_Intersecting(pGrid->Get_Extent()) == INTERSECTION_None ) { return( false ); } //----------------------------------------------------- int x, y, ix, iy; double px, py, ax, ay, d, z; CSG_Matrix S(Get_NY(), Get_NX()), N(Get_NY(), Get_NX()); d = pGrid->Get_Cellsize() / Get_Cellsize(); Set_NoData_Value(pGrid->Get_NoData_Value()); Assign_NoData(); //----------------------------------------------------- ax = 0.5 + (pGrid->Get_XMin() - Get_XMin()) / Get_Cellsize(); ay = 0.5 + (pGrid->Get_YMin() - Get_YMin()) / Get_Cellsize(); for(y=0, py=ay; y<pGrid->Get_NY() && SG_UI_Process_Set_Progress(y, pGrid->Get_NY()); y++, py+=d) { if( (iy = (int)floor(py)) >= 0 && iy < Get_NY() ) { for(x=0, px=ax; x<pGrid->Get_NX(); x++, px+=d) { if( !pGrid->is_NoData(x, y) && (ix = (int)floor(px)) >= 0 && ix < Get_NX() ) { z = pGrid->asDouble(x, y); if( is_NoData(ix, iy) || (bMaximum == true && z > asDouble(ix, iy)) || (bMaximum == false && z < asDouble(ix, iy)) ) { Set_Value(ix, iy, z); } } } } } //----------------------------------------------------- Get_History() = pGrid->Get_History(); Get_History().Add_Child(SG_T("GRID_OPERATION"), CSG_String::Format(SG_T("%f -> %f"), pGrid->Get_Cellsize(), Get_Cellsize()))->Add_Property(SG_T("NAME"), LNG("Resampling")); SG_UI_Process_Set_Ready(); return( true ); }
//--------------------------------------------------------- bool CXYZ_Export::On_Execute(void) { bool bExNoData; int x, y, i; TSG_Point p; CSG_File Stream; CSG_String FileName; CSG_Parameter_Grid_List *pGrids; pGrids = Parameters("GRIDS") ->asGridList(); FileName = Parameters("FILENAME")->asString(); bExNoData = Parameters("EX_NODATA")->asBool(); if( pGrids->Get_Count() > 0 && Stream.Open(FileName, SG_FILE_W, false) ) { if( Parameters("CAPTION")->asBool() ) { Stream.Printf(SG_T("\"X\"\t\"Y\"")); for(i=0; i<pGrids->Get_Count(); i++) { Stream.Printf(SG_T("\t\"%s\""), pGrids->asGrid(i)->Get_Name()); } Stream.Printf(SG_T("\n")); } for(y=0, p.y=Get_YMin(); y<Get_NY() && Set_Progress(y); y++, p.y+=Get_Cellsize()) { for(x=0, p.x=Get_XMin(); x<Get_NX(); x++, p.x+=Get_Cellsize()) { if( !bExNoData || (bExNoData && !pGrids->asGrid(0)->is_NoData(x, y)) ) { Stream.Printf(SG_T("%f\t%f"), p.x, p.y); for(i=0; i<pGrids->Get_Count(); i++) { Stream.Printf(SG_T("\t%f"), pGrids->asGrid(i)->asDouble(x, y)); } Stream.Printf(SG_T("\n")); } } } return( true ); } return( false ); }
//--------------------------------------------------------- CvMat* COpenCV_NNet::GetEvalMatrix(CSG_Parameter_Grid_List *gl_grids, int type) { bool b_NoData; int x,y,i_Grid; CSG_Table *t_data; CSG_Table_Record *tr_rec; TSG_Point p; CvMat *mat; // We will use this table as a temporary data store, // since we cannot dynamically resize the CvMat t_data = new CSG_Table(); // We need a column for each grid and the output lable for (int i = 0; i < gl_grids->Get_Count(); i++) { t_data->Add_Field(CSG_String::Format(SG_T("GRID_%d"), i), SG_DATATYPE_Float, i); } // Traverse all grids, every point for(y=0, p.y=Get_YMin(); y<Get_NY() && Set_Progress(y); y++, p.y+=Get_Cellsize()) { for(x=0, p.x=Get_XMin(); x<Get_NX(); x++, p.x+=Get_Cellsize()) { for(i_Grid=0, b_NoData=false; i_Grid<gl_grids->Get_Count() && !b_NoData; i_Grid++) { // If there is one grid that has no data in this point p, then set the no data flag if( gl_grids->asGrid(i_Grid)->is_NoData(x, y) ) { b_NoData = true; } } if (!b_NoData) { // We have data in all grids, so lets add them to the eval data table tr_rec = t_data->Add_Record(); for(i_Grid=0; i_Grid<gl_grids->Get_Count(); i_Grid++) { tr_rec->Set_Value(i_Grid, (float) gl_grids->asGrid(i_Grid)->asFloat(x, y)); } } } } // Now create the matrix and add all data from the table to the matrix mat = GetEvalMatrix(t_data, type); return mat; }
//--------------------------------------------------------- bool CGrid_Mask::On_Execute(void) { CSG_Grid *pGrid = Parameters("GRID")->asGrid(); CSG_Grid *pMask = Parameters("MASK")->asGrid(); if( !pGrid->is_Intersecting(pMask->Get_Extent()) ) { Message_Add(_TL("no intersection with mask grid.")); return( false ); } //----------------------------------------------------- CSG_Grid *pMasked = Parameters("MASKED")->asGrid(); if( pMasked && pMasked != pGrid ) { pMasked->Create(*pGrid); pMasked->Fmt_Name("%s [%s]", pGrid->Get_Name(), _TL("masked")); pGrid = pMasked; } //----------------------------------------------------- Process_Set_Text(_TL("masking...")); for(int y=0; y<Get_NY() && Set_Progress(y); y++) { double py = Get_YMin() + y * Get_Cellsize(); #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { if( !pGrid->is_NoData(x, y) ) { double px = Get_XMin() + x * Get_Cellsize(); if( !pMask->is_InGrid_byPos(px, py) ) { pGrid->Set_NoData(x, y); } } } } //----------------------------------------------------- return( true ); }
//--------------------------------------------------------- bool CGrid_Completion::On_Execute(void) { int x, y; double xPos, yPos, Value; TSG_Grid_Interpolation Interpolation; CSG_Grid *pGrid, *pAdditional; pAdditional = Parameters("ADDITIONAL") ->asGrid(); pGrid = Parameters("COMPLETED") ->asGrid(); if( pGrid->is_Intersecting(pAdditional->Get_Extent()) ) { if( pGrid != Parameters("ORIGINAL")->asGrid() ) { Process_Set_Text(_TL("Copying original data...")); pGrid->Assign(Parameters("ORIGINAL")->asGrid()); } Interpolation = (TSG_Grid_Interpolation)Parameters("INTERPOLATION")->asInt(); Process_Set_Text(_TL("Data completion...")); for(y=0, yPos=Get_YMin(); y<Get_NY() && Set_Progress(y, Get_NY()); y++, yPos+=Get_Cellsize()) { if( yPos >= pAdditional->Get_YMin() ) { for(x=0, xPos=Get_XMin(); x<Get_NX() && xPos<=pAdditional->Get_XMax(); x++, xPos+=Get_Cellsize()) { if( pGrid->is_NoData(x, y) && xPos >= pAdditional->Get_XMin() ) { if( !pAdditional->is_NoData_Value(Value = pAdditional->Get_Value(xPos, yPos, Interpolation)) ) { pGrid->Set_Value(x, y, Value); } } } } } return( true ); } Error_Set(_TL("Nothing to do: there is no intersection with additonal grid.")); return( false ); }
//--------------------------------------------------------- bool CGWR_Grid_Downscaling::Set_Model(void) { CSG_Grid *pRegression = Parameters("REGRESSION" )->asGrid(); CSG_Grid *pReg_ResCorr = Parameters("REG_RESCORR")->asGrid(); pRegression->Set_Name(CSG_String::Format(SG_T("%s [%s]"), m_pDependent->Get_Name(), _TL("GWR"))); if( pReg_ResCorr ) { pReg_ResCorr->Set_Name(CSG_String::Format(SG_T("%s [%s, %s]"), m_pDependent->Get_Name(), _TL("GWR"), _TL("Residual Correction"))); } for(int y=0; y<Get_NY() && Set_Progress(y); y++) { double p_y = Get_YMin() + y * Get_Cellsize(); #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { double Value, Residual, p_x = Get_XMin() + x * Get_Cellsize(); if( Set_Model(p_x, p_y, Value, Residual) ) { pRegression->Set_Value(x, y, Value); if( pReg_ResCorr ) { pReg_ResCorr->Set_Value(x, y, Value + Residual); } } else { pRegression->Set_NoData(x, y); if( pReg_ResCorr ) { pReg_ResCorr->Set_NoData(x, y); } } } } return( true ); }
//--------------------------------------------------------- bool CGrid_Mask::On_Execute(void) { int x, y; double z; TSG_Point p; CSG_Grid *pGrid, *pMask, *pMasked; pGrid = Parameters("GRID") ->asGrid(); pMask = Parameters("MASK") ->asGrid(); pMasked = Parameters("MASKED") ->asGrid(); if( !pGrid->is_Intersecting(pMask->Get_Extent()) ) { Message_Add(_TL("no intersection with mask grid.")); return( false ); } if( pMasked == NULL ) { pMasked = pGrid; Parameters("MASKED")->Set_Value(pMasked); } else if( pMasked != pGrid ) { pMasked->Assign(pGrid); } Process_Set_Text(_TL("masking...")); for(y=0, p.y=Get_YMin(); y<Get_NY() && Set_Progress(y); y++, p.y+=Get_Cellsize()) { for(x=0, p.x=Get_XMin(); x<Get_NX(); x++, p.x+=Get_Cellsize()) { if( !pMasked->is_NoData(x, y) && !pMask->Get_Value(p, z, GRID_INTERPOLATION_NearestNeighbour) ) { pMasked->Set_NoData(x, y); } } } return( true ); }
//--------------------------------------------------------- void CGrid_3D_Image::_Set_Shapes(CSG_Shapes *pInput) { int iShape, iPart, iPoint; double x, y, z, dx, dy; T3DPoint p; TSG_Point Point; CSG_Shape *pShape; CSG_Shapes *pOutput; if( pInput && pInput->is_Valid() ) { Process_Set_Text("%s \"%s\"", _TL("Project"), pInput->Get_Name()); pOutput = SG_Create_Shapes(*pInput); dx = (double)Get_NX() / Get_System().Get_XRange(); dy = (double)Get_NY() / Get_System().Get_YRange(); for(iShape=0; iShape<pOutput->Get_Count() && Set_Progress(iShape, pOutput->Get_Count()); iShape++) { pShape = pOutput->Get_Shape(iShape); for(iPart=0; iPart<pShape->Get_Part_Count(); iPart++) { for(iPoint=0; iPoint<pShape->Get_Point_Count(iPart); iPoint++) { Point = pShape->Get_Point(iPoint, iPart); x = dx * (Point.x - Get_XMin()); y = dy * (Point.y - Get_YMin()); z = m_pDEM->is_InGrid((int)x, (int)y, true) ? m_pDEM->asDouble((int)x, (int)y) : 0.0; _Get_Position(x, y, z, p); pShape->Set_Point(p.x, p.y, iPoint, iPart); } } } DataObject_Add(pOutput); } }
//--------------------------------------------------------- bool CGW_Multi_Regression_Grid::Set_Model(void) { CSG_Grid *pRegression = Parameters("REGRESSION")->asGrid(); CSG_Grid *pQuality = Parameters("QUALITY" )->asGrid(); pRegression->Set_Name(CSG_String::Format(SG_T("%s [%s]" ), m_Points.Get_Name(), _TL("GWR"))); pQuality ->Set_Name(CSG_String::Format(SG_T("%s [%s, %s]"), m_Points.Get_Name(), _TL("GWR"), _TL("Quality"))); if( m_pQuality == Parameters("QUALITY")->asGrid() ) { pQuality = NULL; } //----------------------------------------------------- for(int y=0; y<Get_NY() && Set_Progress(y); y++) { double p_y = Get_YMin() + y * Get_Cellsize(); #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { double Value, p_x = Get_XMin() + x * Get_Cellsize(); if( Set_Model(p_x, p_y, Value) ) { GRID_SET_VALUE(pRegression, x, y, Value); GRID_SET_VALUE(pQuality , x, y, m_pQuality->Get_Value(p_x, p_y)); } else { GRID_SET_NODATA(pRegression, x, y); GRID_SET_NODATA(pQuality , x, y); } } } //----------------------------------------------------- Set_Residuals(); return( true ); }
//--------------------------------------------------------- bool CGrid_Classify_Supervised::Set_Classifier(CSG_Classifier_Supervised &Classifier, CSG_Shapes *pPolygons, int Field) { Process_Set_Text(_TL("training")); //----------------------------------------------------- TSG_Point p; p.y = Get_YMin(); for(int y=0; y<Get_NY() && Set_Progress(y); y++, p.y+=Get_Cellsize()) { p.x = Get_XMin(); for(int x=0; x<Get_NX(); x++, p.x+=Get_Cellsize()) { CSG_Vector Features(m_pFeatures->Get_Count()); if( Get_Features(x, y, Features) ) { for(int iPolygon=0; iPolygon<pPolygons->Get_Count(); iPolygon++) { CSG_Shape_Polygon *pPolygon = (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon); if( pPolygon->Contains(p) ) { Classifier.Train_Add_Sample(pPolygon->asString(Field), Features); } } } } } //----------------------------------------------------- if( Classifier.Train(true) ) { Classifier.Save(Parameters("FILE_SAVE")->asString()); return( true ); } return( false ); }
//--------------------------------------------------------- bool CMRVBF::Get_Flatness(CSG_Grid *pSlopes, CSG_Grid *pPercentiles, CSG_Grid *pCF, CSG_Grid *pVF, CSG_Grid *pRF, double T_Slope) { // const int Interpolation = GRID_INTERPOLATION_Bilinear; const int Interpolation = GRID_INTERPOLATION_BSpline; if( pSlopes && pSlopes->is_Valid() && pPercentiles && pPercentiles->is_Valid() ) { int x, y; double xp, yp, Slope, Percentile, cf, vf, rf; for(y=0, yp=Get_YMin(); y<Get_NY() && Set_Progress(y); y++, yp+=Get_Cellsize()) { for(x=0, xp=Get_XMin(); x<Get_NX(); x++, xp+=Get_Cellsize()) { if( pSlopes ->Get_Value(xp, yp, Slope , Interpolation) && pPercentiles->Get_Value(xp, yp, Percentile, Interpolation) ) { cf = pCF->asDouble(x, y) * Get_Transformation(Slope, T_Slope, m_P_Slope); vf = cf * Get_Transformation( Percentile, m_T_Pctl_V, m_P_Pctl); rf = cf * Get_Transformation(1.0 - Percentile, m_T_Pctl_R, m_P_Pctl); pCF->Set_Value (x, y, cf); pVF->Set_Value (x, y, 1.0 - Get_Transformation(vf, 0.3, 4.0)); pRF->Set_Value (x, y, 1.0 - Get_Transformation(rf, 0.3, 4.0)); } else { pVF->Set_NoData (x, y); pRF->Set_NoData (x, y); } } } return( true ); } return( false ); }
//--------------------------------------------------------- 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 ); }
//--------------------------------------------------------- bool COpenCV_NNet::On_Execute(void) { //------------------------------------------------- bool b_updateWeights, b_noInputScale, b_noOutputScale, b_NoData; int i_matType, i_layers, i_maxIter, i_neurons, i_areasClassId, i_trainFeatTotalCount, *i_outputFeatureIdxs, i_outputFeatureCount, i_Grid, x, y, i_evalOut, i_winner; double d_alpha, d_beta, d_eps; DATA_TYPE e_dataType; TRAINING_METHOD e_trainMet; ACTIVATION_FUNCTION e_actFunc; CSG_Table *t_Weights, *t_Indices, *t_TrainInput, *t_EvalInput, *t_EvalOutput; CSG_Parameter_Grid_List *gl_TrainInputs; CSG_Grid *g_EvalOutput, *g_EvalOutputCert; CSG_Shapes *s_TrainInputAreas; CSG_Parameters *p_TrainFeatures; TSG_Point p; CvMat *mat_Weights, *mat_Indices, **mat_data, *mat_neuralLayers, mat_layerSizesSub, *mat_EvalInput, *mat_EvalOutput; // todo: mat_indices to respect input indices, mat_weights for initialization CvANN_MLP_TrainParams tp_trainParams; CvANN_MLP model; b_updateWeights = Parameters("UPDATE_WEIGHTS" )->asBool(); b_noInputScale = Parameters("NO_INPUT_SCALE" )->asBool(); b_noOutputScale = Parameters("NO_OUTPUT_SCALE" )->asBool(); i_layers = Parameters("NNET_LAYER" )->asInt(); i_neurons = Parameters("NNET_NEURONS" )->asInt(); i_maxIter = Parameters("MAX_ITER" )->asInt(); i_areasClassId = Parameters("TRAIN_INPUT_AREAS_CLASS_FIELD" )->asInt(); e_dataType = (DATA_TYPE)Parameters("DATA_TYPE" )->asInt(); e_trainMet = (TRAINING_METHOD)Parameters("TRAINING_METHOD" )->asInt(); e_actFunc = (ACTIVATION_FUNCTION)Parameters("ACTIVATION_FUNCTION" )->asInt(); d_alpha = Parameters("ALPHA" )->asDouble(); d_beta = Parameters("BETA" )->asDouble(); d_eps = Parameters("EPSILON" )->asDouble(); t_Weights = Parameters("WEIGHTS" )->asTable(); t_Indices = Parameters("INDICES" )->asTable(); t_TrainInput = Parameters("TRAIN_INPUT_TABLE" )->asTable(); t_EvalInput = Parameters("EVAL_INPUT_TABLE" )->asTable(); t_EvalOutput = Parameters("EVAL_OUTPUT_TABLE" )->asTable(); p_TrainFeatures = Parameters("TRAIN_FEATURES_TABLE" )->asParameters(); gl_TrainInputs = Parameters("TRAIN_INPUT_GRIDS" )->asGridList(); g_EvalOutput = Parameters("EVAL_OUTPUT_GRID_CLASSES" )->asGrid(); g_EvalOutputCert = Parameters("EVAL_OUTPUT_GRID_CERTAINTY" )->asGrid(); s_TrainInputAreas = Parameters("TRAIN_INPUT_AREAS" )->asShapes(); // Fixed matrix type (TODO: Analyze what to do for other types of data (i.e. images)) i_matType = CV_32FC1; //------------------------------------------------- if (e_dataType == TABLE) { // We are working with TABLE data if( t_TrainInput->Get_Count() == 0 || p_TrainFeatures->Get_Count() == 0 ) { Error_Set(_TL("Select an input table and at least one output feature!")); return( false ); } // Count the total number of available features i_trainFeatTotalCount = t_TrainInput->Get_Field_Count(); // Count the number of selected output features i_outputFeatureIdxs = (int *)SG_Calloc(i_trainFeatTotalCount, sizeof(int)); i_outputFeatureCount = 0; for(int i=0; i<p_TrainFeatures->Get_Count(); i++) { if( p_TrainFeatures->Get_Parameter(i)->asBool() ) { i_outputFeatureIdxs[i_outputFeatureCount++] = CSG_String(p_TrainFeatures->Get_Parameter(i)->Get_Identifier()).asInt(); } } // Update the number of training features i_trainFeatTotalCount = i_trainFeatTotalCount-i_outputFeatureCount; if( i_outputFeatureCount <= 0 ) { Error_Set(_TL("Select at least one output feature!")); return( false ); } // Now convert the input and output training data into a OpenCV matrix objects mat_data = GetTrainAndOutputMatrix(t_TrainInput, i_matType, i_outputFeatureIdxs, i_outputFeatureCount); } else { // TODO: Add some grid validation logic i_trainFeatTotalCount = gl_TrainInputs->Get_Count(); i_outputFeatureCount = s_TrainInputAreas->Get_Count(); // Convert the data from the grid into the matrix from mat_data = GetTrainAndOutputMatrix(gl_TrainInputs, i_matType, s_TrainInputAreas, i_areasClassId, g_EvalOutput, g_EvalOutputCert); } //------------------------------------------------- // Add two additional layer to the network topology (0-th layer for input and the last as the output) i_layers = i_layers + 2; mat_neuralLayers = cvCreateMat(i_layers, 1, CV_32SC1); cvGetRows(mat_neuralLayers, &mat_layerSizesSub, 0, i_layers); //Setting the number of neurons on each layer for (int i = 0; i < i_layers; i++) { if (i == 0) { // The first layer needs the same size (number of nerons) as the number of columns in the training data cvSet1D(&mat_layerSizesSub, i, cvScalar(i_trainFeatTotalCount)); } else if (i == i_layers-1) { // The last layer needs the same size (number of neurons) as the number of output columns cvSet1D(&mat_layerSizesSub, i, cvScalar(i_outputFeatureCount)); } else { // On every other layer set the layer size selected by the user cvSet1D(&mat_layerSizesSub, i, cvScalar(i_neurons)); } } //------------------------------------------------- // Create the training params object tp_trainParams = CvANN_MLP_TrainParams(); tp_trainParams.term_crit = cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, i_maxIter, d_eps); // Check which training method was selected and set corresponding params if(e_trainMet == RPROP) { // Set all RPROP specific params tp_trainParams.train_method = CvANN_MLP_TrainParams::RPROP; tp_trainParams.rp_dw0 = Parameters("RP_DW0" )->asDouble(); tp_trainParams.rp_dw_plus = Parameters("RP_DW_PLUS" )->asDouble(); tp_trainParams.rp_dw_minus = Parameters("RP_DW_MINUS" )->asDouble(); tp_trainParams.rp_dw_min = Parameters("RP_DW_MIN" )->asDouble(); tp_trainParams.rp_dw_max = Parameters("RP_DW_MAX" )->asDouble(); } else { // Set all BPROP specific params tp_trainParams.train_method = CvANN_MLP_TrainParams::BACKPROP; tp_trainParams.bp_dw_scale = Parameters("BP_DW_SCALE" )->asDouble(); tp_trainParams.bp_moment_scale = Parameters("BP_MOMENT_SCALE" )->asInt(); } //------------------------------------------------- // Create the model (depending on the activation function) if(e_actFunc == SIGMOID) { model.create(mat_neuralLayers); } else { model.create(mat_neuralLayers, CvANN_MLP::GAUSSIAN, d_alpha, d_beta); } //------------------------------------------------- // Now train the network // TODO: Integrate init weights and indicies for record selection // mat_Weights = GetMatrix(t_Weights, i_matType); // mat_Indices = GetMatrix(t_Indices, i_matType); //model.train(mat_TrainInput, mat_TrainOutput, NULL, NULL, tp_trainParams); model.train(mat_data[0], mat_data[1], NULL, NULL, tp_trainParams); //------------------------------------------------- // Predict data if (e_dataType == TABLE) { // Get the eavaluation/test matrix from the eval table mat_EvalInput = GetEvalMatrix(t_EvalInput, i_matType); } else { // Train and eval data overlap in grid mode mat_EvalInput = GetEvalMatrix(gl_TrainInputs, i_matType); } // Prepare output matrix mat_EvalOutput = cvCreateMat(mat_EvalInput->rows, i_outputFeatureCount, i_matType); // Start prediction model.predict(mat_EvalInput, mat_EvalOutput); Message_Add(_TL("Successfully trained the network and predicted the values. Here comes the output.")); //------------------------------------------------- // Save and print results if (e_dataType == TABLE) { // DEBUG -> Save results to output table and print results for (int i = 0; i < i_outputFeatureCount; i++) { t_EvalOutput->Add_Field(CSG_String(t_TrainInput->Get_Field_Name(i_outputFeatureIdxs[i])), SG_DATATYPE_Float); } for (int i = 0; i < mat_EvalOutput->rows; i++) { CSG_Table_Record* tr_record = t_EvalOutput->Add_Record(); for (int j = 0; j < i_outputFeatureCount; j++) { float f_targetValue = mat_EvalOutput->data.fl[i*i_outputFeatureCount+j]; tr_record->Set_Value(j, f_targetValue); } } } else { // Fill the output table output for (int i = 0; i < i_outputFeatureCount; i++) { // TODO: Get the class name t_EvalOutput->Add_Field(CSG_String::Format(SG_T("CLASS_%d"), i), SG_DATATYPE_Float); } for (int i = 0; i < mat_EvalOutput->rows; i++) { CSG_Table_Record* tr_record = t_EvalOutput->Add_Record(); for (int j = 0; j < i_outputFeatureCount; j++) { float f_targetValue = mat_EvalOutput->data.fl[i*i_outputFeatureCount+j]; tr_record->Set_Value(j, f_targetValue); } } i_evalOut = 0; // Fill the output grid for(y=0, p.y=Get_YMin(); y<Get_NY() && Set_Progress(y); y++, p.y+=Get_Cellsize()) { for(x=0, p.x=Get_XMin(); x<Get_NX(); x++, p.x+=Get_Cellsize()) { for(i_Grid=0, b_NoData=false; i_Grid<gl_TrainInputs->Get_Count() && !b_NoData; i_Grid++) { // If there is one grid that has no data in this point p, then set the no data flag if( gl_TrainInputs->asGrid(i_Grid)->is_NoData(x, y) ) { b_NoData = true; } } if (!b_NoData) { // We have data in all grids, so this is a point that was predicted // Get the winner class for this point and set it to the output grid float f_targetValue = 0; for (int j = 0; j < i_outputFeatureCount; j++) { if (mat_EvalOutput->data.fl[i_evalOut*i_outputFeatureCount+j] > f_targetValue) { // The current value is higher than the last one, so lets memorize the current class f_targetValue = mat_EvalOutput->data.fl[i_evalOut*i_outputFeatureCount+j]; i_winner = j; } } // Now finally set the values to the grids g_EvalOutput->Set_Value(x, y, i_winner); g_EvalOutputCert->Set_Value(x, y, f_targetValue); i_evalOut++; } } } } return( true ); }
//--------------------------------------------------------- bool CTC_Parameter_Base::Get_Parameter(CSG_Grid *pValues, CSG_Grid *pParameter) { DataObject_Set_Colors(pParameter, 10, SG_COLORS_RED_GREY_BLUE, true); //----------------------------------------------------- if( Parameters("METHOD")->asInt() == 0 ) { m_Kernel.Get_Weighting().Set_Parameters(&Parameters); m_Kernel.Get_Weighting().Set_BandWidth(Parameters("SCALE")->asDouble() * m_Kernel.Get_Weighting().Get_BandWidth()); m_Kernel.Set_Radius(Parameters("SCALE")->asDouble()); for(int y=0; y<Get_NY() && Set_Progress(y); y++) { #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { if( pValues->is_NoData(x, y) ) { pParameter->Set_NoData(x, y); } else { double d, w, nTotal = 0.0, nValid = 0.0; for(int i=0, ix, iy; i<m_Kernel.Get_Count(); i++) { if( m_Kernel.Get_Values(i, ix = x, iy = y, d, w, true) && pValues->is_InGrid(ix, iy) ) { nTotal += w; if( pValues->asInt(ix, iy) != 0 ) { nValid += w; } } } pParameter->Set_Value(x, y, nTotal > 0.0 ? 100.0 * nValid / nTotal : 0.0); // make percentage } } } m_Kernel.Destroy(); } //----------------------------------------------------- else { double Cellsize = Parameters("SCALE")->asInt() * Get_Cellsize(); if( Cellsize > 0.5 * SG_Get_Length(Get_System()->Get_XRange(), Get_System()->Get_YRange()) ) { Error_Set(_TL("resampling cell size is too large")); return( false ); } CSG_Grid Values(CSG_Grid_System(Cellsize, Get_XMin(), Get_YMin(), Get_XMax(), Get_YMax()), SG_DATATYPE_Float); Values.Assign(pValues, GRID_RESAMPLING_Mean_Cells); for(int y=0; y<Get_NY() && Set_Progress(y); y++) { double py = Get_YMin() + y * Get_Cellsize(); #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { double z, px = Get_XMin() + x * Get_Cellsize(); if( pValues->is_NoData(x, y) || !Values.Get_Value(px, py, z, GRID_RESAMPLING_BSpline) ) { pParameter->Set_NoData(x, y); } else { pParameter->Set_Value(x, y, 100.0 * z); // make percentage } } } } //----------------------------------------------------- return( true ); }
//--------------------------------------------------------- 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 CTIN_From_Grid_Specific_Points::On_Execute(void) { bool bResult; int x, y, i; CSG_TIN *pTIN; CSG_Grid *pGrid, Grid; CSG_Parameter_Grid_List *pValues; CSG_Shape *pPoint; CSG_Shapes Points; //----------------------------------------------------- pGrid = Parameters("GRID")->asGrid(); Grid.Create(pGrid, SG_DATATYPE_Byte); //----------------------------------------------------- switch( Parameters("METHOD")->asInt() ) { default: bResult = false; break; case 0: bResult = Get_MarkHighestNB (&Grid, pGrid); break; case 1: bResult = Get_OppositeNB (&Grid, pGrid, Parameters("HIGH")->asInt()); break; case 2: bResult = Get_FlowDirection (&Grid, pGrid, (int)Parameters("FLOW")->asRange()->Get_LoVal(), (int)Parameters("FLOW")->asRange()->Get_HiVal() ); break; case 3: bResult = Get_FlowDirection2(&Grid, pGrid, (int)Parameters("FLOW")->asRange()->Get_HiVal() ); break; case 4: bResult = Get_Peucker (&Grid, pGrid, Parameters("PEUCKER")->asDouble()); break; } //----------------------------------------------------- if( bResult ) { pValues = Parameters("VALUES")->asGridList(); Points.Create(SHAPE_TYPE_Point); Points.Add_Field(_TL("VALUE"), SG_DATATYPE_Double); for(i=0; i<pValues->Get_Count(); i++) { Points.Add_Field(pValues->asGrid(i)->Get_Name(), SG_DATATYPE_Double); } for(y=0; y<Get_NY() && Set_Progress(y, Get_NY()); y++) { for(x=0; x<Get_NX(); x++) { if( Grid.asInt(x, y) != 0 ) { pPoint = Points.Add_Shape(); pPoint->Add_Point( Get_XMin() + Get_Cellsize() * x, Get_YMin() + Get_Cellsize() * y ); pPoint->Set_Value(0, pGrid->asDouble(x, y)); for(i=0; i<pValues->Get_Count(); i++) { pPoint->Set_Value(1 + i, pValues->asGrid(i)->asDouble(x, y)); } } } } //------------------------------------------------- if( Points.Get_Count() >= 3 ) { pTIN = Parameters("TIN")->asTIN(); pTIN->Create(&Points); pTIN->Set_Name(pGrid->Get_Name()); } } return( bResult ); }
//--------------------------------------------------------- // This function is executed if the user is pressing the OK button //--------------------------------------------------------- bool CGrid_Polygon_Clip::On_Execute(void) { int x, y, ix, iy, ax, ay, nx, ny; CSG_Parameter_Grid_List *pGrids_in, *pGrids_out; CSG_Grid *pGrid_in, *pGrid_out, Mask; CSG_Shapes *pShapes; //----------------------------------------------------- pGrids_in = Parameters("INPUT" )->asGridList(); pGrids_out = Parameters("OUTPUT" )->asGridList(); pShapes = Parameters("POLYGONS")->asShapes(); m_bNoData = Parameters("NODATA" )->asBool(); //----------------------------------------------------- if( pShapes->Get_Type() == SHAPE_TYPE_Polygon && pShapes->Get_Count() > 0 && Get_System()->Get_Extent().Intersects(pShapes->Get_Extent()) ) { // create temporary grid. // Cells within the shapefile get the value +1 // Cells outside the shapefile get the value -1 Mask.Create(*Get_System(), SG_DATATYPE_Byte); //------------------------------------------------- // Get_Mask assignes +1 values to gridcells within the shapefile // The function has been copied from Module: 'Grid_Statistics_AddTo_Polygon' // Function: Get_ShapeIDs(...) // and check extent of valid values in Mask to // calculate GridSystem parameters pGrid_out if( Get_Mask(pShapes, &Mask) && Get_Extent(ax, nx, ay, ny, &Mask, pGrids_in) ) { for(int iGrid=0; iGrid<pGrids_in->Get_Count(); iGrid++) { pGrid_in = pGrids_in->asGrid(iGrid); pGrid_out = SG_Create_Grid( // creating the output grid GridSystem pGrid_in->Get_Type(), nx, ny, Get_Cellsize(), Get_XMin() + ax * Get_Cellsize(), Get_YMin() + ay * Get_Cellsize() ); pGrid_out ->Set_Name(pGrid_in->Get_Name()); pGrid_out ->Set_NoData_Value(pGrid_in->Get_NoData_Value()); pGrids_out ->Add_Item(pGrid_out); // Assign valid values from input grid to the cells of the // output grid that are within the borders of the shapefile // Assign NoData values to the cells outside the shapefile borders for(y=0, iy=ay; y<ny && Set_Progress(y, ny); y++, iy++) { for(x=0, ix=ax; x<nx; x++, ix++) { if( Mask.asDouble(ix, iy) == MASK_ON ) // -1 = NoData_Value { pGrid_out->Set_Value(x, y, pGrid_in->asDouble(ix, iy)); } else { pGrid_out->Set_NoData(x, y); } } } } return( true ); } } return( false ); }
//--------------------------------------------------------- bool CCropToData::On_Execute(void) { CSG_Parameter_Grid_List *pGrids = Parameters("INPUT")->asGridList(); //----------------------------------------------------- if( pGrids->Get_Count() <= 0 ) { Error_Set(_TL("no grids in selection")); return( false ); } //----------------------------------------------------- bool bCrop = false; int xMin, yMin, xMax, yMax; //----------------------------------------------------- for(int y=0; y<Get_NY() && Set_Progress(y); y++) { for(int x=0; x<Get_NX(); x++) { bool bData = false; for(int i=0; i<pGrids->Get_Count() && !bData; i++) { if( !pGrids->asGrid(i)->is_NoData(x, y) ) { bData = true; } } if( bData ) { if( bCrop == false ) { bCrop = true; 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; } } } } } //----------------------------------------------------- if( bCrop == false ) { Message_Add(CSG_String::Format(SG_T("%s: %s"), _TL("nothing to crop"), _TL("no valid data found in grid(s)"))); } else if( (1 + xMax - xMin) == Get_NX() && (1 + yMax - yMin) == Get_NY() ) { Message_Add(CSG_String::Format(SG_T("%s: %s"), _TL("nothing to crop"), _TL("valid data cells match original grid extent"))); } else { CSG_Parameter_Grid_List *pCropped = Parameters("OUTPUT")->asGridList(); pCropped->Del_Items(); for(int i=0; i<pGrids->Get_Count(); i++) { CSG_Grid *pGrid = SG_Create_Grid( pGrids->asGrid(i)->Get_Type(), 1 + xMax - xMin, 1 + yMax - yMin, Get_Cellsize(), Get_XMin() + xMin * Get_Cellsize(), Get_YMin() + yMin * Get_Cellsize() ); pGrid->Assign(pGrids->asGrid(i), GRID_INTERPOLATION_NearestNeighbour); pGrid->Set_Name(pGrids->asGrid(i)->Get_Name()); pCropped->Add_Item(pGrid); } } //----------------------------------------------------- return( true ); }
//--------------------------------------------------------- CSG_Shape * CWatersheds_ext::Get_Basin(CSG_Grid *pBasins, CSG_Shapes *pPolygons) { int x, y, nEdges, Basin_ID; CSG_Grid Edge; CSG_Shape *pPolygon = NULL; Basin_ID = 1 + pPolygons->Get_Count(); //----------------------------------------------------- Edge.Create(SG_DATATYPE_Char, 2 * Get_NX() + 1, 2 * Get_NY() + 1, 0.5 * Get_Cellsize(), Get_XMin() - 0.5 * Get_Cellsize(), Get_YMin() - 0.5 * Get_Cellsize()); Edge.Set_NoData_Value(0); for(y=0, nEdges=0; y<Get_NY() && Process_Get_Okay(); y++) { for(x=0; x<Get_NX(); x++) { if( pBasins->asInt(x, y) == Basin_ID ) { for(int i=0; i<8; i+=2) { int ix = Get_xTo(i, x); int iy = Get_yTo(i, y); if( !is_InGrid(ix, iy) || pBasins->asInt(ix, iy) != Basin_ID ) { ix = 1 + 2 * x; iy = 1 + 2 * y; Edge.Set_Value( ix, iy , 1); Edge.Set_Value(Get_xTo(i , ix), Get_yTo(i , iy), -1); Edge.Set_Value(Get_xTo(i - 1, ix), Get_yTo(i - 1, iy), -1); nEdges++; } } } } } //----------------------------------------------------- if( nEdges > 0 ) { for(int yEdge=0; yEdge<Edge.Get_NY(); yEdge++) for(int xEdge=0; xEdge<Edge.Get_NX(); xEdge++) { int i = 4; if( Edge.asInt(xEdge, yEdge) == 1 && Edge.asInt(Get_xTo(i, xEdge), Get_yTo(i, yEdge)) == -1 ) { if( pPolygon == NULL ) { pPolygon = pPolygons->Add_Shape(); } int iPart = pPolygon->Get_Part_Count(); int xFirst = x = Get_xTo(i, xEdge); int yFirst = y = Get_yTo(i, yEdge); i = i + 2; pPolygon ->Add_Point(Edge.Get_System().Get_Grid_to_World(x, y), iPart); do { int ix = Get_xTo(i + 2, x); int iy = Get_yTo(i + 2, y); if( Edge.is_InGrid(ix, iy) && Edge.asInt(ix, iy) == -1 ) // go right ? { pPolygon->Add_Point(Edge.Get_System().Get_Grid_to_World(x, y), iPart); i = (i + 2) % 8; } else { if( Edge.asInt(ix, iy) == 1 ) { Edge.Set_NoData(ix, iy); // erase class id in right cells } ix = Get_xTo(i, x); iy = Get_yTo(i, y); if( Edge.is_InGrid(ix, iy) && Edge.asInt(ix, iy) == -1 ) // go ahead ? { // nop } else { ix = Get_xTo(i + 6, x); iy = Get_yTo(i + 6, y); if( Edge.is_InGrid(ix, iy) && Edge.asInt(ix, iy) == -1 ) // go left ? { pPolygon->Add_Point(Edge.Get_System().Get_Grid_to_World(x, y), iPart); i = (i + 6) % 8; } else { return( false ); } } } x = ix; y = iy; } while( x != xFirst || y != yFirst ); pPolygon->Add_Point(Edge.Get_System().Get_Grid_to_World(x, y), iPart); } } } //----------------------------------------------------- return( pPolygon ); }
//--------------------------------------------------------- bool CSADO_SolarRadiation::Initialise(void) { int x, y; Process_Set_Text(_TL("initialising...")); //----------------------------------------------------- CSG_Colors c(100, SG_COLORS_YELLOW_RED, true); c.Set_Ramp(SG_GET_RGB( 0, 0, 64), SG_GET_RGB(255, 159, 0), 0, 50); c.Set_Ramp(SG_GET_RGB(255, 159, 0), SG_GET_RGB(255, 255, 255), 50, 99); if( m_pSumDirect ) { m_pSumDirect->Assign(0.0); m_pSumDirect->Set_Unit(_TL("Joule")); DataObject_Set_Colors(m_pSumDirect, c); if( m_bUpdateDirect ) { m_TmpDirect.Create(*Get_System(), SG_DATATYPE_Float); DataObject_Update(m_pSumDirect, true); } } if( m_pSumDiffus ) { m_pSumDiffus->Assign(0.0); m_pSumDiffus->Set_Unit(_TL("Joule")); DataObject_Set_Colors(m_pSumDiffus, c); if( m_bUpdateDiffus ) { m_TmpDiffus.Create(*Get_System(), SG_DATATYPE_Float); DataObject_Update(m_pSumDiffus, true); } } if( m_pSumTotal ) { m_pSumTotal ->Assign(0.0); m_pSumTotal ->Set_Unit(_TL("Joule")); DataObject_Set_Colors(m_pSumTotal , c); if( m_bUpdateTotal ) { m_TmpTotal.Create(*Get_System(), SG_DATATYPE_Float); DataObject_Update(m_pSumTotal , true); } } //----------------------------------------------------- Process_Set_Text(_TL("initialising gradient...")); m_Shade .Create(*Get_System(), SG_DATATYPE_Byte); m_Slope .Create(*Get_System(), SG_DATATYPE_Float); m_Aspect.Create(*Get_System(), SG_DATATYPE_Float); for(y=0; y<Get_NY() && Set_Progress(y); y++) { for(x=0; x<Get_NX(); x++) { double s, a; if( m_pDEM->Get_Gradient(x, y, s, a) ) { m_Slope .Set_Value(x, y, s); m_Aspect.Set_Value(x, y, a); } else { m_Slope .Set_NoData(x, y); m_Aspect.Set_NoData(x, y); } } } //----------------------------------------------------- if( m_bBending ) { Process_Set_Text(_TL("initialising planetary bending...")); CSG_Grid *pLat = Parameters("GRD_LAT")->asGrid(), *pLon = Parameters("GRD_LON")->asGrid(); m_Lat .Create(*Get_System(), SG_DATATYPE_Float); m_Lon .Create(*Get_System(), SG_DATATYPE_Float); m_Decline .Create(*Get_System(), SG_DATATYPE_Float); m_Azimuth .Create(*Get_System(), SG_DATATYPE_Float); if( pLat || pLon ) { if( pLat ) { m_Lat = *pLat; m_Lat *= M_DEG_TO_RAD; } if( pLon ) { m_Lon = *pLon; m_Lon *= M_DEG_TO_RAD; } } //------------------------------------------------- else { double d, dx, dy, dxA, dyA; d = M_DEG_TO_RAD / (Parameters("RADIUS")->asDouble() * M_PI / 180.0); switch( Parameters("LON_OFFSET")->asInt() ) { case 0: dxA = Get_System()->Get_Extent().Get_XMin(); break; // left case 1: dxA = Get_System()->Get_Extent().Get_XCenter(); break; // center case 2: dxA = Get_System()->Get_Extent().Get_XMax(); break; // right case 3: dxA = Parameters("LON_REF_USER")->asDouble(); break; // user defined coordinate } switch( Parameters("LAT_OFFSET")->asInt() ) { case 0: dyA = Get_System()->Get_Extent().Get_YMin(); break; // bottom case 1: dyA = Get_System()->Get_Extent().Get_YCenter(); break; // center case 2: dyA = Get_System()->Get_Extent().Get_YMax(); break; // top case 3: dyA = Parameters("LAT_REF_USER")->asDouble(); break; // user defined coordinate } dxA = d * (Get_XMin() - dxA); dyA = d * (Get_YMin() - dyA) + m_Latitude; d *= Get_Cellsize(); for(y=0, dy=dyA; y<Get_NY() && Set_Progress(y); y++, dy+=d) { for(x=0, dx=dxA; x<Get_NX(); x++, dx+=d) { m_Lat.Set_Value(x, y, dy); m_Lon.Set_Value(x, y, dx); } } } } //----------------------------------------------------- return( true ); }
//--------------------------------------------------------- CSG_Grid & CSG_Grid::_Operation_Arithmetic(const CSG_Grid &Grid, TSG_Grid_Operation Operation) { if( is_Intersecting(Grid.Get_Extent()) ) { int x, y; double xWorld, yWorld, Value; TSG_Grid_Interpolation Interpolation; Interpolation = Get_Cellsize() == Grid.Get_Cellsize() && fmod(Get_XMin() - Grid.Get_XMin(), Get_Cellsize()) == 0.0 && Get_Cellsize() == Grid.Get_Cellsize() && fmod(Get_YMin() - Grid.Get_YMin(), Get_Cellsize()) == 0.0 ? GRID_INTERPOLATION_NearestNeighbour : GRID_INTERPOLATION_BSpline; for(y=0, yWorld=Get_YMin(); y<Get_NY() && SG_UI_Process_Set_Progress(y, Get_NY()); y++, yWorld+=Get_Cellsize()) { for(x=0, xWorld=Get_XMin(); x<Get_NX(); x++, xWorld+=Get_Cellsize()) { if( !Grid.Get_Value(xWorld, yWorld, Value, Interpolation, true) ) { Set_NoData(x, y); } else switch( Operation ) { case GRID_OPERATION_Addition: Add_Value(x, y, Value); break; case GRID_OPERATION_Subtraction: Add_Value(x, y, -Value); break; case GRID_OPERATION_Multiplication: Mul_Value(x, y, Value); break; case GRID_OPERATION_Division: if( Value != 0.0 ) { Mul_Value(x, y, 1.0 / Value); } else { Set_NoData(x, y); } break; } } } SG_UI_Process_Set_Ready(); //------------------------------------------------- switch( Operation ) { case GRID_OPERATION_Addition: Get_History().Add_Child(SG_T("GRID_OPERATION"), Grid.Get_Name())->Add_Property(SG_T("NAME"), LNG("Addition")); break; case GRID_OPERATION_Subtraction: Get_History().Add_Child(SG_T("GRID_OPERATION"), Grid.Get_Name())->Add_Property(SG_T("NAME"), LNG("Subtraction")); break; case GRID_OPERATION_Multiplication: Get_History().Add_Child(SG_T("GRID_OPERATION"), Grid.Get_Name())->Add_Property(SG_T("NAME"), LNG("Multiplication")); break; case GRID_OPERATION_Division: Get_History().Add_Child(SG_T("GRID_OPERATION"), Grid.Get_Name())->Add_Property(SG_T("NAME"), LNG("Division")); break; } Get_History() += ((CSG_Grid *)&Grid)->Get_History(); } return( *this ); }
//--------------------------------------------------------- bool CSG_Grid::_Assign_MeanValue(CSG_Grid *pGrid, bool bAreaProportional) { if( Get_Cellsize() < pGrid->Get_Cellsize() || is_Intersecting(pGrid->Get_Extent()) == INTERSECTION_None ) { return( false ); } //----------------------------------------------------- int x, y, ix, iy, jx, jy; double px, py, ax, ay, d, w, wx, wy, z; CSG_Matrix S(Get_NY(), Get_NX()), N(Get_NY(), Get_NX()); d = pGrid->Get_Cellsize() / Get_Cellsize(); Set_NoData_Value(pGrid->Get_NoData_Value()); Assign_NoData(); //----------------------------------------------------- if( bAreaProportional == false ) { ax = 0.5 + (pGrid->Get_XMin() - Get_XMin()) / Get_Cellsize(); ay = 0.5 + (pGrid->Get_YMin() - Get_YMin()) / Get_Cellsize(); for(y=0, py=ay; y<pGrid->Get_NY() && SG_UI_Process_Set_Progress(y, pGrid->Get_NY()); y++, py+=d) { if( (iy = (int)floor(py)) >= 0 && iy < Get_NY() ) { for(x=0, px=ax; x<pGrid->Get_NX(); x++, px+=d) { if( !pGrid->is_NoData(x, y) && (ix = (int)floor(px)) >= 0 && ix < Get_NX() ) { S[ix][iy] += pGrid->asDouble(x, y); N[ix][iy] ++; } } } } } //----------------------------------------------------- else // if( bAreaProportional == true ) { ax = ((pGrid->Get_XMin() - 0.5 * pGrid->Get_Cellsize()) - (Get_XMin() - 0.5 * Get_Cellsize())) / Get_Cellsize(); ay = ((pGrid->Get_YMin() - 0.5 * pGrid->Get_Cellsize()) - (Get_YMin() - 0.5 * Get_Cellsize())) / Get_Cellsize(); for(y=0, py=ay; y<pGrid->Get_NY() && SG_UI_Process_Set_Progress(y, pGrid->Get_NY()); y++, py+=d) { if( py > -d || py < Get_NY() ) { iy = (int)floor(py); wy = (py + d) - iy; wy = wy < 1.0 ? 1.0 : wy - 1.0; for(x=0, px=ax; x<pGrid->Get_NX(); x++, px+=d) { if( !pGrid->is_NoData(x, y) && (px > -d && px < Get_NX()) ) { ix = (int)floor(px); wx = (px + d) - ix; wx = wx < 1.0 ? 1.0 : wx - 1.0; z = pGrid->asDouble(x, y); if( iy >= 0 && iy < Get_NY() ) // wy > 0.0 is always true { if( ix >= 0 && ix < Get_NX() ) // wx > 0.0 is always true { w = wx * wy; S[ix][iy] += w * z; N[ix][iy] += w; } if( wx < 1.0 && (jx = ix + 1) >= 0 && jx < Get_NX() ) { w = (1.0 - wx) * wy; S[jx][iy] += w * z; N[jx][iy] += w; } } if( wy < 1.0 && (jy = iy + 1) >= 0 && jy < Get_NY() ) { if( ix >= 0 && ix < Get_NX() ) { w = wx * (1.0 - wy); S[ix][jy] += w * z; N[ix][jy] += w; } if( wx < 1.0 && (jx = ix + 1) >= 0 && jx < Get_NX() ) { w = (1.0 - wx) * (1.0 - wy); S[jx][jy] += w * z; N[jx][jy] += w; } } } } } } } //----------------------------------------------------- for(y=0; y<Get_NY() && SG_UI_Process_Set_Progress(y, Get_NY()); y++) { for(x=0; x<Get_NX(); x++) { if( N[x][y] ) { Set_Value(x, y, S[x][y] / N[x][y]); } else { Set_NoData(x, y); } } } //----------------------------------------------------- Get_History() = pGrid->Get_History(); Get_History().Add_Child(SG_T("GRID_OPERATION"), CSG_String::Format(SG_T("%f -> %f"), pGrid->Get_Cellsize(), Get_Cellsize()))->Add_Property(SG_T("NAME"), LNG("Resampling")); SG_UI_Process_Set_Ready(); return( true ); }
//--------------------------------------------------------- bool CGrid_Gaps_Resampling::On_Execute(void) { //----------------------------------------------------- CSG_Grid *pGrid = Parameters("RESULT")->asGrid(); CSG_Grid *pMask = Parameters("MASK" )->asGrid(); if( pGrid == NULL ) { pGrid = Parameters("INPUT")->asGrid(); } else { pGrid->Assign(Parameters("INPUT")->asGrid()); pGrid->Fmt_Name("%s [%s]", Parameters("INPUT")->asGrid()->Get_Name(), _TL("no gaps")); } //----------------------------------------------------- TSG_Grid_Resampling Resampling; switch( Parameters("RESAMPLING")->asInt() ) { default: Resampling = GRID_RESAMPLING_NearestNeighbour; break; case 1: Resampling = GRID_RESAMPLING_Bilinear ; break; case 2: Resampling = GRID_RESAMPLING_BicubicSpline ; break; case 3: Resampling = GRID_RESAMPLING_BSpline ; break; } //----------------------------------------------------- CSG_Grid_Pyramid Pyramid; if( !Pyramid.Create(pGrid, Parameters("GROW")->asDouble()) ) { Error_Set(_TL("failed to create pyramid")); return( false ); } //----------------------------------------------------- for(int y=0; y<Get_NY() && Set_Progress(y); y++) { double py = Get_YMin() + y * Get_Cellsize(); #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { if( pGrid->is_NoData(x, y) && (!pMask || !pMask->is_NoData(x, y)) ) { double px = Get_XMin() + x * Get_Cellsize(); for(int i=0; i<Pyramid.Get_Count(); i++) { CSG_Grid *pPatch = Pyramid.Get_Grid(i); if( pPatch->is_InGrid_byPos(px, py) ) { pGrid->Set_Value(x, y, pPatch->Get_Value(px, py, Resampling)); break; } } } } } //----------------------------------------------------- if( pGrid == Parameters("INPUT")->asGrid() ) { DataObject_Update(pGrid); } return( true ); }
//--------------------------------------------------------- bool CWatershed_Segmentation::Get_Borders(void) { Process_Set_Text(_TL("Borders")); CSG_Grid *pBorders = SG_Create_Grid(SG_DATATYPE_Byte, Get_NX() + 2, Get_NY() + 2, Get_Cellsize(), Get_XMin() - 0.5 * Get_Cellsize(), Get_YMin() - 0.5 * Get_Cellsize()); pBorders->Set_NoData_Value(0); Parameters("BORDERS")->Set_Value(pBorders); for(int y=0, yy=1; yy<Get_NY() && Set_Progress(yy); y++, yy++) { for(int x=0, xx=1; xx<Get_NX(); x++, xx++) { int id = m_pSegments->asInt(x, y); if( id != m_pSegments->asInt(xx, y) ) { pBorders->Set_Value(xx, y, 1); } if( id != m_pSegments->asInt( x, yy) ) { pBorders->Set_Value( x, yy, 1); } if( id != m_pSegments->asInt(xx, yy) ) { pBorders->Set_Value(xx, yy, 1); } } } return( true ); }
//--------------------------------------------------------- bool CGCS_Grid_Longitude_Range::On_Execute(void) { CSG_Parameter_Grid_List *pInput = Parameters("INPUT" )->asGridList(); CSG_Parameter_Grid_List *pOutput = Parameters("OUTPUT")->asGridList(); if( pInput->Get_Count() <= 0 ) { Message_Dlg(_TL("nothing to do: no data in selection")); return( false ); } pOutput->Del_Items(); //----------------------------------------------------- int xZero; CSG_Grid_System Target; //----------------------------------------------------- if( Parameters("DIRECTION")->asInt() == 0 ) // 0 - 360 >> -180 - 180 { if( Get_XMax() <= 180.0 ) { Message_Add(_TL("Nothing to do. Raster is already within target range.")); return( true ); } else if( Get_XMin() >= 180.0 ) { xZero = 0; Target.Assign(Get_Cellsize(), Get_XMin() - 360.0, Get_YMin(), Get_NX(), Get_NY()); } else if( Get_XMax() - 360.0 < Get_XMin() - Get_Cellsize() ) { Error_Set(_TL("Nothing to do be done. Raster splitting is not supported.")); return( false ); } else { xZero = (int)(0.5 + 180.0 / Get_Cellsize()); Target.Assign(Get_Cellsize(), Get_XMin() - 180.0, Get_YMin(), Get_NX(), Get_NY()); } } //----------------------------------------------------- else // -180 - 180 >> 0 - 360 { if( Get_XMin() >= 0.0 ) { Message_Add(_TL("Nothing to do. Raster is already within target range.")); return( true ); } else if( Get_XMax() <= 0.0 ) { xZero = 0; Target.Assign(Get_Cellsize(), Get_XMin() + 360.0, Get_YMin(), Get_NX(), Get_NY()); } else if( Get_XMin() + 360.0 > Get_XMax() + Get_Cellsize() ) { Error_Set(_TL("Nothing to do be done. Raster splitting is not supported.")); return( false ); } else { xZero = (int)(0.5 + 180.0 / Get_Cellsize()); Target.Assign(Get_Cellsize(), Get_XMin() - 180.0, Get_YMin(), Get_NX(), Get_NY()); } } //----------------------------------------------------- for(int i=0; i<pInput->Get_Count() && Process_Get_Okay(); i++) { CSG_Grid *pIn = pInput->asGrid(i); CSG_Grid *pOut = SG_Create_Grid(Target, pIn->Get_Type()); pOut->Set_Name(pIn->Get_Name()); pOut->Set_NoData_Value_Range(pIn->Get_NoData_Value(), pIn->Get_NoData_hiValue()); pOut->Set_ZFactor(pIn->Get_ZFactor()); pOutput->Add_Item(pOut); for(int y=0; y<Get_NY() && Set_Progress(y); y++) { for(int x=0, xx=xZero; x<Get_NX(); x++, xx++) { if( xx >= Get_NX() ) { xx = 0; } pOut->Set_Value(xx, y, pIn->asDouble(x, y)); } } } //----------------------------------------------------- return( true ); }