Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Class Members | File Members

Raster2D.h

Go to the documentation of this file.
00001 //------------------------------------------------------------------------------
00002 //
00003 //  Thomas Berger (main author), Pepijn Schreinemachers, and Thorsten Arnold
00004 //                                
00005 //
00006 //  Hohenheim University (490d)
00007 //  Professorship for Land Use Economics in the Tropics and Subtropics
00008 //
00009 //  May not be distributed without permission by main author
00010 //
00011 //  File:       Raster2D.h (formerly Raster2D.h)
00012 //
00013 //  Contents:   Auxiliary class, handles 2-dimensional raster
00014 //
00015 //
00016 //
00017 //------------------------------------------------------------------------------
00018 
00019 
00020 #ifndef _Raster2D_h
00021 #define _Raster2D_h
00022 
00023 
00024 // Libraries C++
00025 #include <stdio.h>
00026 #include <iostream>
00027 using namespace std;
00028 #include <fstream>
00029 #include <string.h>
00030 #include "MatrixDouble.h"
00031 #include "BasicEnums.h"
00032 
00034 // INCLUDE TDT FUNTIONS INTO FILE - ONLY POSSIBLE UNDER LINUX
00036 #ifdef DO_TDT
00037    extern "C" {
00038    #include "tdt.h"
00039    }
00040 #endif
00041 
00042 class sector;
00043 
00044 
00045 enum modeRaster {
00046         modeIJ, modeXY
00047 };
00048 
00049 // -------------------------------
00050 // CLASS DEFINITION
00051 // -------------------------------
00052 // Function  contains all infrmation normally written in a binary ascii GIS file,
00053 // as it is exported by Geographical Information Systems (GIS), including ArcInfo, GRASS,
00054 // It is also a standard for many models in hydrology and land use.
00055 // Thus, this class is
00056 //
00057 // Outputs can be translated (or written) as ASCII-Tables, as
00058 //
00059 class Raster2D
00060 {
00061    protected:
00062    int numCols;
00063    int numRows;
00064    double xcoord;
00065    double ycoord;
00066    double cellsize;
00067    int noData;
00068    Content gisCont;
00069 
00070    //GISrel2abs
00071    int Xshift;
00072    int Yshift;
00073 
00074    //Arnold2006_96
00075    long double statanz,statmini,statmaxi,sx,sx2;
00076    float stat_nodata;
00077 
00078    // Matrix of class "matrix9.cpp"
00079    // Thorsten Arnold, Thomas Berger
00080    MatrixDouble mat;
00081 
00082    string filenameGis; //maximal 50 Zeichen
00083 
00084    virtual void copyHeader(Raster2D& gis);
00085 
00086    virtual void copyHeader(const Raster2D& gis);
00087 
00088    // Sum the absolute values of (gisB[r][c] .- gisMother[r][c])
00089    virtual double gisStruct_sumDiff(Raster2D& gisB);
00090 
00091 
00092 
00093    public:
00094       Raster2D(void);                   //Uebergabe: Output-Dateikrzel
00095       Raster2D(int cols, int rows);                     //Uebergabe: Output-Dateikrzel
00096       Raster2D(int cols, int rows, int xcoord, int ycoord, double cellS, int nodata);
00097       Raster2D(int cols, int rows, double xcoord, double ycoord, double cellS, int nodata);
00098       // Opens GIS-ASCII file, then initializes with header-information, and reads data
00099       Raster2D(string fn);
00100       // Expects open GIS-ASCII file, initializes with header-information, and reads data
00101       Raster2D(ifstream&  stream);
00102 
00103       // Allcoate memory
00104       virtual void initializeEmpty();
00105       // NOT SUPPORTED ANY MORE
00106       virtual void initializeFile(ifstream&  stream);
00107       // Opens file <fn> and then calls <initializeFromFile(ifstream&  streamData)>
00108       virtual void initializeFromFile(string fn);
00109       // Reads data from GIS-ASCII-file: First reads header, initializes memory, then reads data.
00110       virtual void initializeFromFile(ifstream&  streamData);
00111 
00112       // Copies only MatrixDouble, without any checks. Assuming same size!
00113       virtual void copyMatFromThis(Raster2D& target);
00114       virtual void initCopy(const Raster2D& RHS);
00115       virtual void copyHeaderFromThis(Raster2D& target);
00116 
00117       virtual void allocate(int rows, int cols);
00118       virtual void allocate(int rows, int cols, double val);
00119       virtual void allocate(int cols, int rows, int xc, int yc, double cellS, int noD); // Cast to int
00120       virtual void allocate(int rows, int cols, double xc, double yc, double cellS, int noD);
00121       virtual void allocate(void);
00122 
00123       // Allocate to new the same dimensions as to passed Raster2D;
00124       // Initialize also with gis.getNodata()
00125       virtual void allocate(Raster2D& gis);
00126       virtual void setEmptyVal(double val);
00127       virtual void setEmptyVal(int val); // cast to double
00128       // Identical to setEmptyVal: Overwrites complete MatrixDouble
00129       virtual void setAllValues(double val);
00130       
00131       // Fill all with nodata
00132       virtual void setEmpty();
00133 
00134       //Write  value 'val' into every MatrixDouble position which is 'noData'
00135       // Also modify NodataVal
00136       virtual void setNodataValuesToVal(int val);
00137 
00138       //virtual bool checkIfEqualHeaders(Raster2D& rhs);  
00139       virtual double sumAll();
00140 
00141 
00142       // Operator "="
00143       const Raster2D& operator = (const Raster2D& );
00144 
00145       // a) Copy Constructur for Raster2D
00146       Raster2D(const Raster2D& gisOrig) ;
00147 
00148    // Destructor
00149         virtual ~Raster2D();
00150         virtual void deallocate(void);
00151 
00152       // -------------------------------------- //
00153       // ACCESS FUNCTIONS
00154       // returns number of columns
00155       int getCols()      { return numCols; }
00156       int cols() const   { return numCols; }  //For consistency with MatrixDouble-class
00157       int cols()         { return numCols; }
00158       // returns number of rows
00159       int getRows()      { return numRows; }
00160       int rows() const   { return numRows; }
00161       int rows()         { return numRows; }
00162 
00163       // returns x-coordinate;
00164       // often internally used as "shift" in cells 
00165       // from origin of larger Raster2D
00166 
00167       double getXcoord()         { return xcoord; }
00168       double getYcoord()         { return ycoord; }
00169       double getXcoord() const   { return xcoord; }
00170       double getYcoord() const   { return ycoord; }
00171 
00172       // returns length of square grid
00173       double getCellsize()       { return cellsize; }
00174       double getCellsize() const { return cellsize; }
00175       // returns value for "empty" or "Nodata"
00176       int getNodata()            { return noData; }
00177       int getNodata() const      { return noData; }
00178       int getNoData()            { return noData; }
00179       int getNoData() const      { return noData; }
00180       Content getContent()       { return gisCont; }
00181       Content getContent() const { return gisCont; }
00182       void setContent(Content gisC){ gisCont = gisC; }
00183 
00184       string getFilename() const { return filenameGis;}
00185       void  setFilename(string s){ filenameGis = s;}
00186 
00187       // Retrieving values from GIS STRUCT
00188       // (Function always returns constant double!)
00189       virtual double getValue(int r, int c) const;
00190             // This function calls for a constant. It is simply
00191             // passed on to the non-constant version!
00192 
00193       // Function for a call with enum-Type
00194       //    (position in irrigation MatrixDouble; internal use only...)
00195       double getValue(enumIrrigationPosition r, int c) const
00196                                  {return getValue((int) r, c);}
00197 
00198 
00199       // Copy complete file to Raster2D "target"
00200       virtual void copyFromThis(Raster2D& target);
00201 
00202       //Arnold2006_87
00203       // get maximum of complete MatrixDouble
00204       virtual double getMax(void);
00205       // get maximum of specified row
00206       virtual double getMax_row(int row);
00207       // get maximum of specified col
00208       virtual double getMax_col(int col);
00209 
00210       // sets number of rows (int numR), DANGEROUS! does not re-size MatrixDouble
00211       void setCols(int c)        { numCols = c;}
00212       void setRows(int r)        {  numRows = r;   }
00213 
00214       //sets double xcoord. Used as "origin" of small gis within larger gis,
00215       // when copying one MatrixDouble into another
00216       void setXcoord(int xc)     { xcoord = (double)xc; } //casted to double
00217       void setYcoord(int yc)     { ycoord = (double)yc; }
00218       void setXcoord(double xc)  { xcoord = xc; }
00219       void setYcoord(double yc)  { ycoord = yc; }
00220 
00221       void setCellsize(double cellS) {cellsize = cellS;}
00222       void setNodata(int nodata) {noData = nodata;}
00223       // Change all noData values to new nodata value
00224       void changeNodata(int);
00225 
00226       // Passing values TO gisstruct FROM extern
00227       virtual void setValue(int r, int c, int val); // Cast to double
00228       virtual void setValue(int r, int c, double val);
00229       
00230       void setValue(enumIrrigationPosition r, int c, double val)
00231       {setValue((int) r, c, val);
00232       }
00233 
00234       // makes histogram of Raster2D
00235       virtual void makeHist(MatrixDouble& mat); // Takes by reference: Empty MatrixDouble (not yet allocated!)
00236       virtual void makeHistNoNodata(MatrixDouble& histMat); 
00237                 // Takes by reference: Empty MatrixDouble (not yet allocated!)
00238                 
00239       virtual void uniqueNoNodata(MatrixDouble& unMat); // Takes by reference: Empty MatrixDouble (not yet allocated!)
00240 
00241         // MatrixDouble matHist;
00242         // Raster2D gis(filename);
00243         // gis.makeHist(mat);
00244         // mat.printToScreenInt();
00245         
00246       // -------------------------------------- //
00247       // FILE ACCESS FUNCTIONS
00248       // writes gis-Struct into open C++ file stream, can be read from ArcGIS
00249       virtual void writeToGisFile_header(ofstream&  streamData);
00250       
00251       virtual void writeToGisFile(ofstream&  stream);
00252       virtual void writeToFile(string str);
00253                 
00254                 // First: Filename 
00255                 //      (default: 
00256                 //                      - FILENAMES(keyLOG) for DOLONG==false, 
00257                 //                      - FILENAMES(keyLOG2)  for DOLONG==true )
00258                 // Name of TDT configuration file
00259                 // type of communication: 1 SEND, 0 RECEIVE
00260                 // DOLONG: Also write some content of MatrixDouble
00261                 virtual void  writeLogfileTDT(string fn, char*  configFile, int type, bool dolong);
00262       virtual void writeLogfileRW(string fn, char* matFN, int type);
00263       virtual void writeLogfileRW(string fn, string matFN, int type);
00264    
00265       virtual void readHeaderAllocate(ifstream&  stream);
00266       virtual void readHeaderAllocate(string fn);
00267       //writes Raster2D as binary file, Routine taken from WASIM-ETH
00268       virtual void writeToBinFile(string  filenameOut);
00269       virtual void readFromBinFile(string  filenameIn);
00270       virtual void initializeSizeFromBinFile(string  fn);
00271       
00272       virtual void readFromFile(string filenameIn);
00273 
00274 
00275 
00276       // Sparse Matrix:
00277       //    header (normal)
00278       //    row  col  val
00279 
00280       virtual void writeToFile_sparse(string str);
00281       virtual void writeToFile_sparse(char* fn);
00282       virtual void writeToFile_sparse(ofstream& out);
00283 
00284       virtual void loadFromFile_sparse(ifstream& streamData);
00285       virtual void loadFromFile_sparse(string fn);
00286       virtual void loadFromFile_sparse(char* fn);
00287 
00289       // OUTPUT FUNCTIONS
00291       virtual void printHeader()   ;
00292 
00293       // Print complete MatrixDouble and header, as doubles
00294       virtual void printToScreen(void);
00295       virtual void printToScreen(MatrixDouble& minmax);
00296       virtual void printToScreen(int rlu, int clu, int rdr, int cdr);
00297 
00298       // shorter form: Print int's as int's, and only up to two digits
00299       virtual void printToScreen_compact(void);
00300 
00301       // takes MatrixDouble minmax (passed back from function <Raster2D::findMinMax(..)>
00302       // Prints in compact form a rectangle from within the complete area
00303       //
00304       //  minmax  [ minRow,  maxRow ]
00305       //          [ minCol,  maxCol ]
00306       virtual void printToScreen_compact(MatrixDouble& minmax);
00307       virtual void printToScreen_compact(int rlu, int clu, int rdr, int cdr);
00308 
00309 
00310 
00312       //    JOINING AND EXTRACTING
00314 
00315 
00316       // Shifts coordinates of Land Use to absolute values, assuming that WASIMluse-coordinates 
00317       // are the origin and <THIS>-coordinates contain the shift as number of grid cells
00318       //
00319       //  Also, remembers relative values of masLU for later re-shift
00320       virtual void shift_coordinats_rel2abs(Raster2D& C);
00321       
00322       // Only calculates shift from ORIGIN from relative coordinates, which are then returned
00323       // as reference
00324       // m.getValue(0): row-shift dY
00325       // m.getValue(1): col-shift dX
00326       virtual void coord_rel2abs(MatrixDouble& m);
00327       
00328 
00329       // Extracts a number of values
00330       // MatrixDouble minmax is passed back from MatrixDouble::findMinMax(MatrixDouble& minmax);
00331       //
00332       //  minmax  [ minRow,  maxRow ]
00333       //          [ minCol,  maxCol ]
00334       // Returns Raster2D with same dimensions, where the row/col-shift is
00335       // still stored in Yshift/ Xshift
00336       virtual void extractNew(
00337                 Raster2D& empt,
00338                 MatrixDouble& minmax);
00339 
00340 
00341       // Extracts a number of values
00342       virtual void extractNew(
00343             Raster2D& empt,
00344             int row_left_up, int col_left_up,
00345             int numRows, int numCols); // default; modeXY
00346 
00347       virtual void extractNew(
00348             Raster2D& empt,
00349             int row_left_up, int col_left_up,
00350             int numRows, int numCols, modeRaster mode);
00351 
00352 
00353       // Extracts map that contains values around
00354       virtual void extractTight(Raster2D& empt);
00355 
00356       
00357       // Extraction function from TOTAL coordinates
00358       // Now xTarget, yTarget are the total coordinates [m]
00359       // lengthXdir, lengthYdir are the length of the target Raster2D in [m]
00360       virtual void extractTotal(Raster2D& target,
00361             double xTarget, double yTarget,
00362             double lengthXdir, double lengthYdir);
00363 
00364       // Extracts a number of values
00365       virtual void extractMat(MatrixDouble& empt,
00366             int row_left_up, int col_left_up,
00367             int numRows, int numCols);
00368 
00369 
00370       // Function copies all data values (not NODATA) from THIS into 'rejoin'.
00371       // REMEMBER: the row/col - shift is taken from xcoord (cols), ycoord (rows)
00372       //           of THIS
00373 //      virtual void join(Raster2D& rejoin);
00374 //      virtual void joinAbs(Raster2D& rejoin);
00375 
00376       virtual void joinTotal(Raster2D& rejoin);
00377 
00378       // Function takes all values of THIS amd copies them into a new Raster2D 'target'
00379       // It shirnks the MatrixDouble by cutting off ALL rows and cols that are both EMPTY
00380       // and WITHIN the Raster2D
00381       //
00382       // This function actually does NOT re-create posMAT, carefull!
00383       // Use 'Raster2D::getPosMatForVal' or the MatrixDouble-functions 'findAllEntriesEquallingValue'
00384       // or 'getAllValPos'  before, create posMat,
00385       //  then pass that (as reference only because of speed!)
00386       virtual void shrink(Raster2D& target, MatrixDouble& posMat);
00387       virtual void shrink(Raster2D& target, MatrixDouble& posMat, modeRaster mode);
00388 
00389 
00390       
00391    // Count entries that are not NODATA
00392    virtual int countNOT_NODATA();
00393    virtual int countDATA(double DATA);
00394 
00395       // Function returns (by reference) a key that is 'true' wherever
00396       // motherGis[r][c] == val
00397       // Also returns Position-Matrix
00398       virtual void getKeyForVal(Raster2D& keyG, double val, MatrixDouble& posMat);
00399       virtual void getKeyForVal(Raster2D& keyG, double val);
00400 
00401    //Writes all values equal to 'val' into posMAT
00402    virtual int findAllEntriesEquallingValue(MatrixDouble& posMat, double ISVAL);
00403 
00404    //Writes all values not equal to 'noVal' into posMAT
00405    virtual int getAllValPos(MatrixDouble& posMat);
00406    
00407 
00408    int getNumberOfDataValues()
00409    {
00410       MatrixDouble posMat;
00411       int numValues = getAllValPos(posMat);
00412       return numValues;    
00413    }
00414 
00415 
00416    virtual void setAllInPosMatWithValue(MatrixDouble& posMat, double val);
00417    virtual void setAllInPosMatWithValueUnequal(MatrixDouble& posMat, double val, double badVal);
00418 
00419       //Gets POSITION MATRIX
00420       // dimension: numValues X 3
00421       //  row   column   value (!=nodata)
00422       virtual void getPosMatForVal(MatrixDouble& posMat, double val);
00423 
00424       // As before, but gets all positions not equal to NODATA
00425       virtual void getPosMatForAllData(MatrixDouble& posMat);
00426       // FUnction returns vector as indicated by posMat
00427       virtual void filterByPosMat(MatrixDouble& posMat, MatrixDouble& vec);
00428       virtual void updatePosMat(MatrixDouble& posMat);
00429             
00430       virtual void overwriteWithPosMatContent(MatrixDouble& posMat);
00431 
00432 
00433       // --------------------------------------------------------------------//
00434       // TRANSLATION FUNCTIONS
00435       // translate()
00436       // Inputs:
00437       //    - original gisSturct
00438       //    - Vector with values of original Raster2D, vOrig
00439       //    - Vector with target values
00440       // Idea:
00441       //    -  first finds value gisO.getValue(r,c) in vOrig, return POS
00442       //    -  vTarget.getVale(pos) returns target value valT
00443       //    -  setValue(r,c,valT);
00444       //
00445       //    Warning: ONLY FOR INTEGER VALUES! CAREFULL
00446       virtual void translate(Raster2D& gisO, MatrixDouble& vOrig, MatrixDouble& vTarget) ;
00447       // Get target value for single value
00448       // Does translation for above function, but only takes single value
00449       virtual double getTrans(int val, MatrixDouble& vOrig, MatrixDouble& vTarget);
00450 
00451       virtual void readGisFile_Cont(Content cont, int catchID);
00452 
00453       //MANIPULATION FUNCTIONS
00454 
00455       //Mast2006_07
00456       // Subtracts GS1 - GS2 and assigns it to mother;
00457       // Also checks if noData is identical for both matrixes
00458       virtual void gisStruct_diff(Raster2D& GS1, Raster2D& GS2);
00459       virtual void gisStruct_diff_rel(Raster2D& GS1, Raster2D& GS2);
00460       virtual void translateLuse(Raster2D& masLuse, MatrixDouble& cAtoMl, MatrixDouble& MAStoWASIM);
00461 
00463 // INCLUDE TDT FUNTIONS INTO FILE - ONLY POSSIBLE UNDER LINUX
00465 
00466    virtual void sendViaTDT(string configFile);
00467    virtual void receiveViaTDT(string configFile);
00468 
00469    virtual void sendViaTDT(char* configFile);
00470    virtual void receiveViaTDT(char* configFile);
00471 
00472    #ifdef DO_TDT
00473    virtual void sendViaTDT_open(TDTConfig& tc, TDTState& ts);
00474    virtual void receiveViaTDT_open(TDTConfig& tc, TDTState& ts);
00475         #endif
00476 
00477    //Arnold2006_97
00478    virtual void clearstat();
00479    virtual void statistics(float *anzahl,float *mini,float *maxi,float *summe,float *mittel,float *std);
00480    virtual void addstat(float x);
00481 
00482    //Arnold2006_101
00483    // Compare header
00484    virtual bool gisStruct_compH(Raster2D& gisB);
00485    // First compares header, later complete file
00486    virtual bool gisStruct_compAll(Raster2D& gisB);
00487 
00488    // Calculate elementwise
00489    // All assume same MatrixDouble dimensions, and return NODATAVALUE.
00490    // If one of the matrixes contains "NODATAVALUE", then THIS will be NODATAVALUE
00491    // Operator performed on m1 - / + / * / div m2
00492    virtual void subtract(Raster2D& g1, Raster2D& g2);
00493    virtual void add(Raster2D& g1, Raster2D& g2);
00494    // Division by zero --> NODATAVAL
00495    virtual void divide(Raster2D& g1, Raster2D& g2);
00496    virtual void mult(Raster2D& g1, Raster2D& g2);
00497 
00498    virtual void addToVal(int r, int c, double val);
00499 
00500 
00501    // Returns position MatrixDouble of all entries that are NOT equal to 'val,
00502    // and also not NoData-values
00503    virtual int findNotEqual(double val, MatrixDouble& FOUND);
00504    virtual int findIsEqual(double val, MatrixDouble& FOUNDPOS);
00505    
00506   // Function determines minimum row / col and maximum row / col
00507    // and writes it into MatrixDouble minmax
00508    //
00509    //  minmax  [ minRow,  maxRow ]
00510    //          [ minCol,  maxCol ]
00511    virtual void findMinMax(MatrixDouble& minmax);
00512 
00513    virtual const Raster2D& mult(double val);
00514 
00515    // Returns "true" if there are values in both the first and last row, and first and last column
00516    //         "false" otherwise
00517    virtual bool isTight();
00518 
00519 
00520    //Arnold2006_200
00521    virtual void setValueByPos(int Pos, double val);
00522    virtual double getValueByPos(int Pos);
00523    //Arnold2006_200
00524    virtual int findMaxNotTrue(int col, MatrixDouble& isTrue);
00525 
00526    //Arnold2006_200
00527    // sorts MatrixDouble THIS by column specified in 'col', and writes result into mSorted
00528    // Function lets THIS untouched, sorts all values in one column 'col',
00529    // and sorts all other rows according to that order
00530    //
00531    // Once too much this function copies internally complete MatrixDouble
00532    virtual void sortByCol(int col, MatrixDouble& mSorted);
00533 
00534    virtual void rescale_C2f(
00535                Raster2D& gis_L,        // data
00536                int Y_shift_C2G,   // data
00537                int X_shift_C2G,    // data
00538                Raster2D& gisTarget     // reference to final data struct
00539                );
00540                
00541    virtual double getMeanIfNotNodata();
00542 
00543   virtual void asci2binary(char* source, char* target);
00544   virtual void asci2binary(string source, string target); 
00545 
00546   virtual double createByCoarseAndCopyDesign(
00547        Raster2D& rasterCoarse,
00548        Raster2D& rasterMASK,
00549        MatrixDouble& design);
00550   
00551 
00552 
00553     virtual void addDesignWhereMaskIsOne(
00554        Raster2D& rasterMASK,
00555        MatrixDouble& design);
00556 
00557   virtual double sizeUpRaster(
00558        Raster2D& rasterCoarseInput,
00559        Raster2D& rasterSize,
00560        MatrixDouble& design);
00561   
00562   virtual double sizeUpRasterAllocated(
00563        Raster2D& rasterCoarseInput,
00564        MatrixDouble& design);
00565   
00566   virtual double sizeUpRaster(
00567        Raster2D& rasterCoarse,
00568        string fn,
00569        MatrixDouble& design);
00570   virtual bool checkIfEqualHeaders(Raster2D& rhs);
00571   
00572 };
00573 
00574 
00575 
00576 #endif
00577 
00578 

Generated on Thu Aug 28 12:38:45 2008 for MPMAS by  doxygen 1.3.9.1