Rev 1068 | Rev 1085 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
1 | |||
671 | werner | 2 | /******************************************************************************************** |
3 | ** iLand - an individual based forest landscape and disturbance model |
||
4 | ** http://iland.boku.ac.at |
||
5 | ** Copyright (C) 2009- Werner Rammer, Rupert Seidl |
||
6 | ** |
||
7 | ** This program is free software: you can redistribute it and/or modify |
||
8 | ** it under the terms of the GNU General Public License as published by |
||
9 | ** the Free Software Foundation, either version 3 of the License, or |
||
10 | ** (at your option) any later version. |
||
11 | ** |
||
12 | ** This program is distributed in the hope that it will be useful, |
||
13 | ** but WITHOUT ANY WARRANTY; without even the implied warranty of |
||
14 | ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
||
15 | ** GNU General Public License for more details. |
||
16 | ** |
||
17 | ** You should have received a copy of the GNU General Public License |
||
18 | ** along with this program. If not, see <http://www.gnu.org/licenses/>. |
||
19 | ********************************************************************************************/ |
||
20 | |||
92 | Werner | 21 | /** @class Model |
247 | werner | 22 | Main object of the iLand model composited of various sub models / sub components. |
697 | werner | 23 | @ingroup core |
24 | The class Model is the top level container of iLand. The Model holds a collection of ResourceUnits, links to SpeciesSet and Climate. |
||
25 | ResourceUnit are grid cells with (currently) a size of 1 ha (100x100m). Many stand level processes (NPP produciton, WaterCycle) operate on this |
||
26 | level. |
||
27 | The Model also contain the landscape-wide 2m LIF-grid (http://iland.boku.ac.at/competition+for+light). |
||
28 | |||
92 | Werner | 29 | */ |
30 | #include "global.h" |
||
31 | #include "model.h" |
||
286 | werner | 32 | #include "sqlhelper.h" |
92 | Werner | 33 | |
105 | Werner | 34 | #include "xmlhelper.h" |
808 | werner | 35 | #include "debugtimer.h" |
281 | werner | 36 | #include "environment.h" |
340 | werner | 37 | #include "timeevents.h" |
106 | Werner | 38 | #include "helper.h" |
189 | iland | 39 | #include "resourceunit.h" |
208 | werner | 40 | #include "climate.h" |
92 | Werner | 41 | #include "speciesset.h" |
106 | Werner | 42 | #include "standloader.h" |
43 | #include "tree.h" |
||
185 | werner | 44 | #include "management.h" |
200 | werner | 45 | #include "modelsettings.h" |
615 | werner | 46 | #include "standstatistics.h" |
543 | werner | 47 | #include "mapgrid.h" |
632 | werner | 48 | #include "modelcontroller.h" |
641 | werner | 49 | #include "modules.h" |
654 | werner | 50 | #include "dem.h" |
1062 | werner | 51 | #include "grasscover.h" |
92 | Werner | 52 | |
202 | werner | 53 | #include "outputmanager.h" |
176 | werner | 54 | |
890 | werner | 55 | #include "forestmanagementengine.h" |
56 | |||
105 | Werner | 57 | #include <QtCore> |
58 | #include <QtXml> |
||
59 | |||
107 | Werner | 60 | /** iterate over all trees of the model. return NULL if all trees processed. |
61 | Usage: |
||
62 | @code |
||
63 | AllTreeIterator trees(model); |
||
64 | while (Tree *tree = trees.next()) { // returns NULL when finished. |
||
65 | tree->something(); // do something |
||
66 | } |
||
281 | werner | 67 | @endcode */ |
107 | Werner | 68 | Tree *AllTreeIterator::next() |
69 | { |
||
143 | Werner | 70 | |
107 | Werner | 71 | if (!mTreeEnd) { |
72 | // initialize to first ressource unit |
||
73 | mRUIterator = mModel->ruList().constBegin(); |
||
314 | werner | 74 | // fast forward to the first RU with trees |
75 | while (mRUIterator!=mModel->ruList().constEnd()) { |
||
76 | if ((*mRUIterator)->trees().count()>0) |
||
77 | break; |
||
753 | werner | 78 | ++mRUIterator; |
314 | werner | 79 | } |
80 | // finished if all RU processed |
||
81 | if (mRUIterator == mModel->ruList().constEnd()) |
||
82 | return NULL; |
||
143 | Werner | 83 | mTreeEnd = &((*mRUIterator)->trees().back()) + 1; // let end point to "1 after end" (STL-style) |
107 | Werner | 84 | mCurrent = &((*mRUIterator)->trees().front()); |
85 | } |
||
86 | if (mCurrent==mTreeEnd) { |
||
753 | werner | 87 | ++mRUIterator; // switch to next RU (loop until RU with trees is found) |
314 | werner | 88 | while (mRUIterator!=mModel->ruList().constEnd()) { |
89 | if ((*mRUIterator)->trees().count()>0) { |
||
90 | break; |
||
91 | } |
||
753 | werner | 92 | ++mRUIterator; |
314 | werner | 93 | } |
107 | Werner | 94 | if (mRUIterator == mModel->ruList().constEnd()) { |
143 | Werner | 95 | mCurrent = NULL; |
96 | return NULL; // finished!! |
||
107 | Werner | 97 | }else { |
143 | Werner | 98 | mTreeEnd = &((*mRUIterator)->trees().back()) + 1; |
107 | Werner | 99 | mCurrent = &((*mRUIterator)->trees().front()); |
100 | } |
||
101 | } |
||
143 | Werner | 102 | |
103 | return mCurrent++; |
||
107 | Werner | 104 | } |
157 | werner | 105 | Tree *AllTreeIterator::nextLiving() |
106 | { |
||
107 | while (Tree *t = next()) |
||
158 | werner | 108 | if (!t->isDead()) return t; |
157 | werner | 109 | return NULL; |
110 | } |
||
111 | Tree *AllTreeIterator::current() const |
||
112 | { |
||
113 | return mCurrent?mCurrent-1:NULL; |
||
114 | } |
||
107 | Werner | 115 | |
116 | |||
200 | werner | 117 | ModelSettings Model::mSettings; |
92 | Werner | 118 | Model::Model() |
119 | { |
||
120 | initialize(); |
||
137 | Werner | 121 | GlobalSettings::instance()->setModel(this); |
767 | werner | 122 | GlobalSettings::instance()->resetScriptEngine(); // clear the script |
130 | Werner | 123 | QString dbg="running in release mode."; |
442 | werner | 124 | DBGMODE( dbg="running in debug mode."; ); |
130 | Werner | 125 | qDebug() << dbg; |
92 | Werner | 126 | } |
127 | |||
128 | Model::~Model() |
||
129 | { |
||
130 | clear(); |
||
137 | Werner | 131 | GlobalSettings::instance()->setModel(NULL); |
92 | Werner | 132 | } |
133 | |||
134 | /** Initial setup of the Model. |
||
135 | */ |
||
136 | void Model::initialize() |
||
137 | { |
||
151 | iland | 138 | mSetup = false; |
162 | werner | 139 | GlobalSettings::instance()->setCurrentYear(0); |
151 | iland | 140 | mGrid = 0; |
141 | mHeightGrid = 0; |
||
185 | werner | 142 | mManagement = 0; |
909 | werner | 143 | mABEManagement = 0; |
281 | werner | 144 | mEnvironment = 0; |
340 | werner | 145 | mTimeEvents = 0; |
549 | werner | 146 | mStandGrid = 0; |
641 | werner | 147 | mModules = 0; |
654 | werner | 148 | mDEM = 0; |
1062 | werner | 149 | mGrassCover = 0; |
92 | Werner | 150 | } |
151 | |||
261 | werner | 152 | /** sets up the simulation space. |
153 | */ |
||
103 | Werner | 154 | void Model::setupSpace() |
155 | { |
||
194 | werner | 156 | XmlHelper xml(GlobalSettings::instance()->settings().node("model.world")); |
192 | werner | 157 | double cellSize = xml.value("cellSize", "2").toDouble(); |
158 | double width = xml.value("width", "100").toDouble(); |
||
159 | double height = xml.value("height", "100").toDouble(); |
||
549 | werner | 160 | double buffer = xml.value("buffer", "60").toDouble(); |
161 | mModelRect = QRectF(0., 0., width, height); |
||
162 | |||
103 | Werner | 163 | qDebug() << QString("setup of the world: %1x%2m with cell-size=%3m and %4m buffer").arg(width).arg(height).arg(cellSize).arg(buffer); |
164 | |||
165 | QRectF total_grid(QPointF(-buffer, -buffer), QPointF(width+buffer, height+buffer)); |
||
166 | qDebug() << "setup grid rectangle:" << total_grid; |
||
167 | |||
151 | iland | 168 | if (mGrid) |
169 | delete mGrid; |
||
103 | Werner | 170 | mGrid = new FloatGrid(total_grid, cellSize); |
156 | werner | 171 | mGrid->initialize(1.f); |
151 | iland | 172 | if (mHeightGrid) |
173 | delete mHeightGrid; |
||
174 | mHeightGrid = new HeightGrid(total_grid, cellSize*5); |
||
285 | werner | 175 | mHeightGrid->wipe(); // set all to zero |
156 | werner | 176 | Tree::setGrid(mGrid, mHeightGrid); |
105 | Werner | 177 | |
569 | werner | 178 | // setup the spatial location of the project area |
179 | if (xml.hasNode("location")) { |
||
180 | // setup of spatial location |
||
181 | double loc_x = xml.valueDouble("location.x"); |
||
182 | double loc_y = xml.valueDouble("location.y"); |
||
183 | double loc_z = xml.valueDouble("location.z"); |
||
184 | double loc_rot = xml.valueDouble("location.rotation"); |
||
185 | setupGISTransformation(loc_x, loc_y, loc_z, loc_rot); |
||
186 | qDebug() << "setup of spatial location: x/y/z" << loc_x << loc_y << loc_z << "rotation:" << loc_rot; |
||
187 | } else { |
||
188 | setupGISTransformation(0., 0., 0., 0.); |
||
189 | } |
||
190 | |||
567 | werner | 191 | // load environment (multiple climates, speciesSets, ... |
192 | if (mEnvironment) |
||
193 | delete mEnvironment; |
||
194 | mEnvironment = new Environment(); |
||
281 | werner | 195 | |
567 | werner | 196 | if (xml.valueBool("environmentEnabled", false)) { |
197 | QString env_file = GlobalSettings::instance()->path(xml.value("environmentFile")); |
||
198 | bool grid_mode = (xml.value("environmentMode")=="grid"); |
||
199 | QString grid_file = GlobalSettings::instance()->path(xml.value("environmentGrid")); |
||
893 | werner | 200 | if (grid_mode) { |
201 | if (QFile::exists(grid_file)) |
||
202 | mEnvironment->setGridMode(grid_file); |
||
203 | else |
||
204 | throw IException(QString("File '%1' specified in key 'environmentGrid' does not exit ('environmentMode' is 'grid').").arg(grid_file) ); |
||
205 | } |
||
567 | werner | 206 | |
207 | if (!mEnvironment->loadFromFile(env_file)) |
||
208 | return; |
||
209 | } else { |
||
210 | // load and prepare default values |
||
211 | // (2) SpeciesSets: currently only one a global species set. |
||
212 | SpeciesSet *speciesSet = new SpeciesSet(); |
||
213 | mSpeciesSets.push_back(speciesSet); |
||
214 | speciesSet->setup(); |
||
215 | // Climate... |
||
216 | Climate *c = new Climate(); |
||
217 | mClimates.push_back(c); |
||
218 | mEnvironment->setDefaultValues(c, speciesSet); |
||
219 | } // environment? |
||
220 | |||
221 | // time series data |
||
222 | if (xml.valueBool(".timeEventsEnabled", false)) { |
||
223 | mTimeEvents = new TimeEvents(); |
||
584 | werner | 224 | mTimeEvents->loadFromFile(GlobalSettings::instance()->path(xml.value("timeEventsFile"), "script")); |
567 | werner | 225 | } |
226 | |||
646 | werner | 227 | |
105 | Werner | 228 | // simple case: create ressource units in a regular grid. |
194 | werner | 229 | if (xml.valueBool("resourceUnitsAsGrid")) { |
881 | werner | 230 | |
281 | werner | 231 | mRUmap.setup(QRectF(0., 0., width, height),100.); // Grid, that holds positions of resource units |
881 | werner | 232 | mRUmap.wipe(); |
646 | werner | 233 | |
539 | werner | 234 | bool mask_is_setup = false; |
235 | if (xml.valueBool("standGrid.enabled")) { |
||
236 | QString fileName = GlobalSettings::instance()->path(xml.value("standGrid.fileName")); |
||
882 | werner | 237 | mStandGrid = new MapGrid(fileName,false); // create stand grid index later |
543 | werner | 238 | |
549 | werner | 239 | if (mStandGrid->isValid()) { |
714 | werner | 240 | for (int i=0;i<mStandGrid->grid().count();i++) { |
241 | const int &grid_value = mStandGrid->grid().constValueAtIndex(i); |
||
242 | mHeightGrid->valueAtIndex(i).setValid( grid_value > -1 ); |
||
881 | werner | 243 | if (grid_value>-1) |
244 | mRUmap.valueAt(mStandGrid->grid().cellCenterPoint(i)) = (ResourceUnit*)1; |
||
714 | werner | 245 | if (grid_value < -1) |
718 | werner | 246 | mHeightGrid->valueAtIndex(i).setForestOutside(true); |
714 | werner | 247 | } |
539 | werner | 248 | } |
249 | mask_is_setup = true; |
||
802 | werner | 250 | } else { |
251 | if (!GlobalSettings::instance()->settings().paramValueBool("torus")) { |
||
252 | // in the case we have no stand grid but only a large rectangle (without the torus option) |
||
253 | // we assume a forest outside |
||
254 | for (int i=0;i<mHeightGrid->count();++i) { |
||
255 | const QPointF &p = mHeightGrid->cellCenterPoint(mHeightGrid->indexOf(i)); |
||
256 | if (p.x() < 0. || p.x()>width || p.y()<0. || p.y()>height) { |
||
257 | mHeightGrid->valueAtIndex(i).setForestOutside(true); |
||
258 | mHeightGrid->valueAtIndex(i).setValid(false); |
||
259 | } |
||
260 | } |
||
261 | |||
262 | } |
||
539 | werner | 263 | } |
264 | |||
881 | werner | 265 | ResourceUnit **p; // ptr to ptr! |
266 | ResourceUnit *new_ru; |
||
267 | |||
268 | int ru_index = 0; |
||
269 | for (p=mRUmap.begin(); p!=mRUmap.end(); ++p) { |
||
270 | QRectF r = mRUmap.cellRect(mRUmap.indexOf(p)); |
||
1032 | werner | 271 | if (!mStandGrid || !mStandGrid->isValid() || *p>NULL) { |
917 | werner | 272 | mEnvironment->setPosition( r.center() ); // if environment is 'disabled' default values from the project file are used. |
881 | werner | 273 | // create resource units for valid positions only |
274 | new_ru = new ResourceUnit(ru_index++); // create resource unit |
||
275 | new_ru->setClimate( mEnvironment->climate() ); |
||
276 | new_ru->setSpeciesSet( mEnvironment->speciesSet() ); |
||
277 | new_ru->setup(); |
||
278 | new_ru->setID( mEnvironment->currentID() ); // set id of resource unit in grid mode |
||
279 | new_ru->setBoundingBox(r); |
||
280 | mRU.append(new_ru); |
||
889 | werner | 281 | *p = new_ru; // save in the RUmap grid |
881 | werner | 282 | } |
283 | } |
||
1013 | werner | 284 | if (mEnvironment) { |
285 | // retrieve species sets and climates (that were really used) |
||
286 | mSpeciesSets << mEnvironment->speciesSetList(); |
||
287 | mClimates << mEnvironment->climateList(); |
||
1064 | werner | 288 | QString climate_file_list; |
289 | for (int i=0, c=0;i<mClimates.count();++i) { |
||
290 | climate_file_list += mClimates[i]->name() + ", "; |
||
291 | if (++c>5) { |
||
292 | climate_file_list += "..."; |
||
293 | break; |
||
294 | } |
||
881 | werner | 295 | |
1064 | werner | 296 | } |
297 | qDebug() << "Setup of climates: #loaded:" << mClimates.count() << "tables:" << climate_file_list; |
||
298 | |||
299 | |||
1013 | werner | 300 | } |
301 | |||
1011 | werner | 302 | qDebug() << "setup of" << mEnvironment->climateList().size() << "climates performed."; |
303 | |||
889 | werner | 304 | if (mStandGrid && mStandGrid->isValid()) |
882 | werner | 305 | mStandGrid->createIndex(); |
881 | werner | 306 | // now store the pointers in the grid. |
307 | // Important: This has to be done after the mRU-QList is complete - otherwise pointers would |
||
308 | // point to invalid memory when QList's memory is reorganized (expanding) |
||
309 | // ru_index = 0; |
||
310 | // for (p=mRUmap.begin();p!=mRUmap.end(); ++p) { |
||
311 | // *p = mRU.value(ru_index++); |
||
312 | // } |
||
313 | qDebug() << "created a grid of ResourceUnits: count=" << mRU.count() << "number of RU-map-cells:" << mRUmap.count(); |
||
314 | |||
315 | |||
574 | werner | 316 | calculateStockableArea(); |
317 | |||
285 | werner | 318 | // setup of the project area mask |
539 | werner | 319 | if (!mask_is_setup && xml.valueBool("areaMask.enabled", false) && xml.hasNode("areaMask.imageFile")) { |
285 | werner | 320 | // to be extended!!! e.g. to load ESRI-style text files.... |
321 | // setup a grid with the same size as the height grid... |
||
322 | FloatGrid tempgrid((int)mHeightGrid->cellsize(), mHeightGrid->sizeX(), mHeightGrid->sizeY()); |
||
323 | QString fileName = GlobalSettings::instance()->path(xml.value("areaMask.imageFile")); |
||
324 | loadGridFromImage(fileName, tempgrid); // fetch from image |
||
325 | for (int i=0;i<tempgrid.count(); i++) |
||
326 | mHeightGrid->valueAtIndex(i).setValid( tempgrid.valueAtIndex(i)>0.99 ); |
||
327 | qDebug() << "loaded project area mask from" << fileName; |
||
328 | } |
||
329 | |||
590 | werner | 330 | // list of "valid" resource units |
331 | QList<ResourceUnit*> valid_rus; |
||
332 | foreach(ResourceUnit* ru, mRU) |
||
333 | if (ru->id()!=-1) |
||
334 | valid_rus.append(ru); |
||
335 | |||
654 | werner | 336 | // setup of the digital elevation map (if present) |
337 | QString dem_file = xml.value("DEM"); |
||
338 | if (!dem_file.isEmpty()) { |
||
656 | werner | 339 | mDEM = new DEM(GlobalSettings::instance()->path(dem_file)); |
340 | // add them to the visuals... |
||
341 | GlobalSettings::instance()->controller()->addGrid(mDEM, "DEM height", GridViewRainbow, 0, 1000); |
||
342 | GlobalSettings::instance()->controller()->addGrid(mDEM->slopeGrid(), "DEM slope", GridViewRainbow, 0, 3); |
||
343 | GlobalSettings::instance()->controller()->addGrid(mDEM->aspectGrid(), "DEM aspect", GridViewRainbow, 0, 360); |
||
344 | GlobalSettings::instance()->controller()->addGrid(mDEM->viewGrid(), "DEM view", GridViewGray, 0, 1); |
||
345 | |||
654 | werner | 346 | } |
347 | |||
1062 | werner | 348 | // setup of the grass cover |
349 | if (!mGrassCover) |
||
350 | mGrassCover = new GrassCover(); |
||
351 | mGrassCover->setup(); |
||
352 | |||
646 | werner | 353 | // setup of external modules |
354 | mModules->setup(); |
||
355 | if (mModules->hasSetupResourceUnits()) { |
||
356 | for (ResourceUnit **p=mRUmap.begin(); p!=mRUmap.end(); ++p) { |
||
357 | QRectF r = mRUmap.cellRect(mRUmap.indexOf(p)); |
||
358 | mEnvironment->setPosition( r.center() ); // if environment is 'disabled' default values from the project file are used. |
||
359 | mModules->setupResourceUnit( *p ); |
||
360 | } |
||
361 | } |
||
362 | |||
767 | werner | 363 | // setup of scripting environment |
364 | ScriptGlobal::setupGlobalScripting(); |
||
365 | |||
123 | Werner | 366 | // setup the helper that does the multithreading |
590 | werner | 367 | threadRunner.setup(valid_rus); |
194 | werner | 368 | threadRunner.setMultithreading(GlobalSettings::instance()->settings().valueBool("system.settings.multithreading")); |
123 | Werner | 369 | threadRunner.print(); |
105 | Werner | 370 | |
1071 | werner | 371 | |
194 | werner | 372 | } else { |
373 | throw IException("resourceUnitsAsGrid MUST be set to true - at least currently :)"); |
||
105 | Werner | 374 | } |
120 | Werner | 375 | mSetup = true; |
103 | Werner | 376 | } |
377 | |||
378 | |||
92 | Werner | 379 | /** clear() frees all ressources allocated with the run of a simulation. |
380 | |||
381 | */ |
||
382 | void Model::clear() |
||
383 | { |
||
143 | Werner | 384 | mSetup = false; |
151 | iland | 385 | qDebug() << "Model clear: attempting to clear" << mRU.count() << "RU, " << mSpeciesSets.count() << "SpeciesSets."; |
92 | Werner | 386 | // clear ressource units |
103 | Werner | 387 | qDeleteAll(mRU); // delete ressource units (and trees) |
92 | Werner | 388 | mRU.clear(); |
103 | Werner | 389 | |
390 | qDeleteAll(mSpeciesSets); // delete species sets |
||
92 | Werner | 391 | mSpeciesSets.clear(); |
103 | Werner | 392 | |
208 | werner | 393 | // delete climate data |
394 | qDeleteAll(mClimates); |
||
395 | |||
151 | iland | 396 | // delete the grids |
397 | if (mGrid) |
||
398 | delete mGrid; |
||
399 | if (mHeightGrid) |
||
400 | delete mHeightGrid; |
||
185 | werner | 401 | if (mManagement) |
402 | delete mManagement; |
||
281 | werner | 403 | if (mEnvironment) |
404 | delete mEnvironment; |
||
340 | werner | 405 | if (mTimeEvents) |
406 | delete mTimeEvents; |
||
549 | werner | 407 | if (mStandGrid) |
408 | delete mStandGrid; |
||
641 | werner | 409 | if (mModules) |
410 | delete mModules; |
||
654 | werner | 411 | if (mDEM) |
412 | delete mDEM; |
||
1062 | werner | 413 | if (mGrassCover) |
414 | delete mGrassCover; |
||
909 | werner | 415 | if (mABEManagement) |
416 | delete mABEManagement; |
||
103 | Werner | 417 | |
185 | werner | 418 | mGrid = 0; |
419 | mHeightGrid = 0; |
||
420 | mManagement = 0; |
||
281 | werner | 421 | mEnvironment = 0; |
340 | werner | 422 | mTimeEvents = 0; |
549 | werner | 423 | mStandGrid = 0; |
641 | werner | 424 | mModules = 0; |
654 | werner | 425 | mDEM = 0; |
1062 | werner | 426 | mGrassCover = 0; |
909 | werner | 427 | mABEManagement = 0; |
185 | werner | 428 | |
583 | werner | 429 | GlobalSettings::instance()->outputManager()->close(); |
430 | |||
92 | Werner | 431 | qDebug() << "Model ressources freed."; |
432 | } |
||
433 | |||
434 | /** Setup of the Simulation. |
||
435 | This really creates the simulation environment and does the setup of various aspects. |
||
436 | */ |
||
102 | Werner | 437 | void Model::loadProject() |
92 | Werner | 438 | { |
109 | Werner | 439 | DebugTimer dt("load project"); |
93 | Werner | 440 | GlobalSettings *g = GlobalSettings::instance(); |
679 | werner | 441 | g->printDirecories(); |
102 | Werner | 442 | const XmlHelper &xml = g->settings(); |
189 | iland | 443 | |
93 | Werner | 444 | g->clearDatabaseConnections(); |
92 | Werner | 445 | // database connections: reset |
94 | Werner | 446 | GlobalSettings::instance()->clearDatabaseConnections(); |
286 | werner | 447 | // input and climate connection |
448 | // see initOutputDatabase() for output database |
||
191 | werner | 449 | QString dbPath = g->path( xml.value("system.database.in"), "database"); |
194 | werner | 450 | GlobalSettings::instance()->setupDatabaseConnection("in", dbPath, true); |
193 | werner | 451 | dbPath = g->path( xml.value("system.database.climate"), "database"); |
194 | werner | 452 | GlobalSettings::instance()->setupDatabaseConnection("climate", dbPath, true); |
92 | Werner | 453 | |
200 | werner | 454 | mSettings.loadModelSettings(); |
455 | mSettings.print(); |
||
416 | werner | 456 | // random seed: if stored value is <> 0, use this as the random seed (and produce hence always an equal sequence of random numbers) |
457 | uint seed = xml.value("system.settings.randomSeed","0").toUInt(); |
||
708 | werner | 458 | RandomGenerator::setup(RandomGenerator::ergMersenneTwister, seed); // use the MersenneTwister as default |
428 | werner | 459 | // linearization of expressions: if true *and* linearize() is explicitely called, then |
460 | // function results will be cached over a defined range of values. |
||
461 | bool do_linearization = xml.valueBool("system.settings.expressionLinearizationEnabled", false); |
||
462 | Expression::setLinearizationEnabled(do_linearization); |
||
431 | werner | 463 | if (do_linearization) |
464 | qDebug() << "The linearization of certains expressions is enabled (performance optimization)."; |
||
465 | |||
466 | // log level |
||
467 | QString log_level = xml.value("system.settings.logLevel", "debug").toLower(); |
||
468 | if (log_level=="debug") setLogLevel(0); |
||
469 | if (log_level=="info") setLogLevel(1); |
||
470 | if (log_level=="warning") setLogLevel(2); |
||
471 | if (log_level=="error") setLogLevel(3); |
||
472 | |||
475 | werner | 473 | // snag dynamics / soil model enabled? (info used during setup of world) |
474 | changeSettings().carbonCycleEnabled = xml.valueBool("model.settings.carbonCycleEnabled", false); |
||
528 | werner | 475 | // class size of snag classes |
476 | Snag::setupThresholds(xml.valueDouble("model.settings.soil.swdDBHClass12"), |
||
477 | xml.valueDouble("model.settings.soil.swdDBHClass23")); |
||
475 | werner | 478 | |
646 | werner | 479 | // setup of modules |
480 | if (mModules) |
||
481 | delete mModules; |
||
482 | mModules = new Modules(); |
||
483 | |||
103 | Werner | 484 | setupSpace(); |
281 | werner | 485 | if (mRU.isEmpty()) |
486 | throw IException("Setup of Model: no resource units present!"); |
||
185 | werner | 487 | |
488 | // (3) additional issues |
||
837 | werner | 489 | // (3.1) load javascript code into the engine |
1065 | werner | 490 | QString script_file = xml.value("system.javascript.fileName"); |
1064 | werner | 491 | if (!script_file.isEmpty()) { |
1065 | werner | 492 | script_file = g->path(script_file, "script"); |
1064 | werner | 493 | ScriptGlobal::loadScript(script_file); |
494 | g->controller()->setLoadedJavascriptFile(script_file); |
||
495 | } |
||
837 | werner | 496 | |
497 | // (3.2) setup of regeneration |
||
391 | werner | 498 | changeSettings().regenerationEnabled = xml.valueBool("model.settings.regenerationEnabled", false); |
499 | if (settings().regenerationEnabled) { |
||
500 | foreach(SpeciesSet *ss, mSpeciesSets) |
||
501 | ss->setupRegeneration(); |
||
387 | werner | 502 | } |
493 | werner | 503 | Sapling::setRecruitmentVariation(xml.valueDouble("model.settings.seedDispersal.recruitmentDimensionVariation",0.1)); |
468 | werner | 504 | |
837 | werner | 505 | // (3.3) management |
890 | werner | 506 | bool use_abe = xml.valueBool("model.management.abeEnabled"); |
507 | if (use_abe) { |
||
508 | // use the agent based forest management engine |
||
909 | werner | 509 | mABEManagement = new ABE::ForestManagementEngine(); |
890 | werner | 510 | // setup of ABE after loading of trees. |
511 | |||
185 | werner | 512 | } |
910 | werner | 513 | // use the standard management |
514 | QString mgmtFile = xml.value("model.management.file"); |
||
515 | if (!mgmtFile.isEmpty() && xml.valueBool("model.management.enabled")) { |
||
516 | mManagement = new Management(); |
||
517 | QString path = GlobalSettings::instance()->path(mgmtFile, "script"); |
||
518 | mManagement->loadScript(path); |
||
519 | qDebug() << "setup management using script" << path; |
||
520 | } |
||
468 | werner | 521 | |
522 | |||
910 | werner | 523 | |
92 | Werner | 524 | } |
105 | Werner | 525 | |
1058 | werner | 526 | void Model::reloadABE() |
527 | { |
||
528 | // delete firest |
||
529 | if (mABEManagement) |
||
530 | delete mABEManagement; |
||
531 | mABEManagement = new ABE::ForestManagementEngine(); |
||
532 | // and setup |
||
533 | mABEManagement->setup(); |
||
534 | mABEManagement->runOnInit(); |
||
105 | Werner | 535 | |
1058 | werner | 536 | mABEManagement->initialize(); |
537 | |||
538 | } |
||
539 | |||
540 | |||
543 | werner | 541 | ResourceUnit *Model::ru(QPointF coord) |
105 | Werner | 542 | { |
106 | Werner | 543 | if (!mRUmap.isEmpty() && mRUmap.coordValid(coord)) |
544 | return mRUmap.valueAt(coord); |
||
281 | werner | 545 | return ru(); // default RU if there is only one |
105 | Werner | 546 | } |
547 | |||
286 | werner | 548 | void Model::initOutputDatabase() |
549 | { |
||
550 | GlobalSettings *g = GlobalSettings::instance(); |
||
551 | QString dbPath = g->path(g->settings().value("system.database.out"), "output"); |
||
552 | // create run-metadata |
||
553 | int maxid = SqlHelper::queryValue("select max(id) from runs", g->dbin()).toInt(); |
||
554 | |||
555 | maxid++; |
||
556 | QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"); |
||
287 | werner | 557 | SqlHelper::executeSql(QString("insert into runs (id, timestamp) values (%1, '%2')").arg(maxid).arg(timestamp), g->dbin()); |
286 | werner | 558 | // replace path information |
559 | dbPath.replace("$id$", QString::number(maxid)); |
||
560 | dbPath.replace("$date$", timestamp); |
||
561 | // setup final path |
||
562 | g->setupDatabaseConnection("out", dbPath, false); |
||
563 | |||
564 | } |
||
565 | |||
903 | werner | 566 | |
824 | werner | 567 | /// multithreaded running function for the resource unit level establishment |
568 | ResourceUnit *nc_sapling_growth_establishment(ResourceUnit *unit) |
||
440 | werner | 569 | { |
632 | werner | 570 | try { |
1001 | werner | 571 | { // DebugTimer t("nc_saplingGrowth"); t.setSilent(); |
824 | werner | 572 | // define a height map for the current resource unit on the stack |
632 | werner | 573 | float sapling_map[cPxPerRU*cPxPerRU]; |
824 | werner | 574 | // set the map and initialize it: |
632 | werner | 575 | unit->setSaplingHeightMap(sapling_map); |
444 | werner | 576 | |
450 | werner | 577 | |
451 | werner | 578 | // (1) calculate the growth of (already established) saplings (populate sapling map) |
824 | werner | 579 | QList<ResourceUnitSpecies*>::const_iterator rus; |
580 | for (rus=unit->ruSpecies().cbegin(); rus!=unit->ruSpecies().cend(); ++rus) |
||
581 | (*rus)->calclulateSaplingGrowth(); |
||
615 | werner | 582 | |
1001 | werner | 583 | } { // DebugTimer t("nc_Establishment"); t.setSilent(); |
998 | werner | 584 | |
824 | werner | 585 | // (2) calculate the establishment probabilities of new saplings |
998 | werner | 586 | for (QList<ResourceUnitSpecies*>::const_iterator rus=unit->ruSpecies().cbegin(); rus!=unit->ruSpecies().cend(); ++rus) |
864 | werner | 587 | (*rus)->calculateEstablishment(); |
615 | werner | 588 | |
998 | werner | 589 | } |
615 | werner | 590 | |
440 | werner | 591 | } catch (const IException& e) { |
632 | werner | 592 | GlobalSettings::instance()->controller()->throwError(e.message()); |
440 | werner | 593 | } |
632 | werner | 594 | |
824 | werner | 595 | unit->setSaplingHeightMap(0); // invalidate again |
440 | werner | 596 | return unit; |
824 | werner | 597 | |
440 | werner | 598 | } |
599 | |||
824 | werner | 600 | |
475 | werner | 601 | /// multithreaded execution of the carbon cycle routine |
602 | ResourceUnit *nc_carbonCycle(ResourceUnit *unit) |
||
603 | { |
||
611 | werner | 604 | try { |
632 | werner | 605 | // (1) do calculations on snag dynamics for the resource unit |
606 | unit->calculateCarbonCycle(); |
||
607 | // (2) do the soil carbon and nitrogen dynamics calculations (ICBM/2N) |
||
608 | } catch (const IException& e) { |
||
609 | GlobalSettings::instance()->controller()->throwError(e.message()); |
||
611 | werner | 610 | } |
611 | |||
475 | werner | 612 | return unit; |
613 | } |
||
614 | |||
440 | werner | 615 | /// beforeRun performs several steps before the models starts running. |
616 | /// inter alia: * setup of the stands |
||
617 | /// * setup of the climates |
||
105 | Werner | 618 | void Model::beforeRun() |
619 | { |
||
395 | werner | 620 | // setup outputs |
621 | // setup output database |
||
539 | werner | 622 | if (GlobalSettings::instance()->dbout().isOpen()) |
623 | GlobalSettings::instance()->dbout().close(); |
||
395 | werner | 624 | initOutputDatabase(); |
625 | GlobalSettings::instance()->outputManager()->setup(); |
||
626 | GlobalSettings::instance()->clearDebugLists(); |
||
627 | |||
105 | Werner | 628 | // initialize stands |
967 | werner | 629 | StandLoader loader(this); |
251 | werner | 630 | { |
106 | Werner | 631 | DebugTimer loadtrees("load trees"); |
632 | loader.processInit(); |
||
251 | werner | 633 | } |
934 | werner | 634 | // initalization of ABE |
635 | if (mABEManagement) { |
||
636 | mABEManagement->setup(); |
||
637 | mABEManagement->runOnInit(); |
||
638 | } |
||
106 | Werner | 639 | |
214 | werner | 640 | // load climate |
251 | werner | 641 | { |
1024 | werner | 642 | if (logLevelDebug()) qDebug() << "attempting to load climate..." ; |
643 | DebugTimer loadclim("load climate"); |
||
644 | foreach(Climate *c, mClimates) { |
||
645 | if (!c->isSetup()) |
||
646 | c->setup(); |
||
647 | } |
||
648 | // load the first year of the climate database |
||
649 | foreach(Climate *c, mClimates) |
||
650 | c->nextYear(); |
||
214 | werner | 651 | |
251 | werner | 652 | } |
653 | |||
934 | werner | 654 | |
251 | werner | 655 | { DebugTimer loadinit("load standstatistics"); |
734 | werner | 656 | if (logLevelDebug()) qDebug() << "attempting to calculate initial stand statistics (incl. apply and read pattern)..." ; |
135 | Werner | 657 | Tree::setGrid(mGrid, mHeightGrid); |
737 | werner | 658 | // debugCheckAllTrees(); // introduced for debugging session (2012-04-06) |
135 | Werner | 659 | applyPattern(); |
660 | readPattern(); |
||
967 | werner | 661 | loader.processAfterInit(); // e.g. initialization of saplings |
106 | Werner | 662 | |
376 | werner | 663 | // force the compilation of initial stand statistics |
241 | werner | 664 | createStandStatistics(); |
251 | werner | 665 | } |
286 | werner | 666 | |
934 | werner | 667 | // initalization of ABE (now all stands are properly set up) |
909 | werner | 668 | if (mABEManagement) { |
934 | werner | 669 | mABEManagement->initialize(); |
890 | werner | 670 | } |
671 | |||
672 | |||
264 | werner | 673 | // outputs to create with inital state (without any growth) are called here: |
936 | werner | 674 | GlobalSettings::instance()->setCurrentYear(0); // set clock to "0" (for outputs with initial state) |
675 | |||
257 | werner | 676 | GlobalSettings::instance()->outputManager()->execute("stand"); // year=0 |
837 | werner | 677 | GlobalSettings::instance()->outputManager()->execute("landscape"); // year=0 |
504 | werner | 678 | GlobalSettings::instance()->outputManager()->execute("sapling"); // year=0 |
264 | werner | 679 | GlobalSettings::instance()->outputManager()->execute("tree"); // year=0 |
395 | werner | 680 | GlobalSettings::instance()->outputManager()->execute("dynamicstand"); // year=0 |
264 | werner | 681 | |
257 | werner | 682 | GlobalSettings::instance()->setCurrentYear(1); // set to first year |
1024 | werner | 683 | |
105 | Werner | 684 | } |
685 | |||
331 | werner | 686 | /** Main model runner. |
687 | The sequence of actions is as follows: |
||
688 | (1) Load the climate of the new year |
||
689 | (2) Reset statistics for resource unit as well as for dead/managed trees |
||
714 | werner | 690 | (3) Invoke Management. |
331 | werner | 691 | (4) *after* that, calculate Light patterns |
692 | (5) 3PG on stand level, tree growth. Clear stand-statistcs before they are filled by single-tree-growth. calculate water cycle (with LAIs before management) |
||
440 | werner | 693 | (6) execute Regeneration |
714 | werner | 694 | (7) invoke disturbance modules |
695 | (8) calculate statistics for the year |
||
696 | (9) write database outputs |
||
331 | werner | 697 | */ |
105 | Werner | 698 | void Model::runYear() |
699 | { |
||
223 | werner | 700 | DebugTimer t("Model::runYear()"); |
615 | werner | 701 | GlobalSettings::instance()->systemStatistics()->reset(); |
707 | werner | 702 | RandomGenerator::checkGenerator(); // see if we need to generate new numbers... |
649 | werner | 703 | // initalization at start of year for external modules |
704 | mModules->yearBegin(); |
||
903 | werner | 705 | |
341 | werner | 706 | // execute scheduled events for the current year |
707 | if (mTimeEvents) |
||
708 | mTimeEvents->run(); |
||
709 | |||
1024 | werner | 710 | // load the next year of the climate database (except for the first year - the first climate year is loaded immediately |
711 | if (GlobalSettings::instance()->currentYear()>1) { |
||
712 | foreach(Climate *c, mClimates) |
||
713 | c->nextYear(); |
||
714 | } |
||
214 | werner | 715 | |
278 | werner | 716 | // reset statistics |
717 | foreach(ResourceUnit *ru, mRU) |
||
718 | ru->newYear(); |
||
719 | |||
391 | werner | 720 | foreach(SpeciesSet *set, mSpeciesSets) |
721 | set->newYear(); |
||
890 | werner | 722 | // management classic |
615 | werner | 723 | if (mManagement) { |
724 | DebugTimer t("management"); |
||
278 | werner | 725 | mManagement->run(); |
615 | werner | 726 | GlobalSettings::instance()->systemStatistics()->tManagement+=t.elapsed(); |
727 | } |
||
909 | werner | 728 | // ... or ABE (the agent based variant) |
729 | if (mABEManagement) { |
||
730 | DebugTimer t("ABE:run"); |
||
731 | mABEManagement->run(); |
||
890 | werner | 732 | GlobalSettings::instance()->systemStatistics()->tManagement+=t.elapsed(); |
733 | } |
||
278 | werner | 734 | |
937 | werner | 735 | // if trees are dead/removed because of management, the tree lists |
736 | // need to be cleaned (and the statistics need to be recreated) |
||
737 | cleanTreeLists(); |
||
738 | |||
214 | werner | 739 | // process a cycle of individual growth |
277 | werner | 740 | applyPattern(); // create Light Influence Patterns |
741 | readPattern(); // readout light state of individual trees |
||
742 | grow(); // let the trees grow (growth on stand-level, tree-level, mortality) |
||
1062 | werner | 743 | mGrassCover->execute(); // evaluate the grass / herb cover (and its effect on regeneration) |
106 | Werner | 744 | |
391 | werner | 745 | // regeneration |
746 | if (settings().regenerationEnabled) { |
||
440 | werner | 747 | // seed dispersal |
483 | werner | 748 | DebugTimer tseed("Regeneration and Establishment"); |
391 | werner | 749 | foreach(SpeciesSet *set, mSpeciesSets) |
475 | werner | 750 | set->regeneration(); // parallel execution for each species set |
440 | werner | 751 | |
615 | werner | 752 | GlobalSettings::instance()->systemStatistics()->tSeedDistribution+=tseed.elapsed(); |
440 | werner | 753 | // establishment |
1063 | werner | 754 | Sapling::updateBrowsingPressure(); |
755 | |||
824 | werner | 756 | { DebugTimer t("saplingGrowthEstablishment"); |
757 | executePerResourceUnit( nc_sapling_growth_establishment, false /* true: force single thraeded operation */); |
||
864 | werner | 758 | GlobalSettings::instance()->systemStatistics()->tSaplingAndEstablishment+=t.elapsed(); |
615 | werner | 759 | } |
824 | werner | 760 | |
1068 | werner | 761 | Establishment::debugInfo(); // debug test |
762 | |||
615 | werner | 763 | } |
440 | werner | 764 | |
468 | werner | 765 | // calculate soil / snag dynamics |
475 | werner | 766 | if (settings().carbonCycleEnabled) { |
767 | DebugTimer ccycle("carbon cylce"); |
||
1063 | werner | 768 | executePerResourceUnit( nc_carbonCycle, false /* true: force single threaded operation */); |
615 | werner | 769 | GlobalSettings::instance()->systemStatistics()->tCarbonCycle+=ccycle.elapsed(); |
770 | |||
475 | werner | 771 | } |
649 | werner | 772 | |
773 | // external modules/disturbances |
||
774 | mModules->run(); |
||
775 | |||
937 | werner | 776 | // cleanup of tree lists if external modules removed trees. |
777 | cleanTreeLists(); |
||
664 | werner | 778 | |
937 | werner | 779 | |
615 | werner | 780 | DebugTimer toutput("outputs"); |
278 | werner | 781 | // calculate statistics |
782 | foreach(ResourceUnit *ru, mRU) |
||
783 | ru->yearEnd(); |
||
124 | Werner | 784 | |
277 | werner | 785 | // create outputs |
184 | werner | 786 | OutputManager *om = GlobalSettings::instance()->outputManager(); |
285 | werner | 787 | om->execute("tree"); // single tree output |
278 | werner | 788 | om->execute("stand"); //resource unit level x species |
837 | werner | 789 | om->execute("landscape"); //landscape x species |
504 | werner | 790 | om->execute("sapling"); // sapling layer per RU x species |
278 | werner | 791 | om->execute("production_month"); // 3pg responses growth per species x RU x month |
285 | werner | 792 | om->execute("dynamicstand"); // output with user-defined columns (based on species x RU) |
278 | werner | 793 | om->execute("standdead"); // resource unit level x species |
794 | om->execute("management"); // resource unit level x species |
||
587 | werner | 795 | om->execute("carbon"); // resource unit level, carbon pools above and belowground |
609 | werner | 796 | om->execute("carbonflow"); // resource unit level, GPP, NPP and total carbon flows (atmosphere, harvest, ...) |
185 | werner | 797 | |
615 | werner | 798 | GlobalSettings::instance()->systemStatistics()->tWriteOutput+=toutput.elapsed(); |
799 | GlobalSettings::instance()->systemStatistics()->tTotalYear+=t.elapsed(); |
||
800 | GlobalSettings::instance()->systemStatistics()->writeOutput(); |
||
801 | |||
162 | werner | 802 | GlobalSettings::instance()->setCurrentYear(GlobalSettings::instance()->currentYear()+1); |
105 | Werner | 803 | } |
804 | |||
278 | werner | 805 | |
806 | |||
105 | Werner | 807 | void Model::afterStop() |
808 | { |
||
809 | // do some cleanup |
||
810 | } |
||
106 | Werner | 811 | |
369 | werner | 812 | /// multithreaded running function for LIP printing |
187 | iland | 813 | ResourceUnit* nc_applyPattern(ResourceUnit *unit) |
106 | Werner | 814 | { |
815 | |||
816 | QVector<Tree>::iterator tit; |
||
118 | Werner | 817 | QVector<Tree>::iterator tend = unit->trees().end(); |
107 | Werner | 818 | |
632 | werner | 819 | try { |
107 | Werner | 820 | |
632 | werner | 821 | // light concurrence influence |
822 | if (!GlobalSettings::instance()->settings().paramValueBool("torus")) { |
||
823 | // height dominance grid |
||
824 | for (tit=unit->trees().begin(); tit!=tend; ++tit) |
||
825 | (*tit).heightGrid(); // just do it ;) |
||
155 | werner | 826 | |
632 | werner | 827 | for (tit=unit->trees().begin(); tit!=tend; ++tit) |
828 | (*tit).applyLIP(); // just do it ;) |
||
155 | werner | 829 | |
632 | werner | 830 | } else { |
831 | // height dominance grid |
||
832 | for (tit=unit->trees().begin(); tit!=tend; ++tit) |
||
833 | (*tit).heightGrid_torus(); // just do it ;) |
||
155 | werner | 834 | |
632 | werner | 835 | for (tit=unit->trees().begin(); tit!=tend; ++tit) |
836 | (*tit).applyLIP_torus(); // do it the wraparound way |
||
837 | } |
||
838 | return unit; |
||
839 | } catch (const IException &e) { |
||
840 | GlobalSettings::instance()->controller()->throwError(e.message()); |
||
118 | Werner | 841 | } |
842 | return unit; |
||
843 | } |
||
106 | Werner | 844 | |
369 | werner | 845 | /// multithreaded running function for LIP value extraction |
187 | iland | 846 | ResourceUnit *nc_readPattern(ResourceUnit *unit) |
118 | Werner | 847 | { |
848 | QVector<Tree>::iterator tit; |
||
849 | QVector<Tree>::iterator tend = unit->trees().end(); |
||
632 | werner | 850 | try { |
851 | if (!GlobalSettings::instance()->settings().paramValueBool("torus")) { |
||
852 | for (tit=unit->trees().begin(); tit!=tend; ++tit) |
||
853 | (*tit).readLIF(); // multipliactive approach |
||
854 | } else { |
||
855 | for (tit=unit->trees().begin(); tit!=tend; ++tit) |
||
856 | (*tit).readLIF_torus(); // do it the wraparound way |
||
857 | } |
||
858 | } catch (const IException &e) { |
||
859 | GlobalSettings::instance()->controller()->throwError(e.message()); |
||
118 | Werner | 860 | } |
861 | return unit; |
||
106 | Werner | 862 | } |
863 | |||
369 | werner | 864 | /// multithreaded running function for the growth of individual trees |
187 | iland | 865 | ResourceUnit *nc_grow(ResourceUnit *unit) |
118 | Werner | 866 | { |
867 | QVector<Tree>::iterator tit; |
||
868 | QVector<Tree>::iterator tend = unit->trees().end(); |
||
632 | werner | 869 | try { |
870 | unit->beforeGrow(); // reset statistics |
||
871 | // calculate light responses |
||
872 | // responses are based on *modified* values for LightResourceIndex |
||
873 | for (tit=unit->trees().begin(); tit!=tend; ++tit) { |
||
874 | (*tit).calcLightResponse(); |
||
875 | } |
||
118 | Werner | 876 | |
632 | werner | 877 | unit->calculateInterceptedArea(); |
251 | werner | 878 | |
632 | werner | 879 | for (tit=unit->trees().begin(); tit!=tend; ++tit) { |
880 | (*tit).grow(); // actual growth of individual trees |
||
881 | } |
||
882 | } catch (const IException &e) { |
||
883 | GlobalSettings::instance()->controller()->throwError(e.message()); |
||
118 | Werner | 884 | } |
615 | werner | 885 | |
886 | GlobalSettings::instance()->systemStatistics()->treeCount+=unit->trees().count(); |
||
118 | Werner | 887 | return unit; |
888 | } |
||
889 | |||
369 | werner | 890 | /// multithreaded running function for the resource level production |
891 | ResourceUnit *nc_production(ResourceUnit *unit) |
||
892 | { |
||
632 | werner | 893 | try { |
894 | unit->production(); |
||
895 | } catch (const IException &e) { |
||
896 | GlobalSettings::instance()->controller()->throwError(e.message()); |
||
897 | } |
||
369 | werner | 898 | return unit; |
899 | } |
||
900 | |||
440 | werner | 901 | |
124 | Werner | 902 | void Model::test() |
903 | { |
||
904 | // Test-funktion: braucht 1/3 time von readGrid() |
||
905 | DebugTimer t("test"); |
||
906 | FloatGrid averaged = mGrid->averaged(10); |
||
907 | int count = 0; |
||
908 | float *end = averaged.end(); |
||
909 | for (float *p=averaged.begin(); p!=end; ++p) |
||
910 | if (*p > 0.9) |
||
911 | count++; |
||
912 | qDebug() << count << "LIF>0.9 of " << averaged.count(); |
||
913 | } |
||
914 | |||
734 | werner | 915 | void Model::debugCheckAllTrees() |
916 | { |
||
917 | AllTreeIterator at(this); |
||
918 | bool has_errors = false; double dummy=0.; |
||
919 | while (Tree *t = at.next()) { |
||
920 | // plausibility |
||
921 | if (t->dbh()<0 || t->dbh()>10000. || t->biomassFoliage()<0. || t->height()>1000. || t->height() < 0. |
||
922 | || t->biomassFoliage() <0.) |
||
923 | has_errors = true; |
||
924 | // check for objects.... |
||
925 | dummy = t->stamp()->offset() + t->ru()->ruSpecies()[1]->statistics().count(); |
||
926 | } |
||
927 | if (has_errors) |
||
928 | qDebug() << "model: debugCheckAllTrees found problems" << dummy; |
||
929 | } |
||
930 | |||
118 | Werner | 931 | void Model::applyPattern() |
932 | { |
||
933 | |||
934 | DebugTimer t("applyPattern()"); |
||
935 | // intialize grids... |
||
720 | werner | 936 | initializeGrid(); |
551 | werner | 937 | |
406 | werner | 938 | // initialize height grid with a value of 4m. This is the height of the regeneration layer |
551 | werner | 939 | for (HeightGridValue *h=mHeightGrid->begin();h!=mHeightGrid->end();++h) { |
940 | h->resetCount(); // set count = 0, but do not touch the flags |
||
941 | h->height = 4.f; |
||
942 | } |
||
118 | Werner | 943 | |
123 | Werner | 944 | threadRunner.run(nc_applyPattern); |
615 | werner | 945 | GlobalSettings::instance()->systemStatistics()->tApplyPattern+=t.elapsed(); |
118 | Werner | 946 | } |
947 | |||
106 | Werner | 948 | void Model::readPattern() |
949 | { |
||
950 | DebugTimer t("readPattern()"); |
||
123 | Werner | 951 | threadRunner.run(nc_readPattern); |
615 | werner | 952 | GlobalSettings::instance()->systemStatistics()->tReadPattern+=t.elapsed(); |
953 | |||
106 | Werner | 954 | } |
955 | |||
331 | werner | 956 | /** Main function for the growth of stands and trees. |
957 | This includes several steps. |
||
958 | (1) calculate the stocked area (i.e. count pixels in height grid) |
||
959 | (2) 3PG production (including response calculation, water cycle) |
||
960 | (3) single tree growth (including mortality) |
||
961 | (4) cleanup of tree lists (remove dead trees) |
||
962 | */ |
||
106 | Werner | 963 | void Model::grow() |
964 | { |
||
151 | iland | 965 | |
369 | werner | 966 | if (!settings().growthEnabled) |
967 | return; |
||
968 | { DebugTimer t("growRU()"); |
||
969 | calculateStockedArea(); |
||
113 | Werner | 970 | |
374 | werner | 971 | // multithreaded: mutex for the message handler in mainwindow solved the crashes. |
972 | threadRunner.run(nc_production); |
||
370 | werner | 973 | } |
974 | |||
975 | DebugTimer t("growTrees()"); |
||
251 | werner | 976 | threadRunner.run(nc_grow); // actual growth of individual trees |
159 | werner | 977 | |
187 | iland | 978 | foreach(ResourceUnit *ru, mRU) { |
159 | werner | 979 | ru->cleanTreeList(); |
376 | werner | 980 | ru->afterGrow(); |
168 | werner | 981 | //qDebug() << (b-n) << "trees died (of" << b << ")."; |
159 | werner | 982 | } |
615 | werner | 983 | GlobalSettings::instance()->systemStatistics()->tTreeGrowth+=t.elapsed(); |
123 | Werner | 984 | } |
151 | iland | 985 | |
240 | werner | 986 | /** calculate for each resource unit the fraction of area which is stocked. |
987 | This is done by checking the pixels of the global height grid. |
||
151 | iland | 988 | */ |
989 | void Model::calculateStockedArea() |
||
990 | { |
||
991 | // iterate over the whole heightgrid and count pixels for each ressource unit |
||
992 | HeightGridValue *end = mHeightGrid->end(); |
||
993 | QPointF cp; |
||
187 | iland | 994 | ResourceUnit *ru; |
151 | iland | 995 | for (HeightGridValue *i=mHeightGrid->begin(); i!=end; ++i) { |
996 | cp = mHeightGrid->cellCenterPoint(mHeightGrid->indexOf(i)); |
||
997 | if (mRUmap.coordValid(cp)) { |
||
998 | ru = mRUmap.valueAt(cp); |
||
999 | if (ru) { |
||
285 | werner | 1000 | ru->countStockedPixel( (*i).count()>0 ); |
151 | iland | 1001 | } |
1002 | } |
||
1003 | |||
1004 | } |
||
1005 | } |
||
240 | werner | 1006 | |
664 | werner | 1007 | /** calculate for each resource unit the stockable area. |
574 | werner | 1008 | "stockability" is determined by the isValid flag of resource units which in turn |
1009 | is derived from stand grid values. |
||
1010 | */ |
||
1011 | void Model::calculateStockableArea() |
||
1012 | { |
||
1013 | |||
1014 | foreach(ResourceUnit *ru, mRU) { |
||
720 | werner | 1015 | // // |
1016 | // if (ru->id()==-1) { |
||
1017 | // ru->setStockableArea(0.); |
||
1018 | // continue; |
||
1019 | // } |
||
574 | werner | 1020 | GridRunner<HeightGridValue> runner(*mHeightGrid, ru->boundingBox()); |
1021 | int valid=0, total=0; |
||
1022 | while (runner.next()) { |
||
1023 | if ( runner.current()->isValid() ) |
||
1024 | valid++; |
||
1025 | total++; |
||
1026 | } |
||
575 | werner | 1027 | if (total) { |
574 | werner | 1028 | ru->setStockableArea( cHeightPixelArea * valid); |
734 | werner | 1029 | if (valid==0 && ru->id()>-1) { |
1030 | // invalidate this resource unit |
||
1031 | ru->setID(-1); |
||
1032 | } |
||
575 | werner | 1033 | if (valid>0 && ru->id()==-1) { |
1034 | qDebug() << "Warning: a resource unit has id=-1 but stockable area (id was set to 0)!!! ru: " << ru->boundingBox() << "with index" << ru->index(); |
||
1035 | ru->setID(0); |
||
664 | werner | 1036 | // test-code |
1037 | //GridRunner<HeightGridValue> runner(*mHeightGrid, ru->boundingBox()); |
||
1038 | //while (runner.next()) { |
||
1039 | // qDebug() << mHeightGrid->cellCenterPoint(mHeightGrid->indexOf( runner.current() )) << ": " << runner.current()->isValid(); |
||
1040 | //} |
||
585 | werner | 1041 | |
575 | werner | 1042 | } |
1043 | } else |
||
574 | werner | 1044 | throw IException("calculateStockableArea: resource unit without pixels!"); |
1045 | |||
1046 | } |
||
720 | werner | 1047 | // mark those pixels that are at the edge of a "forest-out-of-area" |
1048 | GridRunner<HeightGridValue> runner(*mHeightGrid, mHeightGrid->metricRect()); |
||
1049 | HeightGridValue* neighbors[8]; |
||
1050 | while (runner.next()) { |
||
1051 | if (runner.current()->isForestOutside()) { |
||
1052 | // if the current pixel is a "radiating" border pixel, |
||
1053 | // then check the neighbors and set a flag if the pixel is a neighbor of a in-project-area pixel. |
||
1054 | runner.neighbors8(neighbors); |
||
1055 | for (int i=0;i<8;++i) |
||
1056 | if (neighbors[i] && neighbors[i]->isValid()) |
||
1057 | runner.current()->setIsRadiating(); |
||
1058 | |||
1059 | } |
||
1060 | } |
||
1061 | |||
574 | werner | 1062 | } |
1063 | |||
720 | werner | 1064 | void Model::initializeGrid() |
1065 | { |
||
1066 | // fill the whole grid with a value of "1." |
||
1067 | mGrid->initialize(1.f); |
||
574 | werner | 1068 | |
720 | werner | 1069 | // apply special values for grid cells border regions where out-of-area cells |
1070 | // radiate into the main LIF grid. |
||
1071 | QPoint p; |
||
1072 | int ix_min, ix_max, iy_min, iy_max, ix_center, iy_center; |
||
1073 | const int px_offset = cPxPerHeight / 2; // for 5 px per height grid cell, the offset is 2 |
||
1074 | const int max_radiate_distance = 7; |
||
1075 | const float step_width = 1.f / (float)max_radiate_distance; |
||
1076 | int c_rad = 0; |
||
1077 | for (HeightGridValue *hgv=mHeightGrid->begin(); hgv!=mHeightGrid->end(); ++hgv) { |
||
1078 | if (hgv->isRadiating()) { |
||
1079 | p=mHeightGrid->indexOf(hgv); |
||
1080 | ix_min = p.x() * cPxPerHeight - max_radiate_distance + px_offset; |
||
1081 | ix_max = ix_min + 2*max_radiate_distance + 1; |
||
1082 | ix_center = ix_min + max_radiate_distance; |
||
1083 | iy_min = p.y() * cPxPerHeight - max_radiate_distance + px_offset; |
||
1084 | iy_max = iy_min + 2*max_radiate_distance + 1; |
||
1085 | iy_center = iy_min + max_radiate_distance; |
||
1086 | for (int y=iy_min; y<=iy_max; ++y) { |
||
1087 | for (int x=ix_min; x<=ix_max; ++x) { |
||
802 | werner | 1088 | if (!mGrid->isIndexValid(x,y) || !(*mHeightGrid)(x/cPxPerHeight, y/cPxPerHeight).isValid()) |
720 | werner | 1089 | continue; |
1090 | float value = qMax(qAbs(x-ix_center), qAbs(y-iy_center)) * step_width; |
||
1091 | float &v = mGrid->valueAtIndex(x, y); |
||
1092 | if (value>=0.f && v>value) |
||
1093 | v = value; |
||
1094 | } |
||
1095 | } |
||
1096 | c_rad++; |
||
1097 | } |
||
1098 | } |
||
721 | werner | 1099 | if (logLevelDebug()) |
1100 | qDebug() << "initialize grid:" << c_rad << "radiating pixels..."; |
||
720 | werner | 1101 | |
1102 | } |
||
1103 | |||
1104 | |||
241 | werner | 1105 | /// Force the creation of stand statistics. |
1106 | /// - stocked area (for resourceunit-areas) |
||
1107 | /// - ru - statistics |
||
240 | werner | 1108 | void Model::createStandStatistics() |
1109 | { |
||
241 | werner | 1110 | calculateStockedArea(); |
482 | werner | 1111 | foreach(ResourceUnit *ru, mRU) { |
1112 | ru->addTreeAgingForAllTrees(); |
||
240 | werner | 1113 | ru->createStandStatistics(); |
482 | werner | 1114 | } |
240 | werner | 1115 | } |
584 | werner | 1116 | |
936 | werner | 1117 | void Model::cleanTreeLists() |
1118 | { |
||
937 | werner | 1119 | foreach(ResourceUnit *ru, GlobalSettings::instance()->model()->ruList()) { |
1120 | if (ru->hasDiedTrees()) { |
||
1121 | ru->cleanTreeList(); |
||
1122 | ru->recreateStandStatistics(); |
||
1123 | } |
||
1124 | } |
||
936 | werner | 1125 | } |
584 | werner | 1126 | |
936 | werner | 1127 |