Subversion Repositories public iLand

Rev

Rev 1221 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1211 werner 1
/********************************************************************************************
2
**    iLand - an individual based forest landscape and disturbance model
3
**    http://iland.boku.ac.at
4
**    Copyright (C) 2009-  Werner Rammer, Rupert Seidl
5
**
6
**    This program is free software: you can redistribute it and/or modify
7
**    it under the terms of the GNU General Public License as published by
8
**    the Free Software Foundation, either version 3 of the License, or
9
**    (at your option) any later version.
10
**
11
**    This program is distributed in the hope that it will be useful,
12
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
13
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
**    GNU General Public License for more details.
15
**
16
**    You should have received a copy of the GNU General Public License
17
**    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
********************************************************************************************/
1111 werner 19
#include "global.h"
20
#include "saplings.h"
21
 
22
#include "globalsettings.h"
23
#include "model.h"
24
#include "resourceunit.h"
25
#include "resourceunitspecies.h"
26
#include "establishment.h"
27
#include "species.h"
28
#include "seeddispersal.h"
1213 werner 29
#include "mapgrid.h"
1111 werner 30
 
1113 werner 31
double Saplings::mRecruitmentVariation = 0.1; // +/- 10%
32
double Saplings::mBrowsingPressure = 0.;
1111 werner 33
 
1113 werner 34
 
1111 werner 35
Saplings::Saplings()
36
{
37
 
38
}
39
 
40
void Saplings::setup()
41
{
1159 werner 42
    //mGrid.setup(GlobalSettings::instance()->model()->grid()->metricRect(), GlobalSettings::instance()->model()->grid()->cellsize());
43
    FloatGrid *lif_grid = GlobalSettings::instance()->model()->grid();
1111 werner 44
    // mask out out-of-project areas
45
    HeightGrid *hg = GlobalSettings::instance()->model()->heightGrid();
1159 werner 46
    for (int i=0; i<lif_grid->count(); ++i) {
47
        SaplingCell *s = cell(lif_grid->indexOf(i), false); // false: retrieve also invalid cells
48
        if (s) {
49
            if (!hg->valueAtIndex(lif_grid->index5(i)).isValid())
50
                s->state = SaplingCell::CellInvalid;
51
            else
52
                s->state = SaplingCell::CellFree;
53
        }
54
 
1111 werner 55
    }
56
 
57
}
58
 
1178 werner 59
void Saplings::calculateInitialStatistics(const ResourceUnit *ru)
60
{
61
    SaplingCell *sap_cells = ru->saplingCellArray();
1196 werner 62
    if (!sap_cells)
63
        return;
64
 
1178 werner 65
    SaplingCell *s = sap_cells;
66
 
67
    for (int i=0; i<cPxPerHectare; ++i, ++s) {
68
        if (s->state != SaplingCell::CellInvalid) {
69
            int cohorts_on_px = s->n_occupied();
70
            for (int j=0;j<NSAPCELLS;++j) {
71
                if (s->saplings[j].is_occupied()) {
72
                    SaplingTree &tree=s->saplings[j];
73
                    ResourceUnitSpecies *rus = tree.resourceUnitSpecies(ru);
74
                    rus->saplingStat().mLiving++;
75
                    double n_repr = rus->species()->saplingGrowthParameters().representedStemNumberH(tree.height) / static_cast<double>(cohorts_on_px);
76
                    if (tree.height>1.3f)
77
                        rus->saplingStat().mLivingSaplings += n_repr;
78
                    else
79
                        rus->saplingStat().mLivingSmallSaplings += n_repr;
80
 
81
                    rus->saplingStat().mAvgHeight+=tree.height;
82
                    rus->saplingStat().mAvgAge+=tree.age;
83
 
84
                }
85
            }
86
        }
87
    }
88
 
89
 
90
}
91
 
1111 werner 92
void Saplings::establishment(const ResourceUnit *ru)
93
{
94
    FloatGrid *lif_grid = GlobalSettings::instance()->model()->grid();
95
 
1118 werner 96
    QPoint imap = ru->cornerPointOffset(); // offset on LIF/saplings grid
97
    QPoint iseedmap = QPoint(imap.x()/10, imap.y()/10); // seed-map has 20m resolution, LIF 2m -> factor 10
1111 werner 98
 
1158 werner 99
    for (QList<ResourceUnitSpecies*>::const_iterator i=ru->ruSpecies().constBegin(); i!=ru->ruSpecies().constEnd(); ++i)
100
        (*i)->saplingStat().clearStatistics();
101
 
102
    double lif_corr[cPxPerHectare];
103
    for (int i=0;i<cPxPerHectare;++i)
104
        lif_corr[i]=-1.;
105
 
1164 werner 106
    int species_idx;
107
    QVector<int>::const_iterator sbegin, send;
108
    ru->speciesSet()->randomSpeciesOrder(sbegin, send);
109
    for (QVector<int>::const_iterator s_idx=sbegin; s_idx!=send;++s_idx) {
1111 werner 110
 
111
        // start from a random species (and cycle through the available species)
1164 werner 112
        species_idx = *s_idx;
1111 werner 113
 
114
        ResourceUnitSpecies *rus = ru->ruSpecies()[species_idx];
1168 werner 115
        rus->establishment().clear();
116
 
1111 werner 117
        // check if there are seeds of the given species on the resource unit
118
        float seeds = 0.f;
1118 werner 119
        Grid<float> &seedmap =  const_cast<Grid<float>& >(rus->species()->seedDispersal()->seedMap());
1111 werner 120
        for (int iy=0;iy<5;++iy) {
121
            float *p = seedmap.ptr(iseedmap.x(), iseedmap.y());
122
            for (int ix=0;ix<5;++ix)
123
                seeds += *p++;
124
        }
125
        // if there are no seeds: no need to do more
126
        if (seeds==0.f)
127
            continue;
128
 
129
        // calculate the abiotic environment (TACA)
130
        rus->establishment().calculateAbioticEnvironment();
131
        double abiotic_env = rus->establishment().abioticEnvironment();
1168 werner 132
        if (abiotic_env==0.) {
133
            rus->establishment().writeDebugOutputs();
1111 werner 134
            continue;
1168 werner 135
        }
1111 werner 136
 
137
        // loop over all 2m cells on this resource unit
1159 werner 138
        SaplingCell *sap_cells = ru->saplingCellArray();
1111 werner 139
        SaplingCell *s;
140
        int isc = 0; // index on 2m cell
141
        for (int iy=0; iy<cPxPerRU; ++iy) {
1159 werner 142
            s = &sap_cells[iy*cPxPerRU]; // pointer to a row
143
            isc = lif_grid->index(imap.x(), imap.y()+iy);
1111 werner 144
 
1158 werner 145
            for (int ix=0;ix<cPxPerRU; ++ix, ++s, ++isc) {
1111 werner 146
                if (s->state == SaplingCell::CellFree) {
147
                    // is a sapling of the current species already on the pixel?
148
                    // * test for sapling height already in cell state
149
                    // * test for grass-cover already in cell state
1158 werner 150
                    SaplingTree *stree=0;
151
                    SaplingTree *slot=s->saplings;
152
                    for (int i=0;i<NSAPCELLS;++i, ++slot) {
153
                        if (!stree && !slot->is_occupied())
154
                            stree=slot;
155
                        if (slot->species_index == species_idx) {
156
                            stree=0;
157
                            break;
1111 werner 158
                        }
159
                    }
160
 
1158 werner 161
                    if (stree) {
1111 werner 162
                        // grass cover?
1159 werner 163
                        float seed_map_value = seedmap[lif_grid->index10(isc)];
1111 werner 164
                        if (seed_map_value==0.f)
165
                            continue;
166
                        float lif_value = (*lif_grid)[isc];
1158 werner 167
 
168
                        double &lif_corrected = lif_corr[iy*cPxPerRU+ix];
1182 werner 169
                        // calculate the LIFcorrected only once per pixel; the relative height is 0 (light level on the forest floor)
1158 werner 170
                        if (lif_corrected<0.)
1178 werner 171
                            lif_corrected = rus->species()->speciesSet()->LRIcorrection(lif_value, 0.);
1158 werner 172
 
1111 werner 173
                        // check for the combination of seed availability and light on the forest floor
1158 werner 174
                        if (drandom() < seed_map_value*lif_corrected*abiotic_env ) {
175
                            // ok, lets add a sapling at the given position (age is incremented later)
176
                            stree->setSapling(0.05f, 0, species_idx);
177
                            s->checkState();
178
                            rus->saplingStat().mAdded++;
1111 werner 179
 
1158 werner 180
                        }
1111 werner 181
 
182
                    }
183
 
184
                }
185
            }
186
        }
1168 werner 187
        // create debug output related to establishment
188
        rus->establishment().writeDebugOutputs();
1111 werner 189
    }
190
 
191
}
1113 werner 192
 
193
void Saplings::saplingGrowth(const ResourceUnit *ru)
194
{
195
    HeightGrid *height_grid = GlobalSettings::instance()->model()->heightGrid();
196
    FloatGrid *lif_grid = GlobalSettings::instance()->model()->grid();
197
 
1159 werner 198
    QPoint imap = ru->cornerPointOffset();
1115 werner 199
    bool need_check=false;
1159 werner 200
    SaplingCell *sap_cells = ru->saplingCellArray();
1177 werner 201
 
1113 werner 202
    for (int iy=0; iy<cPxPerRU; ++iy) {
1159 werner 203
        SaplingCell *s = &sap_cells[iy*cPxPerRU]; // ptr to row
204
        int isc = lif_grid->index(imap.x(), imap.y()+iy);
1113 werner 205
 
206
        for (int ix=0;ix<cPxPerRU; ++ix, ++s, ++isc) {
207
            if (s->state != SaplingCell::CellInvalid) {
1115 werner 208
                need_check=false;
1177 werner 209
                int n_on_px = s->n_occupied();
1113 werner 210
                for (int i=0;i<NSAPCELLS;++i) {
211
                    if (s->saplings[i].is_occupied()) {
212
                        // growth of this sapling tree
213
                        const HeightGridValue &hgv = (*height_grid)[height_grid->index5(isc)];
214
                        float lif_value = (*lif_grid)[isc];
215
 
1177 werner 216
                        need_check |= growSapling(ru, *s, s->saplings[i], isc, hgv.height, lif_value, n_on_px);
1113 werner 217
                    }
218
                }
1115 werner 219
                if (need_check)
220
                    s->checkState();
1175 werner 221
 
1113 werner 222
            }
223
        }
224
    }
225
 
1158 werner 226
 
227
    // store statistics on saplings/regeneration
228
    for (QList<ResourceUnitSpecies*>::const_iterator i=ru->ruSpecies().constBegin(); i!=ru->ruSpecies().constEnd(); ++i) {
1177 werner 229
        (*i)->saplingStat().calculate((*i)->species(), const_cast<ResourceUnit*>(ru));
1158 werner 230
        (*i)->statistics().add(&((*i)->saplingStat()));
231
    }
1168 werner 232
 
233
    // debug output related to saplings
234
    if (GlobalSettings::instance()->isDebugEnabled(GlobalSettings::dSaplingGrowth)) {
235
 
236
        // establishment details
237
        for (QList<ResourceUnitSpecies*>::const_iterator it=ru->ruSpecies().constBegin();it!=ru->ruSpecies().constEnd();++it) {
1177 werner 238
            if ((*it)->saplingStat().livingCohorts() == 0)
1168 werner 239
                continue;
240
            DebugList &out = GlobalSettings::instance()->debugList(ru->index(), GlobalSettings::dSaplingGrowth);
241
            out << (*it)->species()->id() << ru->index() <<ru->id();
1177 werner 242
            out << (*it)->saplingStat().livingCohorts() << (*it)->saplingStat().averageHeight() << (*it)->saplingStat().averageAge()
1168 werner 243
                << (*it)->saplingStat().averageDeltaHPot() << (*it)->saplingStat().averageDeltaHRealized();
244
            out << (*it)->saplingStat().newSaplings() << (*it)->saplingStat().diedSaplings()
245
                << (*it)->saplingStat().recruitedSaplings() <<(*it)->species()->saplingGrowthParameters().referenceRatio;
246
        }
247
    }
248
 
1113 werner 249
}
250
 
1162 werner 251
SaplingCell *Saplings::cell(QPoint lif_coords, bool only_valid, ResourceUnit **rRUPtr)
1159 werner 252
{
253
    FloatGrid *lif_grid = GlobalSettings::instance()->model()->grid();
254
 
255
    // in this case, getting the actual cell is quite cumbersome: first, retrieve the resource unit, then the
256
    // cell based on the offset of the given coordiantes relative to the corner of the resource unit.
257
    ResourceUnit *ru = GlobalSettings::instance()->model()->ru(lif_grid->cellCenterPoint(lif_coords));
1162 werner 258
    if (rRUPtr)
259
        *rRUPtr = ru;
1160 werner 260
 
1159 werner 261
    if (ru) {
262
        QPoint local_coords = lif_coords - ru->cornerPointOffset();
263
        int idx = local_coords.y() * cPxPerRU + local_coords.x();
264
        DBGMODE( if (idx<0 || idx>=cPxPerHectare)
265
                 qDebug("invalid coords in Saplings::cell");
266
                    );
267
        SaplingCell *s=&ru->saplingCellArray()[idx];
268
        if (s && (!only_valid || s->state!=SaplingCell::CellInvalid))
269
            return s;
270
    }
271
    return 0;
272
}
273
 
1162 werner 274
void Saplings::clearSaplings(const QRectF &rectangle, const bool remove_biomass)
275
{
276
    GridRunner<float> runner(GlobalSettings::instance()->model()->grid(), rectangle);
277
    ResourceUnit *ru;
278
    while (runner.next()) {
279
        SaplingCell *s = cell(runner.currentIndex(), true, &ru);
280
        if (s) {
1165 werner 281
            clearSaplings(s, ru, remove_biomass);
282
        }
1162 werner 283
 
1165 werner 284
    }
285
}
286
 
287
void Saplings::clearSaplings(SaplingCell *s, ResourceUnit *ru, const bool remove_biomass)
288
{
289
    if (s) {
290
        for (int i=0;i<NSAPCELLS;++i)
291
            if (s->saplings[i].is_occupied()) {
292
                if (!remove_biomass) {
1174 werner 293
                    ResourceUnitSpecies *rus = s->saplings[i].resourceUnitSpecies(ru);
1165 werner 294
                    if (!rus && !rus->species()) {
295
                        qDebug() << "Saplings::clearSaplings(): invalid resource unit!!!";
296
                        return;
1162 werner 297
                    }
1165 werner 298
                    rus->saplingStat().addCarbonOfDeadSapling( s->saplings[i].height / rus->species()->saplingGrowthParameters().hdSapling * 100.f );
1162 werner 299
                }
1165 werner 300
                s->saplings[i].clear();
301
            }
302
        s->checkState();
1162 werner 303
 
1165 werner 304
    }
305
 
306
}
307
 
308
int Saplings::addSprout(const Tree *t)
309
{
310
    if (t->species()->saplingGrowthParameters().sproutGrowth==0.)
311
        return 0;
312
    SaplingCell *sc = cell(t->positionIndex());
313
    if (!sc)
314
        return 0;
315
    clearSaplings(sc, const_cast<ResourceUnit*>(t->ru()), false );
316
    SaplingTree *st=sc->addSapling(0.05f, 0, t->species()->index());
317
    if (st)
318
        st->set_sprout(true);
319
 
320
    // neighboring cells
321
    double crown_area = t->crownRadius()*t->crownRadius() * M_PI; //m2
322
    // calculate how many cells on the ground are covered by the crown (this is a rather rough estimate)
323
    // n_cells: in addition to the original cell
324
    int n_cells = static_cast<int>(round( crown_area / static_cast<double>(cPxSize*cPxSize) - 1.));
325
    if (n_cells>0) {
326
        ResourceUnit *ru;
327
        static const int offsets_x[8] = {1,1,0,-1,-1,-1,0,1};
328
        static const int offsets_y[8] = {0,1,1,1,0,-1,-1,-1};
329
        int s=irandom(0,8);
330
        while(n_cells) {
331
            sc = cell(t->positionIndex()+QPoint(offsets_x[s], offsets_y[s]),true,&ru);
332
            if (sc) {
333
                clearSaplings(sc, ru, false );
334
                SaplingTree *st=sc->addSapling(0.05f, 0, t->species()->index());
335
                if (st)
336
                    st->set_sprout(true);
337
            }
338
 
339
            s = (s+1)%8; --n_cells;
1162 werner 340
        }
341
    }
1165 werner 342
    return 1;
1162 werner 343
}
344
 
1113 werner 345
void Saplings::updateBrowsingPressure()
346
{
347
    if (GlobalSettings::instance()->settings().valueBool("model.settings.browsing.enabled"))
348
        Saplings::mBrowsingPressure = GlobalSettings::instance()->settings().valueDouble("model.settings.browsing.browsingPressure");
349
    else
350
        Saplings::mBrowsingPressure = 0.;
351
}
352
 
1177 werner 353
bool Saplings::growSapling(const ResourceUnit *ru, SaplingCell &scell, SaplingTree &tree, int isc, float dom_height, float lif_value, int cohorts_on_px)
1113 werner 354
{
1174 werner 355
    ResourceUnitSpecies *rus = tree.resourceUnitSpecies(ru);
356
 
1113 werner 357
    const Species *species = rus->species();
358
 
359
    // (1) calculate height growth potential for the tree (uses linerization of expressions...)
360
    double h_pot = species->saplingGrowthParameters().heightGrowthPotential.calculate(tree.height);
361
    double delta_h_pot = h_pot - tree.height;
362
 
363
    // (2) reduce height growth potential with species growth response f_env_yr and with light state (i.e. LIF-value) of home-pixel.
364
    if (dom_height==0.f)
365
        throw IException(QString("growSapling: height grid at %1/%2 has value 0").arg(isc));
366
 
367
    double rel_height = tree.height / dom_height;
368
 
369
    double lif_corrected = species->speciesSet()->LRIcorrection(lif_value, rel_height); // correction based on height
370
 
371
    double lr = species->lightResponse(lif_corrected); // species specific light response (LUI, light utilization index)
372
 
1182 werner 373
    rus->calculate(true); // calculate the 3pg module (this is done only once per RU); true: call comes from regeneration
1118 werner 374
    double f_env_yr = rus->prod3PG().fEnvYear();
1113 werner 375
 
1118 werner 376
    double delta_h_factor = f_env_yr * lr; // relative growth
377
 
1113 werner 378
    if (h_pot<0. || delta_h_pot<0. || lif_corrected<0. || lif_corrected>1. || delta_h_factor<0. || delta_h_factor>1. )
379
        qDebug() << "invalid values in Sapling::growSapling";
380
 
1165 werner 381
    // sprouts grow faster. Sprouts therefore are less prone to stress (threshold), and can grow higher than the growth potential.
382
    if (tree.is_sprout())
383
        delta_h_factor = delta_h_factor *species->saplingGrowthParameters().sproutGrowth;
384
 
1113 werner 385
    // check browsing
386
    if (mBrowsingPressure>0. && tree.height<=2.f) {
387
        double p = rus->species()->saplingGrowthParameters().browsingProbability;
388
        // calculate modifed annual browsing probability via odds-ratios
389
        // odds = p/(1-p) -> odds_mod = odds * browsingPressure -> p_mod = odds_mod /( 1 + odds_mod) === p*pressure/(1-p+p*pressure)
390
        double p_browse = p*mBrowsingPressure / (1. - p + p*mBrowsingPressure);
391
        if (drandom() < p_browse) {
392
            delta_h_factor = 0.;
393
        }
394
    }
395
 
396
    // check mortality of saplings
397
    if (delta_h_factor < species->saplingGrowthParameters().stressThreshold) {
398
        tree.stress_years++;
399
        if (tree.stress_years > species->saplingGrowthParameters().maxStressYears) {
400
            // sapling dies...
1160 werner 401
            rus->saplingStat().addCarbonOfDeadSapling( tree.height / species->saplingGrowthParameters().hdSapling * 100.f );
1113 werner 402
            tree.clear();
1115 werner 403
            return true; // need cleanup
1113 werner 404
        }
405
    } else {
406
        tree.stress_years=0; // reset stress counter
407
    }
1165 werner 408
    DBG_IF(delta_h_pot*delta_h_factor < 0.f || (!tree.is_sprout() && delta_h_pot*delta_h_factor > 2.), "Sapling::growSapling", "inplausible height growth.");
1113 werner 409
 
410
    // grow
411
    tree.height += delta_h_pot * delta_h_factor;
412
    tree.age++; // increase age of sapling by 1
413
 
414
    // recruitment?
415
    if (tree.height > 4.f) {
416
        rus->saplingStat().mRecruited++;
417
 
418
        float dbh = tree.height / species->saplingGrowthParameters().hdSapling * 100.f;
419
        // the number of trees to create (result is in trees per pixel)
420
        double n_trees = species->saplingGrowthParameters().representedStemNumber(dbh);
421
        int to_establish = static_cast<int>( n_trees );
422
 
423
        // if n_trees is not an integer, choose randomly if we should add a tree.
424
        // e.g.: n_trees = 2.3 -> add 2 trees with 70% probability, and add 3 trees with p=30%.
425
        if (drandom() < (n_trees-to_establish) || to_establish==0)
426
            to_establish++;
427
 
428
        // add a new tree
429
        for (int i=0;i<to_establish;i++) {
430
            Tree &bigtree = const_cast<ResourceUnit*>(ru)->newTree();
431
 
1159 werner 432
            bigtree.setPosition(GlobalSettings::instance()->model()->grid()->indexOf(isc));
1182 werner 433
            // add variation: add +/-N% to dbh and *independently* to height.
1158 werner 434
            bigtree.setDbh(static_cast<float>(dbh * nrandom(1. - mRecruitmentVariation, 1. + mRecruitmentVariation)));
435
            bigtree.setHeight(static_cast<float>(tree.height * nrandom(1. - mRecruitmentVariation, 1. + mRecruitmentVariation)));
1113 werner 436
            bigtree.setSpecies( const_cast<Species*>(species) );
437
            bigtree.setAge(tree.age,tree.height);
438
            bigtree.setRU(const_cast<ResourceUnit*>(ru));
439
            bigtree.setup();
440
            const Tree *t = &bigtree;
441
            const_cast<ResourceUnitSpecies*>(rus)->statistics().add(t, 0); // count the newly created trees already in the stats
442
        }
443
        // clear all regeneration from this pixel (including this tree)
444
        tree.clear(); // clear this tree (no carbon flow to the ground)
445
        for (int i=0;i<NSAPCELLS;++i) {
1159 werner 446
            if (scell.saplings[i].is_occupied()) {
1113 werner 447
                // add carbon to the ground
1174 werner 448
                ResourceUnitSpecies *srus = scell.saplings[i].resourceUnitSpecies(ru);
449
                srus->saplingStat().addCarbonOfDeadSapling( scell.saplings[i].height / srus->species()->saplingGrowthParameters().hdSapling * 100.f );
1159 werner 450
                scell.saplings[i].clear();
1113 werner 451
            }
452
        }
1115 werner 453
        return true; // need cleanup
1113 werner 454
    }
455
    // book keeping (only for survivors) for the sapling of the resource unit / species
456
    SaplingStat &ss = rus->saplingStat();
1177 werner 457
    double n_repr = species->saplingGrowthParameters().representedStemNumberH(tree.height) / static_cast<double>(cohorts_on_px);
458
    if (tree.height>1.3f)
459
        ss.mLivingSaplings += n_repr;
460
    else
461
        ss.mLivingSmallSaplings += n_repr;
1113 werner 462
    ss.mLiving++;
463
    ss.mAvgHeight+=tree.height;
464
    ss.mAvgAge+=tree.age;
465
    ss.mAvgDeltaHPot+=delta_h_pot;
466
    ss.mAvgHRealized += delta_h_pot * delta_h_factor;
1115 werner 467
    return false;
1113 werner 468
}
469
 
470
void SaplingStat::clearStatistics()
471
{
472
    mRecruited=mDied=mLiving=0;
1177 werner 473
    mLivingSaplings=0.; mLivingSmallSaplings=0.;
1113 werner 474
    mSumDbhDied=0.;
475
    mAvgHeight=0.;
476
    mAvgAge=0.;
477
    mAvgDeltaHPot=mAvgHRealized=0.;
1158 werner 478
    mAdded=0;
1113 werner 479
 
480
}
1158 werner 481
 
1177 werner 482
void SaplingStat::calculate(const Species *species, ResourceUnit *ru)
1158 werner 483
{
484
    if (mLiving) {
485
        mAvgHeight /= double(mLiving);
486
        mAvgAge /= double(mLiving);
487
        mAvgDeltaHPot /= double(mLiving);
488
        mAvgHRealized /= double(mLiving);
489
    }
1178 werner 490
    if (GlobalSettings::instance()->currentYear()==0)
491
        return; // no need for carbon flows in initial run
1158 werner 492
 
493
    // calculate carbon balance
494
    CNPair old_state = mCarbonLiving;
495
    mCarbonLiving.clear();
496
 
497
    CNPair dead_wood, dead_fine; // pools for mortality
498
    // average dbh
499
    if (mLiving>0) {
500
        // calculate the avg dbh and number of stems
501
        double avg_dbh = mAvgHeight / species->saplingGrowthParameters().hdSapling * 100.;
1177 werner 502
        // the number of "real" stems is given by the Reineke formula
503
        double n = mLivingSaplings; // total number of saplings (>0.05m)
1175 werner 504
 
1158 werner 505
        // woody parts: stem, branchse and coarse roots
506
        double woody_bm = species->biomassWoody(avg_dbh) + species->biomassBranch(avg_dbh) + species->biomassRoot(avg_dbh);
507
        double foliage = species->biomassFoliage(avg_dbh);
508
        double fineroot = foliage*species->finerootFoliageRatio();
509
 
510
        mCarbonLiving.addBiomass( woody_bm*n, species->cnWood()  );
511
        mCarbonLiving.addBiomass( foliage*n, species->cnFoliage()  );
512
        mCarbonLiving.addBiomass( fineroot*n, species->cnFineroot()  );
513
 
1160 werner 514
        DBGMODE(
515
        if (isnan(mCarbonLiving.C))
516
            qDebug("carbon NaN in SaplingStat::calculate (living trees).");
517
                );
518
 
1158 werner 519
        // turnover
520
        if (ru->snag())
521
            ru->snag()->addTurnoverLitter(species, foliage*species->turnoverLeaf(), fineroot*species->turnoverRoot());
522
 
523
        // calculate the "mortality from competition", i.e. carbon that stems from reduction of stem numbers
524
        // from Reinekes formula.
525
        //
526
        if (avg_dbh>1.) {
527
            double avg_dbh_before = (mAvgHeight - mAvgHRealized) / species->saplingGrowthParameters().hdSapling * 100.;
1177 werner 528
            double n_before = mLiving * species->saplingGrowthParameters().representedStemNumber( qMax(1.,avg_dbh_before) );
1158 werner 529
            if (n<n_before) {
530
                dead_wood.addBiomass( woody_bm * (n_before-n), species->cnWood() );
531
                dead_fine.addBiomass( foliage * (n_before-n), species->cnFoliage()  );
532
                dead_fine.addBiomass( fineroot * (n_before-n), species->cnFineroot()  );
1160 werner 533
                DBGMODE(
534
                if (isnan(dead_fine.C))
535
                    qDebug("carbon NaN in SaplingStat::calculate (self thinning).");
536
                        );
537
 
1158 werner 538
            }
539
        }
540
 
541
    }
542
    if (mDied) {
543
        double avg_dbh_dead = mSumDbhDied / double(mDied);
1177 werner 544
        double n = mDied * species->saplingGrowthParameters().representedStemNumber( avg_dbh_dead );
1158 werner 545
        // woody parts: stem, branchse and coarse roots
546
 
547
        dead_wood.addBiomass( ( species->biomassWoody(avg_dbh_dead) + species->biomassBranch(avg_dbh_dead) + species->biomassRoot(avg_dbh_dead)) * n, species->cnWood()  );
548
        double foliage = species->biomassFoliage(avg_dbh_dead)*n;
549
 
550
        dead_fine.addBiomass( foliage, species->cnFoliage()  );
551
        dead_fine.addBiomass( foliage*species->finerootFoliageRatio(), species->cnFineroot()  );
1160 werner 552
        DBGMODE(
553
        if (isnan(dead_fine.C))
554
            qDebug("carbon NaN in SaplingStat::calculate (died trees).");
555
                );
556
 
1158 werner 557
    }
558
    if (!dead_wood.isEmpty() || !dead_fine.isEmpty())
559
        if (ru->snag())
560
            ru->snag()->addToSoil(species, dead_wood, dead_fine);
561
 
562
    // calculate net growth:
563
    // delta of stocks
564
    mCarbonGain = mCarbonLiving + dead_fine + dead_wood - old_state;
565
    if (mCarbonGain.C < 0)
566
        mCarbonGain.clear();
567
 
568
 
569
    GlobalSettings::instance()->systemStatistics()->saplingCount+=mLiving;
570
    GlobalSettings::instance()->systemStatistics()->newSaplings+=mAdded;
571
 
572
}
1162 werner 573
 
574
double SaplingStat::livingStemNumber(const Species *species, double &rAvgDbh, double &rAvgHeight, double &rAvgAge) const
575
{
576
     rAvgHeight = averageHeight();
577
     rAvgDbh = rAvgHeight / species->saplingGrowthParameters().hdSapling * 100.f;
578
     rAvgAge = averageAge();
579
     double n= species->saplingGrowthParameters().representedStemNumber(rAvgDbh);
580
     return n;
581
// *** old code (sapling.cpp) ***
582
//    double total = 0.;
583
//    double dbh_sum = 0.;
584
//    double h_sum = 0.;
585
//    double age_sum = 0.;
586
//    const SaplingGrowthParameters &p = mRUS->species()->saplingGrowthParameters();
587
//    for (QVector<SaplingTreeOld>::const_iterator it = mSaplingTrees.constBegin(); it!=mSaplingTrees.constEnd(); ++it) {
588
//        float dbh = it->height / p.hdSapling * 100.f;
589
//        if (dbh<1.) // minimum size: 1cm
590
//            continue;
591
//        double n = p.representedStemNumber(dbh); // one cohort on the pixel represents that number of trees
592
//        dbh_sum += n*dbh;
593
//        h_sum += n*it->height;
594
//        age_sum += n*it->age.age;
595
//        total += n;
596
//    }
597
//    if (total>0.) {
598
//        dbh_sum /= total;
599
//        h_sum /= total;
600
//        age_sum /= total;
601
//    }
602
//    rAvgDbh = dbh_sum;
603
//    rAvgHeight = h_sum;
604
//    rAvgAge = age_sum;
605
//    return total;
606
}
1174 werner 607
 
608
ResourceUnitSpecies *SaplingTree::resourceUnitSpecies(const ResourceUnit *ru)
609
{
610
    if (!ru || !is_occupied())
611
        return 0;
612
    ResourceUnitSpecies *rus = ru->resourceUnitSpecies(species_index);
613
    return rus;
614
}
1213 werner 615
 
616
SaplingCellRunner::SaplingCellRunner(const int stand_id, const MapGrid *stand_grid)
617
{
618
    mRunner = 0;
619
    mRU = 0;
620
    mStandId = stand_id;
621
    mStandGrid = stand_grid ? stand_grid : GlobalSettings::instance()->model()->standGrid();
622
    QRectF box = mStandGrid->boundingBox(stand_id);
623
    mRunner = new GridRunner<float>(GlobalSettings::instance()->model()->grid(), box);
624
 
625
}
626
 
1214 werner 627
SaplingCellRunner::~SaplingCellRunner()
628
{
629
    if (mRunner)
630
        delete mRunner;
631
}
632
 
1213 werner 633
SaplingCell *SaplingCellRunner::next()
634
{
635
    if (!mRunner)
636
        return 0;
637
    while (float *n = mRunner->next()) {
638
        if (!n)
639
            return 0; // end of the bounding box
640
        if (mStandGrid->standIDFromLIFCoord(mRunner->currentIndex()) != mStandId)
641
            continue; // pixel does not belong to the target stand
642
        mRU = GlobalSettings::instance()->model()->ru(mRunner->currentCoord());
643
        SaplingCell *sc=0;
644
        if (mRU)
645
            sc=mRU->saplingCell(mRunner->currentIndex());
646
        if (sc)
647
            return sc;
648
        qDebug() << "SaplingCellRunner::next(): unexected missing SaplingCell!";
649
        return 0;
650
    }
651
    return 0;
652
}
653
 
654
QPointF SaplingCellRunner::currentCoord() const
655
{
656
    return mRunner->currentCoord();
657
}