Subversion Repositories public iLand

Rev

Rev 48 | Rev 50 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1
 
15 Werner 2
#ifndef GRID_H
3
#define GRID_H
4
 
22 Werner 5
#include <QtCore>
15 Werner 6
 
7
 
8
#include <stdexcept>
9
 
10
/** Grid class (template).
11
 
12
  */
13
template <class T>
14
class Grid {
15
public:
16
 
17
    Grid();
18
    Grid(int cellsize, int sizex, int sizey) { mData=0; setup(cellsize, sizex, sizey); }
33 Werner 19
    // copy ctor
20
    Grid(const Grid<T>& toCopy);
15 Werner 21
    ~Grid() { if (mData) delete[] mData; }
22
 
18 Werner 23
    bool setup(const float cellsize, const int sizex, const int sizey);
22 Werner 24
    bool setup(const QRectF& rect, const double cellsize);
37 Werner 25
    void initialize(const T& value) {for( T *p = begin();p!=end(); ++p) *p=value; qDebug()<<"Grid initialize"<<end()-begin()<<"items.";}
15 Werner 26
 
27
    const int sizeX() const { return mSizeX; }
28
    const int sizeY() const { return mSizeY; }
29
    const float metricSizeX() const { return mSizeX*mCellsize; }
30
    const float metricSizeY() const { return mSizeY*mCellsize; }
49 Werner 31
    QRectF metricRect() const { return mRect; }
15 Werner 32
    const float cellsize() const { return mCellsize; }
27 Werner 33
    const int count() const { return mCount; }
49 Werner 34
    const bool isEmpty() const { return mData==NULL; }
32 Werner 35
    // operations
15 Werner 36
    // query
33 Werner 37
    /// access (const) with index variables. use int.
38
    inline const T& operator()(const int ix, const int iy) const { return constValueAtIndex(ix, iy); }
39
    /// access (const) using metric variables. use float.
40
    inline const T& operator()(const float x, const float y) const { return constValueAt(x, y); }
48 Werner 41
    inline const T& operator[] (const QPointF &p) const { return constValueAt(p); }
33 Werner 42
 
25 Werner 43
    T& valueAtIndex(const QPoint& pos); ///< value at position defined by indices (x,y)
33 Werner 44
    T& valueAtIndex(const int ix, const int iy) { return valueAtIndex(QPoint(ix,iy)); } ///< const value at position defined by indices (x,y)
45
 
46
    const T& constValueAtIndex(const QPoint& pos) const; ///< value at position defined by a (integer) QPoint
32 Werner 47
    const T& constValueAtIndex(const int ix, const int iy) const { return constValueAtIndex(QPoint(ix,iy)); }
33 Werner 48
 
49
    T& valueAt(const QPointF& posf); ///< value at position defined by metric coordinates (QPointF)
50
    const T& constValueAt(const QPointF& posf) const; ///< value at position defined by metric coordinates (QPointF)
51
 
52
    T& valueAt(const float x, const float y); ///< value at position defined by metric coordinates (x,y)
53
    const T& constValueAt(const float x, const float y) const; ///< value at position defined by metric coordinates (x,y)
54
 
49 Werner 55
    bool coordValid(const float x, const float y) const { return mRect.contains(x,y); }
56
    bool coordValid(const QPointF &pos) const { return coordValid(pos.x(), pos.y()); }
57
    QPoint indexAt(const QPointF& pos) const { return QPoint(int((pos.x()-mRect.left()) / mCellsize),  int((pos.y()-mRect.top())/mCellsize)); } /// get index of value at position pos (metric)
27 Werner 58
    bool isIndexValid(const QPoint& pos) const { return (pos.x()>=0 && pos.x()<mSizeX && pos.y()>=0 && pos.y()<mSizeY); } /// get index of value at position pos (index)
59
    void validate(QPoint &pos) const{ pos.setX( qMax(qMin(pos.x(), mSizeX-1), 0) );  pos.setY( qMax(qMin(pos.y(), mSizeY-1), 0) );} /// ensure that "pos" is a valid key. if out of range, pos is set to minimum/maximum values.
49 Werner 60
    QPointF cellCoordinates(const QPoint &pos) { return QPointF( (pos.x()+0.5)*mCellsize+mRect.left(), (pos.y()+0.5)*mCellsize + mRect.top());} /// get metric coordinates of the cells center
27 Werner 61
    inline  T* begin() const { return mData; } ///< get "iterator" pointer
37 Werner 62
    inline  T* end() const { return mEnd; } ///< get iterator end-pointer
27 Werner 63
    QPoint indexOf(T* element) const; ///< retrieve index (x/y) of the pointer element. returns -1/-1 if element is not valid.
64
    // special queries
33 Werner 65
    T max() const; ///< retrieve the maximum value of a grid
66
    T sum() const; ///< retrieve the sum of the grid
67
    T avg() const; ///< retrieve the average value of a grid
68
    /// creates a grid with lower resolution and averaged cell values.
69
    /// @param factor factor by which grid size is reduced (e.g. 3 -> 3x3=9 pixels are averaged to 1 result pixel)
70
    /// @param offsetx, offsety: start averaging with an offset from 0/0 (e.g.: x=1, y=2, factor=3: -> 1/2-3/4 -> 0/0)
71
    /// @return Grid with size sizeX()/factor x sizeY()/factor
72
    Grid<T> averaged(const int factor, const int offsetx=0, const int offsety=0) const;
73
    /// normalized returns a normalized grid, in a way that the sum()  = @param targetvalue.
74
    /// if the grid is empty or the sum is 0, no modifications are performed.
75
    Grid<T> normalized(const T targetvalue) const;
15 Werner 76
private:
77
    T* mData;
37 Werner 78
    T* mEnd; ///< pointer to 1 element behind the last
49 Werner 79
    QRectF mRect;
36 Werner 80
    float mCellsize; ///< size of a cell in meter
81
    int mSizeX; ///< count of cells in x-direction
82
    int mSizeY; ///< count of cells in y-direction
83
    int mCount; ///< total number of cells in the grid
15 Werner 84
};
85
 
86
typedef Grid<float> FloatGrid;
87
 
33 Werner 88
// copy constructor
89
template <class T>
90
Grid<T>::Grid(const Grid<T>& toCopy)
91
{
40 Werner 92
    mData = 0;
33 Werner 93
    setup(toCopy.cellsize(), toCopy.sizeX(), toCopy.sizeY());
94
    const T* end = toCopy.end();
95
    T* ptr = begin();
96
    for (T* i= toCopy.begin(); i!=end; ++i, ++ptr)
97
       *ptr = *i;
98
}
22 Werner 99
 
33 Werner 100
// normalize function
32 Werner 101
template <class T>
33 Werner 102
Grid<T> Grid<T>::normalized(const T targetvalue) const
32 Werner 103
{
33 Werner 104
    Grid<T> target(*this);
105
    T total = sum();
106
    T multiplier;
107
    if (total)
108
        multiplier = targetvalue / total;
109
    else
110
        return target;
111
    for (T* p=target.begin();p!=target.end();++p)
112
        *p *= multiplier;
40 Werner 113
    return target;
33 Werner 114
}
115
 
116
 
117
template <class T>
118
Grid<T> Grid<T>::averaged(const int factor, const int offsetx, const int offsety) const
119
{
32 Werner 120
    Grid<T> target;
121
    target.setup(cellsize()*factor, sizeX()/factor, sizeY()/factor);
122
    int x,y;
123
    T sum=0;
124
    target.initialize(sum);
125
    // sum over array of 2x2, 3x3, 4x4, ...
126
    for (x=offsetx;x<mSizeX;x++)
127
        for (y=offsety;y<mSizeY;y++) {
128
            target.valueAtIndex((x-offsetx)/factor, (y-offsety)/factor) += constValueAtIndex(x,y);
129
        }
130
    // divide
131
    double fsquare = factor*factor;
132
    for (T* p=target.begin();p!=target.end();++p)
133
        *p /= fsquare;
134
    return target;
135
}
22 Werner 136
 
15 Werner 137
template <class T>
22 Werner 138
T&  Grid<T>::valueAtIndex(const QPoint& pos)
139
{
140
    if (isIndexValid(pos)) {
37 Werner 141
        return mData[pos.x()*mSizeY + pos.y()];
22 Werner 142
    }
40 Werner 143
    qCritical("Grid::valueAtIndex. invalid: %d/%d", pos.x(), pos.y());
144
    return mData[0];
22 Werner 145
}
36 Werner 146
 
27 Werner 147
template <class T>
148
const T&  Grid<T>::constValueAtIndex(const QPoint& pos) const
149
{
150
    if (isIndexValid(pos)) {
37 Werner 151
        return mData[pos.x()*mSizeY + pos.y()];
27 Werner 152
    }
40 Werner 153
    qCritical("Grid::constValueAtIndex. invalid: %d/%d", pos.x(), pos.y());
154
    return mData[0];
27 Werner 155
}
22 Werner 156
 
157
template <class T>
33 Werner 158
T&  Grid<T>::valueAt(const float x, const float y)
159
{
160
    return valueAtIndex( indexAt(QPointF(x,y)) );
161
}
36 Werner 162
 
33 Werner 163
template <class T>
164
const T&  Grid<T>::constValueAt(const float x, const float y) const
165
{
166
    return constValueAtIndex( indexAt(QPointF(x,y)) );
167
}
36 Werner 168
 
33 Werner 169
template <class T>
22 Werner 170
T&  Grid<T>::valueAt(const QPointF& posf)
171
{
172
    return valueAtIndex( indexAt(posf) );
173
}
36 Werner 174
 
33 Werner 175
template <class T>
176
const T&  Grid<T>::constValueAt(const QPointF& posf) const
177
{
178
    return constValueAtIndex( indexAt(posf) );
179
}
22 Werner 180
 
181
template <class T>
15 Werner 182
Grid<T>::Grid()
183
{
37 Werner 184
    mData = 0; mCellsize=0.f;
185
    mEnd = 0;
15 Werner 186
}
187
 
188
template <class T>
18 Werner 189
bool Grid<T>::setup(const float cellsize, const int sizex, const int sizey)
15 Werner 190
{
37 Werner 191
    mSizeX=sizex; mSizeY=sizey; mCellsize=cellsize;
49 Werner 192
    mRect.setCoords(0., 0., cellsize*sizex, cellsize*sizey);
15 Werner 193
    mCount = mSizeX*mSizeY;
37 Werner 194
    if (mData) {
195
         delete[] mData; mData=NULL;
196
     }
15 Werner 197
   if (mCount>0)
37 Werner 198
        mData = new T[mCount];
199
   mEnd = &(mData[mCount]);
15 Werner 200
   return true;
201
}
202
 
203
template <class T>
22 Werner 204
bool Grid<T>::setup(const QRectF& rect, const double cellsize)
15 Werner 205
{
49 Werner 206
    mRect = rect;
22 Werner 207
    int dx = int(rect.width()/cellsize);
49 Werner 208
    if (mRect.left()+cellsize*dx<rect.right())
22 Werner 209
        dx++;
210
    int dy = int(rect.height()/cellsize);
49 Werner 211
    if (mRect.top()+cellsize*dy<rect.bottom())
22 Werner 212
        dy++;
213
    return setup(cellsize, dx, dy);
15 Werner 214
}
215
 
25 Werner 216
template <class T>
27 Werner 217
QPoint Grid<T>::indexOf(T* element) const
25 Werner 218
{
219
    QPoint result(-1,-1);
220
    if (element==NULL || element<mData || element>=end())
221
        return result;
222
    int idx = element - mData;
41 Werner 223
    result.setX( idx % mSizeY);
224
    result.setY( idx / mSizeY);
25 Werner 225
    return result;
226
}
22 Werner 227
 
27 Werner 228
template <class T>
229
T  Grid<T>::max() const
230
{
231
    T maxv = std::numeric_limits<T>::min();
232
    T* p;
233
    T* pend = end();
234
    for (p=begin(); p!=pend;++p)
235
       maxv = std::max(maxv, *p);
236
    return maxv;
237
}
238
 
33 Werner 239
template <class T>
240
T  Grid<T>::sum() const
241
{
242
    T* pend = end();
243
    T total = 0;
244
    for (T *p=begin(); p!=pend;++p)
245
       total += *p;
246
    return total;
247
}
248
 
249
template <class T>
250
T  Grid<T>::avg() const
251
{
252
    if (count())
253
        return sum() / T(count());
254
    else return 0;
255
}
256
 
36 Werner 257
////////////////////////////////////////////////////////////7
258
// global functions
259
////////////////////////////////////////////////////////////7
260
 
261
/// dumps a FloatGrid to a String.
46 Werner 262
/// rows will be y-lines, columns x-values. (see grid.cpp)
36 Werner 263
QString gridToString(const FloatGrid &grid);
264
 
265
/// creates and return a QImage from Grid-Data.
266
/// @param black_white true: max_value = white, min_value = black, false: color-mode: uses a HSV-color model from blue (min_value) to red (max_value), default: color mode (false)
267
/// @param min_value, max_value min/max bounds for color calcuations. values outside bounds are limited to these values. defaults: min=0, max=1
268
/// @param reverse if true, color ramps are inversed (to: min_value = white (black and white mode) or red (color mode). default = false.
269
/// @return a QImage with the Grids size of pixels. Pixel coordinates relate to the index values of the grid.
270
QImage gridToImage(const FloatGrid &grid,
271
                   bool black_white=false,
272
                   double min_value=0., double max_value=1.,
273
                   bool reverse=false);
274
 
46 Werner 275
/// template version for non-float grids (see also version for FloatGrid)
36 Werner 276
template <class T>
46 Werner 277
        QString gridToString(const Grid<T> &grid)
36 Werner 278
{
279
    QString res;
280
    QTextStream ts(&res);
281
 
46 Werner 282
    for (int y=0;y<grid.sizeY();y++){
283
        for (int x=0;x<grid.sizeX();x++){
36 Werner 284
            ts << grid.constValueAtIndex(x,y) << ";";
285
        }
286
        ts << "\r\n";
287
    }
288
 
289
    return res;
290
}
46 Werner 291
 
15 Werner 292
#endif // GRID_H