bool CSG_Matrix::Create(int nx, int ny, double *Data) { if( nx > 0 && ny > 0 ) { if( nx != m_nx || ny != m_ny ) { Destroy(); if( (m_z = (double **)SG_Malloc(ny * sizeof(double *))) != NULL && (m_z[0] = (double *)SG_Malloc(ny * nx * sizeof(double ))) != NULL ) { m_nx = nx; m_ny = ny; for(ny=1; ny<m_ny; ny++) { m_z[ny] = m_z[ny - 1] + nx; } } else { Destroy(); return( false ); } } if( m_z && m_z[0] ) { if( Data ) { memcpy(m_z[0], Data, m_ny * m_nx * sizeof(double)); } else { memset(m_z[0], 0, m_ny * m_nx * sizeof(double)); } return( true ); } } Destroy(); return( false ); }
//--------------------------------------------------------- void CGrid_3D_Image::_Set_Grid(void) { T3DPoint *a, *b, *c, *d, p[3]; //----------------------------------------------------- a = (T3DPoint *)SG_Malloc(sizeof(T3DPoint) * Get_NX()); b = (T3DPoint *)SG_Malloc(sizeof(T3DPoint) * Get_NX()); c = (T3DPoint *)SG_Malloc(sizeof(T3DPoint) * (Get_NX() - 1)); //----------------------------------------------------- _Get_Line(0, b); for(int y=1; y<Get_NY() && Set_Progress(y); y++) { d = a; a = b; b = d; _Get_Line(y, b); _Get_Line(a, b, c); for(int ax=0, bx=1; bx<Get_NX(); ax++, bx++) { DRAW_TRIANGLE(a[ax], a[bx], c[ax]); DRAW_TRIANGLE(b[ax], b[bx], c[ax]); DRAW_TRIANGLE(a[ax], b[ax], c[ax]); DRAW_TRIANGLE(a[bx], b[bx], c[ax]); } } //----------------------------------------------------- SG_Free(a); SG_Free(b); SG_Free(c); //----------------------------------------------------- DataObject_Add(m_pRGB_Z); DataObject_Add(m_pRGB); DataObject_Set_Colors(m_pRGB, 100, SG_COLORS_BLACK_WHITE); }
//--------------------------------------------------------- bool CSG_Matrix::Set_Inverse(bool bSilent, int nSubSquare) { bool bResult = false; int n = 0; //----------------------------------------------------- if( nSubSquare > 0 ) { if( nSubSquare <= m_nx && nSubSquare <= m_ny ) { n = nSubSquare; } } else if( is_Square() ) { n = m_nx; } //----------------------------------------------------- if( n > 0 ) { CSG_Matrix m(*this); int *Permutation = (int *)SG_Malloc(n * sizeof(int)); if( SG_Matrix_LU_Decomposition(n, Permutation, m.Get_Data(), bSilent) ) { CSG_Vector v(n); for(int j=0; j<n && (bSilent || SG_UI_Process_Set_Progress(j, n)); j++) { v.Set_Zero(); v[j] = 1.0; SG_Matrix_LU_Solve(n, Permutation, m, v.Get_Data(), true); for(int i=0; i<n; i++) { m_z[i][j] = v[i]; } } bResult = true; } SG_Free(Permutation); } return( bResult ); }
//--------------------------------------------------------- void CCandidates::Create(int nMax) { if( nMax <= 1 ) { Create(); return; } Destroy(); m_nMax = nMax; m_Candidates = (TCandidate *)SG_Malloc(m_nMax * sizeof(TCandidate)); }
//--------------------------------------------------------- bool CSG_Translator::Create(class CSG_Table *pTranslations, int iText, int iTranslation, bool bCmpNoCase) { SG_UI_Msg_Lock(true); Destroy(); if( iText != iTranslation && pTranslations && pTranslations->Get_Field_Count() > iText && pTranslations->Get_Field_Count() > iTranslation && pTranslations->Get_Record_Count() > 0 ) { int i; m_bCmpNoCase = bCmpNoCase; if( m_bCmpNoCase ) { for(i=0; i<pTranslations->Get_Record_Count(); i++) { CSG_Table_Record *pRecord = pTranslations->Get_Record(i); CSG_String s = pRecord->asString(iText); pRecord->Set_Value(iText, s.Make_Lower().c_str()); } } pTranslations->Set_Index(iText, TABLE_INDEX_Ascending); m_Translations = (CSG_Translation **)SG_Malloc(pTranslations->Get_Record_Count() * sizeof(CSG_Translation *)); for(i=0; i<pTranslations->Get_Record_Count(); i++) { CSG_Table_Record *pRecord = pTranslations->Get_Record_byIndex(i); if( *pRecord->asString(iText) && *pRecord->asString(iTranslation) ) { m_Translations[m_nTranslations++] = new CSG_Translation(pRecord->asString(iText), pRecord->asString(iTranslation)); } } if( m_nTranslations < pTranslations->Get_Record_Count() ) { m_Translations = (CSG_Translation **)SG_Realloc(m_Translations, m_nTranslations * sizeof(CSG_Translation *)); } } SG_UI_Msg_Lock(false); return( m_nTranslations > 0 ); }
//--------------------------------------------------------- void CTIN_Flow_Parallel::Let_it_flow_multiple(CSG_TIN_Node *pPoint) { int i; double d, dzSum, *dz, Area; Area = pPoint->Get_Polygon_Area(); pPoint->Set_Value(m_iArea, Area); pPoint->Add_Value(m_iFlow, Area); if( pPoint->Get_Neighbor_Count() > 0 ) { dz = (double *)SG_Malloc(pPoint->Get_Neighbor_Count() * sizeof(double)); for(i=0, dzSum=0.0; i<pPoint->Get_Neighbor_Count(); i++) { if( (d = pPoint->Get_Gradient(i, m_iHeight)) > 0.0 ) { dzSum += (dz[i] = d); } else { dz[i] = 0.0; } } if( dzSum > 0.0 ) { d = pPoint->asDouble(m_iFlow); for(i=0; i<pPoint->Get_Neighbor_Count(); i++) { if( dz[i] > 0.0 ) { pPoint->Get_Neighbor(i)->Add_Value( m_iFlow, d * dz[i] / dzSum); } } } SG_Free(dz); } pPoint->Set_Value(m_iSpecific, Area > 0.0 ? 1.0 / Area : -1.0); }
//--------------------------------------------------------- bool CSG_String::to_ASCII(char **pString) const { if( is_Empty() ) { return( false ); } *pString = (char *)SG_Malloc((1 + Length()) * sizeof(char)); if( *pString == NULL ) { return( false ); } memcpy(*pString, m_pString->ToAscii(), Length() * sizeof(char)); (*pString)[Length()] = '\0'; return( true ); }
//--------------------------------------------------------- bool SG_Matrix_Solve(CSG_Matrix &Matrix, CSG_Vector &Vector, bool bSilent) { bool bResult = false; int n = Vector.Get_N(); if( n > 0 && n == Matrix.Get_NX() && n == Matrix.Get_NY() ) { int *Permutation = (int *)SG_Malloc(n * sizeof(int)); if( SG_Matrix_LU_Decomposition(n, Permutation, Matrix.Get_Data(), bSilent) ) { SG_Matrix_LU_Solve(n, Permutation, Matrix, Vector.Get_Data(), bSilent); bResult = true; } SG_Free(Permutation); } return( bResult ); }
//--------------------------------------------------------- int CSG_Shapes_Search::Select_Quadrants(double x, double y, double Radius, int MaxPoints, int MinPoints) { if( MaxPoints <= 0 ) { return( Select_Radius(x, y, Radius, true, MaxPoints) ); } int iQuadrant, i, n, nTotal; CSG_Shape **Selected = (CSG_Shape **)SG_Malloc(4 * MaxPoints * sizeof(CSG_Shape *)); for(iQuadrant=0, nTotal=0; iQuadrant<4; iQuadrant++) { n = Select_Radius(x, y, Radius, false, MaxPoints, iQuadrant); if( n < MinPoints ) { return( 0 ); } for(i=0; i<n; i++) { Selected[nTotal + i] = Get_Selected_Point(i); } nTotal += n; } for(i=0, m_nSelected=0; i<nTotal; i++) { _Select_Add(Selected[i], -1.0); } SG_Free(Selected); return( m_nSelected ); }
//--------------------------------------------------------- // Creates a new DBase-File using FieldDescription... bool CSG_Table_DBase::Open(const SG_Char *FileName, int anFields, TFieldDesc *aFieldDesc) { Close(); #if defined(_SAGA_LINUX) && defined(_SAGA_UNICODE) if( (hFile = SG_FILE_OPEN(CSG_String(FileName).b_str(), "w+b")) != NULL ) #else if( (hFile = SG_FILE_OPEN(FileName, SG_T("w+b"))) != NULL ) #endif { bOpen = true; bReadOnly = false; nFields = anFields; FieldDesc = (TFieldDesc *)SG_Malloc(nFields * sizeof(TFieldDesc)); memcpy(FieldDesc, aFieldDesc, nFields * sizeof(TFieldDesc)); Header_Write(); nFileBytes = nHeaderBytes; } return( bOpen ); }
//--------------------------------------------------------- void CSG_Grid::Flip(void) { int x, yA, yB; double *Line, d; if( is_Valid() ) { Line = (double *)SG_Malloc(Get_NX() * sizeof(double)); for(yA=0, yB=Get_NY()-1; yA<yB && SG_UI_Process_Set_Progress(2 * yA, Get_NY()); yA++, yB--) { for(x=0; x<Get_NX(); x++) { Line[x] = asDouble(x, yA); } for(x=0; x<Get_NX(); x++) { d = Line[x]; Line[x] = asDouble(x, yB); Set_Value(x, yB, d); } for(x=0; x<Get_NX(); x++) { Set_Value(x, yA, Line[x]); } } SG_UI_Process_Set_Ready(); SG_Free(Line); Get_History().Add_Child(SG_T("GRID_OPERATION"), LNG("Vertically mirrored")); } }
//--------------------------------------------------------- bool CSurfer_Export::On_Execute(void) { const char ID_BINARY[] = "DSBB"; FILE *Stream; CSG_Grid *pGrid = Parameters("GRID")->asGrid(); CSG_String File = Parameters("FILE")->asString(); bool bNoData = Parameters("NODATA")->asBool(); switch( Parameters("FORMAT")->asInt() ) { //----------------------------------------------------- case 0: // Surfer 6 - Binary... if( (Stream = fopen(File.b_str(), "wb")) != NULL ) { short sValue; double dValue; fwrite(ID_BINARY, 4, sizeof(char), Stream); sValue = (short)pGrid->Get_NX (); fwrite(&sValue, 1, sizeof(short ), Stream); sValue = (short)pGrid->Get_NY (); fwrite(&sValue, 1, sizeof(short ), Stream); dValue = pGrid->Get_XMin(); fwrite(&dValue, 1, sizeof(double), Stream); dValue = pGrid->Get_XMax(); fwrite(&dValue, 1, sizeof(double), Stream); dValue = pGrid->Get_YMin(); fwrite(&dValue, 1, sizeof(double), Stream); dValue = pGrid->Get_YMax(); fwrite(&dValue, 1, sizeof(double), Stream); dValue = pGrid->Get_Min (); fwrite(&dValue, 1, sizeof(double), Stream); dValue = pGrid->Get_Max (); fwrite(&dValue, 1, sizeof(double), Stream); //--------------------------------------------- float *fLine = (float *)SG_Malloc(pGrid->Get_NX() * sizeof(float)); for(int y=0; y<pGrid->Get_NY() && Set_Progress(y, pGrid->Get_NY()); y++) { for(int x=0; x<pGrid->Get_NX(); x++) { fLine[x] = bNoData && pGrid->is_NoData(x, y) ? NODATAVALUE : pGrid->asFloat(x, y); } fwrite(fLine, pGrid->Get_NX(), sizeof(float), Stream); } SG_Free(fLine); fclose(Stream); return( true ); } break; //----------------------------------------------------- case 1: // Surfer - ASCII... if( (Stream = fopen(File.b_str(), "w")) != NULL ) { fprintf(Stream, "DSAA\n"); fprintf(Stream, "%d %d\n", pGrid->Get_NX (), pGrid->Get_NY ()); fprintf(Stream, "%f %f\n", pGrid->Get_XMin(), pGrid->Get_XMax()); fprintf(Stream, "%f %f\n", pGrid->Get_YMin(), pGrid->Get_YMax()); fprintf(Stream, "%f %f\n", pGrid->Get_Min (), pGrid->Get_Max ()); //--------------------------------------------- for(int y=0; y<pGrid->Get_NY() && Set_Progress(y, pGrid->Get_NY()); y++) { for(int x=0; x<pGrid->Get_NX(); x++) { fprintf(Stream, "%f ", bNoData && pGrid->is_NoData(x, y) ? NODATAVALUE : pGrid->asFloat(x, y)); } fprintf(Stream, "\n"); } fclose(Stream); return( true ); } break; } //----------------------------------------------------- return( false ); }
//--------------------------------------------------------- bool CFilter_3x3::On_Execute(void) { int x, y, ix, iy, dx, dy, fx, fy, fdx, fdy; double Sum, nSum, **f; CSG_Grid *pInput, *pResult; CSG_Table *pFilter; CSG_Table_Record *pRecord; //----------------------------------------------------- pInput = Parameters("INPUT")->asGrid(); pResult = Parameters("RESULT")->asGrid(); //----------------------------------------------------- pFilter = Parameters("FILTER")->asTable(); fdx = pFilter->Get_Field_Count(); fdy = pFilter->Get_Record_Count(); dx = (fdx - 1) / 2; dy = (fdy - 1) / 2; f = (double **)SG_Malloc(fdy * sizeof(double *)); f[0] = (double *)SG_Malloc(fdy * fdx * sizeof(double)); for(fy=0; fy<fdy; fy++) { f[fy] = f[0] + fy * fdx; pRecord = pFilter->Get_Record(fy); for(fx=0; fx<fdx; fx++) { f[fy][fx] = pRecord->asDouble(fx); } } //----------------------------------------------------- for(y=0; y<Get_NY() && Set_Progress(y); y++) { for(x=0; x<Get_NX(); x++) { Sum = nSum = 0.0; for(fy=0, iy=y-dy; fy<fdy; fy++, iy++) { for(fx=0, ix=x-dx; fx<fdx; fx++, ix++) { if( pInput->is_InGrid(ix, iy) ) { Sum += f[fy][fx] * pInput->asDouble(ix, iy); nSum += fabs(f[fy][fx]); } } } if( nSum > 0.0 ) { pResult->Set_Value(x, y, Sum / nSum); } else { pResult->Set_NoData(x, y); } } } //----------------------------------------------------- SG_Free(f[0]); SG_Free(f); return( true ); }
/////////////////////////////////////////////////////////// //--------------------------------------------------------- // This function has been copied from Module: 'Grid_Statistics_AddTo_Polygon' // Function: Get_ShapeIDs(...) // copyright by Olaf Conrad // // added support to clip only with selected polygons (Volker Wichmann) //--------------------------------------------------------- bool CGrid_Polygon_Clip::Get_Mask(CSG_Shapes *pShapes, CSG_Grid *pMask) { bool bFill, *bCrossing; bool bOnlySelected = false; int x, y, ix, xStart, xStop, iShape, iPart, iPoint; double yPos; TSG_Point pLeft, pRight, pa, pb, p; TSG_Rect Extent; CSG_Shape *pShape; //----------------------------------------------------- pMask->Assign(MASK_OFF); bCrossing = (bool *)SG_Malloc(pMask->Get_NX() * sizeof(bool)); if (pShapes->Get_Selection_Count() > 0) bOnlySelected = true; //----------------------------------------------------- for(iShape=0; iShape<pShapes->Get_Count() && Set_Progress(iShape, pShapes->Get_Count()); iShape++) { if (bOnlySelected && !pShapes->Get_Shape(iShape)->is_Selected()) continue; pShape = pShapes->Get_Shape(iShape); Extent = pShape->Get_Extent().m_rect; xStart = Get_System()->Get_xWorld_to_Grid(Extent.xMin) - 1; if( xStart < 0 ) xStart = 0; xStop = Get_System()->Get_xWorld_to_Grid(Extent.xMax) + 1; if( xStop >= Get_NX() ) xStop = Get_NX() - 1; pLeft.x = pMask->Get_XMin() - 1.0; pRight.x = pMask->Get_XMax() + 1.0; //------------------------------------------------- for(y=0, yPos=pMask->Get_YMin(); y<pMask->Get_NY(); y++, yPos+=pMask->Get_Cellsize()) { if( yPos >= Extent.yMin && yPos <= Extent.yMax ) { memset(bCrossing, 0, pMask->Get_NX() * sizeof(bool)); pLeft.y = pRight.y = yPos; //----------------------------------------- for(iPart=0; iPart<pShape->Get_Part_Count(); iPart++) { pb = pShape->Get_Point(pShape->Get_Point_Count(iPart) - 1, iPart); for(iPoint=0; iPoint<pShape->Get_Point_Count(iPart); iPoint++) { pa = pb; pb = pShape->Get_Point(iPoint, iPart); if( ( (pa.y <= yPos && yPos < pb.y) || (pa.y > yPos && yPos >= pb.y) ) ) { SG_Get_Crossing(p, pa, pb, pLeft, pRight, false); ix = (int)((p.x - pMask->Get_XMin()) / pMask->Get_Cellsize() + 1.0); if( ix < 0) { ix = 0; } else if( ix >= pMask->Get_NX() ) { continue; } bCrossing[ix] = !bCrossing[ix]; } } } //----------------------------------------- for(x=xStart, bFill=false; x<=xStop; x++) { if( bCrossing[x] ) { bFill = !bFill; } if( bFill ) { pMask->Set_Value(x, y, MASK_ON); } } } } } //----------------------------------------------------- SG_Free(bCrossing); return( true ); }
//--------------------------------------------------------- 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 CSG_Grid::_Load_Surfer(const CSG_String &File_Name, TSG_Grid_Memory_Type Memory_Type) { bool bResult = false; char Identifier[4]; short sValue; int x, y, NX, NY; float *fLine; double dValue, xMin, yMin, Cellsize; CSG_File Stream; if( Stream.Open(File_Name, SG_FILE_R, true) ) { Stream.Read(Identifier, sizeof(char), 4); //------------------------------------------------- // Binary... if( !strncmp(Identifier, "DSBB", 4) ) { Stream.Read(&sValue , sizeof(short)); NX = sValue; Stream.Read(&sValue , sizeof(short)); NY = sValue; Stream.Read(&xMin , sizeof(double)); Stream.Read(&dValue , sizeof(double)); // XMax Cellsize = (dValue - xMin) / (NX - 1.0); Stream.Read(&yMin , sizeof(double)); Stream.Read(&dValue , sizeof(double)); // YMax... //DY = (dValue - yMin) / (NY - 1.0); // we could check, if cellsizes (x/y) equal... Stream.Read(&dValue , sizeof(double)); // ZMin... Stream.Read(&dValue , sizeof(double)); // ZMax... //--------------------------------------------- if( !Stream.is_EOF() && Create(SG_DATATYPE_Float, NX, NY, Cellsize, xMin, yMin, Memory_Type) ) { bResult = true; fLine = (float *)SG_Malloc(Get_NX() * sizeof(float)); for(y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++) { Stream.Read(fLine, sizeof(float), Get_NX()); for(x=0; x<Get_NX(); x++) { Set_Value(x, y, fLine[x]); } } SG_Free(fLine); } } //------------------------------------------------- // ASCII... else if( !strncmp(Identifier, "DSAA", 4) ) { SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%d %d") , &NX , &NY); SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf %lf"), &xMin , &dValue); Cellsize = (dValue - xMin) / (NX - 1.0); SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf %lf"), &yMin , &dValue); //DY = (dValue - yMin) / (NY - 1.0); SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf %lf"), &dValue, &dValue); //--------------------------------------------- if( !Stream.is_EOF() && Create(SG_DATATYPE_Float, NX, NY, Cellsize, xMin, yMin, Memory_Type) ) { bResult = true; for(y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++) { for(x=0; x<Get_NX(); x++) { SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf"), &dValue); Set_Value(x, y, dValue); } } } } //------------------------------------------------- SG_UI_Process_Set_Ready(); } return( bResult ); }
//--------------------------------------------------------- bool CGrid_Cluster_Analysis::_On_Execute(void) { int i, j, *nMembers, nCluster, nElements; double *Variances, **Centroids, SP; CSG_Grid **Grids, *pCluster; CSG_Parameter_Grid_List *pGrids; //----------------------------------------------------- pGrids = Parameters("GRIDS") ->asGridList(); pCluster = Parameters("CLUSTER") ->asGrid(); nCluster = Parameters("NCLUSTER")->asInt(); if( pGrids->Get_Count() < 1 ) { return( false ); } //----------------------------------------------------- Grids = (CSG_Grid **)SG_Malloc(pGrids->Get_Count() * sizeof(CSG_Grid *)); if( Parameters("NORMALISE")->asBool() ) { for(i=0; i<pGrids->Get_Count(); i++) { Grids[i] = SG_Create_Grid(pGrids->asGrid(i), SG_DATATYPE_Float); Grids[i] ->Assign(pGrids->asGrid(i)); Grids[i] ->Standardise(); } } else { for(i=0; i<pGrids->Get_Count(); i++) { Grids[i] = pGrids->asGrid(i); } } pCluster->Set_NoData_Value(-1.0); pCluster->Assign_NoData(); nMembers = (int *)SG_Malloc(nCluster * sizeof(int)); Variances = (double *)SG_Malloc(nCluster * sizeof(double)); Centroids = (double **)SG_Malloc(nCluster * sizeof(double *)); for(i=0; i<nCluster; i++) { Centroids[i] = (double *)SG_Malloc(pGrids->Get_Count() * sizeof(double)); } //------------------------------------------------- switch( Parameters("METHOD")->asInt() ) { case 0: SP = _MinimumDistance (Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells()); break; case 1: SP = _HillClimbing (Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells()); break; case 2: SP = _MinimumDistance (Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells()); SP = _HillClimbing (Grids, pGrids->Get_Count(), pCluster, nCluster, nMembers, Variances, Centroids, nElements = Get_NCells()); break; } //------------------------------------------------- if( Parameters("NORMALISE")->asBool() ) { for(i=0; i<pGrids->Get_Count(); i++) { delete(Grids[i]); for(j=0; j<nCluster; j++) { Centroids[j][i] = pGrids->asGrid(i)->Get_StdDev() * Centroids[j][i] + pGrids->asGrid(i)->Get_Mean(); } } } //------------------------------------------------- Save_LUT(pCluster); //------------------------------------------------- int iCluster, iFeature; CSG_String s; CSG_Table_Record *pRecord; CSG_Table *pTable; pTable = Parameters("STATISTICS")->asTable(); pTable->Destroy(); pTable->Set_Name(_TL("Cluster Analysis")); pTable->Add_Field(_TL("ClusterID") , SG_DATATYPE_Int); pTable->Add_Field(_TL("Elements") , SG_DATATYPE_Int); pTable->Add_Field(_TL("Std.Dev.") , SG_DATATYPE_Double); s.Printf(SG_T("\n%s:\t%ld \n%s:\t%d \n%s:\t%d \n%s:\t%f\n\n%s\t%s\t%s"), _TL("Number of Elements") , nElements, _TL("Number of Variables") , pGrids->Get_Count(), _TL("Number of Clusters") , nCluster, _TL("Standard Deviation") , sqrt(SP), _TL("Cluster"), _TL("Elements"), _TL("Std.Dev.") ); for(iFeature=0; iFeature<pGrids->Get_Count(); iFeature++) { s += CSG_String::Format(SG_T("\t%s"), pGrids->asGrid(iFeature)->Get_Name()); pTable->Add_Field(pGrids->asGrid(iFeature)->Get_Name(), SG_DATATYPE_Double); } Message_Add(s); for(iCluster=0; iCluster<nCluster; iCluster++) { Variances[iCluster] = nMembers[iCluster] ? Variances[iCluster] / nMembers[iCluster] : 0.0; s.Printf(SG_T("\n%d\t%d\t%f"), iCluster, nMembers[iCluster], sqrt(Variances[iCluster])); pRecord = pTable->Add_Record(); pRecord->Set_Value(0, iCluster); pRecord->Set_Value(1, nMembers[iCluster]); pRecord->Set_Value(2, sqrt(Variances[iCluster])); for(iFeature=0; iFeature<pGrids->Get_Count(); iFeature++) { double Centroid = Centroids[iCluster][iFeature]; if( Parameters("NORMALISE")->asBool() ) { Centroid = pGrids->asGrid(iFeature)->Get_Mean() + Centroid * pGrids->asGrid(iFeature)->Get_StdDev(); } s += CSG_String::Format(SG_T("\t%f"), Centroid); pRecord->Set_Value(iFeature + 3, Centroid); } Message_Add(s, false); } //------------------------------------------------- for(i=0; i<nCluster; i++) { SG_Free(Centroids[i]); } SG_Free(Centroids); SG_Free(Variances); SG_Free(nMembers); SG_Free(Grids); return( true ); }
//--------------------------------------------------------- void CFlow_RecursiveUp::On_Create(void) { int x, y, Method; double *p; //----------------------------------------------------- On_Destroy(); Flow = (double ***)SG_Malloc( Get_NY () * sizeof(double **)); p = (double *)SG_Malloc(8 * Get_NCells() * sizeof(double )); for(y=0; y<Get_NY(); y++) { Flow[y] = (double **)SG_Malloc( Get_NX () * sizeof(double *)); for(x=0; x<Get_NX(); x++, p+=8) { Flow[y][x] = p; } } //----------------------------------------------------- Lock_Create(); Method = Parameters("Method")->asInt(); memset(Flow[0][0], 0, 8 * Get_NCells() * sizeof(double) ); for(y=0; y<Get_NY(); y++) { for(x=0; x<Get_NX(); x++) { if( pRoute && pRoute->asChar(x,y) > 0 ) { Flow[y][x][pRoute->asChar(x,y) % 8] = 1.0; } else { switch( Method ) { case 0: Set_D8(x,y); break; case 1: Set_Rho8(x,y); break; case 2: Set_DInf(x,y); break; case 3: Set_MFD(x,y); break; } } } } }
//--------------------------------------------------------- bool CSG_TIN::_Triangulate(CSG_TIN_Node **Points, int nPoints, TTIN_Triangle *Triangles, int &nTriangles) { int i, j, k, inside, trimax, nedge = 0, emax = 200, status = 0, *complete = NULL; double dmax, xp, yp, x1, y1, x2, y2, x3, y3, xc, yc, r; TTIN_Edge *edges = NULL; //----------------------------------------------------- // Update extent... if( nPoints >= 3 ) { TSG_Rect r; m_Extent.Assign( Points[0]->Get_X(), Points[0]->Get_Y(), Points[0]->Get_X(), Points[0]->Get_Y() ); for(i=1; i<nPoints; i++) { r.xMin = r.xMax = Points[i]->Get_X(); r.yMin = r.yMax = Points[i]->Get_Y(); m_Extent.Union(r); } } else { return( false ); } //----------------------------------------------------- // Allocate memory for the completeness list, flag for each triangle trimax = 4 * nPoints; if( (complete = (int *)SG_Malloc(trimax * sizeof(int))) == NULL ) { status = 1; goto skip; } //----------------------------------------------------- // Allocate memory for the edge list if( (edges = (TTIN_Edge *)SG_Malloc(emax * sizeof(TTIN_Edge))) == NULL ) { status = 2; goto skip; } //----------------------------------------------------- // Find the maximum and minimum vertex bounds. // This is to allow calculation of the bounding triangle // Set up the supertriangle // This is a triangle which encompasses all the sample points. // The supertriangle coordinates are added to the end of the // vertex list. The supertriangle is the first triangle in // the triangle list. dmax = m_Extent.Get_XRange() > m_Extent.Get_YRange() ? m_Extent.Get_XRange() : m_Extent.Get_YRange(); Points[nPoints + 0]->m_Point.x = m_Extent.Get_XCenter() - 20 * dmax; Points[nPoints + 1]->m_Point.x = m_Extent.Get_XCenter(); Points[nPoints + 2]->m_Point.x = m_Extent.Get_XCenter() + 20 * dmax; Points[nPoints + 0]->m_Point.y = m_Extent.Get_YCenter() - dmax; Points[nPoints + 1]->m_Point.y = m_Extent.Get_YCenter() + 20 * dmax; Points[nPoints + 2]->m_Point.y = m_Extent.Get_YCenter() - dmax; Triangles[0].p1 = nPoints; Triangles[0].p2 = nPoints + 1; Triangles[0].p3 = nPoints + 2; complete [0] = false; nTriangles = 1; //----------------------------------------------------- // Include each point one at a time into the existing mesh for(i=0; i<nPoints && SG_UI_Process_Set_Progress(i, nPoints); i++) { xp = Points[i]->Get_X(); yp = Points[i]->Get_Y(); nedge = 0; //------------------------------------------------- // Set up the edge buffer. // If the point (xp,yp) lies inside the circumcircle then the // three edges of that triangle are added to the edge buffer // and that triangle is removed. for(j=0; j<nTriangles; j++) { if( complete[j] ) { continue; } x1 = Points[Triangles[j].p1]->Get_X(); y1 = Points[Triangles[j].p1]->Get_Y(); x2 = Points[Triangles[j].p2]->Get_X(); y2 = Points[Triangles[j].p2]->Get_Y(); x3 = Points[Triangles[j].p3]->Get_X(); y3 = Points[Triangles[j].p3]->Get_Y(); inside = _CircumCircle(xp, yp, x1, y1, x2, y2, x3, y3, &xc, &yc, &r); if( xc + r < xp ) { complete[j] = true; } if( inside ) { // Check that we haven't exceeded the edge list size if( nedge + 3 >= emax ) { emax += 100; if( (edges = (TTIN_Edge *)SG_Realloc(edges, emax * sizeof(TTIN_Edge))) == NULL ) { status = 3; goto skip; } } edges[nedge + 0].p1 = Triangles[j].p1; edges[nedge + 0].p2 = Triangles[j].p2; edges[nedge + 1].p1 = Triangles[j].p2; edges[nedge + 1].p2 = Triangles[j].p3; edges[nedge + 2].p1 = Triangles[j].p3; edges[nedge + 2].p2 = Triangles[j].p1; nedge += 3; Triangles[j] = Triangles[nTriangles - 1]; complete [j] = complete [nTriangles - 1]; nTriangles--; j--; } } //------------------------------------------------- // Tag multiple edges // Note: if all triangles are specified anticlockwise then all // interior edges are opposite pointing in direction. for(j=0; j<nedge-1; j++) { for(k=j+1; k<nedge; k++) { if( (edges[j].p1 == edges[k].p2) && (edges[j].p2 == edges[k].p1) ) { edges[j].p1 = -1; edges[j].p2 = -1; edges[k].p1 = -1; edges[k].p2 = -1; } // Shouldn't need the following, see note above if( (edges[j].p1 == edges[k].p1) && (edges[j].p2 == edges[k].p2) ) { edges[j].p1 = -1; edges[j].p2 = -1; edges[k].p1 = -1; edges[k].p2 = -1; } } } //------------------------------------------------- // Form new triangles for the current point // Skipping over any tagged edges. // All edges are arranged in clockwise order. for(j=0; j<nedge; j++) { if( edges[j].p1 < 0 || edges[j].p2 < 0 ) { continue; } if( nTriangles >= trimax ) { status = 4; goto skip; } Triangles[nTriangles].p1 = edges[j].p1; Triangles[nTriangles].p2 = edges[j].p2; Triangles[nTriangles].p3 = i; complete [nTriangles] = false; nTriangles++; } } //----------------------------------------------------- // Remove triangles with supertriangle vertices // These are triangles which have a vertex number greater than nPoints for(i=0; i<nTriangles; i++) { if( Triangles[i].p1 >= nPoints || Triangles[i].p2 >= nPoints || Triangles[i].p3 >= nPoints ) { Triangles[i] = Triangles[nTriangles - 1]; nTriangles--; i--; } } //----------------------------------------------------- skip: if( edges ) { SG_Free(edges); } if( complete ) { SG_Free(complete); } return( status == 0 ); }
//--------------------------------------------------------- void CShapes2Grid::Set_Polygon(CSG_Shape *pShape) { bool bFill, *bCrossing; int x, y, xStart, xStop; TSG_Point A, B, a, b, c; CSG_Rect Extent; //----------------------------------------------------- bCrossing = (bool *)SG_Malloc(m_pGrid->Get_NX() * sizeof(bool)); Extent = pShape->Get_Extent(); xStart = (int)((Extent.m_rect.xMin - m_pGrid->Get_XMin()) / m_pGrid->Get_Cellsize()) - 1; if( xStart < 0 ) xStart = 0; xStop = (int)((Extent.m_rect.xMax - m_pGrid->Get_XMin()) / m_pGrid->Get_Cellsize()) + 1; if( xStop >= m_pGrid->Get_NX() ) xStop = m_pGrid->Get_NX() - 1; A.x = m_pGrid->Get_XMin() - 1.0; B.x = m_pGrid->Get_XMax() + 1.0; //----------------------------------------------------- for(y=0, A.y=m_pGrid->Get_YMin(); y<m_pGrid->Get_NY(); y++, A.y+=m_pGrid->Get_Cellsize()) { if( A.y >= Extent.m_rect.yMin && A.y <= Extent.m_rect.yMax ) { B.y = A.y; memset(bCrossing, 0, m_pGrid->Get_NX() * sizeof(bool)); for(int iPart=0; iPart<pShape->Get_Part_Count(); iPart++) { b = pShape->Get_Point(pShape->Get_Point_Count(iPart) - 1, iPart); for(int iPoint=0; iPoint<pShape->Get_Point_Count(iPart); iPoint++) { a = b; b = pShape->Get_Point(iPoint, iPart); if( ((a.y <= A.y && A.y < b.y) || (a.y > A.y && A.y >= b.y)) ) { SG_Get_Crossing(c, a, b, A, B, false); x = (int)(1.0 + X_WORLD_TO_GRID(c.x)); if( x < 0 ) { x = 0; } else if( x >= m_pGrid->Get_NX() ) { x = m_pGrid->Get_NX() - 1; } bCrossing[x] = !bCrossing[x]; } } } //--------------------------------------------- for(x=xStart, bFill=false; x<=xStop; x++) { if( bCrossing[x] ) { bFill = !bFill; } if( bFill ) { Set_Value(x, y); } } } } //----------------------------------------------------- SG_Free(bCrossing); }
//--------------------------------------------------------- bool CSurfer_Import::On_Execute(void) { //----------------------------------------------------- CSG_String File = Parameters("FILE")->asString(); FILE *Stream = fopen(File.b_str(), "rb"); if( !Stream ) { Error_Set(_TL("failed to open file")); return( false ); } CSG_Grid *pGrid = NULL; char Id[4]; fread(Id, 1, 4 * sizeof(char), Stream); //----------------------------------------------------- if( !strncmp(Id, "DSRB", 4) ) // Surfer 7: Binary... { long lValue, nx, ny; double dValue, dx, dy, xmin, ymin; fread(&lValue, 1, sizeof(long), Stream); // SectionSize... fread(&lValue, 1, sizeof(long), Stream); // Version fread(&lValue, 1, sizeof(long), Stream); if( lValue == 0x44495247 ) // Grid-Header... { fread(&lValue, 1, sizeof(long ), Stream); // SectionSize... fread(&ny , 1, sizeof(long ), Stream); fread(&nx , 1, sizeof(long ), Stream); fread(&xmin , 1, sizeof(double), Stream); fread(&ymin , 1, sizeof(double), Stream); fread(&dx , 1, sizeof(double), Stream); fread(&dy , 1, sizeof(double), Stream); fread(&dValue, 1, sizeof(double), Stream); fread(&dValue, 1, sizeof(double), Stream); fread(&dValue, 1, sizeof(double), Stream); // Rotation (unused)... fread(&dValue, 1, sizeof(double), Stream); // Blank Value... fread(&lValue, 1, sizeof(long ), Stream); // ???... if( lValue == 0x41544144 ) // Load Binary Double... { fread(&lValue, 1, sizeof(long), Stream); // SectionSize... //----------------------------------------- if( !feof(Stream) && (pGrid = SG_Create_Grid(SG_DATATYPE_Double, nx, ny, dx, xmin, ymin)) != NULL ) { double *Line = (double *)SG_Malloc(pGrid->Get_NX() * sizeof(double)); for(int y=0; y<pGrid->Get_NY() && !feof(Stream) && Set_Progress(y, pGrid->Get_NY()); y++) { fread(Line, pGrid->Get_NX(), sizeof(double), Stream); for(int x=0; x<pGrid->Get_NX(); x++) { pGrid->Set_Value(x, y, Line[x]); } } SG_Free(Line); } } } } //----------------------------------------------------- else if( !strncmp(Id, "DSBB", 4) ) // Surfer 6: Binary... { short nx, ny; double dValue, dx, dy, xmin, ymin; fread(&nx , 1, sizeof(short ), Stream); fread(&ny , 1, sizeof(short ), Stream); fread(&xmin , 1, sizeof(double), Stream); fread(&dx , 1, sizeof(double), Stream); dx = (dx - xmin) / (nx - 1.0); // XMax fread(&ymin , 1, sizeof(double), Stream); fread(&dy , 1, sizeof(double), Stream); dy = (dy - ymin) / (ny - 1.0); // YMax... fread(&dValue, 1, sizeof(double), Stream); // ZMin... fread(&dValue, 1, sizeof(double), Stream); // ZMax... //------------------------------------------------- if( !feof(Stream) && (pGrid = SG_Create_Grid(SG_DATATYPE_Float, nx, ny, dx, xmin, ymin)) != NULL ) { float *Line = (float *)SG_Malloc(pGrid->Get_NX() * sizeof(float)); for(int y=0; y<pGrid->Get_NY() && !feof(Stream) && Set_Progress(y, pGrid->Get_NY()); y++) { fread(Line, pGrid->Get_NX(), sizeof(float), Stream); for(int x=0; x<pGrid->Get_NX(); x++) { pGrid->Set_Value(x, y, Line[x]); } } SG_Free(Line); } } //----------------------------------------------------- else if( !strncmp(Id, "DSAA", 4) ) // Surfer 6: ASCII... { int nx, ny; double dx, dy, xmin, ymin, dValue; fscanf(Stream, "%d %d" , &nx , &ny ); fscanf(Stream, "%lf %lf", &xmin , &dx ); dx = (dx - xmin) / (nx - 1.0); fscanf(Stream, "%lf %lf", &ymin , &dy ); dy = (dy - ymin) / (ny - 1.0); fscanf(Stream, "%lf %lf", &dValue, &dValue); //------------------------------------------------- if( !feof(Stream) && (pGrid = SG_Create_Grid(SG_DATATYPE_Float, nx, ny, dx, xmin, ymin)) != NULL ) { for(int y=0; y<pGrid->Get_NY() && !feof(Stream) && Set_Progress(y, pGrid->Get_NY()); y++) { for(int x=0; x<pGrid->Get_NX(); x++) { fscanf(Stream, "%lf", &dValue); pGrid->Set_Value(x, y, dValue); } } } } //----------------------------------------------------- fclose(Stream); if( pGrid ) { pGrid->Set_Name(SG_File_Get_Name(File, false)); pGrid->Set_NoData_Value(Parameters("NODATA")->asInt() == 0 ? NODATAVALUE : Parameters("NODATA_VAL")->asDouble()); Parameters("GRID")->Set_Value(pGrid); return( true ); } return( false ); }
//--------------------------------------------------------- bool CSG_Table::_Load_DBase(const CSG_String &File_Name) { int iField; CSG_Table_DBase dbf; CSG_Table_Record *pRecord; //----------------------------------------------------- if( dbf.Open(File_Name) ) { Destroy(); for(iField=0; iField<dbf.Get_FieldCount(); iField++) { TSG_Data_Type Type; switch( dbf.Get_FieldType(iField) ) { case DBF_FT_LOGICAL: Type = SG_DATATYPE_Char; break; case DBF_FT_CHARACTER: default: Type = SG_DATATYPE_String; break; case DBF_FT_DATE: Type = SG_DATATYPE_Date; break; case DBF_FT_NUMERIC: Type = dbf.Get_FieldDecimals(iField) > 0 ? SG_DATATYPE_Double : SG_DATATYPE_Long; break; } Add_Field(SG_STR_MBTOSG(dbf.Get_FieldName(iField)), Type); } //------------------------------------------------- if( dbf.Move_First() && dbf.Get_Record_Count() > 0 ) { m_nRecords = m_nBuffer = dbf.Get_Record_Count(); m_Records = (CSG_Table_Record **)SG_Malloc(m_nRecords * sizeof(CSG_Table_Record *)); for(int iRecord=0; iRecord<m_nRecords && SG_UI_Process_Set_Progress(iRecord, m_nRecords); iRecord++) { m_Records[iRecord] = pRecord = _Get_New_Record(iRecord); for(iField=0; iField<Get_Field_Count(); iField++) { switch( Get_Field_Type(iField) ) { case SG_DATATYPE_Char: pRecord->Set_Value(iField, SG_STR_MBTOSG(dbf.asString(iField)) ); break; case SG_DATATYPE_String: default: pRecord->Set_Value(iField, SG_STR_MBTOSG(dbf.asString(iField)) ); break; case SG_DATATYPE_Date: pRecord->Set_Value(iField, dbf.asDouble(iField) ); break; case SG_DATATYPE_Long: pRecord->Set_Value(iField, dbf.asInt(iField) ); break; case SG_DATATYPE_Double: pRecord->Set_Value(iField, dbf.asDouble(iField) ); break; } } dbf.Move_Next(); } SG_UI_Process_Set_Ready(); Set_Modified(false); Set_Update_Flag(); _Stats_Invalidate(); } return( true ); } return( false ); }
//--------------------------------------------------------- bool CGridding_Spline_CSA::On_Execute(void) { //----------------------------------------------------- if( Initialise(m_Points, true) == false ) { return( false ); } //----------------------------------------------------- int i, x, y; TSG_Point p; csa *pCSA = csa_create(); csa_setnpmin(pCSA, Parameters("NPMIN") ->asInt()); csa_setnpmax(pCSA, Parameters("NPMAX") ->asInt()); csa_setk (pCSA, Parameters("K") ->asInt()); csa_setnppc (pCSA, Parameters("NPPC") ->asDouble()); //----------------------------------------------------- point *pSrc = (point *)SG_Malloc(m_Points.Get_Count() * sizeof(point)); for(i=0; i<m_Points.Get_Count() && Set_Progress(i, m_Points.Get_Count()); i++) { pSrc[i].x = m_Points[i].x; pSrc[i].y = m_Points[i].y; pSrc[i].z = m_Points[i].z; } csa_addpoints(pCSA, m_Points.Get_Count(), pSrc); m_Points.Clear(); //----------------------------------------------------- point *pDst = (point *)SG_Malloc(m_pGrid->Get_NCells() * sizeof(point)); for(y=0, i=0, p.y=m_pGrid->Get_YMin(); y<m_pGrid->Get_NY() && Set_Progress(y, m_pGrid->Get_NY()); y++, p.y+=m_pGrid->Get_Cellsize()) { for(x=0, p.x=m_pGrid->Get_XMin(); x<m_pGrid->Get_NX(); x++, p.x+=m_pGrid->Get_Cellsize(), i++) { pDst[i].x = p.x; pDst[i].y = p.y; } } //----------------------------------------------------- Process_Set_Text(_TL("calculating splines...")); csa_calculatespline (pCSA); Process_Set_Text(_TL("approximating points...")); csa_approximate_points (pCSA, m_pGrid->Get_NCells(), pDst); //----------------------------------------------------- for(y=0, i=0; y<m_pGrid->Get_NY() && Set_Progress(y, m_pGrid->Get_NY()); y++) { for(x=0; x<m_pGrid->Get_NX(); x++, i++) { if( isnan(pDst[i].z) ) { m_pGrid->Set_NoData(x, y); } else { m_pGrid->Set_Value(x, y, pDst[i].z); } } } //----------------------------------------------------- csa_destroy(pCSA); SG_Free(pSrc); SG_Free(pDst); //----------------------------------------------------- return( true ); }
//--------------------------------------------------------- bool CGDAL_Export::On_Execute(void) { char **pOptions = NULL; int x, y, n; double *zLine; CSG_String File_Name; CSG_Parameter_Grid_List *pGrids; CSG_Grid *pGrid; GDALDataType gdal_Type; GDALDriver *pDriver; GDALDataset *pDataset; GDALRasterBand *pBand; //----------------------------------------------------- pGrids = Parameters("GRIDS") ->asGridList(); File_Name = Parameters("FILE") ->asString(); //----------------------------------------------------- switch( Parameters("TYPE")->asInt() ) { default: case 0: gdal_Type = g_GDAL_Driver.Get_GDAL_Type(pGrids); break; // match input data case 1: gdal_Type = GDT_Byte; break; // Eight bit unsigned integer case 2: gdal_Type = GDT_UInt16; break; // Sixteen bit unsigned integer case 3: gdal_Type = GDT_Int16; break; // Sixteen bit signed integer case 4: gdal_Type = GDT_UInt32; break; // Thirty two bit unsigned integer case 5: gdal_Type = GDT_Int32; break; // Thirty two bit signed integer case 6: gdal_Type = GDT_Float32; break; // Thirty two bit floating point case 7: gdal_Type = GDT_Float64; break; // Sixty four bit floating point } //----------------------------------------------------- if( (pDriver = g_GDAL_Driver.Get_Driver(SG_STR_SGTOMB(m_DriverNames[Parameters("FORMAT")->asInt()]))) == NULL ) { Message_Add(_TL("Driver not found.")); } else if( CSLFetchBoolean(pDriver->GetMetadata(), GDAL_DCAP_CREATE, false) == false ) { Message_Add(_TL("Driver does not support file creation.")); } else if( (pDataset = pDriver->Create(File_Name.b_str(), Get_NX(), Get_NY(), pGrids->Get_Count(), gdal_Type, pOptions)) == NULL ) { Message_Add(_TL("Could not create dataset.")); } else { g_GDAL_Driver.Set_Transform(pDataset, Get_System()); if( pGrids->asGrid(0)->Get_Projection().Get_Type() != SG_PROJ_TYPE_CS_Undefined ) { pDataset->SetProjection(SG_STR_SGTOMB(pGrids->asGrid(0)->Get_Projection().Get_WKT())); } zLine = (double *)SG_Malloc(Get_NX() * sizeof(double)); for(n=0; n<pGrids->Get_Count(); n++) { Process_Set_Text(CSG_String::Format(SG_T("%s %d"), _TL("Band"), n + 1)); pGrid = pGrids->asGrid(n); pBand = pDataset->GetRasterBand(n + 1); for(y=0; y<Get_NY() && Set_Progress(y, Get_NY()); y++) { for(x=0; x<Get_NX(); x++) { zLine[x] = pGrid->asDouble(x, Get_NY() - 1 - y); } pBand->RasterIO(GF_Write, 0, y, Get_NX(), 1, zLine, Get_NX(), 1, GDT_Float64, 0, 0); } } //------------------------------------------------- SG_Free(zLine); GDALClose(pDataset); return( true ); } //----------------------------------------------------- return( false ); }
//--------------------------------------------------------- bool CSG_TIN::_Triangulate(void) { bool bResult; int i, j, n, nTriangles; CSG_TIN_Node **Nodes; TTIN_Triangle *Triangles; //----------------------------------------------------- _Destroy_Edges(); _Destroy_Triangles(); //----------------------------------------------------- Nodes = (CSG_TIN_Node **)SG_Malloc((Get_Node_Count() + 3) * sizeof(CSG_TIN_Node *)); for(i=0; i<Get_Node_Count(); i++) { Nodes[i] = Get_Node(i); Nodes[i] ->_Del_Relations(); } //----------------------------------------------------- qsort(Nodes, Get_Node_Count(), sizeof(CSG_TIN_Node *), SG_TIN_Compare); for(i=0, j=0, n=Get_Node_Count(); j<n; i++) // remove duplicates { Nodes[i] = Nodes[j++]; while( j < n && Nodes[i]->Get_X() == Nodes[j]->Get_X() && Nodes[i]->Get_Y() == Nodes[j]->Get_Y() ) { Del_Node(Nodes[j++]->Get_Index(), false); } } //----------------------------------------------------- for(i=Get_Node_Count(); i<Get_Node_Count()+3; i++) { Nodes[i] = new CSG_TIN_Node(this, 0); } //----------------------------------------------------- Triangles = (TTIN_Triangle *)SG_Malloc(3 * Get_Node_Count() * sizeof(TTIN_Triangle)); if( (bResult = _Triangulate(Nodes, Get_Node_Count(), Triangles, nTriangles)) == true ) { for(i=0; i<nTriangles && SG_UI_Process_Set_Progress(i, nTriangles); i++) { _Add_Triangle(Nodes[Triangles[i].p1], Nodes[Triangles[i].p2], Nodes[Triangles[i].p3]); } } SG_Free(Triangles); //----------------------------------------------------- for(i=Get_Node_Count(); i<Get_Node_Count()+3; i++) { delete(Nodes[i]); } SG_Free(Nodes); SG_UI_Process_Set_Ready(); return( bResult ); }
//--------------------------------------------------------- bool CPC_Cluster_Analysis::On_Execute(void) { int nCluster; long nElements; double SP; CSG_Parameters Parms; m_bUpdateView = false; //----------------------------------------------------- nCluster = Parameters("NCLUSTER")->asInt(); pInput = Parameters("PC_IN") ->asPointCloud(); pResult = Parameters("PC_OUT") ->asPointCloud(); if( SG_UI_Get_Window_Main() ) m_bUpdateView = Parameters("UPDATEVIEW")->asBool(); //------------------------------------------------- m_Features = (int *)Parameters("FIELDS")->asPointer(); m_nFeatures = Parameters("FIELDS")->asInt (); if( !m_Features || m_nFeatures <= 0 ) { Error_Set(_TL("no features in selection")); return( false ); } //----------------------------------------------------- pResult->Create(pInput); pResult->Set_Name(CSG_String::Format(SG_T("%s_cluster"), pInput->Get_Name())); pResult->Add_Field(SG_T("CLUSTER"), SG_DATATYPE_Int); DataObject_Update(pResult); pResult->Set_NoData_Value(-1.0); clustField = pResult->Get_Field_Count() - 1; //----------------------------------------------------- Process_Set_Text(_TL("Initializing ...")); for( int i=0; i<m_nFeatures; i++ ) vValues.push_back( std::vector<double>() ); for( int i=0; i<pInput->Get_Record_Count() && SG_UI_Process_Set_Progress(i, pInput->Get_Record_Count()); i++ ) { pResult->Add_Point(pInput->Get_X(i), pInput->Get_Y(i), pInput->Get_Z(i)); for( int j=0; j<pInput->Get_Attribute_Count(); j++ ) pResult->Set_Attribute(i, j, pInput->Get_Attribute(i, j)); pResult->Set_NoData(i, clustField); bool bNoData = false; for( int j=0; j<m_nFeatures; j++) { if( pInput->is_NoData(i, m_Features[j]) ) { bNoData = true; break; } } if( !bNoData ) { for( int j=0; j<m_nFeatures; j++ ) { if( Parameters("NORMALISE")->asBool() ) vValues.at(j).push_back( (pInput->Get_Value(i, m_Features[j]) - pInput->Get_Mean(m_Features[j])) / pInput->Get_StdDev(m_Features[j]) ); else vValues.at(j).push_back(pInput->Get_Value(i, m_Features[j])); } } else { for( int j=0; j<m_nFeatures; j++ ) { vValues.at(j).push_back(pInput->Get_NoData_Value()); } } } if( m_bUpdateView ) { if( DataObject_Get_Parameters(pResult, Parms) && Parms("COLORS_TYPE") && Parms("METRIC_ATTRIB") && Parms("METRIC_COLORS") && Parms("METRIC_ZRANGE") ) { Parms("COLORS_TYPE") ->Set_Value(2); // graduated color Parms("METRIC_COLORS")->asColors() ->Set_Count(nCluster); Parms("METRIC_ATTRIB") ->Set_Value(clustField); Parms("METRIC_ZRANGE")->asRange() ->Set_Range(0, nCluster); } DataObject_Set_Parameters(pResult, Parms); DataObject_Update(pResult, SG_UI_DATAOBJECT_SHOW_LAST_MAP); } nMembers = (int *)SG_Malloc(nCluster * sizeof(int)); Variances = (double *)SG_Malloc(nCluster * sizeof(double)); Centroids = (double **)SG_Malloc(nCluster * sizeof(double *)); for( int i=0; i<nCluster; i++ ) { Centroids[i] = (double *)SG_Malloc(m_nFeatures * sizeof(double)); } //------------------------------------------------- nElements = pInput->Get_Point_Count(); switch( Parameters("METHOD")->asInt() ) { case 0: SP = MinimumDistance (nElements, nCluster); break; case 1: SP = HillClimbing (nElements, nCluster); break; case 2: SP = MinimumDistance (nElements, nCluster); nElements = pInput->Get_Point_Count(); // may have been diminished because of no data values... SP = HillClimbing (nElements, nCluster); break; } //------------------------------------------------- if( Parameters("NORMALISE")->asBool() ) { int iv = 0; for( int i=0; i<m_nFeatures; i++ ) { for( int j=0; j<nCluster; j++ ) { Centroids[j][iv] = sqrt(pInput->Get_Variance(m_Features[i])) * Centroids[j][iv] + pInput->Get_Mean(m_Features[i]); } iv++; } } Write_Result(Parameters("STATISTICS")->asTable(), nElements, nCluster, SP); //------------------------------------------------- if( DataObject_Get_Parameters(pResult, Parms) && Parms("COLORS_TYPE") && Parms("LUT") && Parms("LUT_ATTRIB") ) { CSG_Table_Record *pClass; CSG_Table *pLUT = Parms("LUT")->asTable(); for( int i=0; i<nCluster; i++ ) { if( (pClass = pLUT->Get_Record(i)) == NULL ) { pClass = pLUT->Add_Record(); pClass->Set_Value(0, SG_GET_RGB(rand() * 255.0 / RAND_MAX, rand() * 255.0 / RAND_MAX, rand() * 255.0 / RAND_MAX)); } pClass->Set_Value(1, CSG_String::Format(SG_T("%s %d"), _TL("Class"), i)); pClass->Set_Value(2, CSG_String::Format(SG_T("%s %d"), _TL("Class"), i)); pClass->Set_Value(3, i); pClass->Set_Value(4, i); } while( pLUT->Get_Record_Count() > nCluster ) { pLUT->Del_Record(pLUT->Get_Record_Count() - 1); } Parms("COLORS_TYPE") ->Set_Value(1); // Color Classification Type: Lookup Table Parms("LUT_ATTRIB") ->Set_Value(clustField); DataObject_Set_Parameters(pResult, Parms); } //------------------------------------------------- for( int i=0; i<nCluster; i++ ) { SG_Free(Centroids[i]); } SG_Free(Centroids); SG_Free(Variances); SG_Free(nMembers); vValues.clear(); return( true ); }
//--------------------------------------------------------- bool CMOLA_Import::On_Execute(void) { bool bDown; int xa, xb, y, yy, NX, NY; short *sLine; double D, xMin, yMin; CSG_File Stream; TSG_Data_Type Type; CSG_Grid *pGrid; CSG_String fName, sName; //----------------------------------------------------- pGrid = NULL; switch( Parameters("TYPE")->asInt() ) { case 0: Type = SG_DATATYPE_Short; break; case 1: default: Type = SG_DATATYPE_Float; break; } bDown = Parameters("ORIENT")->asInt() == 1; //----------------------------------------------------- // MEGpxxnyyyrv // 012345678901 // p indicates the product type (A for areoid, C for counts, R for // radius, and T for topography) // xx is the latitude of the upper left corner of the image // n indicates whether the latitude is north (N) or south (S) // yyy is the east longitude of the upper left corner of the image // r is the map resolution using the pattern // c = 4 pixel per degree // e = 16 pixel per degree // f = 32 pixel per degree // g = 64 pixel per degree // h = 128 pixel per degree // (This convention is consistent with that used for the Mars Digital // Image Model [MDIM] archives.) // v is a letter indicating the product version. fName = SG_File_Get_Name(Parameters("FILE")->asString(), false); fName.Make_Upper(); if( fName.Length() < 12 ) { return( false ); } //----------------------------------------------------- switch( fName[3] ) { default: return( false ); case 'A': sName.Printf(SG_T("MOLA: Areoid v%c") , fName[11]); break; case 'C': sName.Printf(SG_T("MOLA: Counts v%c") , fName[11]); break; case 'R': sName.Printf(SG_T("MOLA: Radius v%c") , fName[11]); break; case 'T': sName.Printf(SG_T("MOLA: Topography v%c") , fName[11]); break; } //----------------------------------------------------- switch( fName[10] ) { default: return( false ); case 'C': // 1/4th degree... D = 1.0 / 4.0; NX = 4 * 360; NY = 4 * 180; yMin = - 90.0; xMin = -180.0; break; case 'D': // 1/8th degree... D = 1.0 / 8.0; NX = 8 * 360; NY = 8 * 180; yMin = - 90.0; xMin = -180.0; break; case 'E': // 1/16th degree... D = 1.0 / 16.0; NX = 16 * 360; NY = 16 * 180; yMin = - 90.0; xMin = -180.0; break; case 'F': // 1/32th degree... D = 1.0 / 32.0; NX = 32 * 360; NY = 32 * 180; yMin = - 90.0; xMin = -180.0; break; case 'G': // 1/64th degree... D = 1.0 / 64.0; NX = 64 * 180; NY = 64 * 90; yMin = (fName[6] == 'S' ? -1.0 : 1.0) * fName.Right(8).asInt(); yMin = bDown ? yMin - NY * D : -yMin; xMin = fName.Right(5).asInt(); if( xMin >= 180.0 ) { xMin -= 360.0; } break; case 'H': // 1/128th degree... D = 1.0 / 128.0; NX = 128 * 90; NY = 128 * 44; yMin = (fName[6] == 'S' ? -1.0 : 1.0) * fName.Right(8).asInt(); yMin = bDown ? yMin - NY * D : -yMin; xMin = fName.Right(5).asInt(); if( xMin >= 180.0 ) { xMin -= 360.0; } break; } //----------------------------------------------------- if( Stream.Open(Parameters("FILE")->asString(), SG_FILE_R, true) ) { if( (pGrid = SG_Create_Grid(Type, NX, NY, D, xMin + D / 2.0, yMin + D / 2.0)) != NULL ) { pGrid->Set_Name(sName); pGrid->Set_NoData_Value(-999999); pGrid->Get_Projection().Create(SG_T("+proj=lonlat +units=m +a=3396200.000000 +b=3376200.000000"), SG_PROJ_FMT_Proj4); //--------------------------------------------- sLine = (short *)SG_Malloc(NX * sizeof(short)); for(y=0; y<NY && !Stream.is_EOF() && Set_Progress(y, NY); y++) { yy = bDown ? NY - 1 - y : y; Stream.Read(sLine, NX, sizeof(short)); if( fName[10] == 'G' || fName[10] == 'H' ) { for(xa=0; xa<NX; xa++) { SG_Swap_Bytes(sLine + xa, sizeof(short)); pGrid->Set_Value(xa, yy, sLine[xa]); } } else { for(xa=0, xb=NX/2; xb<NX; xa++, xb++) { SG_Swap_Bytes(sLine + xa, sizeof(short)); SG_Swap_Bytes(sLine + xb, sizeof(short)); pGrid->Set_Value(xa, yy, sLine[xb]); pGrid->Set_Value(xb, yy, sLine[xa]); } } } //--------------------------------------------- SG_Free(sLine); Parameters("GRID")->Set_Value(pGrid); } } return( pGrid != NULL ); }
//--------------------------------------------------------- bool CSG_Grid::_Load_Binary(CSG_File &Stream, TSG_Data_Type File_Type, bool bFlip, bool bSwapBytes) { char *Line, *pValue; int x, y, i, iy, dy, nxBytes, nValueBytes; if( Stream.is_Open() && is_Valid() ) { Set_File_Type(GRID_FILE_FORMAT_Binary); if( bFlip ) { y = Get_NY() - 1; dy = -1; } else { y = 0; dy = 1; } //------------------------------------------------- if( File_Type == SG_DATATYPE_Bit ) { nxBytes = Get_NX() / 8 + 1; if( m_Type == File_Type && m_Memory_Type == GRID_MEMORY_Normal ) { for(iy=0; iy<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(iy, Get_NY()); iy++, y+=dy) { Stream.Read(m_Values[y], sizeof(char), nxBytes); } } else { Line = (char *)SG_Malloc(nxBytes); for(iy=0; iy<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(iy, Get_NY()); iy++, y+=dy) { Stream.Read(Line, sizeof(char), nxBytes); for(x=0, pValue=Line; x<Get_NX(); pValue++) { for(i=0; i<8 && x<Get_NX(); i++, x++) { Set_Value(x, y, (*pValue & m_Bitmask[i]) == 0 ? 0.0 : 1.0); } } } SG_Free(Line); } } //------------------------------------------------- else { nValueBytes = SG_Data_Type_Get_Size(File_Type); nxBytes = Get_NX() * nValueBytes; if( m_Type == File_Type && m_Memory_Type == GRID_MEMORY_Normal && !bSwapBytes ) { for(iy=0; iy<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(iy, Get_NY()); iy++, y+=dy) { Stream.Read(m_Values[y], sizeof(char), nxBytes); } } else { Line = (char *)SG_Malloc(nxBytes); for(iy=0; iy<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(iy, Get_NY()); iy++, y+=dy) { Stream.Read(Line, sizeof(char), nxBytes); for(x=0, pValue=Line; x<Get_NX(); x++, pValue+=nValueBytes) { if( bSwapBytes ) { _Swap_Bytes(pValue, nValueBytes); } switch( File_Type ) { default: break; case SG_DATATYPE_Byte: Set_Value(x, y, *(BYTE *)pValue); break; case SG_DATATYPE_Char: Set_Value(x, y, *(char *)pValue); break; case SG_DATATYPE_Word: Set_Value(x, y, *(WORD *)pValue); break; case SG_DATATYPE_Short: Set_Value(x, y, *(short *)pValue); break; case SG_DATATYPE_DWord: Set_Value(x, y, *(DWORD *)pValue); break; case SG_DATATYPE_Int: Set_Value(x, y, *(int *)pValue); break; case SG_DATATYPE_Float: Set_Value(x, y, *(float *)pValue); break; case SG_DATATYPE_Double: Set_Value(x, y, *(double *)pValue); break; } } } SG_Free(Line); } } //------------------------------------------------- SG_UI_Process_Set_Ready(); return( true ); } return( false ); }
//--------------------------------------------------------- bool CSG_mRMR::Get_Selection(int nFeatures, int Method) { m_pSelection->Del_Records(); if( !m_Samples[0] ) { SG_UI_Msg_Add_Error("The input data is NULL."); return( false ); } if( nFeatures < 0 ) { SG_UI_Msg_Add_Error("The input number of features is negative."); return( false ); } long poolUseFeaLen = 500; if( poolUseFeaLen > m_nVars - 1 ) // there is a target variable (the first one), that is why must remove one poolUseFeaLen = m_nVars - 1; if( nFeatures > poolUseFeaLen ) nFeatures = poolUseFeaLen; long *feaInd = new long[nFeatures]; if( !feaInd ) { SG_UI_Msg_Add_Error("Fail to allocate memory."); return( false ); } //----------------------------------------------------- // determine the pool TPool *Pool = (TPool *)SG_Malloc(m_nVars * sizeof(TPool)); if( !Pool ) { SG_UI_Msg_Add_Error("Fail to allocate memory."); return( false ); } //----------------------------------------------------- long i, j, k; for(i=0; i<m_nVars; i++) // the Pool[0].mival is the entropy of target classification variable { Pool[i].mival = -Get_MutualInfo(0, i); // set as negative for sorting purpose Pool[i].Index = i; Pool[i].Mask = 1; // initialized to be everything in pool would be considered } qsort(Pool + 1, m_nVars - 1, sizeof(TPool), Pool_Compare); Pool[0].mival = -Pool[0].mival; ADD_MESSAGE(CSG_String::Format( SG_T("\nTarget classification variable (#%d column in the input data) has name=%s \tentropy score=%5.3f"), 0 + 1, m_VarNames[0].c_str(), Pool[0].mival )); ADD_MESSAGE("\n*** MaxRel features ***"); ADD_MESSAGE("Order\tFea\tName\tScore"); for(i=1; i<m_nVars-1; i++) { Pool[i].mival = -Pool[i].mival; if( i <= nFeatures ) { ADD_MESSAGE(CSG_String::Format(SG_T("%d \t %d \t %s \t %5.3f"), i, (int)Pool[i].Index, m_VarNames[(int)Pool[i].Index].c_str(), Pool[i].mival )); } } //----------------------------------------------------- // mRMR selection long poolFeaIndMin = 1; long poolFeaIndMax = poolFeaIndMin + poolUseFeaLen - 1; feaInd[0] = Pool[1].Index; Pool[feaInd[0]].Mask = 0; // after selection, no longer consider this feature Pool[0 ].Mask = 0; // of course the first one, which corresponds to the classification variable, should not be considered. Just set the mask as 0 for safety. ADD_MESSAGE("\n*** mRMR features ***"); ADD_MESSAGE("Order\tFea\tName\tScore"); ADD_FEATURE(0, Pool[1].mival); for(k=1; k<nFeatures; k++) //the first one, feaInd[0] has been determined already { double relevanceVal, redundancyVal, tmpscore, selectscore; long selectind; int b_firstSelected = 0; for(i=poolFeaIndMin; i<=poolFeaIndMax; i++) { if( Pool[Pool[i].Index].Mask == 0 ) { continue; // skip this feature as it was selected already } relevanceVal = Get_MutualInfo(0, Pool[i].Index); // actually no necessary to re-compute it, this value can be retrieved from Pool[].mival vector redundancyVal = 0; for(j=0; j<k; j++) { redundancyVal += Get_MutualInfo(feaInd[j], Pool[i].Index); } redundancyVal /= k; switch( Method ) { default: // fprintf(stderr, "Undefined selection method=%d. Use MID instead.\n", mymethod); case SG_mRMR_Method_MID: tmpscore = relevanceVal - redundancyVal; break; case SG_mRMR_Method_MIQ: tmpscore = relevanceVal / (redundancyVal + 0.0001); break; } if( b_firstSelected == 0 ) { selectscore = tmpscore; selectind = Pool[i].Index; b_firstSelected = 1; } else if( tmpscore > selectscore ) { //update the best feature found and the score selectscore = tmpscore; selectind = Pool[i].Index; } } feaInd[k] = selectind; Pool[selectind].Mask = 0; ADD_FEATURE(k, selectscore); } //----------------------------------------------------- return( true ); }
//--------------------------------------------------------- bool CSG_Grid::_Save_Binary(CSG_File &Stream, int xA, int yA, int xN, int yN, TSG_Data_Type File_Type, bool bFlip, bool bSwapBytes) { char *Line, *pValue; int x, y, i, ix, iy, dy, axBytes, nxBytes, nValueBytes; //----------------------------------------------------- if( Stream.is_Open() && m_System.is_Valid() && m_Type != SG_DATATYPE_Undefined ) { Set_File_Type(GRID_FILE_FORMAT_Binary); if( bFlip ) { y = yA + yN - 1; dy = -1; } else { y = yA; dy = 1; } //------------------------------------------------- if( File_Type == SG_DATATYPE_Bit ) { nxBytes = xN / 8 + 1; if( m_Type == File_Type && m_Memory_Type == GRID_MEMORY_Normal && xA % 8 == 0 ) { axBytes = xA / 8; for(iy=0; iy<yN && SG_UI_Process_Set_Progress(iy, yN); iy++, y+=dy) { Stream.Write((char *)m_Values[y] + axBytes, sizeof(char), nxBytes); } } else { Line = (char *)SG_Malloc(nxBytes); for(iy=0; iy<yN && SG_UI_Process_Set_Progress(iy, yN); iy++, y+=dy) { for(ix=0, x=xA, pValue=Line; ix<xN; pValue++) { for(i=0; i<8 && ix<xN; i++, ix++, x++) { *pValue = asChar(x, y) != 0.0 ? *pValue | m_Bitmask[i] : *pValue & (~m_Bitmask[i]); } } Stream.Write(Line, sizeof(char), nxBytes); } SG_Free(Line); } } //------------------------------------------------- else { nValueBytes = SG_Data_Type_Get_Size(File_Type); nxBytes = xN * nValueBytes; if( m_Type == File_Type && m_Memory_Type == GRID_MEMORY_Normal && !bSwapBytes ) { axBytes = xA * nValueBytes; for(iy=0; iy<yN && SG_UI_Process_Set_Progress(iy, yN); iy++, y+=dy) { Stream.Write((char *)m_Values[y] + axBytes, sizeof(char), nxBytes); } } else { Line = (char *)SG_Malloc(nxBytes); for(iy=0; iy<yN && SG_UI_Process_Set_Progress(iy, yN); iy++, y+=dy) { for(ix=0, x=xA, pValue=Line; ix<xN; ix++, x++, pValue+=nValueBytes) { switch( File_Type ) { default: break; case SG_DATATYPE_Byte: *(BYTE *)pValue = asChar (x, y); break; case SG_DATATYPE_Char: *(char *)pValue = asChar (x, y); break; case SG_DATATYPE_Word: *(WORD *)pValue = asShort (x, y); break; case SG_DATATYPE_Short: *(short *)pValue = asShort (x, y); break; case SG_DATATYPE_DWord: *(DWORD *)pValue = asInt (x, y); break; case SG_DATATYPE_Int: *(int *)pValue = asInt (x, y); break; case SG_DATATYPE_Float: *(float *)pValue = asFloat (x, y); break; case SG_DATATYPE_Double: *(double *)pValue = asDouble (x, y); break; } if( bSwapBytes ) { _Swap_Bytes(pValue, nValueBytes); } } Stream.Write(Line, sizeof(char), nxBytes); } SG_Free(Line); } } //------------------------------------------------- SG_UI_Process_Set_Ready(); return( true ); } return( false ); }