Subversion Repositories public iLand

Rev

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

Rev Author Line No. Line
1
 
534 werner 2
/** @class ResourceUnit
3
  ResourceUnit is the spatial unit that encapsulates a forest stand and links to several environmental components
4
  (Climate, Soil, Water, ...).
5
 
6
  */
7
#include <QtCore>
8
#include "global.h"
9
 
10
#include "resourceunit.h"
11
#include "resourceunitspecies.h"
12
#include "speciesset.h"
13
#include "species.h"
14
#include "production3pg.h"
15
#include "model.h"
16
#include "climate.h"
17
#include "watercycle.h"
18
#include "snag.h"
19
#include "soil.h"
20
#include "helper.h"
21
 
22
ResourceUnit::~ResourceUnit()
23
{
24
    if (mWater)
25
        delete mWater;
26
    mWater = 0;
27
    if (mSnag)
28
        delete mSnag;
29
    if (mSoil)
30
        delete mSoil;
31
 
32
    mSnag = 0;
33
    mSoil = 0;
34
}
35
 
36
ResourceUnit::ResourceUnit(const int index)
37
{
38
    qDeleteAll(mRUSpecies);
39
    mSpeciesSet = 0;
40
    mClimate = 0;
41
    mPixelCount=0;
42
    mStockedArea = 0;
43
    mStockedPixelCount = 0;
44
    mIndex = index;
45
    mSaplingHeightMap = 0;
46
    mEffectiveArea_perWLA = 0.;
47
    mWater = new WaterCycle();
48
    mSnag = 0;
49
    mSoil = 0;
569 werner 50
    mID = 0;
534 werner 51
}
52
 
53
void ResourceUnit::setup()
54
{
55
    mWater->setup(this);
56
 
57
    if (mSnag)
58
        delete mSnag;
59
    mSnag=0;
60
    if (mSoil)
61
        delete mSoil;
62
    mSoil=0;
63
    if (Model::settings().carbonCycleEnabled) {
591 werner 64
        mSoil = new Soil(this);
534 werner 65
        mSnag = new Snag;
66
        mSnag->setup(this);
67
        const XmlHelper &xml=GlobalSettings::instance()->settings();
68
 
69
        // setup contents of the soil of the RU; use values for C and N (kg/ha)
70
        mSoil->setInitialState(CNPool(xml.valueDouble("model.site.youngLabileC", -1),
71
                                      xml.valueDouble("model.site.youngLabileN", -1),
72
                                      xml.valueDouble("model.site.youngLabileDecompRate", -1)),
73
                               CNPool(xml.valueDouble("model.site.youngRefractoryC", -1),
74
                                      xml.valueDouble("model.site.youngRefractoryN", -1),
75
                                      xml.valueDouble("model.site.youngRefractoryDecompRate", -1)),
76
                               CNPair(xml.valueDouble("model.site.somC", -1), xml.valueDouble("model.site.somN", -1)));
77
    }
78
 
79
    // setup variables
80
    mUnitVariables.nitrogenAvailable = GlobalSettings::instance()->settings().valueDouble("model.site.availableNitrogen", 40);
81
 
82
    // if dynamic coupling of soil nitrogen is enabled, the calculate a starting value for available n.
83
    if (mSoil && Model::settings().useDynamicAvailableNitrogen && Model::settings().carbonCycleEnabled) {
84
        mSoil->setClimateFactor(1.);
85
        mSoil->calculateYear();
86
        mUnitVariables.nitrogenAvailable = mSoil->availableNitrogen();
87
    }
88
    mAverageAging = 0.;
89
 
90
}
91
void ResourceUnit::setBoundingBox(const QRectF &bb)
92
{
93
    mBoundingBox = bb;
94
    mCornerCoord = GlobalSettings::instance()->model()->grid()->indexAt(bb.topLeft());
95
}
96
 
97
/// set species and setup the species-per-RU-data
98
void ResourceUnit::setSpeciesSet(SpeciesSet *set)
99
{
100
    mSpeciesSet = set;
101
    qDeleteAll(mRUSpecies);
102
 
103
    //mRUSpecies.resize(set->count()); // ensure that the vector space is not relocated
104
    for (int i=0;i<set->count();i++) {
105
        Species *s = const_cast<Species*>(mSpeciesSet->species(i));
106
        if (!s)
107
            throw IException("ResourceUnit::setSpeciesSet: invalid index!");
108
 
109
        ResourceUnitSpecies *rus = new ResourceUnitSpecies();
110
        mRUSpecies.push_back(rus);
111
        rus->setup(s, this);
112
        /* be careful: setup() is called with a pointer somewhere to the content of the mRUSpecies container.
113
           If the container memory is relocated (QVector), the pointer gets invalid!!!
114
           Therefore, a resize() is called before the loop (no resize()-operations during the loop)! */
115
        //mRUSpecies[i].setup(s,this); // setup this element
116
 
117
    }
118
}
119
 
120
ResourceUnitSpecies &ResourceUnit::resourceUnitSpecies(const Species *species)
121
{
122
    return *mRUSpecies[species->index()];
123
}
124
 
125
Tree &ResourceUnit::newTree()
126
{
127
    // start simple: just append to the vector...
128
    if (mTrees.isEmpty())
129
        mTrees.reserve(100); // reserve a junk of memory for trees
130
 
131
    mTrees.append(Tree());
132
    return mTrees.back();
133
}
134
int ResourceUnit::newTreeIndex()
135
{
136
    // start simple: just append to the vector...
137
    mTrees.append(Tree());
138
    return mTrees.count()-1;
139
}
140
 
141
/// remove dead trees from tree list
142
/// reduce size of vector if lots of space is free
143
/// tests showed that this way of cleanup is very fast,
144
/// because no memory allocations are performed (simple memmove())
145
/// when trees are moved.
146
void ResourceUnit::cleanTreeList()
147
{
148
    QVector<Tree>::iterator last=mTrees.end()-1;
149
    QVector<Tree>::iterator current = mTrees.begin();
150
    while (last>=current && (*last).isDead())
151
        --last;
152
 
153
    while (current<last) {
154
        if ((*current).isDead()) {
155
            *current = *last; // copy data!
156
            --last; //
157
            while (last>=current && (*last).isDead())
158
                --last;
159
        }
160
        ++current;
161
    }
162
    ++last; // last points now to the first dead tree
163
 
164
    // free ressources
165
    if (last!=mTrees.end()) {
166
        mTrees.erase(last, mTrees.end());
167
        if (mTrees.capacity()>100) {
168
            if (mTrees.count() / double(mTrees.capacity()) < 0.2) {
169
                //int target_size = mTrees.count()*2;
170
                //qDebug() << "reduce size from "<<mTrees.capacity() << "to" << target_size;
171
                //mTrees.reserve(qMax(target_size, 100));
172
                qDebug() << "reduce tree storage of RU" << index() << " from " << mTrees.capacity() << "to" << mTrees.count();
173
                mTrees.squeeze();
174
            }
175
        }
176
    }
177
}
178
 
179
void ResourceUnit::newYear()
180
{
181
    mAggregatedWLA = 0.;
182
    mAggregatedLA = 0.;
183
    mAggregatedLR = 0.;
184
    mEffectiveArea = 0.;
185
    mPixelCount = mStockedPixelCount = 0;
186
    snagNewYear();
609 werner 187
    if (mSoil)
188
        mSoil->newYear();
534 werner 189
    // clear statistics global and per species...
190
    QList<ResourceUnitSpecies*>::const_iterator i;
191
    QList<ResourceUnitSpecies*>::const_iterator iend = mRUSpecies.constEnd();
192
    mStatistics.clear();
193
    for (i=mRUSpecies.constBegin(); i!=iend; ++i) {
194
        (*i)->statisticsDead().clear();
195
        (*i)->statisticsMgmt().clear();
662 werner 196
        (*i)->changeSapling().newYear();
534 werner 197
    }
198
 
199
}
200
 
201
/** production() is the "stand-level" part of the biomass production (3PG).
202
    - The amount of radiation intercepted by the stand is calculated
203
    - the water cycle is calculated
204
    - statistics for each species are cleared
205
    - The 3PG production for each species and ressource unit is called (calculates species-responses and NPP production)
206
    see also: http://iland.boku.ac.at/individual+tree+light+availability */
207
void ResourceUnit::production()
208
{
209
 
210
    if (mAggregatedWLA==0 || mPixelCount==0) {
211
        // nothing to do...
212
        return;
213
    }
214
 
215
    // the pixel counters are filled during the height-grid-calculations
216
    mStockedArea = 100. * mStockedPixelCount; // m2 (1 height grid pixel = 10x10m)
217
 
218
    // calculate the leaf area index (LAI)
219
    double LAI = mAggregatedLA / mStockedArea;
220
    // calculate the intercepted radiation fraction using the law of Beer Lambert
221
    const double k = Model::settings().lightExtinctionCoefficient;
222
    double interception_fraction = 1. - exp(-k * LAI);
223
    mEffectiveArea = mStockedArea * interception_fraction; // m2
224
 
225
    // calculate the total weighted leaf area on this RU:
226
    mLRI_modification = interception_fraction *  mStockedArea / mAggregatedWLA; // p_WLA
227
    if (mLRI_modification == 0.)
228
        qDebug() << "lri modifaction==0!";
229
 
611 werner 230
    if (logLevelDebug()) {
534 werner 231
    DBGMODE(qDebug() << QString("production: LAI: %1 (intercepted fraction: %2, stocked area: %4). LRI-Multiplier: %3")
232
            .arg(LAI)
233
            .arg(interception_fraction)
234
            .arg(mLRI_modification)
235
            .arg(mStockedArea);
236
    );
611 werner 237
    }
534 werner 238
 
239
    // calculate LAI fractions
240
    QList<ResourceUnitSpecies*>::const_iterator i;
241
    QList<ResourceUnitSpecies*>::const_iterator iend = mRUSpecies.constEnd();
242
    double ru_lai = leafAreaIndex();
243
    if (ru_lai < 1.)
244
        ru_lai = 1.;
245
    // note: LAIFactors are only 1 if sum of LAI is > 1. (see WaterCycle)
246
    for (i=mRUSpecies.constBegin(); i!=iend; ++i) {
247
         (*i)->setLAIfactor((*i)->statistics().leafAreaIndex() / ru_lai);
248
    }
249
 
250
    // soil water model - this determines soil water contents needed for response calculations
251
    {
252
    mWater->run();
253
    }
254
 
255
    // invoke species specific calculation (3PG)
256
    for (i=mRUSpecies.constBegin(); i!=iend; ++i) {
257
        (*i)->calculate(); // CALCULATE 3PG
258
        if (logLevelInfo() &&  (*i)->LAIfactor()>0)
259
            qDebug() << "ru" << mIndex << "species" << (*i)->species()->id() << "LAIfraction" << (*i)->LAIfactor() << "raw_gpp_m2"
260
                     << (*i)->prod3PG().GPPperArea() << "area:" << productiveArea() << "gpp:"
261
                     << productiveArea()*(*i)->prod3PG().GPPperArea()
262
                     << "aging(lastyear):" << averageAging() << "f_env,yr:" << (*i)->prod3PG().fEnvYear();
263
    }
264
}
265
 
266
void ResourceUnit::calculateInterceptedArea()
267
{
268
    if (mAggregatedLR==0) {
269
        mEffectiveArea_perWLA = 0.;
270
        return;
271
    }
272
    Q_ASSERT(mAggregatedLR>0.);
273
    mEffectiveArea_perWLA = mEffectiveArea / mAggregatedLR;
274
    if (logLevelDebug()) qDebug() << "RU: aggregated lightresponse:" << mAggregatedLR  << "eff.area./wla:" << mEffectiveArea_perWLA;
275
}
276
 
277
// function is called immediately before the growth of individuals
278
void ResourceUnit::beforeGrow()
279
{
280
    mAverageAging = 0.;
281
}
282
 
283
// function is called after finishing the indivdual growth / mortality.
284
void ResourceUnit::afterGrow()
285
{
286
    mAverageAging = leafArea()>0.?mAverageAging/leafArea():0; // calculate aging value (calls to addAverageAging() by individual trees)
287
    if (mAverageAging>0. && mAverageAging<0.00001)
288
        qDebug() << "ru" << mIndex << "aging <0.00001";
289
    if (mAverageAging<0. || mAverageAging>1.)
290
        qDebug() << "Average aging invalid: (RU, LAI):" << index() << mStatistics.leafAreaIndex();
291
}
292
 
293
void ResourceUnit::yearEnd()
294
{
295
    // calculate statistics for all tree species of the ressource unit
296
    int c = mRUSpecies.count();
297
    for (int i=0;i<c; i++) {
298
        mRUSpecies[i]->statisticsDead().calculate(); // calculate the dead trees
299
        mRUSpecies[i]->statisticsMgmt().calculate(); // stats of removed trees
300
        mRUSpecies[i]->updateGWL(); // get sum of dead trees (died + removed)
301
        mRUSpecies[i]->statistics().calculate(); // calculate the living (and add removed volume to gwl)
302
        mStatistics.add(mRUSpecies[i]->statistics());
303
    }
304
    mStatistics.calculate(); // aggreagte on stand level
305
 
306
}
307
 
308
void ResourceUnit::addTreeAgingForAllTrees()
309
{
310
    mAverageAging = 0.;
311
    foreach(const Tree &t, mTrees) {
312
        addTreeAging(t.leafArea(), t.species()->aging(t.height(), t.age()));
313
    }
314
 
315
}
316
 
317
/// refresh of tree based statistics.
318
/// WARNING: this function is only called once (during startup).
319
/// see function "yearEnd()" above!!!
320
void ResourceUnit::createStandStatistics()
321
{
322
    // clear statistics (ru-level and ru-species level)
323
    mStatistics.clear();
324
    for (int i=0;i<mRUSpecies.count();i++) {
325
        mRUSpecies[i]->statistics().clear();
326
        mRUSpecies[i]->statisticsDead().clear();
327
        mRUSpecies[i]->statisticsMgmt().clear();
328
    }
329
 
330
    // add all trees to the statistics objects of the species
331
    foreach(const Tree &t, mTrees) {
332
        if (!t.isDead())
333
            resourceUnitSpecies(t.species()).statistics().add(&t, 0);
334
    }
335
    // summarize statistics for the whole resource unit
336
    for (int i=0;i<mRUSpecies.count();i++) {
337
        mRUSpecies[i]->statistics().calculate();
338
        mStatistics.add(mRUSpecies[i]->statistics());
339
    }
340
    mStatistics.calculate();
575 werner 341
    mAverageAging = mStatistics.leafAreaIndex()>0.?mAverageAging / (mStatistics.leafAreaIndex()*stockableArea()):0.;
534 werner 342
    if (mAverageAging<0. || mAverageAging>1.)
343
        qDebug() << "Average aging invalid: (RU, LAI):" << index() << mStatistics.leafAreaIndex();
344
}
345
 
346
void ResourceUnit::setMaxSaplingHeightAt(const QPoint &position, const float height)
347
{
348
    Q_ASSERT(mSaplingHeightMap);
349
    int pixel_index = cPxPerRU*(position.x()-mCornerCoord.x())+(position.y()-mCornerCoord.y());
350
    if (pixel_index<0 || pixel_index>=cPxPerRU*cPxPerRU) {
351
        qDebug() << "setSaplingHeightAt-Error for position" << position << "for RU at" << boundingBox() << "with corner" << mCornerCoord;
352
    } else {
353
        if (mSaplingHeightMap[pixel_index]<height)
354
            mSaplingHeightMap[pixel_index]=height;
355
    }
356
}
357
 
358
/// clear all saplings of all species on a given position (after recruitment)
359
void ResourceUnit::clearSaplings(const QPoint &position)
360
{
361
    foreach(ResourceUnitSpecies* rus, mRUSpecies)
362
        rus->clearSaplings(position);
363
 
364
}
365
 
662 werner 366
/// kill all saplings within a given rect
367
void ResourceUnit::clearSaplings(const QRectF pixel_rect, const bool remove_from_soil)
368
{
369
    foreach(ResourceUnitSpecies* rus, mRUSpecies) {
370
        rus->changeSapling().clearSaplings(pixel_rect, remove_from_soil);
371
    }
372
 
373
}
374
 
600 werner 375
float ResourceUnit::saplingHeightForInit(const QPoint &position) const
376
{
377
    double maxh = 0.;
378
    foreach(ResourceUnitSpecies* rus, mRUSpecies)
379
        maxh = qMax(maxh, rus->sapling().heightAt(position));
380
    return maxh;
381
}
534 werner 382
 
383
void ResourceUnit::calculateCarbonCycle()
384
{
385
    if (!snag())
386
        return;
387
 
388
    // (1) calculate the snag dynamics
389
    // because all carbon/nitrogen-flows from trees to the soil are routed through the snag-layer,
390
    // all soil inputs (litter + deadwood) are collected in the Snag-object.
391
    snag()->calculateYear();
392
    soil()->setClimateFactor( snag()->climateFactor() ); // the climate factor is only calculated once
393
    soil()->setSoilInput( snag()->labileFlux(), snag()->refractoryFlux());
394
    soil()->calculateYear(); // update the ICBM/2N model
395
    // use available nitrogen?
396
    if (Model::settings().useDynamicAvailableNitrogen)
397
        mUnitVariables.nitrogenAvailable = soil()->availableNitrogen();
398
 
399
    // debug output
400
    if (GlobalSettings::instance()->isDebugEnabled(GlobalSettings::dCarbonCycle) && !snag()->isEmpty()) {
401
        DebugList &out = GlobalSettings::instance()->debugList(index(), GlobalSettings::dCarbonCycle);
605 werner 402
        out << index() << id(); // resource unit index and id
534 werner 403
        out << snag()->debugList(); // snag debug outs
404
        out << soil()->debugList(); // ICBM/2N debug outs
405
    }
406
 
407
}
600 werner 408
 
409