Subversion Repositories public iLand

Rev

Rev 611 | Rev 639 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 611 Rev 626
1
Redirecting to URL 'https://iland.boku.ac.at/svn/iland/tags/release_1.0/src/core/resourceunit.cpp':
1
Redirecting to URL 'https://iland.boku.ac.at/svn/iland/tags/release_1.0/src/core/resourceunit.cpp':
2
/** @class ResourceUnit
2
/** @class ResourceUnit
3
  ResourceUnit is the spatial unit that encapsulates a forest stand and links to several environmental components
3
  ResourceUnit is the spatial unit that encapsulates a forest stand and links to several environmental components
4
  (Climate, Soil, Water, ...).
4
  (Climate, Soil, Water, ...).
5

5

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