Subversion Repositories public iLand

Rev

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

Rev Author Line No. Line
1
 
671 werner 2
/********************************************************************************************
3
**    iLand - an individual based forest landscape and disturbance model
4
**    http://iland.boku.ac.at
5
**    Copyright (C) 2009-  Werner Rammer, Rupert Seidl
6
**
7
**    This program is free software: you can redistribute it and/or modify
8
**    it under the terms of the GNU General Public License as published by
9
**    the Free Software Foundation, either version 3 of the License, or
10
**    (at your option) any later version.
11
**
12
**    This program is distributed in the hope that it will be useful,
13
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
**    GNU General Public License for more details.
16
**
17
**    You should have received a copy of the GNU General Public License
18
**    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
********************************************************************************************/
20
 
33 Werner 21
#include "stampcontainer.h"
102 Werner 22
#include "globalsettings.h"
103 Werner 23
#include "exception.h"
33 Werner 24
 
25
//constants
26
const int StampContainer::cBHDclassWidth=4;
632 werner 27
const int StampContainer::cBHDclassLow = 4; ///< bhd classes start with 4cm
357 werner 28
const int StampContainer::cBHDclassCount = 70; ///< class count, see getKey(): for lower dbhs classes are smaller
33 Werner 29
const int StampContainer::cHDclassWidth=10;
61 Werner 30
const int StampContainer::cHDclassLow = 35; ///< hd classes offset is 35: class 0 = 35-45, class 1 = 45-55
362 werner 31
const int StampContainer::cHDclassCount = 16; ///< class count. highest class:  185-195
33 Werner 32
 
401 werner 33
// static values
34
Grid<float> StampContainer::m_distance;
33 Werner 35
 
36
StampContainer::StampContainer()
37
{
38
    //
39
    m_lookup.setup(1., // cellsize
40
                   cBHDclassCount, // count x
41
                   cHDclassCount); // count y
42
    m_lookup.initialize(NULL);
37 Werner 43
    //qDebug() << "grid after init" << gridToString(m_lookup);
33 Werner 44
    m_maxBhd = -1;
45
    m_useLookup = true;
46
}
47
 
48
StampContainer::~StampContainer()
49
{
50
    // delete stamps.
51
    while (!m_stamps.isEmpty())
52
        delete m_stamps.takeLast().stamp;
53
 
54
}
64 Werner 55
/// getKey: decodes a floating point piar of dbh and hd-ratio to indices for the
56
/// lookup table containing pointers to the actual stamps.
632 werner 57
inline void StampContainer::getKey(const float dbh, const float hd_value, int &dbh_class, int &hd_class) const
33 Werner 58
{
64 Werner 59
    hd_class = int(hd_value - cHDclassLow) / cHDclassWidth;
632 werner 60
    // dbh_class = int(dbh - cBHDclassLow) / cBHDclassWidth;
64 Werner 61
    // fixed scheme: smallest classification scheme for tree-diameters:
62
    // 1cm width from 4 up to 9cm,
63
    // 2cm bins from 10 to 18cm
1102 werner 64
    // 4cm bins starting from 20cm, max DBH=255 (with 70 classes)
64 Werner 65
    if (dbh < 10.f) {
66
        dbh_class = qMax(0, int(dbh-4.)); // classes from 0..5
67
    } else if (dbh<20.f) {
68
        dbh_class = 6 + int((dbh-10.f) / 2.f); // 10-12cm has index 6
69
    } else {
70
        dbh_class = 11 + int((dbh-20.f) / 4.f); // 20-24cm has index 11
71
    }
33 Werner 72
}
73
 
58 Werner 74
/** fill up the NULLs in the lookup map */
75
void StampContainer::finalizeSetup()
76
{
77
    if (!m_useLookup)
78
        return;
79
    Stamp *s;
80
    int h;
401 werner 81
    int max_size=0;
58 Werner 82
    for (int b=0;b<cBHDclassCount;b++) {
83
        // find lowest value...
84
        for (h=0;h<cHDclassCount;h++) {
85
            s=m_lookup.valueAtIndex(b,h);
86
            if (s) {
87
                // fill up values left from this value
88
                for (int hfill=0;hfill<h;hfill++)
361 werner 89
                    m_lookup.valueAtIndex(b,hfill) = s;
58 Werner 90
                break;
91
            }
92
        }
93
        // go to last filled cell...
94
        for (;h<cHDclassCount;h++) {
95
            if (m_lookup.valueAtIndex(b,h)==0)
96
                break;
97
            s=m_lookup.valueAtIndex(b,h);
98
        }
99
        // fill up the rest...
100
        for (;h<cHDclassCount;h++) {
101
            m_lookup.valueAtIndex(b,h)=s;
102
        }
401 werner 103
        if(s)
104
            max_size = std::max(max_size, s->dataSize());
498 werner 105
 
106
        // if no stamps in this dbh-class, copy values (from last row)
107
        if (!s && b>0) {
108
           for (h=0;h<cHDclassCount;h++)
109
               m_lookup.valueAtIndex(b,h) = m_lookup(b-1, h);
110
        }
58 Werner 111
    }
505 werner 112
    if (!m_lookup.valueAtIndex(0,0)) {
113
        // first values are missing
114
        int b=0;
115
        while (b<cBHDclassCount && m_lookup.valueAtIndex(b,0)==NULL)
116
            b++;
117
        for (int fill=0;fill<b;fill++)
118
            for (h=0;h<cHDclassCount;h++)
119
                m_lookup.valueAtIndex(fill, h) = m_lookup.valueAtIndex(b,h);
120
    }
401 werner 121
    // distance grid
122
    if (m_distance.sizeX()<max_size) {
123
        setupDistanceGrid(max_size);
124
    }
58 Werner 125
}
126
 
401 werner 127
void StampContainer::setupDistanceGrid(const int size)
128
{
129
    const float px_size = cPxSize;
130
    m_distance.setup(px_size, size, size);
131
    float *p=m_distance.begin();
132
    QPoint idx;
133
    for (;p!=m_distance.end();++p) {
134
        idx = m_distance.indexOf(p);
135
        *p = sqrt(double(idx.x()*idx.x()) + double(idx.y()*idx.y()))*px_size;
136
    }
137
}
64 Werner 138
 
139
 void StampContainer::addStamp(Stamp* stamp, const int cls_dbh, const int cls_hd, const float crown_radius_m, const float dbh, const float hd_value)
140
 {
33 Werner 141
    if (m_useLookup) {
357 werner 142
        if (cls_dbh<0 || cls_dbh>=cBHDclassCount || cls_hd<0 || cls_hd>=cHDclassCount)
143
            throw IException(QString("StampContainer::addStamp: Stamp out of range. dbh=%1 hd=%2.").arg(dbh).arg(hd_value));
64 Werner 144
        m_lookup.valueAtIndex(cls_dbh, cls_hd) = stamp; // save address in look up table
33 Werner 145
    } // if (useLookup)
430 werner 146
    stamp->setCrownRadius(crown_radius_m);
33 Werner 147
    StampItem si;
64 Werner 148
    si.dbh = dbh;
33 Werner 149
    si.hd = hd_value;
47 Werner 150
    si.crown_radius = crown_radius_m;
33 Werner 151
    si.stamp = stamp;
152
    m_stamps.append(si); // store entry in list of stamps
153
 
64 Werner 154
 }
155
 
156
 
157
/** add a stamp to the internal storage.
158
    After loading the function finalizeSetup() must be called to ensure that gaps in the matrix get filled. */
65 Werner 159
void  StampContainer::addStamp(Stamp* stamp, const float dbh, const float hd_value, const float crown_radius)
64 Werner 160
{
161
    int cls_dbh, cls_hd;
162
    getKey(dbh, hd_value, cls_dbh, cls_hd); // decode dbh/hd-value
65 Werner 163
    addStamp(stamp, cls_dbh, cls_hd, crown_radius, dbh, hd_value); // dont set crownradius
33 Werner 164
}
165
 
64 Werner 166
void StampContainer::addReaderStamp(Stamp *stamp, const float crown_radius_m)
40 Werner 167
{
781 werner 168
    double rest = fmod(crown_radius_m, 1.f)+0.0001;
397 werner 169
    int cls_hd = int( rest * 10 ); // 0 .. 9.99999999
40 Werner 170
    if (cls_hd>=cHDclassCount)
171
        cls_hd=cHDclassCount-1;
64 Werner 172
    int cls_dbh = int(crown_radius_m);
102 Werner 173
    //qDebug() << "Readerstamp r="<< crown_radius_m<<" index dbh hd:" << cls_dbh << cls_hd;
397 werner 174
    stamp->setCrownRadius(crown_radius_m);
175
 
64 Werner 176
    // prepare special keys for reader stamps
177
    addStamp(stamp,cls_dbh, cls_hd, crown_radius_m, 0., 0.); // set crownradius, but not dbh/hd
178
}
40 Werner 179
 
180
 
181
/** retrieve a read-out-stamp. Readers depend solely on a crown radius.
182
Internally, readers are stored in the same lookup-table, but using a encoding/decoding trick.*/
183
const Stamp* StampContainer::readerStamp(const float crown_radius_m) const
184
{
185
    // Readers: from 0..10m in 50 steps???
781 werner 186
    int cls_hd = int( (fmod(crown_radius_m, 1.f)+0.0001) * 10 ); // 0 .. 9.99999999
40 Werner 187
    if (cls_hd>=cHDclassCount)
188
        cls_hd=cHDclassCount-1;
189
    int cls_bhd = int(crown_radius_m);
190
    const Stamp* stamp = m_lookup(cls_bhd, cls_hd);
58 Werner 191
    if (!stamp)
192
        qDebug() << "Stamp::readerStamp(): no stamp found for radius" << crown_radius_m;
40 Werner 193
    return stamp;
194
}
195
 
33 Werner 196
/** fast access for an individual stamp using a lookup table.
197
    the dimensions of the lookup table are defined by class-constants.
198
    If stamp is not found there, the more complete list of stamps is searched. */
39 Werner 199
const Stamp* StampContainer::stamp(const float bhd_cm, const float height_m) const
33 Werner 200
{
201
 
40 Werner 202
    float hd_value = 100.f * height_m / bhd_cm;
35 Werner 203
 
498 werner 204
    int cls_dbh, cls_hd;
205
    getKey(bhd_cm, hd_value, cls_dbh, cls_hd);
35 Werner 206
 
33 Werner 207
    // check loopup table
498 werner 208
    if (cls_dbh<cBHDclassCount && cls_dbh>=0 && cls_hd < cHDclassCount && cls_hd>=0) {
209
        const Stamp* stamp = m_lookup(cls_dbh, cls_hd);
40 Werner 210
        if (stamp)
211
            return stamp;
498 werner 212
        if (logLevelDebug())
213
            qDebug() << "StampContainer::stamp(): not in list: dbh height:" << bhd_cm << height_m << "in" << m_fileName;
40 Werner 214
    }
33 Werner 215
 
216
    // extra work: search in list...
498 werner 217
    // look for a stamp if the HD-ratio is out of range
218
    if (cls_dbh<cBHDclassCount && cls_dbh>=0) {
219
        if (logLevelDebug())
220
            qDebug() << "HD for stamp out of range dbh " << bhd_cm << "and h="<< height_m << "(using smallest/largeset HD)";
143 Werner 221
        if (cls_hd>=cHDclassCount)
498 werner 222
            return m_lookup(cls_dbh, cHDclassCount-1); // highest
223
        return m_lookup(cls_dbh, 0); // smallest
143 Werner 224
    }
498 werner 225
    // look for a stamp if the DBH is out of range.
226
    if (cls_hd<cHDclassCount && cls_hd>=0) {
227
        if (logLevelDebug())
228
            qDebug() << "DBH for stamp out of range dbh " << bhd_cm << "and h="<< height_m << "-> using largest available DBH.";
229
        if (cls_dbh>=cBHDclassCount)
230
            return m_lookup(cBHDclassCount-1, cls_hd); // highest
231
        return m_lookup(0, cls_hd); // smallest
33 Werner 232
 
498 werner 233
    }
632 werner 234
    // handle the case DBH and HD are out of range
235
    if (cls_dbh>=cBHDclassCount && cls_hd<0) {
236
        if (logLevelDebug())
237
            qDebug() << "DBH AND HD for stamp out of range dbh " << bhd_cm << "and h="<< height_m << "-> using largest available DBH/smallest HD.";
238
        return m_lookup(cBHDclassCount-1, 0);
239
    }
240
    // handle the case that DBH is too high and HD is too high (not very likely)
241
    if (cls_dbh>=cBHDclassCount && cls_hd>=cHDclassCount) {
242
        if (logLevelDebug())
243
            qDebug() << "DBH AND HD for stamp out of range dbh " << bhd_cm << "and h="<< height_m << "-> using largest available DBH.";
244
        return m_lookup(cBHDclassCount-1, cHDclassCount-1);
245
 
246
    }
498 werner 247
    qDebug() << "ERROR: No stamp defined for dbh " << bhd_cm << "and h="<< height_m;
248
    throw IException("StampContainer:: did not find a valid stamp.");
33 Werner 249
}
250
 
63 Werner 251
 
47 Werner 252
void StampContainer::attachReaderStamps(const StampContainer &source)
253
{
254
    int found=0, total=0;
802 werner 255
    foreach (const StampItem &si, m_stamps) {
47 Werner 256
        const Stamp *s = source.readerStamp(si.crown_radius);
257
        si.stamp->setReader(const_cast<Stamp*>(s));
258
        if (s) found++;
259
        total++;
260
        //si.crown_radius
261
    }
550 werner 262
    if (logLevelInfo()) qDebug() << "attachReaderStamps: found" << found << "stamps of" << total;
47 Werner 263
}
264
 
51 Werner 265
void StampContainer::invert()
266
{
267
    StampItem  si;
268
    foreach(si, m_stamps) {
269
        Stamp *s =si.stamp;
270
        float *p = s->data();
271
        while (p!=s->end()) {
272
            *p = 1. - *p;
273
            p++;
274
        }
275
    }
276
}
99 Werner 277
/// convenience function that loads stamps directly from a single file.
278
void StampContainer::load(const QString &fileName)
279
{
280
    QFile readerfile(fileName);
102 Werner 281
    if (!readerfile.exists())
282
        throw IException(QString("The LIP stampfile %1 cannot be found!").arg(fileName));
429 werner 283
    m_fileName = fileName;
99 Werner 284
    readerfile.open(QIODevice::ReadOnly);
285
    QDataStream rin(&readerfile);
361 werner 286
    qDebug() << "loading stamp file" << fileName;
99 Werner 287
    load(rin);
288
    readerfile.close();
289
}
51 Werner 290
 
33 Werner 291
void StampContainer::load(QDataStream &in)
292
{
293
    qint32 type;
294
    qint32 count;
802 werner 295
    float dbh, hdvalue, crownradius;
400 werner 296
    quint32 magic;
297
    in >> magic;
298
    if (magic!=0xFEED0001)
299
        throw IException("StampContainer: invalid file type!");
300
    quint16 version;
301
    in >> version;
302
    if (version != 100)
303
        throw IException(QString("StampContainer: invalid file version: %1").arg(version));
304
    in.setVersion(QDataStream::Qt_4_5);
305
 
33 Werner 306
    in >> count; // read count of stamps
550 werner 307
    if (logLevelInfo()) qDebug() << count << "stamps to read";
63 Werner 308
    QString desc;
309
    in >> desc; // read textual description of stamp
550 werner 310
    if (logLevelInfo()) qDebug() << "Stamp notes:" << desc;
63 Werner 311
    m_desc = desc;
33 Werner 312
    for (int i=0;i<count;i++) {
313
        in >> type; // read type
802 werner 314
        in >> dbh;
33 Werner 315
        in >> hdvalue;
47 Werner 316
        in >> crownradius;
309 werner 317
        //qDebug() << "stamp bhd hdvalue type readsum dominance type" << bhd << hdvalue << type << readsum << domvalue << type;
64 Werner 318
 
735 werner 319
        Stamp *stamp = new Stamp(type);
33 Werner 320
        stamp->load(in);
400 werner 321
 
802 werner 322
        if (dbh > 0.f)
323
            addStamp(stamp, dbh, hdvalue, crownradius);
65 Werner 324
        else
64 Werner 325
            addReaderStamp(stamp, crownradius);
33 Werner 326
    }
58 Werner 327
    finalizeSetup(); // fill up lookup grid
102 Werner 328
    if (count==0)
329
        throw IException("no stamps loaded!");
33 Werner 330
}
331
/** Saves all stamps of the container to a binary stream.
34 Werner 332
  Format: * count of stamps (int32)
63 Werner 333
          * a string containing a description (free text) (QString)
33 Werner 334
      for each stamp:
335
      - type (enum Stamp::StampType, 4, 8, 12, 16, ...)
336
      - bhd of the stamp (float)
42 Werner 337
      - hd-value of the tree (float)
47 Werner 338
      - crownradius of the stamp (float) in [m]
43 Werner 339
      - the sum of values in the center of the stamp (used for read out)
340
      - the dominance value of the stamp
33 Werner 341
      - individual data values (Stamp::save() / Stamp::load())
342
      -- offset (int) no. of pixels away from center
343
      -- list of data items (type*type items)
34 Werner 344
      see also stamp creation (FonStudio application, MainWindow.cpp).
33 Werner 345
*/
346
void StampContainer::save(QDataStream &out)
347
{
348
    qint32 type;
34 Werner 349
    qint32 size = m_stamps.count();
400 werner 350
    out << (quint32)0xFEED0001; // magic number
351
    out << (quint16)100; // version
352
    out.setVersion(QDataStream::Qt_4_5);
353
 
63 Werner 354
    out << size; // count of stamps...
355
    out << m_desc; // text...
33 Werner 356
    foreach(StampItem si, m_stamps) {
40 Werner 357
        type = si.stamp->dataSize();
35 Werner 358
        out << type;
64 Werner 359
        out << si.dbh;
35 Werner 360
        out << si.hd;
47 Werner 361
        out << si.crown_radius;
34 Werner 362
        si.stamp->save(out);
33 Werner 363
    }
34 Werner 364
 
33 Werner 365
}
35 Werner 366
 
367
QString StampContainer::dump()
368
{
369
    QString res;
370
    QString line;
371
    int x,y;
372
    int maxidx;
429 werner 373
    res = QString("****** Dump of StampContainer %1 **********\r\n").arg(m_fileName);
35 Werner 374
    foreach (StampItem si, m_stamps) {
375
        line = QString("%5 -> size: %1 offset: %2 dbh: %3 hd-ratio: %4\r\n")
781 werner 376
               .arg(sqrt((double)si.stamp->count())).arg(si.stamp->offset())
835 werner 377
               .arg(si.dbh).arg(si.hd).arg((ptrdiff_t)si.stamp, 0, 16);
35 Werner 378
        // add data....
379
        maxidx = 2*si.stamp->offset() + 1;
41 Werner 380
        for (y=0;y<maxidx;++y)  {
381
            for (x=0;x<maxidx;++x)  {
35 Werner 382
                line+= QString::number(*si.stamp->data(x,y)) + " ";
383
            }
384
            line+="\r\n";
385
        }
386
        line+="==============================================\r\n";
387
        res+=line;
388
    }
36 Werner 389
    res+= "Dump of lookup map\r\n=====================\r\n";
35 Werner 390
    for (Stamp **s = m_lookup.begin(); s!=m_lookup.end(); ++s) {
391
        if (*s)
835 werner 392
         res += QString("P: x/y: %1/%2 addr %3\r\n").arg( m_lookup.indexOf(s).x()).arg(m_lookup.indexOf(s).y()).arg((ptrdiff_t)*s, 0, 16);
35 Werner 393
    }
36 Werner 394
    res+="\r\n" + gridToString(m_lookup);
35 Werner 395
    return res;
396
}