Subversion Repositories public iLand

Rev

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

Rev Author Line No. Line
1
 
106 Werner 2
#include "global.h"
3
#include "standloader.h"
4
 
290 werner 5
 
106 Werner 6
#include "grid.h"
7
#include "model.h"
189 iland 8
#include "resourceunit.h"
106 Werner 9
#include "speciesset.h"
10
 
11
#include "helper.h"
290 werner 12
#include "random.h"
137 Werner 13
#include "expression.h"
140 Werner 14
#include "expressionwrapper.h"
284 werner 15
#include "environment.h"
287 werner 16
#include "csvfile.h"
106 Werner 17
 
381 werner 18
// provide a mapping between "Picus"-style and "iLand"-style species Ids
384 werner 19
QVector<int> picusSpeciesIds = QVector<int>() << 0 << 1 << 17;
155 werner 20
QStringList iLandSpeciesIds = QStringList() << "piab" << "piab" << "fasy";
290 werner 21
StandLoader::~StandLoader()
22
{
23
    if (mRandom)
24
        delete mRandom;
25
}
106 Werner 26
 
281 werner 27
void StandLoader::loadForUnit()
28
{
106 Werner 29
 
281 werner 30
}
106 Werner 31
 
281 werner 32
void StandLoader::copyTrees()
33
{
34
    // we assume that all stands are equal, so wie simply COPY the trees and modify them afterwards
35
    const Grid<ResourceUnit*> &ruGrid=mModel->RUgrid();
36
    ResourceUnit **p = ruGrid.begin();
37
    if (!p)
38
        throw IException("Standloader: invalid resource unit pointer!");
39
    ++p; // skip the first...
40
    const QVector<Tree> &tocopy = mModel->ru()->trees();
41
    for (; p!=ruGrid.end(); ++p) {
42
        QRectF rect = (*p)->boundingBox();
43
        foreach(const Tree& tree, tocopy) {
44
            Tree &newtree = (*p)->newTree();
45
            newtree = tree; // copy tree data...
46
            newtree.setPosition(tree.position()+(*p)->boundingBox().topLeft());
47
            newtree.setRU(*p);
48
            newtree.setNewId();
49
        }
50
    }
51
    qDebug() << Tree::statCreated() << "trees loaded / copied.";
52
}
53
 
284 werner 54
/** main routine of the stand setup.
55
*/
106 Werner 56
void StandLoader::processInit()
57
{
58
    GlobalSettings *g = GlobalSettings::instance();
192 werner 59
    XmlHelper xml(g->settings().node("model.initialization"));
191 werner 60
 
281 werner 61
    QString copy_mode = xml.value("mode", "copy");
62
    QString type = xml.value("type", "");
192 werner 63
    QString  fileName = xml.value("file", "");
106 Werner 64
 
65
    Tree::resetStatistics();
281 werner 66
 
67
    // one global init-file for the whole area:
284 werner 68
    if (copy_mode=="single") {
281 werner 69
        loadInitFile(fileName, type);
299 werner 70
        evaluateDebugTrees();
281 werner 71
        return;
284 werner 72
    }
281 werner 73
 
74
    // copy trees from first unit to all other units:
75
    if (copy_mode=="copy") {
76
        loadInitFile(fileName, type);
77
        copyTrees();
299 werner 78
        evaluateDebugTrees();
281 werner 79
        return;
106 Werner 80
    }
137 Werner 81
 
281 werner 82
    // call a single tree init for each resource unit
83
    if (copy_mode=="unit") {
284 werner 84
        foreach( const ResourceUnit *const_ru, g->model()->ruList()) {
85
            ResourceUnit *ru = const_cast<ResourceUnit*>(const_ru);
86
            // set environment
87
            g->model()->environment()->setPosition(ru->boundingBox().center());
88
            type = xml.value("type", "");
89
            fileName = xml.value("file", "");
319 werner 90
            if (fileName.isEmpty())
91
                continue;
284 werner 92
            loadInitFile(fileName, type, ru);
93
            qDebug() << "loaded" << fileName << "on" << ru->boundingBox() << "," << ru->trees().count() << "trees.";
94
        }
299 werner 95
        evaluateDebugTrees();
284 werner 96
        return;
281 werner 97
    }
299 werner 98
 
281 werner 99
    throw IException("StandLoader::processInit: invalid initalization.mode!");
100
}
101
 
102
void StandLoader::evaluateDebugTrees()
103
{
137 Werner 104
    // evaluate debugging
105
    QString dbg_str = GlobalSettings::instance()->settings().paramValueString("debug_tree");
299 werner 106
    int counter=0;
137 Werner 107
    if (!dbg_str.isEmpty()) {
140 Werner 108
       TreeWrapper tw;
109
       Expression dexp(dbg_str, &tw); // load expression dbg_str and enable external model variables
137 Werner 110
        AllTreeIterator at(GlobalSettings::instance()->model());
111
        double result;
112
        while (Tree *t = at.next()) {
140 Werner 113
            tw.setTree(t);
137 Werner 114
            result = dexp.execute();
299 werner 115
            if (result) {
137 Werner 116
                t->enableDebugging();
299 werner 117
                counter++;
118
            }
137 Werner 119
        }
120
    }
299 werner 121
    qDebug() << "evaluateDebugTrees: enabled debugging for" << counter << "trees.";
106 Werner 122
}
123
 
284 werner 124
void StandLoader::loadInitFile(const QString &fileName, const QString &type, ResourceUnit *ru)
281 werner 125
{
284 werner 126
    QString pathFileName = GlobalSettings::instance()->path(fileName, "init");
127
    if (!QFile::exists(pathFileName))
128
        throw IException(QString("StandLoader::loadInitFile: File %1 does not exist!").arg(pathFileName));
281 werner 129
 
384 werner 130
    if (type=="picus" || type=="single")
294 werner 131
        return loadPicusFile(pathFileName, ru);
384 werner 132
    if (type=="iland" || type=="distribution")
287 werner 133
        return loadiLandFile(pathFileName, ru);
281 werner 134
 
384 werner 135
    throw IException(QLatin1String("StandLoader::loadInitFile: unknown initalization.type:")+type);
281 werner 136
}
137
 
294 werner 138
void StandLoader::loadPicusFile(const QString &fileName, ResourceUnit *ru)
106 Werner 139
{
294 werner 140
    QString content = Helper::loadTextFile(fileName);
141
    if (content.isEmpty()) {
142
        qDebug() << "file not found: " + fileName;
143
        return;
144
    }
145
    loadSingleTreeList(content, ru, fileName);
146
}
147
 
389 werner 148
/** load a list of trees (given by content) to a resource unit. Param fileName is just for error reporting.
149
  returns the number of loaded trees.
150
  */
151
int StandLoader::loadSingleTreeList(const QString &content, ResourceUnit *ru, const QString &fileName)
294 werner 152
{
106 Werner 153
    if (!ru)
154
        ru = mModel->ru();
284 werner 155
    Q_ASSERT(ru!=0);
106 Werner 156
 
284 werner 157
    QPointF offset = ru->boundingBox().topLeft();
158
    SpeciesSet *speciesSet = ru->speciesSet(); // of default RU
159
 
384 werner 160
    QString my_content(content);
161
    // cut out the <trees> </trees> part if present
162
    if (content.contains("<trees>")) {
163
        QRegExp rx(".*<trees>(.*)</trees>.*");
164
        rx.indexIn(content, 0);
165
        if (rx.capturedTexts().count()<1)
389 werner 166
            return 0;
384 werner 167
        my_content = rx.cap(1).trimmed();
168
    }
169
 
294 werner 170
    QStringList lines=my_content.split('\n');
106 Werner 171
    if (lines.count()<2)
389 werner 172
        return 0;
384 werner 173
    // drop comments
174
    while (!lines.isEmpty() && lines.front().startsWith('#') )
175
        lines.pop_front();
176
    while (!lines.isEmpty() && lines.last().isEmpty())
177
        lines.removeLast();
178
 
106 Werner 179
    char sep='\t';
180
    if (!lines[0].contains(sep))
181
        sep=';';
155 werner 182
    QStringList headers = lines[0].trimmed().split(sep);
138 Werner 183
 
247 werner 184
    int iID = headers.indexOf("id");
106 Werner 185
    int iX = headers.indexOf("x");
186
    int iY = headers.indexOf("y");
187
    int iBhd = headers.indexOf("bhdfrom");
384 werner 188
    if (iBhd<0)
189
        iBhd = headers.indexOf("dbh");
190
    double height_conversion = 100.;
106 Werner 191
    int iHeight = headers.indexOf("treeheight");
384 werner 192
    if (iHeight<0) {
193
        iHeight = headers.indexOf("height");
194
        height_conversion = 1.; // in meter
195
    }
106 Werner 196
    int iSpecies = headers.indexOf("species");
170 werner 197
    int iAge = headers.indexOf("age");
204 werner 198
    if (iX==-1 || iY==-1 || iBhd==-1 || iSpecies==-1 || iHeight==-1)
384 werner 199
        throw IException(QString("Initfile %1 is not valid!\nObligatory columns are: x,y, bhdfrom or dbh, species, treeheight or height.").arg(fileName));
106 Werner 200
 
138 Werner 201
    double dbh;
384 werner 202
    bool ok;
389 werner 203
    int cnt=0;
384 werner 204
    QString speciesid;
106 Werner 205
    for (int i=1;i<lines.count();i++) {
206
        QString &line = lines[i];
138 Werner 207
        dbh = line.section(sep, iBhd, iBhd).toDouble();
208
        if (dbh<5.)
209
            continue;
285 werner 210
 
106 Werner 211
        QPointF f;
212
        if (iX>=0 && iY>=0) {
213
           f.setX( line.section(sep, iX, iX).toDouble() );
214
           f.setY( line.section(sep, iY, iY).toDouble() );
215
           f+=offset;
285 werner 216
 
106 Werner 217
        }
285 werner 218
        // position valid?
219
        if (!mModel->heightGrid()->valueAt(f).isValid())
220
            continue;
221
        Tree &tree = ru->newTree();
222
        tree.setPosition(f);
247 werner 223
        if (iID>=0)
224
            tree.setId(line.section(sep, iID, iID).toInt() );
106 Werner 225
 
138 Werner 226
        tree.setDbh(dbh);
384 werner 227
        tree.setHeight(line.section(sep, iHeight, iHeight).toDouble()/height_conversion); // convert from Picus-cm to m if necessary
228
 
389 werner 229
        speciesid = line.section(sep, iSpecies, iSpecies).trimmed();
270 werner 230
        int picusid = speciesid.toInt(&ok);
231
        if (ok) {
384 werner 232
            int idx = picusSpeciesIds.indexOf(picusid);
270 werner 233
            if (idx==-1)
234
                throw IException(QString("Loading init-file: invalid Picus-species-id. Species: %1").arg(picusid));
138 Werner 235
            speciesid = iLandSpeciesIds[idx];
270 werner 236
        }
138 Werner 237
        Species *s = speciesSet->species(speciesid);
238
        if (!ru || !s)
389 werner 239
            throw IException(QString("Loading init-file: either resource unit or species invalid. Species: %1").arg(speciesid));
388 werner 240
        tree.setSpecies(s);
107 Werner 241
 
388 werner 242
        ok = true;
243
        if (iAge>=0)
244
           tree.setAge(line.section(sep, iAge, iAge).toInt(&ok), tree.height()); // this is a *real* age
245
        if (iAge<0 || !ok || tree.age()==0)
246
           tree.setAge(0, tree.height()); // no real tree age available
247
 
138 Werner 248
        tree.setRU(ru);
106 Werner 249
        tree.setup();
389 werner 250
        cnt++;
106 Werner 251
    }
389 werner 252
    return cnt;
106 Werner 253
    //qDebug() << "loaded init-file contained" << lines.count() <<"lines.";
254
    //qDebug() << "lines: " << lines;
255
}
287 werner 256
 
294 werner 257
void StandLoader::loadDistributionList(const QString &content, ResourceUnit *ru, const QString &fileName)
287 werner 258
{
259
    if (!ru)
260
        ru = mModel->ru();
261
    Q_ASSERT(ru!=0);
262
    SpeciesSet *speciesSet = ru->speciesSet(); // of default RU
263
    Q_ASSERT(speciesSet!=0);
264
 
265
    DebugTimer t("StandLoader::loadiLandFile");
294 werner 266
    CSVFile infile;
267
    infile.loadFromString(content);
268
 
287 werner 269
    int icount = infile.columnIndex("count");
270
    int ispecies = infile.columnIndex("species");
271
    int idbh_from = infile.columnIndex("dbh_from");
272
    int idbh_to = infile.columnIndex("dbh_to");
273
    int ihd = infile.columnIndex("hd");
274
    int iage = infile.columnIndex("age");
311 werner 275
    int idensity = infile.columnIndex("density");
287 werner 276
    if (icount<0 || ispecies<0 || idbh_from<0 || idbh_to<0 || ihd<0 || iage<0)
277
        throw IException(QString("load-ini-file: file '%1' containts not all required fields (count, species, dbh_from, dbh_to, hd, age).").arg(fileName));
278
 
294 werner 279
    mInitItems.clear();
287 werner 280
    InitFileItem item;
384 werner 281
    bool ok;
287 werner 282
    for (int row=0;row<infile.rowCount();row++) {
283
         item.count = infile.value(row, icount).toInt();
284
         item.dbh_from = infile.value(row, idbh_from).toDouble();
285
         item.dbh_to = infile.value(row, idbh_to).toDouble();
286
         item.hd = infile.value(row, ihd).toDouble();
384 werner 287
         ok = true;
381 werner 288
         if (iage>=0)
384 werner 289
             item.age = infile.value(row, iage).toInt(&ok);
290
         if (iage<0 || !ok)
291
             item.age = 0;
292
 
287 werner 293
         item.species = speciesSet->species(infile.value(row, ispecies).toString());
311 werner 294
         if (idensity>=0)
295
             item.density = infile.value(row, idensity).toDouble();
296
         else
297
             item.density = 0.;
298
         if (item.density<-1 || item.density>1)
299
             throw IException(QString("load-ini-file: invalid value for density. Allowed range is -1..1: '%1' in file '%2', line %3.")
300
                              .arg(item.density)
301
                              .arg(fileName)
302
                              .arg(row));
287 werner 303
         if (!item.species) {
304
             throw IException(QString("load-ini-file: unknown speices '%1' in file '%2', line %3.")
305
                              .arg(infile.value(row, ispecies).toString())
306
                              .arg(fileName)
307
                              .arg(row));
308
         }
290 werner 309
         mInitItems.push_back(item);
287 werner 310
    }
290 werner 311
    // setup the random distribution
312
    QString density_func = GlobalSettings::instance()->settings().value("model.initialization.randomFunction", "1-x^2");
313
    qDebug() << "density function:" << density_func;
314
    if (!mRandom || (mRandom->densityFunction()!= density_func)) {
315
        if (mRandom)
316
            delete mRandom;
317
        mRandom=new RandomCustomPDF(density_func);
318
        qDebug() << "new probabilty density function:" << density_func;
319
    }
320
 
287 werner 321
    // exeucte the
322
    executeiLandInit(ru);
290 werner 323
    ru->cleanTreeList();
287 werner 324
 
325
}
326
 
294 werner 327
void StandLoader::loadiLandFile(const QString &fileName, ResourceUnit *ru)
328
{
329
    if (!QFile::exists(fileName))
330
        throw IException(QString("load-ini-file: file '%1' does not exist.").arg(fileName));
331
    QString content = Helper::loadTextFile(fileName);
332
    loadDistributionList(content, ru, fileName);
333
}
334
 
287 werner 335
// evenlist: tentative order of pixel-indices (within a 5x5 grid) used as tree positions.
336
// e.g. 12 = centerpixel, 0: upper left corner, ...
337
int evenlist[25] = { 12, 6, 18, 16, 8, 22, 2, 10, 14, 0, 24, 20, 4,
338
                     1, 13, 15, 19, 21, 3, 7, 11, 17, 23, 5, 9};
290 werner 339
int unevenlist[25] = { 11,13,7,17, 1,19,5,21, 9,23,3,15,
340
                       6,18,2,10,4,24,12,0,8,14,20,22};
341
 
342
 
287 werner 343
// sort function
344
bool sortPairLessThan(const QPair<int, double> &s1, const QPair<int, double> &s2)
311 werner 345
{
346
    return s1.second < s2.second;
347
}
348
 
349
/**
350
*/
290 werner 351
void StandLoader::executeiLandInit(ResourceUnit *ru)
287 werner 352
{
290 werner 353
 
287 werner 354
    QPointF offset = ru->boundingBox().topLeft();
355
    QPoint offsetIdx = GlobalSettings::instance()->model()->grid()->indexAt(offset);
356
 
357
    // a multimap holds a list for all trees.
358
    // key is the index of a 10x10m pixel within the resource unit
359
    QMultiMap<int, int> tree_map;
360
    QVector<QPair<int, double> > tcount; // counts
361
    for (int i=0;i<100;i++)
362
        tcount.push_back(QPair<int,double>(i,0.));
363
 
364
    int key;
311 werner 365
    double rand_val, rand_fraction;
312 werner 366
    int total_count = 0;
290 werner 367
    foreach(const InitFileItem &item, mInitItems) {
311 werner 368
        rand_fraction = fabs(double(item.density));
287 werner 369
        for (int i=0;i<item.count;i++) {
370
            // create trees
371
            int tree_idx = ru->newTreeIndex();
372
            Tree &tree = ru->trees()[tree_idx]; // get reference to modify tree
373
            tree.setDbh(nrandom(item.dbh_from, item.dbh_to));
374
            tree.setHeight(tree.dbh()/100. * item.hd); // dbh from cm->m, *hd-ratio -> meter height
375
            tree.setSpecies(item.species);
384 werner 376
            if (item.age<=0)
388 werner 377
                tree.setAge(0,tree.height());
381 werner 378
            else
388 werner 379
                tree.setAge(item.age, tree.height());
287 werner 380
            tree.setRU(ru);
381
            tree.setup();
312 werner 382
            total_count++;
311 werner 383
 
384
            // calculate random value. "density" is from 1..-1.
385
            rand_val = mRandom->get();
386
            if (item.density<0)
387
                rand_val = 1. - rand_val;
312 werner 388
            rand_val = rand_val * rand_fraction + drandom()*(1.-rand_fraction);
311 werner 389
 
287 werner 390
            // key: rank of target pixel
391
            // first: index of target pixel
392
            // second: sum of target pixel
311 werner 393
            key = limit(int(100*rand_val), 0, 99); // get from random number generator
287 werner 394
            tree_map.insert(tcount[key].first, tree_idx); // store tree in map
395
            tcount[key].second+=tree.basalArea(); // aggregate the basal area for each 10m pixel
312 werner 396
            if ( (total_count < 20 && i%2==0)
397
                || (total_count<100 && i%10==0 )
398
                || (i%30==0) ) {
287 werner 399
                qSort(tcount.begin(), tcount.end(), sortPairLessThan);
312 werner 400
            }
287 werner 401
        }
402
        qSort(tcount.begin(), tcount.end(), sortPairLessThan);
403
    }
404
 
405
    int bits, index, pos;
406
    int c;
407
    QList<int> trees;
408
    QPoint tree_pos;
289 werner 409
 
287 werner 410
    for (int i=0;i<100;i++) {
411
        trees = tree_map.values(i);
412
        c = trees.count();
290 werner 413
        QPointF pixel_center = ru->boundingBox().topLeft() + QPointF((i/10)*10. + 5., (i%10)*10. + 5.);
414
        if (!mModel->heightGrid()->valueAt(pixel_center).isValid()) {
415
            // no trees on that pixel: let trees die
416
            foreach(int tree_idx, trees) {
417
                ru->trees()[tree_idx].die();
418
            }
419
            continue;
420
        }
421
 
287 werner 422
        bits = 0;
423
        index = -1;
290 werner 424
        double r;
287 werner 425
        foreach(int tree_idx, trees) {
426
            if (c>18) {
427
                index = (index + 1)%25;
428
            } else {
429
                int stop=1000;
290 werner 430
                index = 0;
287 werner 431
                do {
290 werner 432
                    //r = drandom();
433
                    //if (r<0.5)  // skip position with a prob. of 50% -> adds a little "noise"
434
                    //    index++;
435
                    //index = (index + 1)%25; // increase and roll over
436
 
437
                    // search a random position
438
                    r = drandom();
439
                    index = limit(int(25 *  r*r), 0, 24); // use rnd()^2 to search for locations -> higher number of low indices (i.e. 50% of lookups in first 25% of locations)
287 werner 440
                } while (isBitSet(bits, index)==true && stop--);
441
                if (!stop)
442
                    qDebug() << "executeiLandInit: found no free bit.";
443
                setBit(bits, index, true); // mark position as used
444
            }
290 werner 445
            // get position from fixed lists (one for even, one for uneven resource units)
446
            pos = ru->index()%2?evenlist[index]:unevenlist[index];
287 werner 447
            tree_pos = offsetIdx  // position of resource unit
448
                       + QPoint(5*(i/10), 5*(i%10)) // relative position of 10x10m pixel
449
                       + QPoint(pos/5, pos%5); // relative position within 10x10m pixel
450
            //qDebug() << tree_no++ << "to" << index;
451
            ru->trees()[tree_idx].setPosition(tree_pos);
452
        }
453
    }
454
}