Subversion Repositories public iLand

Rev

Rev 575 | Rev 600 | 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();
187
    // clear statistics global and per species...
188
    QList<ResourceUnitSpecies*>::const_iterator i;
189
    QList<ResourceUnitSpecies*>::const_iterator iend = mRUSpecies.constEnd();
190
    mStatistics.clear();
191
    for (i=mRUSpecies.constBegin(); i!=iend; ++i) {
192
        (*i)->statisticsDead().clear();
193
        (*i)->statisticsMgmt().clear();
194
    }
195
 
196
}
197
 
198
/** production() is the "stand-level" part of the biomass production (3PG).
199
    - The amount of radiation intercepted by the stand is calculated
200
    - the water cycle is calculated
201
    - statistics for each species are cleared
202
    - The 3PG production for each species and ressource unit is called (calculates species-responses and NPP production)
203
    see also: http://iland.boku.ac.at/individual+tree+light+availability */
204
void ResourceUnit::production()
205
{
206
 
207
    if (mAggregatedWLA==0 || mPixelCount==0) {
208
        // nothing to do...
209
        return;
210
    }
211
 
212
    // the pixel counters are filled during the height-grid-calculations
213
    mStockedArea = 100. * mStockedPixelCount; // m2 (1 height grid pixel = 10x10m)
214
 
215
    // calculate the leaf area index (LAI)
216
    double LAI = mAggregatedLA / mStockedArea;
217
    // calculate the intercepted radiation fraction using the law of Beer Lambert
218
    const double k = Model::settings().lightExtinctionCoefficient;
219
    double interception_fraction = 1. - exp(-k * LAI);
220
    mEffectiveArea = mStockedArea * interception_fraction; // m2
221
 
222
    // calculate the total weighted leaf area on this RU:
223
    mLRI_modification = interception_fraction *  mStockedArea / mAggregatedWLA; // p_WLA
224
    if (mLRI_modification == 0.)
225
        qDebug() << "lri modifaction==0!";
226
 
227
 
228
    DBGMODE(qDebug() << QString("production: LAI: %1 (intercepted fraction: %2, stocked area: %4). LRI-Multiplier: %3")
229
            .arg(LAI)
230
            .arg(interception_fraction)
231
            .arg(mLRI_modification)
232
            .arg(mStockedArea);
233
    );
234
 
235
    // calculate LAI fractions
236
    QList<ResourceUnitSpecies*>::const_iterator i;
237
    QList<ResourceUnitSpecies*>::const_iterator iend = mRUSpecies.constEnd();
238
    double ru_lai = leafAreaIndex();
239
    if (ru_lai < 1.)
240
        ru_lai = 1.;
241
    // note: LAIFactors are only 1 if sum of LAI is > 1. (see WaterCycle)
242
    for (i=mRUSpecies.constBegin(); i!=iend; ++i) {
243
         (*i)->setLAIfactor((*i)->statistics().leafAreaIndex() / ru_lai);
244
    }
245
 
246
    // soil water model - this determines soil water contents needed for response calculations
247
    {
248
    DebugTimer tw("water:run");
249
    mWater->run();
250
    }
251
 
252
    // invoke species specific calculation (3PG)
253
    for (i=mRUSpecies.constBegin(); i!=iend; ++i) {
254
        (*i)->calculate(); // CALCULATE 3PG
255
        if (logLevelInfo() &&  (*i)->LAIfactor()>0)
256
            qDebug() << "ru" << mIndex << "species" << (*i)->species()->id() << "LAIfraction" << (*i)->LAIfactor() << "raw_gpp_m2"
257
                     << (*i)->prod3PG().GPPperArea() << "area:" << productiveArea() << "gpp:"
258
                     << productiveArea()*(*i)->prod3PG().GPPperArea()
259
                     << "aging(lastyear):" << averageAging() << "f_env,yr:" << (*i)->prod3PG().fEnvYear();
260
    }
261
}
262
 
263
void ResourceUnit::calculateInterceptedArea()
264
{
265
    if (mAggregatedLR==0) {
266
        mEffectiveArea_perWLA = 0.;
267
        return;
268
    }
269
    Q_ASSERT(mAggregatedLR>0.);
270
    mEffectiveArea_perWLA = mEffectiveArea / mAggregatedLR;
271
    if (logLevelDebug()) qDebug() << "RU: aggregated lightresponse:" << mAggregatedLR  << "eff.area./wla:" << mEffectiveArea_perWLA;
272
}
273
 
274
// function is called immediately before the growth of individuals
275
void ResourceUnit::beforeGrow()
276
{
277
    mAverageAging = 0.;
278
}
279
 
280
// function is called after finishing the indivdual growth / mortality.
281
void ResourceUnit::afterGrow()
282
{
283
    mAverageAging = leafArea()>0.?mAverageAging/leafArea():0; // calculate aging value (calls to addAverageAging() by individual trees)
284
    if (mAverageAging>0. && mAverageAging<0.00001)
285
        qDebug() << "ru" << mIndex << "aging <0.00001";
286
    if (mAverageAging<0. || mAverageAging>1.)
287
        qDebug() << "Average aging invalid: (RU, LAI):" << index() << mStatistics.leafAreaIndex();
288
}
289
 
290
void ResourceUnit::yearEnd()
291
{
292
    // calculate statistics for all tree species of the ressource unit
293
    int c = mRUSpecies.count();
294
    for (int i=0;i<c; i++) {
295
        mRUSpecies[i]->statisticsDead().calculate(); // calculate the dead trees
296
        mRUSpecies[i]->statisticsMgmt().calculate(); // stats of removed trees
297
        mRUSpecies[i]->updateGWL(); // get sum of dead trees (died + removed)
298
        mRUSpecies[i]->statistics().calculate(); // calculate the living (and add removed volume to gwl)
299
        mStatistics.add(mRUSpecies[i]->statistics());
300
    }
301
    mStatistics.calculate(); // aggreagte on stand level
302
 
303
}
304
 
305
void ResourceUnit::addTreeAgingForAllTrees()
306
{
307
    mAverageAging = 0.;
308
    foreach(const Tree &t, mTrees) {
309
        addTreeAging(t.leafArea(), t.species()->aging(t.height(), t.age()));
310
    }
311
 
312
}
313
 
314
/// refresh of tree based statistics.
315
/// WARNING: this function is only called once (during startup).
316
/// see function "yearEnd()" above!!!
317
void ResourceUnit::createStandStatistics()
318
{
319
    // clear statistics (ru-level and ru-species level)
320
    mStatistics.clear();
321
    for (int i=0;i<mRUSpecies.count();i++) {
322
        mRUSpecies[i]->statistics().clear();
323
        mRUSpecies[i]->statisticsDead().clear();
324
        mRUSpecies[i]->statisticsMgmt().clear();
325
    }
326
 
327
    // add all trees to the statistics objects of the species
328
    foreach(const Tree &t, mTrees) {
329
        if (!t.isDead())
330
            resourceUnitSpecies(t.species()).statistics().add(&t, 0);
331
    }
332
    // summarize statistics for the whole resource unit
333
    for (int i=0;i<mRUSpecies.count();i++) {
334
        mRUSpecies[i]->statistics().calculate();
335
        mStatistics.add(mRUSpecies[i]->statistics());
336
    }
337
    mStatistics.calculate();
575 werner 338
    mAverageAging = mStatistics.leafAreaIndex()>0.?mAverageAging / (mStatistics.leafAreaIndex()*stockableArea()):0.;
534 werner 339
    if (mAverageAging<0. || mAverageAging>1.)
340
        qDebug() << "Average aging invalid: (RU, LAI):" << index() << mStatistics.leafAreaIndex();
341
}
342
 
343
void ResourceUnit::setMaxSaplingHeightAt(const QPoint &position, const float height)
344
{
345
    Q_ASSERT(mSaplingHeightMap);
346
    int pixel_index = cPxPerRU*(position.x()-mCornerCoord.x())+(position.y()-mCornerCoord.y());
347
    if (pixel_index<0 || pixel_index>=cPxPerRU*cPxPerRU) {
348
        qDebug() << "setSaplingHeightAt-Error for position" << position << "for RU at" << boundingBox() << "with corner" << mCornerCoord;
349
    } else {
350
        if (mSaplingHeightMap[pixel_index]<height)
351
            mSaplingHeightMap[pixel_index]=height;
352
    }
353
}
354
 
355
/// clear all saplings of all species on a given position (after recruitment)
356
void ResourceUnit::clearSaplings(const QPoint &position)
357
{
358
    foreach(ResourceUnitSpecies* rus, mRUSpecies)
359
        rus->clearSaplings(position);
360
 
361
}
362
 
363
 
364
void ResourceUnit::calculateCarbonCycle()
365
{
366
    if (!snag())
367
        return;
368
 
369
    // (1) calculate the snag dynamics
370
    // because all carbon/nitrogen-flows from trees to the soil are routed through the snag-layer,
371
    // all soil inputs (litter + deadwood) are collected in the Snag-object.
372
    snag()->calculateYear();
373
    soil()->setClimateFactor( snag()->climateFactor() ); // the climate factor is only calculated once
374
    soil()->setSoilInput( snag()->labileFlux(), snag()->refractoryFlux());
375
    soil()->calculateYear(); // update the ICBM/2N model
376
    // use available nitrogen?
377
    if (Model::settings().useDynamicAvailableNitrogen)
378
        mUnitVariables.nitrogenAvailable = soil()->availableNitrogen();
379
 
380
    // debug output
381
    if (GlobalSettings::instance()->isDebugEnabled(GlobalSettings::dCarbonCycle) && !snag()->isEmpty()) {
382
        DebugList &out = GlobalSettings::instance()->debugList(index(), GlobalSettings::dCarbonCycle);
383
        out << index();
384
        out << snag()->debugList(); // snag debug outs
385
        out << soil()->debugList(); // ICBM/2N debug outs
386
    }
387
 
388
}