unisim explained 2015-06-08

196
Universal Simulator Explained Niels Holst [email protected] www.ecolmod.org 8 June 2015 Draft in progress Department of Agroecology Aarhus University Denmark

Upload: yudha-artika

Post on 08-Dec-2015

225 views

Category:

Documents


3 download

DESCRIPTION

unisim tutorial for dummies

TRANSCRIPT

Page 1: Unisim Explained 2015-06-08

Universal Simulator Explained

Niels Holst

[email protected]

www.ecolmod.org

8 June 2015

Draft in progress

Department of Agroecology

Aarhus University

Denmark

Page 2: Unisim Explained 2015-06-08

About this book

Universal Simulator is a software package for collaborative ecological modelling. It is composedof a GUI main module which is used to open and execute model specifications read from XMLfiles. The XML files specify the components constituting a model. The functionality of thesecomponents are defined in plug-in libraries. This makes UniSim extendible and open for re-use.It is programmed in standard C++ but relies on Qt. Universal Simulator is open source andreleased under the terms of the GNU General Public License version 3.0 or later.

This book tells you how to download and run existing models developed for UniversalSimulator. You are instructed how to change the parameters and outputs of existing models (insome cases also how to change the composition of sub-models). In-depth chapters explains howthe models were coded in C++.

This book is in the writing. Upcoming chapters will show you how to provide your ownmodels, coded in C++, as plug-in modules to Universal Simulator.

Universal Simulator currently runs only on Microsoft Windows; Linux and Mac OS versionsof Universal Simulator are in preparation.

Copyrights. Universal Simulator Explained by Niels Holst, Aarhus University, Denmarkis licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Citation. Holst, N. (2013). A universal simulator for ecological models. EcologicalInformatics 13:70-76. dx.doi.org/10.1016/j.ecoinf.2012.11.001.

Acknowledgements. The development of Universal Simulator and the writing of thisbook were supported by ENDURE (EU Network of Excellence) during 2007-2010, ICROFS(International Centre for Research in Organic Food Systems) during 2008-2011 and PURE (EUFP7) 2011-2014 . This document was produced using Lout, an open-source document-formattingsystem.

Page 3: Unisim Explained 2015-06-08

Contents

About this book .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ii

Chapter 1. Installation .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 1

1.1. Installing Universal Simulator .. .. .. .. .. .. .. .. .. .. .. .. 1

1.2. Running simulations .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 1

Chapter 2. Writing recipes .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 3

2.1. Recipe structure and context .. .. .. .. .. .. .. .. .. .. .. .. 3

2.2. References to parameters and variables .. .. .. .. .. .. .. .. .. .. 4

2.3. Parameter elements .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 6

2.4. The integrator element .. .. .. .. .. .. .. .. .. .. .. .. .. .. 6

2.5. Model elements .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 7

2.6. Additional input files .. .. .. .. .. .. .. .. .. .. .. .. .. .. 8

2.7. Output and trace elements .. .. .. .. .. .. .. .. .. .. .. .. .. 8

2.8. Applications .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 11

2.8.1. Application 1. Life stage sequence .. .. .. .. .. .. .. .. 11

2.8.2. Application 2. Random parameter values .. .. .. .. .. .. 14

2.8.3. Application 3. Stage-structured population dynamics .. .. .. 18

2.8.4. Application 4. Stage-structured SEIR epidemics model .. .. .. 20

2.8.5. Application 5. Functional response: predation, parasitisation, in-fection .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 28

2.8.6. Application 6. Multi-way functional response .. .. .. .. .. 32

2.9. Advanced handling of many models .. .. .. .. .. .. .. .. .. .. 36

Chapter 3. Working with source code .. .. .. .. .. .. .. .. .. .. .. .. .. 43

3.1. Downloading source code .. .. .. .. .. .. .. .. .. .. .. .. .. 43

3.2. Navigating source code .. .. .. .. .. .. .. .. .. .. .. .. .. .. 44

3.3. Building from source code .. .. .. .. .. .. .. .. .. .. .. .. .. 47

3.4. Universal Simulator algorithm .. .. .. .. .. .. .. .. .. .. .. .. 51

3.5. Communicating with models .. .. .. .. .. .. .. .. .. .. .. .. 53

3.6. Navigating model structure .. .. .. .. .. .. .. .. .. .. .. .. .. 57

3.7. Plug-in structure .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 62

Chapter 4. The BtButTox model .. .. .. .. .. .. .. .. .. .. .. .. .. .. 64

4.1. Scenario simulations .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 64

4.2. Scenario recipes .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 65

Page 4: Unisim Explained 2015-06-08

4.3. Scenario outputs .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 65

Chapter 5. Conductance model .. .. .. .. .. .. .. .. .. .. .. .. .. .. 70

5.1. Plant model .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 70

5.2. Community model .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 75

5.3. Weather model .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 78

5.4. Running the model .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 78

5.5. Discussion .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 80

Chapter 6. The INTERCOM model .. .. .. .. .. .. .. .. .. .. .. .. .. 82

6.1. Light absorption explained .. .. .. .. .. .. .. .. .. .. .. .. .. 82

6.2. Light absorption refactored .. .. .. .. .. .. .. .. .. .. .. .. .. 93

Chapter 7. Student projects .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 94

7.1. Lake oxygen model .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 94

7.1.1. Introduction .. .. .. .. .. .. .. .. .. .. .. .. .. .. 94

7.1.2. Calculations .. .. .. .. .. .. .. .. .. .. .. .. .. .. 94

7.1.3. Predicting NCP in Real Lakes .. .. .. .. .. .. .. .. .. 96

7.1.4. Unit of output .. .. .. .. .. .. .. .. .. .. .. .. .. .. 97

7.1.5. Setting the stochastic sampling number .. .. .. .. .. .. .. 97

7.1.6. Plotting .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 97

7.1.7. Output from the model .. .. .. .. .. .. .. .. .. .. .. 98

7.2. Microbial community model .. .. .. .. .. .. .. .. .. .. .. .. 99

7.2.1. Introduction .. .. .. .. .. .. .. .. .. .. .. .. .. .. 99

7.2.2. Population model .. .. .. .. .. .. .. .. .. .. .. .. .. 99

7.2.3. Population Growth .. .. .. .. .. .. .. .. .. .. .. .. 99

7.2.4. Competition Model .. .. .. .. .. .. .. .. .. .. .. .. 100

7.2.5. Reaction Models .. .. .. .. .. .. .. .. .. .. .. .. .. 102

7.2.6. GeneralEffect Model .. .. .. .. .. .. .. .. .. .. .. .. 106

7.2.7. Community Model .. .. .. .. .. .. .. .. .. .. .. .. 108

Appendix A. Plug-ins Reference .. .. .. .. .. .. .. .. .. .. .. .. .. .. 111

A.1. awe plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 111

A.2. conductance plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 117

A.3. dynamic_photosynthesis plugin .. .. .. .. .. .. .. .. .. .. .. 119

A.4. ecotox plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 120

A.5. intercom plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 124

A.6. MicrobialCommunity plugin .. .. .. .. .. .. .. .. .. .. .. .. 132

A.7. mussel_bed plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 137

iv

Page 5: Unisim Explained 2015-06-08

A.8. rvf plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 141

A.9. seed_emergence plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. 143

A.10. strawberry plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 144

A.11. UniSim plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 145

A.12. vg plugin .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 162

References .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 181

Index .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 183

v

Page 6: Unisim Explained 2015-06-08
Page 7: Unisim Explained 2015-06-08

Chapter 1. InstallationThis chapter takes you through the steps of downloading and installing Universal Simulator fromInternet and running your first simulations with Universal Simulator.

1.1. Installing Universal Simulator

First you must install the necessary software. Download the Universal Simulator installation filefrom www.ecolmod.org. Execute this installation file and accept all default suggestions. Afterinstallation you should be able to find the flying squirrel icon of Universal Simulator amongyour programs.

Universal Simulator is installed in a folder inside your standard folder for programs, forexample C:/Program Files/UniSim-1-37, where 1-37, or something similar, refers tothe version of Universal Simulator. If different versions of Universal Simulator are installed, theywill simply occupy different folders and will not interfere with each other.

Inside the Universal Simulator program folder, for exampleC:/Program Files/UniSim-1-37, there will be a folder with the GraphViz program whichis used by Universal Simulator to construct model diagrams.

Another folder with the same name will have been created in your standard documentsfolder, for example C:/Users/Nho/Documents/UniSim-1-37. This folder contains arecipes folder with recipes for existing models, an output folder for generated simulationoutput and a temp folder for temporary files generated during simulation. The easiest way tonavigate to these folders is to run Universal Simulator and via itsFile menu select Locations.Here you can see (and change, if you want) the location of these and other folders used byUniversal Simulator. For instance, you can re-direct simulation output to some other folder.

Currently, File|Locations does not function intuitively: If you want to change the locationof a standard folder, you must click on a file (any file) inside the new folder location, rather thanclicking the new folder location itself. This will be fixed…

1.2. Running simulations

Now is a good time to test your installation.First, start Universal Simulator. Open one of the sim-ulation recipes, for example ambrosia DK.xml, which is found in the recipes/ambrosiafolder. Use the File|Open menu.

Universal Simulator will read the recipe, which is stored as an XML file, and from thatconstruct a diagram which shows the hierarchial structure of models that makes up the recipe.The diagram is actually constructed by GraphViz which is always installed together withUniversal Simulator.

You can inspect the XML code of the recipe through the Edit|Model menu. If nothinghappens then follow the steps explained in the Edit|Help menu and try again. If you want to

1

Page 8: Unisim Explained 2015-06-08

2 Chapter 1. Installation

change parameter values, or what is shown as output (in plots on screen or in tab-separated textfiles), you always do this in three steps:

1. Edit the recipe in the XML file using a text or XML editor.

2. In the editor, save the changed XML file.

3. In Universal Simulator, open the XML file again using File|Open or File|Reopen.

After opening (or re-opening) an XML recipe file you can run the simulation with Simula-tion|Run. This will result in a display of output plots on the screen and maybe some files in theoutput folder. If you forgot where the output folder is, you can check the File|Locations menu.

Instructions on how to read and edit XML recipe files can be found in the next chapter.

Page 9: Unisim Explained 2015-06-08

Chapter 2. Writing recipes

Universal Simulator recipes have much in common with recipes used in the kitchen. Theycontain a list of models (ingredients), parameter values (measures), and how the models shouldbe connected (cooking instructions). Universal Simulator recipes are formulated as XML filesas explained below. A general introduction to XML can easily be found on Internet and is notincluded here. First the basic recipe elements are described (2.1-2.7). Then follow examplesshowing typical applications (2.8.1-2.8.2). Finally, an advanced section describes how to writerecipes with many (hundreds or thousands) similar models (2.9).

Note: The upcoming major revision of Universal Simulator will offer a more intuitive andflexible input language, in addition to XML.

2.1. Recipe structure and context

When you start the Universal Simulator program, it first creates a simulation environment insidethe computer’s memory. The simulation environment is then equipped with a library of modelsloaded from the available plug-in files. Now the simulation environment is ready to receiverecipes from the user.

When the user provides a recipe (an XML file selected through the File|Open menu), UniversalSimulator creates live versions of the models listed in the recipe, as objects living in the

3

Page 10: Unisim Explained 2015-06-08

4 Chapter 2. Writing recipes

simulation environment. The recipe specifies, by name and type, which models will take partin the simulation and with which parameter values. To create the live models, the simulationenvironment finds their code in the plug-in libraries. Some recipes may specify additional input,such as weather data, provided as text file records.

When the user selects Simulation|Run on the menu, all the model objects created in thesimulation environment go into gear, each carrying out its specific ’behaviour’ (or ’logic’,if you prefer). Interaction with other model objects present in the simulation environment isusually an important part of model behaviour. This allows, for example, leaf models to accessdaily irradiation readings from a weather model, and predator models to feed on prey models.Finally, when the simulations ends (as determined by the recipe, or when the user interrupts thesimulation), output is produced from the simulation environment, in terms of plots on the screenand records in text files. Which output to produce is also described in the recipe.

The recipe is written in a much reduced subset of the XML language (see sections 2.1-2.7).To edit XML files you can use a general purpose text editor or a dedicated XML editor. On MSWindows, Notepad will do, but NotePad++ with its XML syntax highlighting is a better choice.The most complete, free tool for XML editing seems to be Komodo Edit, which helps you evenmore writing correct XML code.

The general structure of a recipe written in XML looks like this

<?xml version="1.0" encoding="ISO-8859-1"?><simulation name="Forest">

... one integrator ...

... one or more models ...

... one or more outputs ...</simulation>

The root of the XML document must be a simulation element.You should give the simulationa meaningfull name with the name attribute, in this case Forest. The simulation elementmust contain in order: an integrator element, one or more model elements, and one or moreoutput elements. The integrator and model elements may hold additional model elementsinside. In addition,integrator,model and output elements may hold parameter elements.The trace element can only be used inside output elements.

Elements may be given various attributes, such as name above, to provide detailed informa-tion. The elements that can be used in recipes, their attributes and their meaning are all describedbelow. First, however, comes an explanation of parameter and variable references, because weoften need to refer to a parameter or variable from one place in the recipe to another.

2.2. References to parameters and variables

The logic of a model is not accessible from the recipe. It is behind closed doors, written in C++not XML. Models, however, provide a public interface which allows outsiders (the recipe andother models) to set their parameters and to query the current value of their parameters andvariables. Note, however, that only the model itself (in its C++ code) can change its variables.

The syntax for referring to a parameter and a variable is the same.You supply a model name,that is unique within the recipe, followed by the name of the parameter or variable in brackets.

Page 11: Unisim Explained 2015-06-08

2.2. References to parameters and variables 5

Here is a reference to the parameter or variable named lossRate inside the mass model:

mass[lossRate]

If mass is not unique inside the recipe, i.e. more than one model has the name mass, then youmust nail it down more precisely by providing its location. For instance, if you have a mass

model inside both a larva and a pupa model, you can refer to the latter by writing

pupa/mass[lossRate]

You can provide as a long a path as needed to make the reference unique:

drosophila/pupa/mass[lossRate]

All the examples above are examples of references. They can be used in the ref attribute ofparameter (2.3) and trace (2.7) elements.

A common usage of references is when several parameters logically must have the samevalue, or when the parameter of one model is referring to the current value of a state variablein another model. This example demonstrates this and also shows how to make use of relativereferences, which are refences starting with one or two periods:

<model name="colony"><model name="egg" type="Vespa::Egg">

<parameter name="newEggs" ref="../queen[eggsLaid"/><parameter name="newFertilisedEggs" ref=".[newEggs]"/>

<model name="mass" type="UniSim::Stage"><parameter name="duration" value="2"/><parameter name="k" value="30"/>

</model>

<model name="number" type="UniSim::Stage"><parameter name="duration" ref="../mass[duration]"/><parameter name="k" ref="../mass[k]"/>

</model></model>

<model name="queen" type="Vespa::Queen"></model>

</model>

Here, the parameter newEggs is referring to the eggsLaid variable, which is maintained bythe model named queen. The double-period notation means, go one step up, in the hierarchy. Inthis case to the colony model. Thus one double-period (../) takes you to a sibling model, two(../../) to an uncle model and so forth.

The single-period (./) refers to the element itself. Hence, newFertilisedEggs will takeon the same value as the newEggs parameter in the same model.

The value of parameters duration and k are fixed in the mass model. Because they

Page 12: Unisim Explained 2015-06-08

6 Chapter 2. Writing recipes

must have the same values in the number model, the number model defines its parameters byreference to the mass model. Note that references may refer to models anywhere, upwards ordownwards, in the recipe.

2.3. Parameter elements

The parameter element is used to set the value of a parameter. Here the k parameter is set tothe value 30:

<parameter name="k" value="30"/>

Note the XML syntax: Since a parameter element never holds another element inside, itwill always end with a slash (/) before the closing sharp parenthesis (>). The format of theparameter’s value attribute depends on the type of the parameter:

Parameter type Examples

Integer -11, 0, 30

Floating point -2.4, 1e6

String paris_1919.txt

Boolean true, false, yes, no

Date 18/8/2011, 2011/8/18

Time 21:48:10, 9:13

Dates follow the European (dd/mm/yyyy) or international (yyyy/mm/dd) convention. Since yearmust be given with four digits, it is clear which convention is meant. Time of day can be givenwith (hh:mm:ss) or without seconds (hh:mm).

The parameters available for each model can be looked up in the Plug-ins Reference. Forexample, if you look up the k parameter of the Stage model in the UniSim plug-in (page 157),you find both an explanation of its use and its default value. All models come with default valuesfor their parameters.Unless you change the parameter value in the recipe, the parameter will keepits default value.

If you use the ref attribute instead of the value attribute, the parameter value will beretrieved from another parameter or a variable. For example:

<parameter name="mortality" ref="herbicide[effect]"/>

In this example, you cannot tell whether effect in the model named herbicide is a parameteror a variable but the result will be the same: mortality will take on the current value ofeffect.

2.4. The integrator element

An integrator element should always be the first element inside the simulation element,which makes up the outermost element, also called the root element. Moreover there can only

Page 13: Unisim Explained 2015-06-08

2.4. The integrator element 7

be one integrator element. The integrator is, in fact, just a model with a special role: itdetermines for how may time steps the simulation should be running. For example,

<integrator type="UniSim::Steps"><parameter name="maxSteps" value="365"/>

</integrator>

The type attribute is used to select the kind of integrator needed, here the Steps integrator,which belongs to the Universal Simulator standard plug-in, named UniSim. Currently, this isthe only type of integrator available but one for sensitivity analysis is under development(autumn 2013).

The duration of the simulation is given in terms of time steps. In this example, it has beenset to 365 which suggest that the length of a time step is one day. Time step length, however, isnot determined by the integrator. Most UniSim XML documents will have a calender model(page 145) to manage the time scale.

If the simulation contains stochastic models, it is useful to run the simulation for severaliterations. This is specified by including a child model named runIterator:

<integrator type="UniSim::Steps"><parameter name="maxSteps" value="365"/><model name="runIterator" type="UniSim::RunIteratorFixed">

<parameter name="numIterations" value="30"/></model>

</integrator>

In this case the model will be running for 30 iterations.

2.5. Model elements

Model elements define the configuration and settings of models in the simulation. A model

element can hold additional model elements inside to any depth thus forming a hierarchy ofmodels. Before a parent model is handled in the simulation, all its child models will be handledin a recursive fashion. Sibling models will be handled in the order they appear in the recipe.

A model element has two attributes: name and type. One or both can be left out: namedefaults to anonymous and type defaults to UniSim::AnonymousModel. You should,however, use the name attribute to give the model a meaningful name. The type attribute tellswhich model, of those defined in the available plug-ins, is wanted. The two-parts type nameconsists of the plug-in name (for example, UniSim) glued together by :: with the name of themodel class (for example, Stage). You can leave out the plug-in name but then you rely on, thatthe model class name alone is (and will remain) unique among all plug-ins.

In this example, the model ChickenFlock holds three sibling models inside:time, eggsand juveniles. The first will create a model of the type Days found in the UniSim plug-in.The two others will create a model of type Stage, likewise found in the UniSim plug-in:

<model name="ChickenFlock"><model name="time" type="UniSim:.Days"/>

Page 14: Unisim Explained 2015-06-08

8 Chapter 2. Writing recipes

<model name="eggs" type="UniSim::Stage"><parameter name="duration" value="21"/>

</model><model name="juveniles" type="UniSim::Stage">

<parameter name="duration" value="140"/><parameter name="inflow" ref="../eggs[outflow]"/>

</model></model>

2.6. Additional input files

Some models may need access to additional input files, quite often column-oriented text files, asused by the Records model in the UniSim plug-in. For example,

<model name="weather" type="UniSim::Weather"><model name="records" type="UniSim::Records">

<parameter name="fileName" value="ngorongoro.txt"/></model>

</model>

The question is where the file ngorongoro.txt should be located? The Records model,and other models that need text file input, will look for input files in various locations in thefollowing order:

1. In the same folder as the recipe (the recipe folder)

2. In a child folder of the recipe folder named input

3. In the parent folder of the recipe folder

4. In a child folder of that parent folder named input

5. The last two steps are repeated for the grandparent folder and levels further up

This allows you to place input files where they can be shared by the relevant recipes.

2.7. Output and trace elements

The trace element is used only inside output elements where it used to define the modelparameter or variable to show in the output, for example, as a curve in a plot or a column in atable. For output plots, the first trace defines the x-axis. The subsequent traces each define acurve to display:

<output type="plot"><parameter name="title" value ="Larva population dynamics"/><trace label="Day" ref="calendar[dayInYear]"/>

Page 15: Unisim Explained 2015-06-08

2.7. Output and trace elements 9

<trace label="Mass" ref="larva/mass[value]"/><trace label="Number" ref="larva/number[value]"/>

</output>

Here the type attribute has been set to plot to show this output as a plot on the screen, and theensuing parameter element sets the title of that plot. The label attribute of the first-comingtrace element (here,Day) is used to label the x-axis. The label attribute of subsequent traceelements are used to label each curve. In this case, two curves labelled Mass and Number. Theref attributes of the trace elements refers to variables (dayInYear,value and value) foundin the respective models (calendar, larva/mass and larva/number). Similar output, sentto a text file named larva_pop_dyn.txt, and with three columns, labelled Day, Mass andNumber, would be produced by this code:

<output type="table"><parameter name="fileName" value ="larva_pop_dyn.txt"/><trace label="Day" ref="calendar[dayInYear]"/><trace label="Mass" ref="larva/mass[value]"/><trace label="Number" ref="larva/number[value]"/>

</output>

Currently, only floating point variables and parameters (C++ type double) will be showncorrectly in output. If the ref attribute inside a trace cannot be resolved then that traceelement will silently by ignored. If less than two traces are found for a plot output or no tracesare found for a table output, an error message will appear.

Sometimes you may want to log-transform the y-axis or to set the minimum and maximumvalue of the y-axis. The following example shows how to achieve this through the parameterslogy, ymin and ymax. You can use one or more of these parameters in any combination. Here,they are used in concert:

<output type="plot"><parameter name="title" value ="Larva population dynamics"/><parameter name="logy" value ="true"/><parameter name="ymin" value ="0.01"/><parameter name="ymax" value ="1e7"/><trace label="Day" ref="calendar[dayInYear]"/><trace label="Mass" ref="larva/mass[value]"/><trace label="Number" ref="larva/number[value]"/>

</output>

With these parameter values, the y-axis will be shown as log10-transformed values; zero-valuedy-values will be ignored. The minimum and maximum values always refer to the original scale.

You can scale an axis by using the multiplier or divisor attributes. Here time isdivided by 7 and mass is multiplied by 1000, before they are shown on the axes:

<output type="plot"><parameter name="title" value ="Growth"/><trace label="Week" ref="calendar[totalTimeSteps]"

divisor=7/>

Page 16: Unisim Explained 2015-06-08

10 Chapter 2. Writing recipes

<trace label="Mass (g)" ref="larva/mass[value]"multiplier=1000/></output>

Traces will be shown as lines by default but they can also be shown as symbols, or both line andsymbols. This is set by the type attribute of trace elements:

<output type="plot"><parameter name="title" value ="Larva population dynamics"/><parameter name="logy" value ="true"/><parameter name="ymin" value ="0.01"/><parameter name="ymax" value ="1e7"/><trace label="Day" ref="calendar[dayInYear]"/><trace label="Number" ref="larva/number[k]" type="Line"/><trace label="Mass" ref="larva/mass[value]" type="Symbols"/><trace label="Number" ref="larva/number[value]" type="Both"/>

</output>

If you put a run iterator inside the integrator element (page 6) to run the simulation multipletimes, then output will be produced for every simulation run.For output elements of type plot,additional output will simply be added producing a trace in the plot for every run. For outputelements of type table, the output from each run will go into a separate file; the files will benumbered from 1 and onwards.

You can also request for additional output to summarise the result of multiple simulationruns. For example, you might want to see a plot with the maximum population density, achievedin each simulation run, plotted against some parameter. For this purpose you use summary plots.To request summary output, you use the summary attribute of the trace element. For instance,if you set a fecundity parameter to some random value before each simulation run, and you wantto see the simulated response in terms of maximum larval density, you could write

<output type="plot" ><parameter name="title" value ="Max. larva mass"/><trace label="Fecundity" ref="adult[fecundity]"/><trace label="Mass" ref="larva/mass[value]" summary="max"/>

</output>

The default type of a trace element that holds a summary attribute is Symbol. So this codewill show a plot with as many symbols as the number of simulation runs. You can include morethan one summary trace in a plot, although in practice you most often have just one. You can alsouse the summary attribute for trace elements to produce file output, i.e. for output elementswith type attribute set to table.

Different values for the summary attribute results in different values:

Page 17: Unisim Explained 2015-06-08

2.7. Output and trace elements 11

Summary Meaning

max Maximum value achieved during a simulation run

min Minimum value achieved during a simulation run

avg Average of all values achieved during a simulation run

sum Sum of all values achieved during a simulation run

final Final value achieved at the end of a simulation run

xAtMax X-value (e.g. time) at which the maximum value was achieved during asimulation run

xAtMin X-value (e.g. time) at which the minimum value was achieved during asimulation run

2.8. Applications

This section shows a selection of recipes for various applications. The recipes can all be foundin the recipes/unisim_explained/writing_recipes folder.

2.8.1. Application 1. Life stage sequence

If you work with stage-structured models of populations dynamics, you often need to stringlife stages together, transferring individuals from one stage to the next as they develop. TheStage model of the UniSim plug-in can be used to model the development in each individualstage. To pass individuals on to the following stage, you use outflow (a variable of the Stagemodel) and inflow (a parameter of the Stage model). Naturally, the outflow from a life stagemust be modelled and computed by the life stage itself, whereas the inflow to it is comingfrom outside and is thus a parameter for the life stage. This recipe simulates the life stages of aholometabolous insect:

<?xml version="1.0" encoding="ISO-8859-1"?><simulation name="insect">

<integrator type="UniSim::Steps"><parameter name="maxSteps" value="100"/>

</integrator>

<model name="calendar" type="UniSim::Calendar"></model>

<model name="weather" type="UniSim::Weather"><model name="records" type="UniSim::Records">

<parameter name="fileName" value="Harlingen2008.txt"/></model>

</model>

Page 18: Unisim Explained 2015-06-08

12 Chapter 2. Writing recipes

<model name="insect"><model name="egg">

<model name="time" type="UniSim::DayDegrees"><parameter name="T0" value="4.5"/>

</model><model name="number" type="UniSim::Stage">

<parameter name="duration" value="41"/><parameter name="k" value="30"/><parameter name="initialInflow" value="100"/>

</model></model>

<model name="larva"><model name="time" type="UniSim::DayDegrees">

<parameter name="T0" value="6.7"/></model><model name="number" type="UniSim::Stage">

<parameter name="duration" value="205"/><parameter name="k" value="30"/><parameter name="inflow"

ref="egg/number[outflow]"/></model>

</model>

<model name="pupa"><model name="time" type="UniSim::DayDegrees">

<parameter name="T0" value="8.2"/></model><model name="number" type="UniSim::Stage">

<parameter name="duration" value="98"/><parameter name="k" value="30"/><parameter name="inflow"

ref="larva/number[outflow]"/></model>

</model>

<model name="adult"><model name="time" type="UniSim::Days"/><model name="number" type="UniSim::Stage">

<parameter name="duration" value="30"/><parameter name="k" value="10"/><parameter name="inflow"

ref="pupa/number[outflow]"/></model>

</model></model>

Page 19: Unisim Explained 2015-06-08

2.8. Applications 13

<output type="plot"><parameter name="title" value ="Harlingen weather log"/><trace label="Day" ref="calendar[totalTime]"/><trace label="Temperature" ref="weather[Tavg]"/>

</output>

<output type="plot"><parameter name="title" value ="Insect numbers"/><trace label="Day" ref="calendar[totalTime]"/><trace label="Eggs" ref="egg/number[value]"/><trace label="Larvae" ref="larva/number[value]"/><trace label="Pupae" ref="pupa/number[value]"/><trace label="Adults" ref="adult/number[value]"/>

</output></simulation>

The integrator of the simulation tells it to run for 100 time steps. A Calendar modelkeeps track of time, and a Weather model reads weather records from a weather log file. TheStage models runs on different time scales, either days or day-degrees, as given by the siblingmodel named time. The DayDegrees models will automatically search for a model namedweather and will pull daily temperature readings from the weathermodel.At the end, one plotshows the daily temperature reading, and another plot shows the resulting insect development:

Page 20: Unisim Explained 2015-06-08

14 Chapter 2. Writing recipes

Note that several models simply acts as containers of other models: insect, egg, larva,pupa and adult. These models add no behaviour of their own. Consequently, they have notype attribute.

2.8.2. Application 2. Random parameter values

If some parameters are uncertain, or if you want to explore the sensitivity of the model tovariance in some parameters, you need to run the simulation repeatedly to assess the possibleoutcomes. In this continuation of the example above, we want to explore the sensitivity of themodel to the lower temperature threshold for development of the three immature life stages:

<?xml version="1.0" encoding="ISO-8859-1"?><simulation name="SHBmodel">

<integrator type="Steps"><parameter name="maxSteps" value="100"/><model name="runIterator" type="RunIteratorFixed">

<parameter name="numIterations" value="100"/></model>

</integrator>

<model name="calendar" type="Calendar"></model>

<model name="weather" type="UniSim::Weather"><model name="records" type="UniSim::Records">

<parameter name="fileName" value="Harlingen2008.txt"/></model>

</model>

<model name="random"><model name="eggT0" type="UniSim::RandomUniform">

<parameter name="minValue" value="0"/><parameter name="maxValue" value="8"/>

</model><model name="larvaT0" type="UniSim::RandomUniform">

<parameter name="minValue" value="0"/><parameter name="maxValue" value="8"/>

</model><model name="pupaT0" type="UniSim::RandomUniform">

<parameter name="minValue" value="0"/><parameter name="maxValue" value="8"/>

</model></model>

<model name="insect"><model name="egg">

<model name="time" type="UniSim::DayDegrees">

Page 21: Unisim Explained 2015-06-08

2.8. Applications 15

<parameter name="T0" ref="random/eggT0[value]"/></model><model name="number" type="UniSim::Stage">

<parameter name="duration" value="41"/><parameter name="k" value="30"/><parameter name="initialInflow" value="100"/>

</model></model>

<model name="larva"><model name="time" type="UniSim::DayDegrees">

<parameter name="T0" ref="random/larvaT0[value]"/></model><model name="number" type="UniSim::Stage">

<parameter name="duration" value="205"/><parameter name="k" value="30"/><parameter name="inflow"

ref="egg/number[outflow]"/></model>

</model>

<model name="pupa"><model name="time" type="UniSim::DayDegrees">

<parameter name="T0" ref="random/pupaT0[value]"/></model><model name="number" type="UniSim::Stage">

<parameter name="duration" value="98"/><parameter name="k" value="30"/><parameter name="inflow"

ref="larva/number[outflow]"/></model>

</model>

<model name="adult"><model name="time" type="UniSim::Days"/><model name="number" type="UniSim::Stage">

<parameter name="duration" value="30"/><parameter name="k" value="10"/><parameter name="inflow"

ref="pupa/number[outflow]"/></model>

</model></model>

<output type="plot"><parameter name="title" value ="Harlingen weather log"/>

Page 22: Unisim Explained 2015-06-08

16 Chapter 2. Writing recipes

<trace label="Day" ref="calendar[totalTime]"/><trace label="Temperature" ref="weather[Tavg]"/>

</output>

<output type="plot"><parameter name="title" value ="Insect numbers"/><trace label="Day" ref="calendar[totalTime]"/><trace label="Eggs" ref="egg/number[value]"/><trace label="Larvae" ref="larva/number[value]"/><trace label="Pupae" ref="pupa/number[value]"/><trace label="Adults" ref="adult/number[value]"/>

</output>

<output type="plot"><parameter name="title" value ="Sensitivity to egg

temperature threshold"/><trace label="Egg T0" ref="random/eggT0[value]"/><trace label="Peak adults day" ref="adult/number[value]"

summary="xAtMax"/></output>

<output type="plot"><parameter name="title" value ="Sensitivity to larva

temperature threshold"/><trace label="Larva T0" ref="random/larvaT0[value]"/><trace label="Peak adults day" ref="adult/number[value]"

summary="xAtMax"/></output>

<output type="plot"><parameter name="title" value ="Sensitivity to pupa

temperature threshold"/><trace label="Pupa T0" ref="random/pupaT0[value]"/><trace label="Peak adults day" ref="adult/number[value]"

summary="xAtMax"/></output>

</simulation>

We have added a model named runIterator inside the iterator element to achieverepeated simulations. In this case, we have sete numIterations to achieve 100 repeated runsof the model.

The random model is simply a container for three models producing random numbers.The numbers are uniformly distributed between the minimum and maximum values, yieldingevenly distributed values in the range 0 to 8 from all three models. The RandomUniform modelproduces a new random value immediately before each simulation run.

Page 23: Unisim Explained 2015-06-08

2.8. Applications 17

The parameter values for T0 which were previously set to fixed values by the value

attribute have now been set to refer to the pertinent random values. This has been effectuated byreplacing the value attribute with a ref attribute.

Three plots have been added at then end to show the sensitivity of the model to the lowertemperature thresholds of each of the three immature life stages.Each plot shows the value of thetemperature threshold on the x-axis and the time, at which the adult density peaked, on the y-axis.These plots are constructed by using the summary attribute for the second trace element inthe plot. Here, the summary has been set to xAtMax. For other possible values of the summaryattribute, see page 10.

As can be seen in the plots, weather was the same all simulations (there is only one temper-ature curve), while the 100 sets of curves showing population numbers illustrate the variabilitycaused by the random temperature threshold values:

Page 24: Unisim Explained 2015-06-08

18 Chapter 2. Writing recipes

In conclusion, the model was most sensitive to variability in the lower temperature thresholdof the larvae, probably because they had the longest development time. Note that all threeparameters varied at the same time. If you want to see the effect of just one random threshold,you must set the other two threshold to fixed values using the value attribute instead of theref attribute.

2.8.3. Application 3. Stage-structured population dynamics

In Application 1 we modelled only the phenology of one generation of an insect. To includepopulation dynamics, we must add insect reproduction to the recipe. We achieve this beintroducing a Stage model called eggsToBeLaid with a growthRate corresponding to thelife time fecundity of an adult:

Page 25: Unisim Explained 2015-06-08

2.8. Applications 19

<model name="adult"><model name="time" type="UniSim::Days"/><model name="number" type="UniSim::Stage">

<parameter name="duration" value="30"/><parameter name="k" value="10"/><parameter name="inflow" ref="pupa/number[outflow]"/>

</model><model name="eggsToBeLaid" type="UniSim::Stage">

<parameter name="duration" value="10"/><parameter name="k" value="20"/><parameter name="inflow" ref="pupa/number[outflow]"/><parameter name="growthRate" value="60"/>

</model></model>

For every unit that flows into eggsToBelaid, 60 units will eventually flow out; These are theeggs laid, and they are added as inflow to the egg stage:

<model name="egg"><model name="time" type="UniSim::DayDegrees">

<parameter name="T0" value="4.5"/></model><model name="number" type="UniSim::Stage">

<parameter name="duration" value="41"/><parameter name="k" value="30"/><parameter name="initialInflow" value="100"/><parameter name="inflow"

ref="adult/eggsToBeLaid[outflow]"/></model>

</model>

With these settings, the adult will live 30 days on average, and eggs will be laid by females atthe age of 10 days on average. If the population has a sex ratio of 50% then a growthRate

of 60 means, that the life time fecundity of a female is 120 eggs. If the model is later extendedwith a mortality factor on adults, one should remember to effectuate mortality on both stages,number and eggsToBeLaid inside adult. In the simulation output, it is difficult to discern thegenerations on a linear scale:

Page 26: Unisim Explained 2015-06-08

20 Chapter 2. Writing recipes

However, on a log-scale we can see that two new generations result from the original cohortof 100 eggs:

2.8.4. Application 4. Stage-structured SEIR epidemics model

Models of epidemiology can become quite complex due to the many interactions betweenpopulations. The complexity is exacerbated if the populations are stage-structured and, evenmore, if vectors of the pathogen are involved. A standard conceptual framework is providedby the SEIR family of models, in which individuals can go through the phases: S)usceptible,E)xposed, I)nfectious and R)esistent. As an example we can imagine this system:

Page 27: Unisim Explained 2015-06-08

2.8. Applications 21

The host has two stages J)uvenile and A)dult but only the adult stage can become infectedand, after infection, eventually becomes resistent. The adults only die from old age; theirexpected lifespan is unaffected by the disease. The juvenile stage receives inflows from all fouradult sub-populations, irrespective of which phase of infection they are in. It should be notedthat adults of the S, E and I sub-populations can leave their current either by ageing (they die) or

Page 28: Unisim Explained 2015-06-08

22 Chapter 2. Writing recipes

their phase (they proceed to the next step of infection). The disease is not promoted from motherto child, hence all offspring enter as susceptible juveniles. Only adults can become infected, andthe infection rate depends on the density of infectious adult vectors.

The vector is an insect with four life stages:E)gg, L)arva, P)upa and A)dult. Only the adultscan be infected; the infection rate depends on the density of infectious adult hosts. In addition,all eggs laid by infectious adults will eventually themselves become infectious adults, whereaseggs laid by exposed adults go into the egg stage of the susceptible sub-population. Just as forthe host population, adult vectors in the S and E stages have two possible fates: either they die orthey pass on to the next phase of infection.

We will begin with the part of the recipe that describes the host model. For the susceptiblephase S we have

<model name="host"><model name="time" type="UniSim::Days"/>

<model name="S"><model name="juvenile" type="UniSim::Stage">

<parameter name="initialInflow" value="80"/><parameter name="inflow" ref="../toBeBorn[outflow]"/><parameter name="duration" value="1095"/><parameter name="k" value="30"/>

</model>

<model name="adult" type="UniSim::Stage"><parameter name="initialInflow" value="50"/><parameter name="inflow" ref="../juvenile[outflow]"/><parameter name="duration" value="3650"/><parameter name="k" value="30"/><parameter name="phaseOutflowProportion" value="0.01"/>

</model>

<model name="toBeBorn" type="UniSim::Stage"><parameter name="inflow" ref="../juvenile[outflow]"/><parameter name="duration" value="730"/><parameter name="k" value="30"/><parameter name="growthRate" value="2.5"/>

</model></model><...>

</model>

We apply the technique from the previous application (2.8.3) to model reproduction.We introducea Stage model called toBeBorn which takes the same inflow as the adult stage. In this case,where adults in all phases produce juveniles in the susceptible phase, it simplifies matters: thetoBeBorn model is only needed here, as a sub-model of the susceptible phase S. Host develop-ment is measured in days, as set by the time model. The parameter values correspond to some

Page 29: Unisim Explained 2015-06-08

2.8. Applications 23

imaginary vertebrate species. For simplicity, the toBeBorn model is not shown in the figure.

The adult stage has a parameter which defines the proportion of the adults that willbchanging phase in the next time step. The name of this parameter is phaseOutflowPropor-tion. In a more complete version of the e model, this proportion would be dynamic, varyingwith the attack rate of the infectious vector population. In this first version, it is kept simple as afixed rate of 1% per day.

The adult stage has two outflows, which can be accessed through the variables outflowand phaseOutflow. In this case, outflow simply is the loss due to old age while the phase-Outflow must be taken up by the adult stage in the subsequent, exposed phase (E). To link theflow between phases, the phaseInflow parameter is used, as seen in the subsequent phases ofthe host model E, I and R:

<model name="E"><model name="adult" type="UniSim::StageAndPhase">

<parameter name="duration" ref="../S/adult[duration]"/><parameter name="k" ref="../S/adult[k]"/><parameter name="timeStep" ref="../time[step]"/>

<parameter name="phaseInflow"ref="../S/adult[phaseOutflow]"/>

<parameter name="phaseDuration" value="10"/><parameter name="phaseK" value="15"/><parameter name="phaseTimeStep" ref="../time[step]"/>

</model></model>

<model name="I"><model name="adult" type="UniSim::StageAndPhase">

<parameter name="duration" ref="../S/adult[duration]"/><parameter name="k" ref="../S/adult[k]"/><parameter name="timeStep" ref="../time[step]"/>

<parameter name="phaseInflow"ref="../E/adult[phaseOutflow]"/>

<parameter name="phaseDuration" value="20"/><parameter name="phaseK" value="15"/>

</model></model>

<model name="R"><model name="adult" type="UniSim::Stage">

<parameter name="duration" ref="../S/adult[duration]"/><parameter name="k" ref="../S/adult[k]"/>

<parameter name="phaseInflow"ref="../I/adult[phaseOutflow]"/>

Page 30: Unisim Explained 2015-06-08

24 Chapter 2. Writing recipes

</model></model>

There are several linkages between different models defined here. To start with the simple ones,the parameters duration and k of the adult models in the E, I and R phases, all refer back tothe same parameters in the S phase. Thus adult ageing is not affected by the infection.

Next, the models for the E and I phases are of type StageAndPhase, instead of Stage. AStageAndPhase model has two development processes going on simultaneously:developmentby ageing (vertical arrows in the figure) and development to the next phase of the infection(rightwards arrows in the figure). Both processes need parameters to characterise the averageduration and dispersion of development time:duration and k for life stage development, andphaseDuration and phaseK for phase development.

Parameters specifying the inflow and the duration of the time step, are supplied asparameters, inflow and timeStep, and phaseInflow and phaseTimeStep, respectively.Note, that for models of Stage type, we did not specify the timeStep parameter. This is notnecessary because Stage models automatically look up the nearest model called time and pullsthe step variable from that. But for StageAndPhase model we have to specify the time stepparameter for both directions of development.

In the final phase (R), the adult model again is a Stage model because development onlyoccurs in one direction, which is ageing.

The vector model is more complicated than the host model, because it has more lifestages. In the host model, we introduced a toBeBorn stage to model reproduction. Likewise,we introduce a toBeLaid stage in each of the three vector phases. The recipe for the sus-ceptible phase is simply a series of Stage models, one for each life stage and one for the to-BeLaid stage:

<model name="vector"><model name="time" type="UniSim::DayDegrees">

<parameter name="T0" value="8"/></model>

<model name="S"><model name="egg" type="UniSim::Stage">

<model name="inflows" type="UniSim::Sum"><parameter name="toAdd" value="(../toBeBorn[outflow]

vector/E/toBeBorn[outflow])"/></model><parameter name="initialInflow" value="100"/><parameter name="inflow" ref="./inflows[value]"/><parameter name="duration" value="50"/><parameter name="k" value="30"/>

</model><model name="larva" type="UniSim::Stage">

<parameter name="inflow" ref="../egg[outflow]"/><parameter name="duration" value="250"/><parameter name="k" value="30"/>

Page 31: Unisim Explained 2015-06-08

2.8. Applications 25

</model><model name="pupa" type="UniSim::Stage">

<parameter name="inflow" ref="../larva[outflow]"/><parameter name="duration" value="80"/><parameter name="k" value="30"/>

</model><model name="adult" type="UniSim::Stage">

<parameter name="inflow" ref="../pupa[outflow]"/><parameter name="duration" value="100"/><parameter name="k" value="30"/><parameter name="phaseOutflowProportion" value="0.04"/>

</model><model name="toBeLaid" type="UniSim::Stage">

<parameter name="inflow" ref="../pupa[outflow]"/><parameter name="duration" ref="../adult[duration]"/><parameter name="k" ref="../adult[k]"/><parameter name="growthRate" value="50"/><parameter name="phaseOutflowProportion"

ref="../adult[phaseOutflowProportion]"/></model>

</model><...>

</model>

Since the egg model takes input from two models, toBeLaid both in the S and E phase, we usea Sum type model to add the outflows from these. A Sum model has just one parameter toAddwhich contains a list of references to add.

The other Stage models are standard in their parameter settings, except for the toBeBornstage for which we must remember to set the same phaseOutflowProportion as for theadult stage. Biologically, we should think of the eggs to be laid as developing inside the adults.Then it follows logically that adult and toBeBorn populations should walk hand in handthrough the phases of infection.

All vector stages run on a day-degree scale as set by the time model. The life historyparameters settings suggest that the vector is an invertebrate species, for example, a mosquito.The phaseOutflowProportion has been set to a fixed value of 4% per day. In a completemodel this parameter would be dynamic depending on the attack rate of susceptible vectors oninfectious hosts.

The exposed phase of the vector only contains the adults. Hence we should expect a simplerecipe for that phase. However we must remember to include a toBeLaid stage:

<model name="E"><model name="adult" type="UniSim::StageAndPhase">

<parameter name="duration" ref="../S/adult[duration]"/><parameter name="k" ref="../S/adult[k]"/><parameter name="timeStep" ref="vector/time[step]"/>

Page 32: Unisim Explained 2015-06-08

26 Chapter 2. Writing recipes

<parameter name="phaseInflow"ref="../S/adult[phaseOutflow]"/>

<parameter name="phaseDuration" value="20"/><parameter name="phaseK" value="15"/><parameter name="phaseTimeStep" ref="vector/time[step]"/>

</model><model name="toBeLaid" type="UniSim::StageAndPhase">

<parameter name="duration" ref="../S/toBeLaid[duration]"/><parameter name="k" ref="../S/toBeLaid[k]"/><parameter name="growthRate"

ref="../S/toBeLaid[growthRate]"/><parameter name="timeStep" ref="vector/time[step]"/>

<parameter name="phaseInflow"ref="../S/toBeLaid[phaseOutflow]"/>

<parameter name="phaseDuration"ref="../adult[phaseDuration]"/>

<parameter name="phaseK" ref="../adult[phaseK]"/><parameter name="phaseTimeStep" ref="vector/time[step]"/>

</model></model>

Both of the models in the exposed phase undergo development in two directions. Followinglythey are modelled as StageAndPhase models. It is worth noticing that the only parametersparticular to the exposed phase are phaseDuration (20) and phaseK (15). Moreover, as adultsand eggs to be laid go hand in hand, the two parameters are set to the same values in the adultand toBeLaid models.

The remaining parameters are set by reference to those parameters, that they are logicallyequivalent to. There are no inflows set by the inflow parameter but the phaseInflow pa-rameter links both the adult and toBeLaid models to their similar models in the suscepti-ble phase.

In the final, infectious phase there is only one direction of development. So, all life stagemodels are back to the Stage type:

<model name="I"><model name="egg" type="UniSim::Stage">

<parameter name="inflow" ref="../toBeLaid[outflow]"/><parameter name="duration" ref="vector/S/egg[duration]"/><parameter name="k" ref="vector/S/egg[k]"/>

</model><model name="larva" type="UniSim::Stage">

<parameter name="inflow" ref="../egg[outflow]"/><parameter name="duration"

ref="vector/S/larva[duration]"/><parameter name="k" ref="vector/S/larva[k]"/>

</model>

Page 33: Unisim Explained 2015-06-08

2.8. Applications 27

<model name="pupa" type="UniSim::Stage"><parameter name="inflow" ref="../larva[outflow]"/><parameter name="duration" ref="vector/S/pupa[duration]"/><parameter name="k" ref="vector/S/pupa[k]"/>

</model><model name="adult" type="UniSim::Stage">

<parameter name="inflow" ref="../pupa[outflow]"/><parameter name="duration"

ref="vector/S/adult[duration]"/><parameter name="k" ref="vector/S/adult[k]"/><parameter name="phaseInflow"

ref="vector/E/adult[phaseOutflow]"/></model><model name="toBeLaid" type="UniSim::Stage">

<parameter name="inflow" ref="../pupa[outflow]"/><parameter name="duration"

ref="vector/S/toBeLaid[duration]"/><parameter name="k" ref="vector/S/toBeLaid[k]"/><parameter name="growthRate"

ref="vector/S/toBeLaid[growthRate]"/><parameter name="phaseInflow"

ref="vector/E/toBeLaid[phaseOutflow]"/></model>

</model>

The recipe is straightforward, except for all the references that must be set to reflect the correctbiological bindings. No new parameter values are needed.

When a recipe contains many information flows between models, it is always a good idea totest that the plumbing is correct. In this case, the initial inflow marked a in the figure should equalthe sum of the two outflows marked b and c, provided that there is no reproduction. To check thisassertion we make a special version of the recipe, in which no reproduction occurs. All in all, weexpect these balance equations to hold (with reference to the figure): a=b+c, c=d+e, e=f . Thisis what we see for 1 year’s simulation:

Page 34: Unisim Explained 2015-06-08

28 Chapter 2. Writing recipes

The final values of flows a-f can be read off the plot by clicking the curves but they canalso be retrieved from the output file produced by the recipe. We find a=100, b=65.17, c=34.82,d=5.71, e=29.11, f =29.11 from which we confirm that all balances hold as expected.

Next we can add reproduction back into the recipe and follow the dynamics of hosts andvectors. We should remember though that the epidemics are still not modelled realistically, sincewe still hold the infection rates of susceptible hosts and susceptible vectors at fixed values (1and4%per day, respectively).The host population shows a steady increase in the resistent population,while the first juveniles of the next generation are on their way (as the toBeborn population):

The initial 100 eggs of the vector population resulted in two generations of adult vectors:

The population of exposed vectors continues to increase at the end of the year, but this isan artifact of the model: the rate of susceptible adults turning exposed is 4% per day, while thedevelopment rate of exposed adults into infectious runs on a day-degree scale, that by the end ofthe year has come to a halt due to falling temperatures. Clearly, the infection rates should not befixed but rely on some biologically realistic model.

2.8.5. Application 5. Functional response: predation, parasitisation, infection

In Universal Simulator, the FunctionalResponseGB model implements the Gutierrez-Baumgärtner functional response model:

Page 35: Unisim Explained 2015-06-08

2.8. Applications 29

ΔS = ΔD⎡⎢⎣

1 − exp⎧⎨⎩

− αXΔD

⎫⎬⎭

⎤⎥⎦

This model works with the concepts demand (ΔD), supply (ΔS) and ressource apparancy (α) withpopulations denoted as consumer/predator/parasite/patogen (Y) and resource/prey/host (X). Fora predator-prey system with a time step of one day, the demand and supply could be modelledin units of, for example, biomass per 2m per day. The demand will be time-varying, as it willincrease with the density of the predator population. For a predator working on a day-degreescale, the demand will moreover increase with temperature. The demand is often calculated as

ΔD = dYΔt

where d is the per capita demand rate per time unit, Y is the predator density and Δt is the timestep measured on the predator time scale.

Demand is a possibly multi-layered concept. If a predator needs a certain input forgrowth, it will need to eat more than this to satisfy that demand, because it also spends ener-gy on metabolism. Moreover, it needs to kill more prey than the total demand for growth andmetabolism: Part of the prey will go unutilised, either because it was never eaten (for example,the skeleton), or because it was quickly ejected (for example, the honey dew excreted by aphids).One should be aware of these demands at different physiological levels when using the functionalresponse model.

The demand puts an upper limit on the supply rate; the predator population cannot acquiremore than it needs. How close the supply (ΔS) gets to the demand (ΔD) depends on prey densityand the search efficiency of the predator. In the (G-B) functional response, this is parameterisedas the apparancy (α) of the prey, a number between zero and one (inclusive). Search behaviouris difficult to measure, and it makes sense that this difficult aspect is translated into a singleparameter, which usually must be determined by calibration (i.e. fitting of model output toobserved field data).

In this example (the recipe can be found in therecipes/unisim_explained/writing_recipes folder), apparancy has been set to α = 0.8 and demand to ΔD = 10 with prey density in the range X = 0..100:

Egestion and base metabolic rate have both been set to zero. Supply can be seen to reach

Page 36: Unisim Explained 2015-06-08

30 Chapter 2. Writing recipes

the demand asymptotically. Next, we set the egestion ratio to 20%:

The supply curve now increases less steeply with increasing prey density, because thepredator needs to kill more to obtain the same net supply. In a final step we add basic metabolicrate as a constant with the value 1. Again, we see the supply curve slacken; an even higher preydensity is needed to obtain the same net supply::

The allocation of the acquired net supply lies outside the logic of the FunctionalRe-sponseGB model. Further losses my incur, for example the cost of growth respiration (i.e., con-version costs of food intake).

Energy budget considerations can have a dramatic effect on the predicted number of preykilled. The three models above all have an asymptote of net supply equal to 10, but by includinglosses first to egestion and then to basic metabolism, the potential number of prey killed rises:

Page 37: Unisim Explained 2015-06-08

2.8. Applications 31

In this last graph the variable totalSupply is shown, whereas the previous three graphsshowed the supply, egestion and respiration variables of the FunctionalRespon-seGB model. Hence supply denotes the net supply, which is the totalSupply corrected foregestion and respiration.

A final variable that is commonly calculated is the supply/demand ratio.The example showshow this is decreasing when losses to egestion and base respiration are included:

The above description fits a functional response in a predator-prey or consumer-resourcesystem. With some consideration it can also be used for a parasitoid-host, parasite-host orpatogen-host system. The demand will then be defined by the optimal egg-laying rate of theparasitoid or the maximal contact rate between infectuous hosts (or vectors) and susceptiblehosts. The supply, meaning the number of parasitoid eggs laid or the number of host-vectorcontacts achieved, follow the same logic as for predators: it is limited by the density of the hostand the search efficiency of the parasitoid or vector.

Some parasitoids will lay one egg only per host, in that sense they function like predators,which can only eat each prey once. However, some parasitoids will lay more than one egg perhost. For diseases it may be inconsequential whether one or more contacts with the pathogenoccured, although one could imagine a dose-response relationship for some pathogens.

Therefore we need to compute not only the number of attacks (eggs laid or vector contacts)but also how these are distributed in the host population: 1, 2, 3, .. attacks. If we assume thatattacks occur at random in the host population, they will follow a Poison distribution defined by

Page 38: Unisim Explained 2015-06-08

32 Chapter 2. Writing recipes

the average number of attacks per host,

m = ΔSX

Commonly we would be interested in knowing the number of hosts attacked (ΔXa), which wecan infer from the zero term of the Poisson distribution,

ΔXa = X⎡⎢⎣

1 − exp( − m) ⎤⎥⎦

The FunctionalResponseGB model gives access to these variables as attacksPerHost,numHostsAttacked and propHostsAttacked. If, for example, 20 hosts are attacked 8times (X = 20, ΔS = 8), we get attacksPerHost = 8/20 = 0.4, numHostsAttacked = 20(1 -exp(0.4)) = 6.6 and propHostsAttacked = 6.6/20 = 0.33.

2.8.6. Application 6. Multi-way functional response

The Predation model solves the problem when many predators feed upon many prey. Forexample, we could imagine a scenario with leopard (Y1) and lion (Y2) feeding on gazella (X1), gnu(X2) and zebra (X3). The hunger of the predators would be defined by their demand (ΔDj), and thesearch rates defined by a matrix addressing all predator(j)-prey(i) combinations (αij). We couldlet lions eat a leapard now and them by including leopards as both predator and prey:

Prey apparancy

Predator Demand Gazella Gnu Zebra Leopard

Leopard 12 0.05 0.001 0.02 0

Lion 18 0.08 0.01 0.04 0.0005

Prey density

100 200 150 5

The single zero occuring among the apparancy values implies that leopards are not cannibalistic.Whatever applies in nature, the Predation model would accept cannibalism too.

The application_6_predation.xml recipe (found in therecipes/unisim_explained/writing_recipes folder) calculates the predation ratesthat would result from the table above. However, in this recipe only the the Predation modelis truely functional, whereas the five animal models are just mockups with fixed values for Den-sity and Demand. In a realistic model Density and Demand would be time-varying. Here, themodel keeps calculating the same predation rates, without any kills being effectuated:

<simulation version="1.0"><integrator type="Steps">

<parameter name="maxSteps" value="10"/></integrator>

Page 39: Unisim Explained 2015-06-08

2.8. Applications 33

<model name="calendar" type="unisim::Calendar"></model>

<model name="Gazella" type="UniSim::Fixed"><parameter name="parameters" value="((Density 100.0)) "/>

</model><model name="Gnu" type="UniSim::Fixed">

<parameter name="parameters" value="((Density 200.0)) "/></model><model name="Zebra" type="UniSim::Fixed">

<parameter name="parameters" value="((Density 150.0)) "/></model><model name="Leopard" type="UniSim::Fixed">

<parameter name="parameters" value="((Density 5.0) (Demand12.0)) "/>

</model><model name="Lion" type="UniSim::Fixed">

<parameter name="parameters" value="((Demand 18.0)) "/></model>

<model name="Predation" type="UniSim::Predation"><parameter name="apparancyMatrix"

value="application_6_predation_apparancies.txt"/></model>

<output type="plot"><parameter name="title" value="Predation.prn"/><trace label="TotalTimeSteps"

ref="calendar[totalTimeSteps]"/><trace label="Gazella" ref="Gazella[Density]"/><trace label="LionGazella" ref="predation[Lion-Gazella]"/><trace label="LionLeopard" ref="predation[Lion-Leopard]"/><trace label="LeopardGazella"

ref="predation[Leopard-Gazella]"/><trace label="LeopardSupply"

ref="predation[Leopard-Supply]"/><trace label="LeopardLoss" ref="predation[Leopard-Loss]"/><trace label="GnuLoss" ref="predation[Gnu-Loss]"/>

</output>

The apparancy parametersare provided as the parameterapparancyMatrix to thePredationmodel as a tab-separated, text file with the following format:

Page 40: Unisim Explained 2015-06-08

34 Chapter 2. Writing recipes

Gazel-la[density]

Gnu[density] Zebra[density] Leop-ard[density]

Leop-ard[demand]

0.05 0.001 0.02 0

Lion[demand] 0.08 0.01 0.04 0.0005

The first column contains references to predator demands. A column label is optional andinconsequential. The following columns all bear column headings that are references to thevariables holding the density of prey. Both prey densities and predator demands can obviouslybe time-varying, so the model needs references to keep track of them. The entries in the mainbody of the table shows the apparancy values for each predator-prey combination.The apparancyvalues are constant.

With the apparancy matrix above and the prey densities shown in the earlier table, thePredation model will yield these predation rates when updated:

Gazella Gnu Zebra Leopard ∑ Supply

Leopard 3.410 0.169 2.241 0.000 5.821

Lion 5.000 1.491 3.990 0.002 10.481

∑ Loss 8.410 1.660 6.230 0.002 16.302

You can reproduce these numbers by running the application_6_predation.xml recipe.As you can see the leopard population got a total supply of 5.821 compared to its demand of 12,and the lion population got a supply of 10.481compared to its demand of 18. The distribution ofpredation rates among prey populations reflects both their relative population densities and theirapparancy values (the apparancy matrix above). In a real simulation these predation rates wouldbe applied as mortality rates on the prey populations and as a ressource input to the predatorpopulations.For this purpose different models would need to pick up the relevant predations ratesfrom the above table.

The predation rates are not actually written to a table, as it would become quite tedious toread the predation rates from a file in every time step. Instead the Predation model createsvariables which can be used to pull values from the table above. These variables are of the formpredator-prey. If you have named the Predation model predation, you can refer to, for ex-ample,predation[Lion-Gazella] (equal to 5.000) but not predation[Gazella-Lion].In addition, there are variables for the totals, named Supply and Loss, for example, preda-tion[Lion-Supply] (equal to 10.481) and predation[Gazella-Loss] (equal to 8.410).For models that appear both as predator and prey, both totals would be present, for example,predation[Leopard-Supply] (equal to 5.821) and predation[Leopard-Loss] (equalto 0.002).

If a model reference in the apparancy matrix contains slashes, as inLion/female[demand] and Lion/female[demand], these are replaced by underscores inthe variable names of the Predation model. This is because slashes are not allowed in variable

Page 41: Unisim Explained 2015-06-08

2.8. Applications 35

names. So, the variables names would be for instance,predation[Lion_female-Gazella]and predation[Lion_male-Gazella].

Multiway parasitisation and infection are modelled by the Infection model, which alsohas an apparancyMatrix parameter. We can imagine three butterfly species being infected bytwo species of parasitoids, a fly and a wasp. To ease comparison with the Predation model,the matrix is the same, except for the names:

Host apparancy

Parasitoid Demand io levana paphia io/fly

Fly 12 0.05 0.001 0.02 0

Wasp 18 0.08 0.01 0.04 0.0005

Host density

100 200 150 5

For the Infection model, the demand denotes the potential egg-laying rate of a parasitoid, orfor a vector, the potential rate of encounters between vector and host. The number of interactionscan grow dramatically as parasitoids, vectors and hosts are added to the system, because hostpopulations may need to be split into different sub-populations. Thus sub-populations may beneeded to keep separate, parasitised and non-parasitised hosts, and different phases of infection(susceptible, exposed, infectious and recovered). Here we include only one such sub-populationnamed io/fly which denotes io butterflies parasitised by the fly. According to the apparancymatrix above, fly-parasitised io cannot be attacked by the fly again, but it can be attacked by thewasp (at a very low rate).

The application_6_infection.xml recipe yields this simulation output:

io levana paphia io/fly ∑ Attacks

Fly 3.500 0.170 2.272 0.000 5.941

Wasp 5.088 1.491 4.020 0.002 10.601

∑ Attacks 8.588 1.661 6.291 0.002 16.542

The outcome of the Infection model is shown here in terms of the number of attacks. If youcompare this outcome with that of the Predation model, you will find that the Infectionmodel yields slightly higher numbers. This is because infections can overlap; one host canreceive more than one parasitoid egg or encounter more than vector during a time step. For manypurposes you would also be interested in the number of hosts attacked, in addition to the numberof attacks. The number of hosts attacked will be slightly smaller than the number of attacks,because a few hosts by chance will have been attacked more than once:

Page 42: Unisim Explained 2015-06-08

36 Chapter 2. Writing recipes

io levana paphia io/fly ∑ Attacked

Fly 3.439 0.170 2.255 0.000 5.863

Wasp 4.961 1.486 3.966 0.002 10.415

∑ Attacked 8.400 1.655 6.221 0.002 16.278

These rates, denoting the number of hosts attacked, are inbetween those of predation and numberof attacks, as you can verify by comparing the three respective tables above. The last table stillcontains some overlap, as hosts can be attacked by both fly and wasp. For instance, for the iopopulation the 3.500 attacks (eggs laid) by the fly population led to 3.439 io indivuals beingattacked (having 1 on or more parasitoid eggs inside), and the 5.088 attacks (eggs laid) by thewasp population led to 4.961 individuals being attacked. Of those individuals attacked somewould have been attacked coincidentally by both fly and wasp. How to sort this out depends onthe biology of the involved species.

The Infection model computes more variables than the Predation model. These vari-ables are named parasitoid-host or vector-host. For the number of attacks, attacks is append-ed to the name, for example, infection[Fly-paphia-attacks] (equal to 2.272) or in-fection[Wasp-io_fly-attacks] (equal to 0.002). As noted for the Predation model,slashes (/) are not allowed in variable names and will be replaced by underscores by the In-fection model; here we must write io_fly, instead of io/fly. For the number of hosts at-tacked, attacked is appended to the name, for example infection[Fly-paphia-attacked](equal to 2.255). The totals are named by just the parasitoid, vector or host followed by at-tacks or attacked, for example infection[Wasp-attacks] (equal to 10.601) or infec-tion[paphia-attacked] (equal to 6.221).

2.9. Advanced handling of many models

Suppose you need several instances of the same model; they have the exact same settings forparameters and any child models. Then you use the instances attribute:

<model name="generation" type="Insect" instances="3">...

</model>

I this example you would get three instance of the Insect model. They would be namedgeneration(1), generation(2) and generation(3). You would need these names, forinstance, when referring to the models in an output element.

In other cases you may need several instances but with different parameter values. Maybeyou have got hundreds of farms each represented by a Farm model. Specifying all these in anXML recipe would be very cumbersome. Just imagine the first four out of many hundreds:

<model name="landscape" type="My::Landscape"><model name="A" type="My::Farm">

<parameter name="FarmType" value="Cattle"/>;<parameter name="SoilType" value="Sand"/>;

Page 43: Unisim Explained 2015-06-08

2.9. Advanced handling of many models 37

<parameter name="Economy" value="Business"/>;</model><model name="B" type="My::Farm">

<parameter name="FarmType" value="Cattle"/>;<parameter name="SoilType" value="Sand"/>;<parameter name="Economy" value="Leisure"/>;

</model><model name="C" type="My::Farm">

<parameter name="FarmType" value="Plant"/>;<parameter name="SoilType" value="Sand"/>;<parameter name="Economy" value="Business"/>;

</model><model name="D" type="My::Farm">

<parameter name="FarmType" value="Plant"/>;<parameter name="SoilType" value="Clay"/>;<parameter name="Economy" value="Business"/>;

</model></model>

In this example the plug-in called My defines models of type Landscape and Farm. In the above,one Landscape model with four Farm models inside is created.

Usually such information would stem from a spreadsheet or database. If you export theinformation into a tab-separated text file then you can get the same result as above much moreconveniently, irrespectively of the number of models you want to create:

<model name="landscape" type="My::Landscape"><model type="My::Farm" table="farms.txt"></model>

</model>

Where the farms.txt file has this content (with tab-seperated columns):

*My::Farm FarmType SoilType Economy

A Cattle Sand Business

B Cattle Sand Leisure

C Plant Sand Business

D Plant Clay Business

Note that the parameter values are taken from the columns, identified by the column heading.These column headings function like the usual name attribute. The name of the model itself istaken from the column with a heading that matches the model’s type, in this case My::Farm.To mark this special functionality it must be preceeded by an asterisc *My::Farm.

The next level of complexity arises once we realize that the farms differ in their acreage of

Page 44: Unisim Explained 2015-06-08

38 Chapter 2. Writing recipes

different crops, and we need a Crop model for each of these on each farm. Could we somehowuse the same syntax?

<model name="landscape" type="My::Landscape"><model type="My::Farm" table="farms.txt">

<model type="My::Crop" table="crops_on_farms.txt"></model>

</model></model>

That certainly does look neat. Now, the crops_on_farms.txt file must hold columns both forthe farm and the crop to specify the parameters for each farm x crop combination:

*My::Farm *My::Crop Area

A Oats 10

A SBarley 30

B Oats 20

B WBarley 40

D SBarley 15

D WBarley 25

D Oats 55

Here farms A and B each have two crops, farm C has none, and farm D has three. In thisexample, the Crop model only has one parameter called Area. Or, if the Crop model holds moreparameters, they will keep their default value as defined in the C++ code for the Crop class.

You can re-apply this principle to any level. In this case, you could for example add a fieldoperations level telling the date when different operations were carried out in each crop oneach farm:

<model name="landscape" type="My::Landscape"><model type="My::Farm" table="farms.txt">

<model type="My::Crop" table="crops_on_farms.txt"><model type="My::Operation"

table="operations_on_crops_on_farms.txt"/></model>

</model></model>

With this input in operations_on_crops_on_farms.txt:

Page 45: Unisim Explained 2015-06-08

2.9. Advanced handling of many models 39

*My::Farm *My::Crop *My::Operation Date

A Oats Sowing 20/4/2010

A Oats Harvest 15/8/2010

A SBarley Sowing 21/4/2010

A SBarley Harvest 16/8/2010

B Oats Sowing 22/4/2010

B Oats Harvest 17/8/2010

B WBarley Sowing 15/9/2009

B WBarley Spraying 1/10/2009

B WBarley Harvest 25/7/2010

D SBarley Sowing 23/4/2010

D SBarley Harvest 18/8/2010

D WBarley Sowing 16/9/2009

D WBarley Spraying 2/10/2009

D WBarley Harvest 26/7/2010

D Oats Sowing 24/4/2010

D Oats Harvest 19/8/2010

But now we realize this does not solve the problem completely, because when we look at theOperation model it has two more parameters besides Date. These parameters are Cost andIsOrganic. In fact, we have them in this table:

*My::Operation Cost IsOrganic

Sowing 100 yes

Harvest 350 yes

Spraying 20 no

It would be a bad design to duplicate these values into the table above but, of course, if allthese tables are maintained by database software that could be an option. However, we can alsoformulate this more succinctly in the XML recipe:

<model name="landscape" type="My::Landscape"><model type="My::Farm" table="farms.txt">

<model type="My::Crop" table="crops_on_farms.txt"><model type="My::Operation"

table="operations_on_crops_on_farms.txt"/><parameter table="operations.txt"/>

Page 46: Unisim Explained 2015-06-08

40 Chapter 2. Writing recipes

</model></model>

</model>

One should take note of the two different functionalities of the table attribute exposed here.When a table is attributed to a model element, one model instance will be created for each linein the table; parameter values will be set from those given in the table columns. When a tableis attributed to a parameter element, it is simply used to look up parameter values for the parentmodel. In this example, when an Operation instance with the name Harvest is created, thenits Cost parameter will be set to 350 and its IsOrganic parameter to yes.

If you need to build a model with a complex data structure like in this example, you shouldnot try to build it all at once. Start from the outermost level and work yourself inwards. Youshould also notice that your C++ coding will look just the same whether you create modelsand set parameters with the table attribute, or whether you use the much simpler method ofspecifying each model and each parameter individually in the XML code. This is only natural.Your C++ code should work the same, no matter how many objects of type Farm, Crop andOperation are present in the simulation. You can find an example of C++ code implementingFarm, Crop and Operation in src/plugins/test_models.

There are a few more possibilities to cover. Suppose you have the data on crop acreagerepresented in cross-tabular format as in this file crops_area_on_farms.txt:

*My::Farm Oats SBarley WBarley

A 10 30 0

B 20 0 40

C 0 0 0

D 55 15 25

This is also readable by Universal Simulator if you use the crosstab attribute in stead of thetable attribute. In addition you must supply the parameter name (Area, in this case) in theparameter attribute:

<model name="landscape" type="My::Landscape"><model type="My::Farm" table="farms.txt">

<model type="My::Crop" name="Area"crosstab="crops_area_on_farms.txt">

</model></model>

</model>

Note that with this method all farms get the full complement of crops. In this case the missingcrops are given an area of zero.You are only allowed to specify one key column with this method.Each entry in the table is identified by the value in the first column and the name of the parent inthe column heading.

Page 47: Unisim Explained 2015-06-08

2.9. Advanced handling of many models 41

If you have additional parameter values in the same form, these can be added as a parame-ter element. For example, if you have the number of fields for each farm x crop combination:

<model name="landscape" type="My::Landscape"><model type="My::Farm" table="farms.txt">

<model type="My::Crop" name="Area"crosstab="crops_area_on_farms.txt">

<parameter name="numFields"crosstab="crops_num_fields_on_farms.txt">

</model></model>

</model>

with this content of the file crops_num_fields_on_farms.txt:

*My::Farm Oats SBarley WBarley

A 2 3 0

B 1 0 4

C 0 0 0

D 8 5 6

You can add as many as you need of these parameter tables and, indeed, combine this methodwith any of the above.

In all of the examples above, key columns were used to define the context of the table bythe name of one or more ancestors (parent, grandparent, …) of the parameter. However, youcan also define the context by the value of one of the ancestors’ parameters. This is easiest tounderstand by example:Let’s say that nitrogenNorm is a parameter of Crop. But the value ofnitrogenNorm depends both on the Crop and on the soilType of the Farm. This is easy todefine in a table:

*SoilType Oats SBarley WBarley

Clay 90 110 120

Sandy 105 130 145

When Universal Simulator searches for the key value named SoilType in the column heading,it will find it as a parameter of the Farm, and the value will be extracted from there. The XMLcode is straightforward:

<model name="landscape" type="My::Landscape"><model type="My::Farm" table="farms.txt">

<model type="My::Crop" name="Area"

Page 48: Unisim Explained 2015-06-08

42 Chapter 2. Writing recipes

crosstab="crops_area_on_farms.txt"><parameter name="numFields"

crosstab="crops_num_fields_on_farms.txt"><parameter name="nitrogenNorm"

crosstab="nitrogen_norms.txt"></model>

</model></model>

Page 49: Unisim Explained 2015-06-08

Chapter 3. Working with source code

This chapter takes you through the steps needed to download and unpack the source code ofUniversal Simulator (3.1). Subsequently, you are shown how to navigate the source code to findthe implementation of specific plug-ins and models (3.2). For the expert, instructions are givenhow to build your own version of Universion Simulator from the downloaded source code (3.3).This latter step is needed, if you want to develop your own plug-ins and models.

3.1. Downloading source code

You find the source code of Universal Simulator in the download section of www.ecolmod.org.Follow the instructions there to download the UniSim source code package. The package iscomplete and contains all Universal Simulator code which is written in C++ and XML.

To study the C++ and XML files, you can use an all-purpose text editor, such as Notepadfound on MS Windows. However, a much better choice is Notepad++, which offers syntax-high-lighting of both C++ and XML code. It can be downloaded for free at notepad-plus-plus.org. ForXML files you may find Komodo Edit a superior tool, as it will help you write XML code that isvalid. Freely available at www.activestate.com/komodo-edit.

Once you have downloaded the source code package, which comes as one huge zip file,create a folder to hold your source code, for example, C:/dev. Unpack the zip file there, anda sub-folder will be created with the contents of the zip file. After unzipping the file, feel free torename the resulting folder. Here you see a successful installation of the source code, where thefolder was renamed UniSim:

Do not clutter your folder structure. You can, for example, easily find yourself in this situationafter unpacking:

43

Page 50: Unisim Explained 2015-06-08

44 Chapter 3. Working with source code

Keep your folder structure as simple as possible. In this case, delete the unnecessary duplicationof UniSim folders. Otherwise, confusion is imminent. You will soon have plenty of folders andfiles to keep track of.

If you later on download newer versions of the source code, you can end up with severalversions in sibling folders:

This developer seemingly chose to keep a folder for each of three different versions of the sourcecode: versions 1.36 and 1.37 and then maybe the newest version. This will cause no problems(other than, potentially, your own confusion). At any time you can delete folders with outdatedversions of the source code but always consider whether some files should be salvaged first.Maybe your own XML files, or even C++ files, are hiding inside those older folders.

3.2. Navigating source code

The folder, where you unpacked the source code, is called the root folder of Universal Simulator.In this example, the root folder is located in C:/dev/UniSim:

Page 51: Unisim Explained 2015-06-08

3.2. Navigating source code 45

The C++ files are found in the src folder. To enable different modellers to program in well-defined work spaces, the source code is split into modules called plug-ins, which are found in thesrc/plugins folder. In the example above, the files inside the ecotox plug-in are shown.

The XML files, which form the recipes that you can open and execute withthe Universal Simulator program, are found in the src/recipes folder. For exam-ple, you can find the XML files, used as examples in the previous chapter, in thesrc/recipes/unisim_explained/writing_recipes folder:

Page 52: Unisim Explained 2015-06-08

46 Chapter 3. Working with source code

If you previously installed the Universal Simulator program (Chapter 1), you will alreadyhave these XML recipes present on your computer. They are in the Universal Simulator fold-er inside your standard documents folder. Possibly, you also wrote some additional XMLrecipes yourself earlier and, most likely, you also saved them there. Take care not to confuse

Page 53: Unisim Explained 2015-06-08

3.2. Navigating source code 47

the two different recipes folders: the one inside the Universal Simulator root folder (e.g.,C:/dev/UniSim/src/recipes) and the one possibly inside your standard documents folder(e.g., C:/Users/niels/Documents/UniSim-1-41/recipes).

3.3. Building from source code

This section is only for the reader who has previous experience with C++ programming, and whowants to extend the existing set of models available for Universal Simulator. Before you startwriting your own code, you must build Universal Simulator from the downloaded source code.The download procedure was described in section 3.1.

If you earlier on installed the end-user version of Universal Simulator (as described inChapter 1) then you automatically installed the Graphviz software as well. Graphviz is used byUniversal Simulator to draw diagrams. However, you may have gone directly to this chapter,skipping the end-user installation,which is fine but then you have to install Graphviz yourself.Gohere to install Graphviz: www.graphviz.org. Follow the ’download’ and subsequent links. Pickthe version for your operating system and finally pick the ’current stable release’ version. Firsttime you run Universal Simulator, you will be asked in which folder you installed Graphviz.

To build Universal Simulator, you need to download the Boost library found atwww.boost.org. Click on the ’Get Boost’ link found there and follow the links to download thelatest version as a zip file. Unpack the zip file in a separate folder, together with the folder for theUniversal Simulator source code, for example in C:/dev/boost_1_48_0. To prevent confu-sion, avoid nested sub-folders, such as C:/dev/boost_1_48_0/boost_1_48_0.

Qt Creator is the IDE (Integrated Development Environment) used to build Universal Sim-ulator. You can install Qt Creator from Qt Project. Notice that there are many diffent versionsdepending on your computing platform.The interactive installation program will show you avail-able options. To follow this tutorial, you should install Qt Creator on Windows with the MinGW32-bits tool. After that crucial choice, simply accept all default suggestions during installation.

To prepare your computer for building Universal Simulator, you must set three environmentvariables:

1. Create the BOOST_ROOT environment variable. Typically as C:\dev\boost_1_48_0.

2. Create the QT_ROOT environment variable. Typically asC:\Qt\5.1.0\mingw48_32\bin.

3. Amend the Path environment variable. Typically with the same path as set for QT_ROOT.

Note: You typically will have later version numbers for both Boost and Qt.

Sometimes it may occur that you have no folder called C:\Qt\5.1.0\mingw48_32.Maybe you picked the wrong installation file and installed a version of Qt Creator meantto work together with MS Visual Studio. In that case, you will have a folder namedC:\Qt\5.1.0\msvc2010 or similar. However, in this manual we do not use that tool, so youneed to fix your Qt installation. Go to the Windows program menu, find the Qt folder and in-side that click on the Qt Maintainance Tool application. In this application, choose Packagemanager and proceed. In the options tree that appears, drill down this track (using the triangleicon to move down one step): Qt - Qt 5.1.0. There, place a check mark to select the MinGW

Page 54: Unisim Explained 2015-06-08

48 Chapter 3. Working with source code

component. Now proceed and let the installation complete. Afterwards check that the folderC:\Qt\5.1.0\mingw48_32\bin is now present.

To access the environment variables: right-click Computer, click Properties, clickAdvanced system settings, click Environment Variables, and you are brought to a view of youenvironment variables.

Under User variables click New and create a variable called BOOST_ROOT with a valuereferring to the folder where you put the Boost library, for instance, C:\dev\boost_1_48_0:

Repeat this procedure and create the QT_ROOT variable. Its value should refer to the folderspecifying your version of the Qt libraries. This folder is located inside the folder with the QtCreator installation, usually C:\Qt. The complete path, which you should put in the QT_ROOTvariable, should be something like C:\Qt\5.1.0\mingw48_32\bin:

Page 55: Unisim Explained 2015-06-08

3.3. Building from source code 49

You might have a higher version number of the Qt library than version 4.8.1 as in this example.Check the folder structure on your computer and use the version number that you find.

Finally, find the Path variable under System variables. Double-click that and you willsee that its value is a long string of folder names, separated by semicolons. You may find itconvenient to copy and paste the whole string into a text editor, to get an overview of whatit contains.

The Path variable tells the Windows operating system in which folders to look forexecutable files. Universal Simulator relies on a few libraries which reside in folders, that youmust include in the Path. Otherwise, the Universal Simulator version that you are about to buildwill not work.

You need to append one additional folder to the Path. Luckily, it is the exact same folder asyou just set for QT_ROOT, i.e. C:\Qt\5.1.0\mingw48_32\bin, or similar. To add this folderto the Path variable, type a semicolon at the end of the string that lists all the Path folders andthen add the path at the end:

Page 56: Unisim Explained 2015-06-08

50 Chapter 3. Working with source code

The Universal Source code is found in the src folder:

To begin with you should go to the src/build/win folder and execute the batch file foundthere called build_all.bat. This will cause a complete build of the Universal Simulatorprogram and all its plug-ins. You can follow the progress, both in the rolling text window thatappears and in the folders, where the build products are saved.

Page 57: Unisim Explained 2015-06-08

3.3. Building from source code 51

In the src/library folder, two library files will be produced. Their names begin withbase and engine and will be of DLL file type. In the src/plugins folder, one plug-in librarywill be produced for each of the sub-folders in the src/plugins folder. They will be namedafter their folder and will also be of DLL type. Together with a DLL file, you will always find afile with the same name, except with lib in front.

Finally, in the src/applications folder, the Universal Simulator itself will appear. Itsname begins with UniSim. Another program, to run the suite of unit tests that follows UniversalSimulator, is built as well. Its name begins with test-unisim.

All the files built end with -n-nd, where n-n stands for the version number and the d standsfor developer. The d is put there to distinguish these files from those destined for the end-user.The end-user files are those that are installed by the Universal Simulator installer, as describedin Chapter 1.

If you previously installed the Universal Simulator (Chapter 1), and if the building processby build_all was successful, you now have two versions of Universal Simulator on yourcomputer. The first one is the end-user version, which you can execute through the Programsmenu. The second one is the developer version, which you can execute by double-clicking theUniSim-n-nd.exe file found in src/applications. You can change the C++ code of thedeveloper version but not of the end-user version. However, both versions will accept the sameXML recipe files.

When you run Universal Simulator, you can tell easily whether it is the developer orend-user version: The developer version has an x appended to its version number, wheres theend-user version has not. For example, version 1.37.x vs. version 1.37. The version number isdisplayed in the title line of the application and under Help|About.

If an error message appears when you try to run Universal Simulator, complaining abouta missing .dll file, it is because the Path variable on your computer was not set up correctly.Check the steps explained previously in this section (3.3). The name of the missing .dll canmaybe guide you to find the correct folder to put in the Path.

You will find it a lot easier to navigate the source code, now that you have Qt Creatorinstalled. From its menu you can choose File|Open project and open any of the project files(recognised by their type which is .pro). Notably, there is one inside each of the src/pluginsfolders.

3.4. Universal Simulator algorithm

When you develop your own models, you define a new model class for each kind of model thatyou need. A Model base class is supplied for this purpose. Its header file is in the folder of theusbase library, and the Model class resides in the UniSim namespace. To set your modelsapart from those of other developers, you pick you own namespace. In this case the modeller haspicked meadow for his namespace:

#include <usbase/model.h>

namespace meadow {

class Frog : public UniSim::Model

Page 58: Unisim Explained 2015-06-08

52 Chapter 3. Working with source code

{public:

Frog(UniSim::Identifier name, QObject *parent);void reset();void update();

private:// parametersdouble initDensity, lengthOfJump;// variablesdouble n, totalDistance;

};}

namespace The Model base class declares six virtual methods which are all defined empty in thebase class. You equip your model class with the desired behaviour by re-defining one or moreof these virtual methods. For the Frog class, methods reset and update were re-defined; theconstructor Frog(name, parent)will be called by Universal Simulator should a Frogmodelbe required by the recipe.

Here are the names and typical usage of the six virtual methods of the Model base class:

• amend()Called once just after the recipe has been opened by the user.The amendmethod allows youto create model objects in addition to those already specified in the recipe. This can be usedto make quite sophisticated models.For instance,anEcologicalCommunitymodel couldtake the number of species as a parameter.The amendmethod of EcologicalCommunitycould then create the appropriate number of Species models.

• initialize()The initializemethod is called once, just after the user has started a simulation run. Theinitialize method is commonly used for the model object to find other models that itwill collaborate with. Such connections are held in pointers, which will then usually be usedby the reset and update methods.

• reset()The reset method is called once before every iteration of the simulation. If the simulationis only carried out once, then the reset method will likewise be called only once. Thereset method is defined for most models because its main purpose is to set all statevariables to their initial value. For the Frog class, totalDistance could be set to zero.

• update()The update method is usually the most important of the six methods, incarnating mostof the biological behaviour of the model. The update method is called once every timestep. Its main purpose is to update all state variables. In the Frog class, totalDistancecould be incremented with lengthOfJump. This would result in a linear increase intotalDistance with time.

• cleanup()The cleanupmethod is called once after a simulation iteration has completed. It is not used

Page 59: Unisim Explained 2015-06-08

3.4. Universal Simulator algorithm 53

very often. Its typical use is to summarise the results of the simulation iteration.

• debrief()The debrief method is called once after the last simulation iteration has completed. It isused even less than the cleanup method.

Since these methods will be called, once or repeatedly, for all model objects present in a simu-lation, it is important to know the order in which they are called. First of all, the logic explainedabove is described equivalently and more succinctly, by this algorithm:

user opens recipe with File|Open menu;amend all models;show model diagram on screen;user starts simulation with Simulation|Run menu;initialize all models;for each iteration {

reset all models;for each time step

update all models;clean-up all models;

}debrief all models;show output on screen and in files;

Whenever one of the six Model base class methods (amend, initialize, reset, update,cleanup, debrief) is called in this algorithm, it is called for all models present in the simu-lation. Moreover, they are always called in the order in which the appear in the recipe. If somemodels reside inside another model then the models inside will be handled first - in their order ofappearance in the recipe. These nested method invocations can go on to any depth, as defined bythe model hierarchy found in the recipe.

3.5. Communicating with models

The data members of your models should be private to the class, as exemplified by the Frog

class above. Yet, some data members must be made accessible, both for the recipe and for othermodels, to enable your model to communicate. There are two ways to create access to a datamember: it can serve as an input, which gives others both read and write access to it, or as anoutput, which only provides read access.

In the Universal Simulator framework, access is provided by the functions (actually, they areC++ macros but you can disregard that detail)Input and Output. You use Input and Outputto set up the desired interface to the data members of your model. The correct place to add inputsand outputs is in the model constructor:

#include <usbase/parameter.h>#include <usbase/variable.h>

Page 60: Unisim Explained 2015-06-08

54 Chapter 3. Working with source code

#include "frog.h"#include "publish.h"

using namespace UniSim;

namespace Meadow {

PUBLISH(Frog)

Frog::Frog(UniSim::Identifier name, QObject *parent): Model(name, parent)

{Input(double, initDensity, 500.); // Initial density of frogs

(per km2)"Input(double, lengthOfJump, 12.); // Average length of a

jump (cm)");Output(double, density); // Density of frogs (per km2)Output(double, totalDistance); // Total distance jumped during

the simulation (cm)}} // namespace

The inputs and outputs must all be declared in the header file, in this case in frog.h. In theexample above, they have all been declared of type double. The type given here must matchhow the parameter or variable was declared (in the header file), otherwise a compilation errorwill ensue. The valid types are int, double, bool, QString, QDate and QTime.

To make the model available in the XML recipe, it must be published in the source file.This is accomplished by the PUBLISH macro as shown. The PUBLISH macro is included frompublish.h.

Inputs have the benefit that their values can be set in the recipe. In this example, the user hasset initDensity to 800, while lengthOfJump is not mentioned and thus retains its defaultvalue (12):

<model name="Rana" type="Pond::Frog"><parameter name="initDensity" value="800"/>

</model>

Outputs cannot be changed from the recipe but you can refer to them, for instance, to be shownin the output:

<output type="plot"><parameter name="title" value="Total distance"/><trace name="time" ref="calendar[totalTime]"/><trace name="Total" ref="Rana[totalDistance]"/>

</output>

Page 61: Unisim Explained 2015-06-08

3.5. Communicating with models 55

Let’s say that we implement a Stork model, which needs frog density as an input to calculateits food intake. Its constructor could look like this:

Stork::Stork(UniSim::Identifier name, QObject *parent): Model(name, parent)

{}

This code setspreyDensity to a default of 50 but the user would likely prefer to link that valueto the actual population density of prey, e.g., the frogs. That could be achieved in the recipe:

<model name="stork" type="Pond::Stork"><parameter name="preyDensity" ref="Rana[density]"/>

</model>

Would it be possible somehow to set that reference as the default value, so that the user in mostcases would not have to bother? Yes, we can do it, like this, in the Stork constructor:

Stork::Stork(UniSim::Identifier name, QObject *parent): Model(name, parent)

{Input(double, initDensity, 500.); // Initial density of storks

(per km2)InputRef(double, preyDensity, "Rana[density]"); // Density of

prey (per km2)Output(double, density); // Density of storks (per km2)

}

However, if the user happens to have put no model named Rana in the recipe, this will causean error when the recipe is opened, because the reference cannot be found. The problem wouldpersist, even if the user added a Frog model but with another name than Rana, for example,Rana_esculenta:

<model name="Rana_esculanta" type="Pond::Frog"><parameter name="initDensity" value="800"/>

</model>

The question then arise if we could make the Storkmodel itself intelligent enough, that it wouldlook up any model in the recipe of the class Frog? Or, indeed, any number of models of classesFrog, Fish or whatever would be allowed in the pond universe? Here, we will limit ourselvesto find just a single Frog model:

// In stork.h#include <usbase/model.h>

namespace meadow {

class Stork : public UniSim::Model

Page 62: Unisim Explained 2015-06-08

56 Chapter 3. Working with source code

{public:

Stork(UniSim::Identifier name, QObject *parent);void initialize();void reset();void update();

private:// parametersdouble initDensity;// variablesdouble density;// linksconst double *preyDensity;

};} // namespace

// In stork.cpp#include "frog.h"#include "publish.h"#include "stork.h"

namespace meadow {

PUBLISH(Stork)

void Stork::initialize() {Model *prey = seekOne<Frog*>("*");preyDensity = prey->pullValuePtr<double>("density");

}} // namespace

First of all, we do not need preyDensity as a parameter any more; the Stork model willfind that independently. In initialize(), the Stork model orientates itself to find theFrog model. It finds the other model by the its class name Frog. By giving the model nameas a joker "*", any model of the class Frog will be found irrespective of its name, e.g., Rana,Rana_esculanta or whatever.

The various seek and peek methods used to find model objects are explained below (3.6).The prey pointer that we just obtained is asked, by way of the pullValuePtr method, fora pointer to density. From now on Stork will have access to density through the pointervariable preyDensity. The access will be read-only, as notified by the const modifier in thedeclaration:const double *preyDensity.

It is not easy to judge whether a model should be imbibed with some intelligence to seekout other models or not. As a general rule, you should only apply this technique when necessary.In any case, it pays off first to establish all connections between models in the recipe only. Then,as the model matures, inflexibilities may evolve which you can only solve by some built-in model

Page 63: Unisim Explained 2015-06-08

3.5. Communicating with models 57

intelligence.The drawbacks of the technique are that your C++ code becomes more complicated,the recipe less clear - and maybe even less flexible, thus opposing your original intent.

3.6. Navigating model structure

Model structure is defined by the user via the recipe. You must decide what makes a valid recipe.Does a Stork model require that a Frog model is also present? Would it be allowed for morethan one Frog model to be present? To check such conditions and set up the necessary linksbetween models, your model may need to orientate itself at some point. The best place to dothat is in the initialize method. The method will only be invoked once during a simulationrun, and you are certain that all model objects belonging to the simulation have been created atthat time.

The Model base class provides a suite of peek and seek methods. All these methods lookfor objects of a certain class and with a certain name. A joker ("*") can be used for the name tofind all objects of a certain class. Here are some introductory examples:

// Find any Model object called weatherModel *weather = seekOne<Model*>("weather");

// Find any Records object called weatherRecords *weather = seekOne<Records*>("weather");

// Find all Fish children of oceanQList<Fish*> fish = ocean->seekChildren<Fish*>("*");

// Find all my Model siblingssiblings = seekSiblings<Model*>("*">

In all the following diagrams, the object orientating itself is painted blue and the part of thefamily tree that is searched is painted yellow. None of the methods will return the object itself asa result (the object itself is excluded from the search).

These facilities may seem quite overwhelming. It is good to know, that you are unlikely toneed them in your first steps of model development.

Page 64: Unisim Explained 2015-06-08

58 Chapter 3. Working with source code

Seeking any object

These methods search globally and are often used to find objects representing time and envi-ronment:

Model *calendar = seekOne<Model*>("calendar");Model *weather = seekOne<Model*>("weather");

• peekOne returns a pointer to object, or null if none was found, or throws an Exception

if more than one was found

• seekOne returns a pointer to object, or throws an Exception if none or more than onewas found

• seekMany returns a list of pointers to objects

Seeking children

Models commonly need to establish contact with their children. The Insect model in thefollowing code builds a list of all itsStage children, finds itsegg child in particular (which mustexist) and peeks for a Model named mould inside the egg. This mould object may exist or not.In the latter case mould will become null:

Page 65: Unisim Explained 2015-06-08

3.6. Navigating model structure 59

void Insect::initialize() {QList<Stage*> stages = seekChildren<Stage*>("*");Model *egg = seekOneChild<Model*>("egg");Model *eggMould = egg->peekOneChild<Model*>("mould");

}

• peekOneChild returns a pointer to object, or null if none was found, or throws anException if more than one was found

• seekOneChild returns a pointer to object, or throws an Exception if none or more thanone was found

• seekChildren returns a list of pointers to objects

Seeking nearest object

6

1 2 3

4 5

7

The nearest object matching the given class and name is searched for in the order indicated bynumbers: first among the children, then among the ancestors’ children, step by step all the wayback to the root. The effect is close to the scope look-up rules for variable names in C++. Thisoffers great flexibility for the end-user. For example, it is used by UniSim::Stage to find thenearest time object used for updating the development of the stage:

void Stage::initialize() {Model *time = seekOneNearest<Model*>("time");

}

Thus the user can put a time model inside the Stage model to define a special chronology forthat Stage object.Or, the user can put it at a heigher level where it can be shared by manyStagemodels, having this time model in common. Should a time model be placed both as a child andfurther up search path (shown in the diagram above), then the result will be the first time objectone found (it being the nearest).

• peekOneNearest returns a pointer to object, or null if none was found

• seekOneNearest returns a pointer to object, or throws an Exception if none was

Page 66: Unisim Explained 2015-06-08

60 Chapter 3. Working with source code

found

Seeking parent

There can be at most one parent of an object, so there is no seekParents. Sometime a parentis needed to find shared relatives. Here an Animal objects finds all models of the Plant class,which are nested inside the Animal object’s parent:

void Animal::initialize() {Model *parent = seekParent<Model*>("*");QList<Plant*> plants = parent->seekDescendants<Plant*>("*");

}

• peekParent returns a pointer to object, or null if none was found

• seekParent returns a pointer to object, or throws an Exception if none was found

Seeking siblings

A model my share an interest with its siblings. Perhaps they are predators and prey?

Page 67: Unisim Explained 2015-06-08

3.6. Navigating model structure 61

QList<Predator*> predators = seekSiblings<Predator*>("*");QList<Prey*> prey = seekSiblings<Prey*>("*");

• peekOneSibling returns a pointer to object, or null if none was found, or throws anException if more than one was found

• seekOneSibling returns a pointer to object, or throws an Exception if none or morethan one was found

• seekSiblings returns a list of pointers to objects

Seeking descendants

Whenever you seek for an object’s child or children, consider whether this is too strict. Maybeit is enough to demand that objects you look for are among the objects descendants? Maybe youjust want to look for all Organ’s inside, or for any model that has a child called mass:

QList<Organs*> organs = seekDescendants<Organ*>("*");QList<Model*> masses = seekDescendants<Model*>("mass");QSet<Model*> hasMass;for (int i = 0;i < masses.size(); ++i)

hasMass << masses[i]->seekParent<Model*>("*");

• peekOneDescendant returns a pointer to object, or null if none was found, or throws anException if more than one was found

• seekOneDescendant returns a pointer to object, or throws an Exception if none ormore than one was found

• seekDescendants returns a list of pointers to objects

Seeking ascendants

Page 68: Unisim Explained 2015-06-08

62 Chapter 3. Working with source code

The ascendant search is short. Often you want to find some containing model without knowinghow deep you are in the model hierarchy yourself. Maybe you are a leaf on a tree, but do notknow how many model layers (twig, trunk) are in between you and the Tree. So, you searchfor an ancestor of class Tree, or maybe just any type of Model called tree:

Tree *tree = seekOneAscendant<Tree*>("*");Model *model = seekOneAscendant<Model*>("tree");

Neither method accepts that more than one ancestor, matching the search criteria, are found.

• peekOneAscendant returns a pointer to object, or null if none was found, or throws anException if more than one was found

• seekOneAscendant returns a pointer to object, or throws an Exception if none or morethan one was found

• seekAscendants returns a list of pointers to objects

In addition, two methods work like peekOneAscendant and seekOneAscendant, ex-cept they refer to the nearest ascendant: peekNearestAscendant and seekNearestAs-cendant

3.7. Plug-in structure

All the source code of one plug-in goes into one Qt project. The source code resides in a folderbearing the name of the plug-in. The folders with plug-in source code are all sub-folders ofsrc/plugins. The example plug-in in src/plugins/example exemplifies a minimalplug-in, which defines only one model. It contains five files:

• example.pro which is the Qt project file

• example_factory.h and example_factor.cpp which provide the interface toproduce the models defined in the plug-in

• even_odd.h and even_odd.cpp with source code for the EvenOdd model

The example plug-in is provided as a basis to create new plug-ins. You simple copy the folder

Page 69: Unisim Explained 2015-06-08

3.7. Plug-in structure 63

with contents and rename the copy. Software, such as Notepad++, provides search and replacefor all files in a folder and can help you renaming throughout the copied plug-in folder. These arethe necessary steps, for example to create a new plug-in called ocean. For the search-and-replaceoperations, include files *.h;*.cpp;*.pro, unselect the option to match whole words only,and select the option to match letter case:

1. Copy src/plugins/example to src/plugins/ocean.

2. Rename example.pro as ocean.pro, and example_factory.h and .cpp asocean_factory.h and .cpp.

3. Search and replace "example" with "ocean".

4. Search and replace "Example" with "Ocean".

5. Search and replace "EXAMPLE" with "OCEAN".

6. In Qt Creator, open the ocean project file and build it.

7. Write an XML recipe to test that the plug-in works. Recipes found in recipes/examplescan be used as a starting point.

8. Start Universal Simulator from src/applications, open your test recipe and run a simu-lation

Page 70: Unisim Explained 2015-06-08

Chapter 4. The BtButTox model

The BtButTox model simulates the side effects of Bt-maize on the Peacock butterfly Inachis ioliving in the vicinity of Bt-maize fields. It is composed of three parts: a maize pollen depositionmodel, a dose-response model and a butterfly model. The model runs for a whole year. Thebutterfly overwinters as an adult and gives rise to 1-2 generations.

The model includes no density-dependent processes or mortalities, other than that causedby larvae being exposed to Bt-maize pollen. Hence the model works in nominal numbers: onefemale emerges from hibernation, and it produces only one egg. The number of larvae enteringpupation, to become the overwintering adults, marks the simulation end point. If Bt-maize hasno effect in the simulation, then one larva will enter pupation for every egg laid. The model isfurther described by Holst et al. (2013).

The model can be changed by the end-user, both in terms of parameter values and modelstructure, which are specified in XML recipe files. These files can be opened and the simulationcarried out with the Universal Simulator program. The installation of Universal Simulator isdescribed in Chapter 1 and the writing of XML recipes in Chapter 2. The organisation of themodel source code and how to download is described in Chapter 3.

4.1. Scenario simulations

Recipes for scenarios in Northern Germany (where I. io has one generation) and Southern Ger-many (where I. io has two generations) can be found in the recipes/BtButTox/scenariosfolder. There are three recipes for both scenarios, file names beginning with N or S, respectively.The recipes define these simulations:

• one year (files N_one_yr.xml and S_one_yr.xml)The simulation runs for one year from 1 January to 31 December. Population dynamics areshown on screen.

• a few years (files N_few_yrs.xml and S_few_yrs.xml)The simulation runs in 10 independent iterations, each lasting one year. Populationdynamics are shown on screen.

• many years (files N_many_yrs.xml and S_many_yrs.xml)The simulation runs in 1,000 independent iterations, each lasting one year. Sensitivity plotsare shown on screen. Summary statistics are written to a single file, while the populationdynamics of each simulated year are written to separate files.

Since the pollen deposition model contains random parameters, and the butterfly model is drivenby day-degrees according to a year picked at random, it makes sense to run the model iterativelyto assess the distribution of possible outcomes.

64

Page 71: Unisim Explained 2015-06-08

4.2. Scenario recipes 65

4.2. Scenario recipes

The six scenario recipes share many common attributes. For instance, the I. io model is the samefor all eight recipes, except that the number of generations differs between the Northern andSouthern Germany scenarios (one and two generations, respectively). To avoid duplication ofinformation between recipes, common parts have been formulated in separate recipes.

This table show how the six scenario recipes are put together from oth-er recipes. A recipe depends on all those appearing in the stack of recipes below:

N_few_yrs S_few_yrs

N_one_yr N_many_yrs S_one_yr S_many_yrs

base_N_records, base_N_output base_S_records, base_S_output

base_pollen, base_io, base_output

So if you change the base_io recipe, all six scenario recipes will be affected, and if youchange the base_N_records recipe the three North Germany recipes will be affected. Recipesbeginning with base do not formulate a complete recipe on their own. They are only used asbuilding blocks for the scenario recipes.

4.3. Scenario outputs

If we start out with the northern scenario defined in the N_few_yrs recipe, we will be grantedfive figures of output when the simulation is run. They all have curves overlaid, representing teniterations of the simulation, and all have x-axes showing time as the number of days since thebeginning of the year. The first figure shows the average temperature during the year:

Next, the pollen figure shows the daily rate of pollen deposition on nettle leaves (pollen per 2cmper day in red), the actual density pollen on nettle leaves (pollen per 2cm in blue) and the totalaccumulation of pollen deposited on nettle leaves, not corrected for loss of pollen from the leaves(pollen per 2cm in yellow):

Page 72: Unisim Explained 2015-06-08

66 Chapter 4. The BtButTox model

Overwintering butterflies emerge in early spring according to the calendar. Hence, there is novariation between years in their flight time. The development of subsequent stages, however, aredriven by day-degrees, which leads to variation between years:

To visualise the exposure of larvae to pollen, we combine the curves for pollen and larva densityin the same figure:

A log10-scale let us follow the predicted overlap also at low densities (values less than -2 notshown). What we see is no overlap; the larvae finish their development before pollen depositionbegins

Page 73: Unisim Explained 2015-06-08

4.3. Scenario outputs 67

If larvae are exposed to pollen during their development, they will suffer an increased mor-tality, as determined by the dose-response curve included in the model. The net effect is illustrat-ed in the last figure, which shows that, in this scenario, all larvae complete their development.Consequently, the number of overwintering butterflies is the same at the end of the season as atthe beginning:

We can contrast these model predictions with those of the southern scenario defined in theS_few_yrs recipe. Temperature is slightly higher, and the pollen season comes slightly earlier:

In this scenario, the butterfly has two generations. Both the emerging overwintering adults andthe newly produced first generation of adults are shown in the same figure:

Page 74: Unisim Explained 2015-06-08

68 Chapter 4. The BtButTox model

For the second generation, the prediction is that the pupae will not alwaus have time to completetheir development:

This prediction of incomplete pupal development has no impact on the risk analysis, however,because the end point is taken, not as the number of hibernating adults at the end of the year, butas the number of larvae completing their development.

When we consider exposure, we realise that 1. generation larvae is present earlier than thepollen season, while the 2. generation larvae seems fully exposed:

The response of the population is evident. In quite many years, only a fraction of the larvae

Page 75: Unisim Explained 2015-06-08

4.3. Scenario outputs 69

complete their development:

In years with cold autumns, even the successful larvae do not all reach adulthood but, asnoted above, this prediction does not affect the risk analysis. For further details consultHolst et al. (2013).

Page 76: Unisim Explained 2015-06-08

Chapter 5. Conductance model

The Conductance model is a model that simulates plant growth under competition for light,either in monoculture or in bi-culture (Benjamin & Park 2007). In contrast to the INTERCOMmodel which focuses on the vertical distribution of the canopy, the Conductance model dealsonly with the horizontal distribution of leaf area.

The word ’ conductance ’ stems from early versions of the model which used the principleof conductance to construct a synthetic time scale, based on several physiological time scales.

The Conductance model was implemented in the conductance_models plugin foundin the src/plugins/conductance_models folder inside your Unisim root folder. TheXML files can be found in the xml/models/conductance folder, also inside the UniSimroot folder.

5.1. Plant model

The Plant model (found in plant.h and plant.cpp) define quite many pull variableswhereby to track the state of the plant.For an overview you can either consult the C++ code in theconstructor Plant::Plant, or you can look up the documentation on page 117. The parametersfor the Plant model are described on the same page.

A Plant object needs some orientation during initialization:

void Plant::initialize() {weather = seekOne<Model*>("weather");

other = 0;QList<Plant*> siblings = seekSiblings<Plant*>("*");if (siblings.size() > 1)

throw Exception("Max. 2 plants are allowed in ""community", this);

other = siblings.isEmpty() ? 0 : siblings[0];}

It looks up the weather object and also checks how many sibling Plant objects it has. Sinceonly zero or one sibling is allowed, it faults otherwise. The throw statement will result in anerror showing up on the user screen. The other variable is a pointer to a Plant object (see itsdeclaration in plant.h), which is set in initialize, either to null or to point to the otherPlant object.

Once every day the update function of all Models objects is automatically invoked. Theupdate function of the Plant model consists of three steps which update, in sequence, thecrown zone area, light interception and weight:

void Plant::update() {

70

Page 77: Unisim Explained 2015-06-08

5.1. Plant model 71

updateCrownZoneArea();updateLightInterception();updateWeight();

}

The crown zone area sz (sz in the code) is what makes the Conductance model special. It is thearea of the smallest circle that circumferences the whole canopy of one single plant. The plant isconsidered to own this area. It is available only for the plant itself to fill up with leaf area. Thusits dimension is

[sz] =2m ground area owned

plant

The crown zone area is computed in one of three ways depending on which growth phase theplant is currently in:

void Plant::updateCrownZoneArea() {switch (phase) {case Unlimited:

sz = A*pow(weight, phi);break;

case UnderCompression:sz = other ?

(1. - other->pullVariable("total_sz"))/n :1./n;

break;case WeightProportional:

Q_ASSERT(other);sz = weight/(totalWeight +

other->pullVariable("totalWeight"));}

total_sz = n*sz;if (total_sz < 0)

sz = total_sz = 0.;else if (total_sz > 1) {

total_sz = 1.;sz = 1./n;

}}

What isphase? It is a C++ enumeration. Enumerations are one of the simplest constructs in C++and their explanation in any textbook is not frightening. The phase variable is declared in theheader plant.h, and the declaration of the Phase type is declared in phase.h.

In the Unlimited phase, the plant population simply grows as if each plant were growingin isolation without competition. In that case, the crown zone area sz is computed according tothe allometric relation, given as a power function.

Page 78: Unisim Explained 2015-06-08

72 Chapter 5. Conductance model

In the UnderCompression phase, the plants (one or two populations, represented by oneor two Plant objects) completely fill out the available area. To understand the logic, let us havea look at the dimensions of the involved variables. Plant density is denoted by n. Hence

[n] =plants

2m ground area available

If there is only one plant population present (in which case other is null, which in C++ isequivalent to false) then

sz = 1 ⁄ n

To make the dimensions match we can infer the suiting units of the enumerator 1 in 1⁄ n,

[ enumerator ] =2m ground area owned

2m ground area available

and thus

[1 ⁄ n] =

2m ground area owned2m ground area available ⁄ plants

2m ground area available=

2m ground area ownedplant

= [sz]

Hence an enumerator value of 1allows the plants to own only as much ground area as is available.This sets the upper limit on the total crown zone area of all plants in the population:

nsz ≤ 1 2m ground area owned per 2m ground area available

In case another population is present, we first subtract the total crown zone area total_sz

taken up by that other population. Then the remaining ground area is divided among the plantsof this population:

(1. - other->pullVariable<double>("total_sz"))/n

Notice the use of the pullVariable method to require the current value of a variable from themodel pointer to by other. A complete list of the pull variables available for Plant models isfound in the documentation for the Plant class beginning on page 117.

In the WeightProportional phase, both plant populations are alloted a total crownzone area in proportion to their total weight (eqs. 21 and 22 in Benjamin & Park (2007)). Forpopulation 1, the proportion is

w1n1w1n1 + w2n2

Page 79: Unisim Explained 2015-06-08

5.1. Plant model 73

The corresponding code is

Q_ASSERT(other);sz = weight/(totalWeight + other->pullVariable("totalWeight"));

The assertion Q_ASSERT(other) will cause a run time error if other is null. That is becausethis calculation only makes sense if two populatios are present. To obtain the crown zone area ofplants in population 1, we have divided with the density of plants (n1) to obtain

sz1 =w1

w1n1 + w2n2

A dimensional analysis of the right hand side shows the its dimension matches that of the crownzone area. Moreover, it follows that the total crown zone area of both populations together addsup to 1,

n1sz1 + n2sz2 = 1 2m ground area owned per 2m ground area available

The code is valid for either plant, so in the coding w1 is represented as weight, w1n1 as total-Weight and w2n2 as totalWeight pulled from the other plant.

After updating the total population crown zone area total_sz, checks are made to ensurethat it remains inside the valid [0..1] interval:

total_sz = n*sz;if (total_sz < 0)

sz = total_sz = 0.;else if (total_sz > 1) {

total_sz = 1.;sz = 1./n;

}

This is necessary to guard against rounding off errors. The checks also evens out when the modelovershoots the crown zone area at the passage from the Unlimited to the UnderCompressionphase and from the UnderCompression phase to the WeightProportional phase.

Since the concept of crown zone area is particular to the Conductance model, it comes asno surprise that its calculation is also the most complicated part of the model. The remainingcalculations are comparatively simple. Let us review how far we have come in our walk throughtthe code.

void Plant::update() {updateCrownZoneArea();updateLightInterception();updateWeight();

}

We have just covered the updateCrownZoneArea function, so we are now ready to calculatelight interception.

The fraction of light intercepted fz is calculated from the leaf area index within the crown

Page 80: Unisim Explained 2015-06-08

74 Chapter 5. Conductance model

zone Lz 2(m leaf area per 2m ground area owned), which is calculated as the leaf area of a plantdivided by its crown zone area.

The plant leaf area LA_per_plant is estimated from plant weight assuming a simpleallometric relation. Thus we arrive at this implementation:

void Plant::updateLightInterception() {LA_per_plant = F*pow(weight, theta);Lz = LA_per_plant/sz;fz = 1. - exp(-k*Lz);

}

where k is the light extinction coefficient of the plant species.

We are now ready to calculate and add the increment in plant weight dweight during thistime step of 1 day:

void Plant::updateWeight() {double I = weather->pullVariable<double>("irradiation");dweight = eps*I*sz*fz;weight += dweight;totalWeight = n*weight;

}

First we pull the daily global irradiation I from the weather object. We multiply I with thelight-to-dry weight conversion efficiency eps, the crown zone area sz which is the effectivearea that takes up light, and the fraction of light intercepted fz.

Only half of the global irradiation is photosynthetically active radiation (PAR = I / 2).However, ε (eps, in code) was parameterized to operate on I rather than PAR. This choice isarbitrary and inconsequential but one should always be aware whether ε should be applied to Ior PAR.

Next we add the increment dweight (g per plant) to the plant weight, and we update thetotal population plant weight (g per 2m ground area available) by multiplying with plant densityn.

The update updates the state of the Plant object, in terms of its crown zone area, leaf areaand weight. But the code we have inspected so far, does not change its growth phase, whetherit be Unlimited, UnderCompression or WeightProportional. So, a Plant object doesnot determine itself when to change phase; this instruction comes from the outside. The methodfor that is naturally called changePhase:

void Plant::changePhase(Phase newPhase) {phase = newPhase;_phase = int(phase);Q_ASSERT(phase == Unlimited || phase == UnderCompression|| other);

}

The code is inconspicuous. Apart from actually changing the phase variable, it also updates the

Page 81: Unisim Explained 2015-06-08

5.1. Plant model 75

related _phase which will take the value 0, 1or 2 depending on the phase. The _phase serves asa pull variable so that the phase can be displayed as numeric figure, for example as a time trend.The final assertion is put there to ensure consistency. It asserts that either we are in the Unlimit-ed or UnderCompression phase, or there exist an other plant model. Thus it disallows beingin the WeightProportional phase, if there is only one Plant model present.

Now it is time to wonder what all this functionality is good for. The code is just sitting there.Who is going to activate it? The UniSim framework will call the functions initialize onceand update daily. But who will be calling changePhase at the right time? We need somepowerful entity, another kind of object to oversee this business. This is what the Community

model is for.

But before continuing we need to add one more function to Plant, because Communitywill need it: The function reUpdate undoes the weight increment of the last update and thenreinvokes update:

void Plant::reUpdate() {weight -= dweight;totalWeight = n*weight;update();

}

Now, why would we possibly want that? Read on to find out.

5.2. Community model

The Community model has been rather boldly named, as it will accept only one or two Plantobjects being present. The plants are looked up during initialization:

void Community::initialize() {plants = seekChildren<Plant*>("*");if (plants.isEmpty())

throw Exception("Community has no plants", this);else if (plants.size() > 2)

throw Exception("Max. 2 plants are allowed in community",this);}

Just as was the case for the Plant class, the update function of the Community class is doingall the work with the help of a few other functions:

void Community::update() {while (phaseChanged())

reUpdatePlants();}

Before contemplating this code one should realise, that the automatic daily call of all updatefunctions proceeds in the order children-first. Thus the Plant objects are updated before theCommunity object, because the plants are children of the community.

Page 82: Unisim Explained 2015-06-08

76 Chapter 5. Conductance model

What we see is a while loop which potentially can re-update the plants one or more times.This depends on the outcome of the phaseChanged function.

The community is in the same phase as the plant(s), except when there are two Plant

models present and one of them is in the UnderCompression phase. Then the other one is,by necessity, still in the Unlimited phase, and the whole community is considered to be in theUnderCompression phase.

The phaseChanged function is all about changing the phases of both the Community

model and the Plant model(s), as needed. It returns as a result (bool) whether phase wasactually changed:

bool Community::phaseChanged() {updateTotalCrownZoneArea();if (phase == Unlimited)

return phaseUnlimitedChanged();else if (phase == UnderCompression && plants.size() == 2)

return phaseUnderCompressionChanged();return false;

}

First one function is called to calculate the total crown zone area of the Plant model(s). Theremainder of the work is passed on to two other functions, called if the community is currentlyin the Unlimited or UnderCompression phase, respectively. In the latter case, the phasecan only change further if two Plant models are present; if only one Plant model is presentit cannot proceed further than the UnderCompression phase. If the community has reachedthe final phase WeightProportional, it cannot proceed either, which means that no action isneeded and the function simply returns false.

The summation of the total crown zone area could not be simpler:

void Community::updateTotalCrownZoneArea() {sum_sz = 0.;for (int i = 0; i < plants.size(); ++i)

sum_sz += plants[i]->pullVariable<double>("total_sz");}

Next let us consider the case when we are in the Unlimited phase. If the total crown zone areasum_sz has reached 1 thus exhausting the available ground area, then phase must change toUnderCompression. This is what the phaseUnlimitedChanged does:

bool Community::phaseUnlimitedChanged() {bool availableAreaExhausted = sum_sz >= 1.;if (availableAreaExhausted) {

sortPlants();smaller->changePhase(UnderCompression);phase = UnderCompression;return true;

}return false;

Page 83: Unisim Explained 2015-06-08

5.2. Community model 77

}

The sortPlants function finds out which of the plants are smaller by weight and sets the twoPlant pointers,smaller and larger, accordingly.Only the smaller plant will change phaseto UnderCompression while the larger (if present) will continue to grow Unlimited.

The code for sortPlants is straightforward:

void Community::sortPlants() {bool onlyOnePlant = plants.size() == 1;if (onlyOnePlant) {

smaller = plants[0];larger = 0;return;

}

bool firstIsSmaller =plants[0]->pullVariable<double>("weight") <plants[1]->pullVariable<double>("weight");

if (firstIsSmaller) {smaller = plants[0];larger = plants[1];

}else {

smaller = plants[1];larger = plants[0];

}}

In case only one plant is present, that one defaults to be the smaller and larger is set to null,meaning it does not exist.

The final piece of the Community phase change puzzle is the phaseUnderCompres-sionChanged function. This function does nothing until it happens that the leaf area indexinside the crown zone of the smaller plant has reached that of the larger plant. Since thesmaller plant has been UnderCompression, this may happen given enough time:

bool Community::phaseUnderCompressionChanged() {bool plantsAreEven =

smaller->pullVariable<double>("Lz") >=larger->pullVariable<double>("Lz");

if (plantsAreEven){

smaller->changePhase(WeightProportional);larger->changePhase(WeightProportional);phase = WeightProportional;return true;

}return false;

Page 84: Unisim Explained 2015-06-08

78 Chapter 5. Conductance model

}

The consequence is quite simple: both Plant models and the Community model goes into theterminal WeightProportional phase.

Now it is time to revisit the while loop inside the update function:

void Community::update() {while (phaseChanged())

reUpdatePlants();}

All the code evoked by phaseChanged, that we just walked through, aimed to change phaseas needed and then returning false if phase remained unaltered and true, if it actuallywere changed. We can see that in the latter case the plants will be re-updated. We need thisbacktracking, because some conditions might otherwise remain broken; for example, the totalcrown zone area might exceed 1.

This last function of Community contains no surprises:

void Community::reUpdatePlants() {for (int i = 0; i < plants.size(); ++i)

plants[i]->reUpdate();}

5.3. Weather model

To enable us to do simple experiments with the Conductance model, the influence of weather iskept as simple as possible. In its basic version, it depends only on global irradiation 2MJ/m /day)not on temperature. Consequently the Weather model is simplest possible:

Weather::Weather(UniSim::Identifier name, QObject *parent): Model(name, parent)

{Input(double, irradiation, 10.);

}

The model just contains one input irradiation which will be used as an output as well. Itsvalue remain constant throughout the simulation.

5.4. Running the model

The Conductance model is simple and demands only six parameters to be estimated: two foreach of the allometric relationships, one for the extinction coefficient and one for the conversionefficiency. The table shows parameter values for two crops and five weed species.

Page 85: Unisim Explained 2015-06-08

5.4. Running the model 79

Table. Parameter values for the Conductance model (from Park et al. 2007).

Leaf area Crown zone area

Species F 2(m / θg ) θ A 2(m / ϕg ) ϕ k ε (g / MJ)

Cabbage 0.0158 0.840 0.0314 0.529 0.71 1.40

Carrot 0.00975 0.801 0.0255 0.591 0.65 1.23

Tripleurospermuminodurum

0.0185 0.890 0.0245 0.623 0.59 1.63

Solanum nigrum 0.0171 0.866 0.0265 0.747 0.70 1.20

Stellaria media 0.0173 0.849 0.0455 0.585 0.71 0.90

Trifolium repens 0.0158 0.916 0.0273 0.692 0.54 1.13

Veronica persica 0.0162 0.869 0.0242 0.696 0.53 1.33

To get a better sense of the Conductance model, let us look at a cabbage-nightshade system.Nightshade has a more expansive growth form than cabbae. At a certain biomass, a nightshadeplant has a wider crown zone and a larger leaf area than a cabbage plant of the same weight(see Fig.). The two species are equally good at absorbing light per leaf area since the extinctioncoefficients k are about equal. But cabbage is more efficient at utilizing the absormed light asexpressed by its higher light use efficiency ε.

Lea

far

ea2

(m)

0 10 20 30

0.0

0.1

0.2

0.3

0.4

Cro

wn

zone

area

2(m

)

0 10 20 30

0.0

0.1

0.2

0.3

0.4

nightshade

cabbage

Plant dry weight (g per plant)

Figure. Allometric relations for cabbage and nightshade (Solanum nigrum). Parametersfrom table.

Page 86: Unisim Explained 2015-06-08

80 Chapter 5. Conductance model

The question is what the net result of these differences in traits will be on the outcome ofcompetition. To address this problem we will do two experiments with the model:one simulationwith cabbage only and one with cabbage in competition with nightshade. The model XML filesto set up these simulations are found in the xml/models/conductance folder inside yourUniSim root folder.

Now is time to start the UniSim software and open the cabbage.xml file.You can see fromthe model diagram, that shows up when you open the file, that the simulation has four modelsinside it:

UniSim::Simulation

UniSim::TimeStepLimited

UniSim::Calendarcalendar

conductance::Weatherweather

conductance::Communitycommunity

conductance::Plantcabbage

The models include a Calendar to keep track of time. Calendar is part of theUniSim package, as shown by the namespace qualification UniSim before its class nameUniSim::Calendar. In addition we find as expected, a Weather model and a Communitymodel to hold one or two Plant models. In this example only one Plant model, named cab-bage, is presemt.

Try running (click the Simulation | Run menu) a simulation with cabbage alone (in filecabbage.xml) and together with nightshade (in file cabbage-nightshade.xml). Verify thatthe plots shown on screen makes sense. You can also study the output found in the output textfile, found in the folder you chose for output files.

To change the parameter values just open the XML file with a text editor such asNotepad++. There is no need to close the UniSim program while you are editing the file.Save theXML file in the editor when you are finished editing the parameters (let the editor remain opentoo, for your convenience) and swap to UniSim where you click the File | Reopen menu to readthe XML file again and thus obtain the changed parameter settings. Run the simulation again andstudy the output. You can swap between the editor and UniSim as you please keeping any XMLfiles open all the while.

5.5. Discussion

The Conductance model simulatesonly the growth of plants not their physiological development.It would be quite simple though to add another model for plant development, say a day-degreemodel for the period from emergence to flowering. At flowering growth would stop for species

Page 87: Unisim Explained 2015-06-08

5.5. Discussion 81

with determinate growth. For species with indeterminate growth, growth would continue maybeuntil the first frost which could easily be pulled from a weather log file. A simple harvest modelwould set harvest at a fixed date which would be the end of the story for many plants, even thoughsome weeds would re-grow from a stubble field.

In short, the Conductance model nicely encapsulates a period of plant growth in the field.This makes it very easy to combine with other models.

Page 88: Unisim Explained 2015-06-08

Chapter 6. The INTERCOM model

The INTERCOM model, which simulates photosynthesis in a mixed-species canopy, is well-described in the free online book by Kropff & Laar (1993). The book describes the principlesand mathematics of the model and, in addition, contains the full FORTRAN source code, mostnotably functions TOTASS (pp. 237-238) and ASSIMC (pp. 225-229). It is not a complex model,yet the mixture of biology, physics, mathematics and FORTRAN coding can be overwhelming.Here I will first describe the INTERCOM photosynthesis model in prose before presenting a newimplementation of the model in C++.

In section 6.1, the description given by Kropff and Laar is expanded with additional detailsand with explanations of what was left implicit in the book. This exposition contains no codeor mathematics. The illustrations were all generated with R scripts (download) which optionallycan be studied further. The R code is equivalent to the FORTRAN code of Kropff and Laar. Youshould read both the book and the treatise here, possibly twice.

In section 6.2, I explain how INTERCOM was re-implemented in C++ as a UniSim plugin.The original FORTRAN code was completely refactored (=reorganised) into an object-orientedand pluggable framework.This makes the UniSim version easier and more flexible to re-use.TheR code served the purpose of verifying the correctness of the C++ code.

6.1. Light absorption explained

The amount of energy radiated from the sun that would reach 1 2m of the earth surface, if therewere no atmosphere, is called ’Angot’s value’. This value depends on the solar constant (theamount of solar energy intercepted by earth) and the elevation angle (height) of the sun, so itvaries according to both latitude and day of the year. Units in common use are 2MJ/m /d and

2W/m . Remember that W equals J/s. Angot’s value is bimodal around the equinoxes near equatorand unimodal around the summer solstice at higher latitudes (unimodal around the wintersolstice on the southern hemisphere). INTERCOM measures Angot’s value in 2MJ/m /d units.

Angot’s value2[MJ/m /d]

0 100 200 300

0

10

20

30

40 2[W/m ]

0 °

30 °N

60 °N

Day of year

0

100

200

300

400

500

82

Page 89: Unisim Explained 2015-06-08

6.1. Light absorption explained 83

A weather station will usually register total daily irradiation per 2m . But to calculate dailyphotosynthesis we need more detailed information than that: How much of the irradition isdiffuse and how much is direct? How is irradiation distributed over the day?

The fraction of light that gets dissipated and thus turns diffuse depends on the atmosphere,foremost the cloud cover. However, there exists an empirical relation between the fraction oflight that gets through the atmosphere (i.e. the irradiation measured by the weather station inproportion to Angot’s value) and the fraction of light that is diffuse.

Fraction of

diffuse light

[0;1]

0 10 20 30 40

0.0

0.2

0.4

0.6

0.8

1.0

Measured irradiation 2[MJ/m /d]

The figure show this relation at 55 °N on Julian day 120. The fraction of diffuse light decreaseswith increasing measured irradiation, from 100% at low light levels to a minimum of 23% whenthe light is most intense.

The course of light intensity over the day goes from zero at sunrise to a maximum at midday,when the sun is in zenith, and then down to zero again at sunset. The measured irradiation is theaverage over the whole day, and it follows that the maximum intensity will be larger than themeasured daily average. Hours in this context are astronomically defined, irrespective of timezones and daylight saving schedules. Only part of the sunlight is in the frequency spectrumutilized by photosynthesis. This photosynthetically active radiation (PAR) comprises half of thetotal sunlight energy.

PAR

[W per 2m ground]

0 6 12 18 24

0

100

200

300

total

direct

diffuse

Time of day [h]

Page 90: Unisim Explained 2015-06-08

84 Chapter 6. The INTERCOM model

The figure shows the course of indirect, direct and total PAR at 55 °N on Julian day 120 with ameasured irradiation of 20 2MJ/m /d (231 2W/m , since 1W = 1J/s).A rough numerical integrationto calculate the average total PAR from this figure yields 115.7 2W/m (9.996 2MJ/m /d),corresponding to half of the measured irradiation, as expected. INTERCOM measures PAR in

2W/m units.

To calculate photosynthesis we must integrate over the whole day from sunrise to sunset.To speed up this calculation INTERCOM applies Gaussian integration. For this, every day, therate of photosynthesis needs only to be calculated three times during the afternoon. The totalphotosynthesis over the whole day is then calculated as a weighted average of these three pointvalues. The specific times will vary according to latiude and day of the year. At 55 °N on Julianday 120, for example, photosynthesis will be calculated on 12:50h, 15:43h and 18:58h. Theweights attributed to these are fixed (0.28, 0.44 and 0.28) and sum up to 1.

The density and structural characteristics of the plant canopy are important for the resultingphotosynthesis. First we will consider a canopy consisting only of the leaves of one species.Later we will generalize this to any number of organs and any number of species. The verticaldistribution of leaf area can be summarized by an equation, such as a parabola, which will yielda symmetric distribution of area on the vertical axis.

Leaf density2[m leaf per 3m space]

0.0 0.2 0.4 0.6 0.8 1.0

0

1

2

3

4

5

Height above ground [m]

Described this way, the variable actually is a leaf density measured in 2m leaf per 3m space. In thisexample, maximum plant height was set to 1 m and the total leaf area index (LAI) of the canopywas set to 3. The leaf density at 0.5 m is larger than 3 -1m , so if the canopy was this dense all over,LAI would be larger than 3. But at the bottom and the top of the canopy, this is compensated forby a leaf density smaller than 3 -1m , so it all adds up to LAI equal to 3.

If we integrate leaf density vertically, accumulating the total leaf density from a certainheight above the ground and up to the top of the canopy, we arrive at the LAI above that height.After factoring in the vertical integration in meters, we get the proper LAI units of 2m leaf per

2m ground.

Page 91: Unisim Explained 2015-06-08

6.1. Light absorption explained 85

LAI above height2[m leaf per 2m ground]

0.0 0.2 0.4 0.6 0.8 1.0

0

1

2

3

Height above ground [m]

To model photosynthesis down through the canopy, we must integrate photosynthesis fromthe top of the canopy downwards. To achieve this INTERCOM again uses Gaussion integrationbut, in stead of calculation at 3points as for PAR during the day, we need 5 points to obtain properprecision. The 5 points are located at 5%, 23%, 50%, 77% and 95% of maximum plant height.Their weights (0.12, 0.24, 0.28, 0.24 and 0.12) again add up to 1 for the weighted average, whichis a mathematical approximation of the integrated photosynthesis over the whole canopy.

We are now all set to begin the actual calculation of light absorption and CO2 assimilation:We know the latitude, day of the year, time of the day, diffuse and direct PAR, and the LAI aboveand the leaf density at a certain height in the canopy. We must repeat the calculation 15 times tocover the 3 integration points during the day and 5 integration points down the canopy. In the endwe add all the calculated light absorption and assimilation rates, applaying the pertinent weightsof Gaussian integration and end up with the total light absorption and assimilation of the day.

First we make a further subdivision of the incoming direct light, which we now call ’totaldirect light’. The part of direct light that is directly absorbed as such by the leaf we call ’direct-direct light’. The remainder is dispersed and results in secondary diffuse light. The extinctioncoefficient of the leaves can be measured empirically under 100% diffuse light and is then calledkdf . The extinction coefficients for total direct light (kdr,t) and for direct-direct light (kdr,bl) bothdepend on sun height and thus on latitude, day of the year and time of the day.

Extinction

coefficient

[-]

0 6 12 18 24

0

2

4

6

8

Type of light:

diffuse

direct-direct

direct total

Time of day [h]

In this example, it can be seen that direct light is extinguished effectively when the sun is low.

Page 92: Unisim Explained 2015-06-08

86 Chapter 6. The INTERCOM model

So, when the sun is low, whatever little direct light there is, dies out quickly in the canopy.

The light penetrating to a certain level in the canopy decreases exponentially with theeffective LAI above that level. The effective LAI is the LAI times the extinction coefficient(page 36 in Kropff & Laar 1993). For reasons explained further down we will instead call thisthe effective extinction. Anyway, we can calculate the rate of light penetration for all three kindsof light, applying the appropriate extinctions coefficient. However, a fraction of the light isimmediately reflected by the canopy and is thereby not available for absorption. Leaf reflectancediffers for the three kinds of light but, surprisingly, can be assumed equal for all plant species.It has a fixed value for diffuse and direct-direct light whereas it depends on sun height for thedirect-total light.

Leaf

reflectance

[-]

0 6 12 18 24

0.0

0.05

0.1

0.15

0.2

Type of light:

diffuse

direct-direct

direct total

Time of day [h]

The light available at any height in the canopy can now be calculated from the total LAIabove that height and the pertinent extinction coefficients and reflectances. Here it is shown at15:43h, the second integration point of the day, keeping the parameter settings so far (20 2MJ/m /dof sun light impinging at 55 °N on day 120).

Available

light

[W per 2m ground]

0.0 0.2 0.4 0.6 0.8 1.0

0

20

40

60

80

100

Type of light:

diffuse

direct-direct

direct total

Height above ground [m]

To obtain how much of the available light is actually absorbed at any height in the canopy,we just need to multiply the available light with the pertinent extinction coefficients.

Page 93: Unisim Explained 2015-06-08

6.1. Light absorption explained 87

Light

absorption rate

[W per 2m leaf]

0.0 0.2 0.4 0.6 0.8 1.0

0

20

40

60

80

100

Type of light:

diffuse

direct-direct

direct total

Height above ground [m]

The diligent reader will have noticed that the units changed from available W per 2m groundto absorbed W per 2m leaf (eq. 4.12 in Kropff & Laar (1993)). How could this be accomplishedby multiplication with the extinction coefficient, which is after all unitless? Well, consider thenegative exponential law of light extinction: exp ( − k × LAI ). If we consider LAI unitless, kbecomes unitless by implication. But if we consider LAI in 2m leaf per 2m ground then k musthave the inverse dimension, 2m ground per 2m leaf. And, if we apply this dimension as wemultiply with k to go from light availability per ground area to light absorption per leaf area, theunits work out nicely.

To calculate the light absorption rate of ’shaded leaves’ (Ia,sh), i.e. leaf area not struck bylight directly, we take from above the absorption of diffuse light (red curve) and add to thatabsorption of secondary diffuse light, which is simply the difference between the absorbed totaldirect light (yellow curve) and direct-direct light (blue curve). This yields the red curve below.

Light

absorption rate

for shaded leaves

[W per 2m leaf]

0.0 0.2 0.4 0.6 0.8 1.0

0

20

40

60

80

100

Assimilation rate

for shaded leaves

[kg CO2 per ha leaf

per hour]

Height above ground [m]

0

10

20

30

40

50

Photosynthesis turns assimilated CO2 into carbohydrates using the energy of the absorbedlight. In INTERCOM the assimilation rate is expressed in the (akward, you may think) unitsof kg CO2 per ha leaf per hour. The light response curve, which converts absorbed light intoassimilated CO2, is defined by the conversion efficiency ε (kg CO2 per ha leaf per hour per (Wper 2m leaf)’) and the maximum assimilation rate Amax (kg CO2 per ha leaf per hour); ε can also

be expressed in more intuitive units, such as g CO2 per MJ, by multiplication with 6+310 4/10 2/60= 27.78.

Page 94: Unisim Explained 2015-06-08

88 Chapter 6. The INTERCOM model

Assimilation rate

[kg CO2 per ha leaf

per hour]

0 100 200 300 400 500

0

10

20

30

40

50

Light absorption rate [W per 2m leaf]

The curvature of light saturation causes assimilation (blue line above) to be less efficient towardsthe top of the canopy where light is most intense. The parameters ε and Amax vary with plantspecies, leaf quality and environmental conditions. Storkey (2005) determined the empiricalrelationship between ε and Amax and temperature (T):

ε = − 0.0095T + 0.635Amax = 50(1 − T0.882 )

We used these relations here, applying the values at 20 °C, ε = 0.445 kg CO2 per ha leaf per hourper (W per 2m leaf) and Amax = 45.9 kg CO2 per ha leaf per hour. The upper limit on Amax was setto 50 kg CO2 per ha leaf per hour, whereas in the original paper it was operating in other units.

The calculation of light absorption by ’sunlit leaves’ is more complicated because the ab-sorption rate depends on the angle of the leaf surface with respect to the sun.The leaf distributionis assumed to be spheric which means that all leaf angles are equally represented; one can thinkof the green area in the canopy as a uniform, green sphere, the intensity of green correspondingto the LAI. The light flux hitting this sphere perpendicularly, relatively to the light flux hittingthe ground (the measured direct PAR per ground 2m ), depends on the height of the sun. At theequator at noon the two fluxes are equal but at lower heights of the sun, the relation shifts (inproportion to the shadow that the sphere would cast) while at the same time the intensity of sun-light drops.

The net effect can be seen here at 55 °N on Julian day 120. As both sun height and sun lightapproaches zero, the perpendicular light intensity approaches zero divided by zero; hence, it isshown only from early morning until late afternoon.

Page 95: Unisim Explained 2015-06-08

6.1. Light absorption explained 89

Incoming

perpendicular PAR

[W per 2m leaf]

Incoming

direct PAR

[W per 2m ground]0 6 12 18 24

0

100

200

Time of day [h]

The calculated rate of light hitting perpendicularly can be used to calculate the absorptionrate of the whole canopy, which will be hit at all angles, according to the spheric leaf distributionassumption. This integration over all leaf angles is carried out in INTERCOM using a 3-pointGaussion integration. To get the total absorption rate of sunlit leaves, we must add to this, theabsorption rate of diffuse light, which will be the same as calculated above for shaded leaves.

Finally, this total light absorption rate of sunlit leaves is turned into an assimilation rateby the same light saturation curve as for shaded leaves, exemplified here at 15:43h, the secondintegration point of the day.

Light

absorption rate

for sunlit leaves

[W per 2m leaf]

0.0 0.2 0.4 0.6 0.8 1.0

0

50

100

150

Assimilation rate

for sunlit leaves

[kg CO2 per ha leaf

per hour]

Height above ground [m]

0

20

40

60

Knowing the absorption and assimilation rate for both shaded and sunlit leaves, we onlyneed to divide the leaf area into these two proportions. Assuming a random distribution of leafarea, the proportion of sunlit leaves is simply the negative exponential of the leaf area indexweighted by the extinction coefficient for direct-direct light (kdr,bl; ’bl’ is for black which makessense in this context, since we are calculating the area not obstructed by leaves).

Continuing our example from 55 °N, Julian day 120, we get this profile of direct sunlightfilering down through the canopy at 15:43h.

Page 96: Unisim Explained 2015-06-08

90 Chapter 6. The INTERCOM model

Fraction sunlit

leaves [-]

0.0 0.2 0.4 0.6 0.8 1.0

0.0

0.2

0.4

0.6

0.8

1.0

Height above ground [m]

Now, at any height we know both the fraction of shaded and sunlit leaves and their rates ofabsorption and assimilation.We can obtain the net total light absorption and CO2 assimilation atany height in the canopy, as the sum of the contributions from shaded and sunlit leaves, weighedby their fraction of the the total. We get curves that go from the rates of sunlit leaves at the topof the canopy to the most shaded leaves at the bottom.

Light

absorption rate

of leaves total

[W per 2m leaf]

0.0 0.2 0.4 0.6 0.8 1.0

0

50

100

150

Assimilation rate

of leaves total

[kg CO2 per ha leaf

per hour]

Height above ground [m]

0

20

40

60

But these rates are still per leaf area.To proceed we have got to convert them to a per groundarea base. For that purpose we multiply the rates down the canopy with the leaf density 2(m leafper 3m space) at that height. To convert from leaf density to leaf area index, we also multiplywith plant height (set to 1 m, in this example). Thus the units per leaf area in the figure aboveare multiplied with 2m leaf per 2m ground or, equally, ha leaf per ha ground, which yields theunits per ground area in the figure below. Since we chose a parabolic model of leaf density,the resulting rates turn out quite small at the top of the canopy, because leaf density here isquite small.

Page 97: Unisim Explained 2015-06-08

6.1. Light absorption explained 91

Light

absorption rate

of leaves total

[W per 2m ground]

0.0 0.2 0.4 0.6 0.8 1.0

0

100

200

300

400

500

Assimilation rate

of leaves total

[kg CO2 per ha ground

per hour]

Height above ground [m]

0

50

100

150

200

250

At this point you may have forgotten what the points are used for: They are used as ashortcut to integrate the curves via Gaussion integration. If you leaf back through the figures,curves with 5 points on them, really exist in 3 versions, one for each integration point during theday. And curves with 3 points on them, really exist in 5 versions, one for each integration pointthrough the canopy. To arrive at the total amount of light absorption and CO2 assimilation forthe whole canopy and the whole day, we need to integrate these 15 curves, first over the canopyand then over the day.

In our example, integration over canopy height yields this course of the whole-canopy rateduring the day.

Light

absorption rate

for leaves total

[W per 2m ground]

0 6 12 18 24

0

100

200

300

Assimilation rate

for leaves total

[kg CO2 per ha ground

per hour]

Time of day [h]

0

50

100

150

Taking the integration one step further, using the 3 Gaussion points to integrate these curvesover the day, we arrive at a light absorption rate of 156.74 W per 2m ground and an assimilationrate of 42.23 kg CO2 per ha ground per h. To factor out time and arrive at the finite rates per day,we must multiply by daylength (14.84 h, in this case). Thus we arrive, finally, at the end of thecalculations with 8.37 MJ absorbed per 2m ground and 641.42 kg CO2 assimilated per ha ground.This should be held up against the total daily irradiation, set at 10 MJ PAR per 2m ground inour example.

Let’s congratulate ourselves with this achievement! But… we are not quite finished yet. Inour canopy model we limited ourselves to consider only one population, namely that of a pop-ulation of leaves with a parabolic vertical distribution. But in reality a canopy may consist ofany number of plant organ populations, leaves, stems, flowers, fruits, belonging to one or morespecies. We must take a deep breath, retrace our steps and go through the logic right from the

Page 98: Unisim Explained 2015-06-08

92 Chapter 6. The INTERCOM model

beginning and see, which calculations would need to be changed to accomodate a multi-popula-tion canopy.

Our first discovery is the leaf density to height relation. There will, in general, be one suchrelation, particular to each population present and possible of different shape, total LAI, andmaximum height.Consequently we must imagine the canopy as a multitude of such curves.Let’sconsider three populations.

Leaf density2[m leaf per 3m space]

0.0 0.2 0.4 0.6 0.8 1.0

0

1

2

3

4

5

Height above ground [m]

Each curve translates easily into the cumulative curve of that population’s LAI above a certainheight .

LAI above height2[m leaf per 2m ground]

0.0 0.2 0.4 0.6 0.8 1.0

0

1

2

3

Height above ground [m]

The light available down through the canopy still decreases exponentially with the totalLAI above any particular. The only difference in the multi-population case is that the effectiveextinction (k × LAI) must be summed for all populations, applying their pertinent extinction co-efficients.

The remaining calculations will remain, irrespective of the number of populations present.The calculations just need to be repeated for each population to arrive at its daily finite rates oflight absorption and CO2 assimilation. It is a minor step then, in the end, to add up the finite dailyrates of light absorption and CO2 assimilation for each species, summing up the contributionsfrom the populations of plant organs belonging to that species.

Page 99: Unisim Explained 2015-06-08

6.1. Light absorption explained 93

To finish the story, we must subsequently turn the daily rate of CO2 assimilation into adaily rate of biomass accumulation. This is achieved first by multipliction with 30/44 which isthe photosynthetic exchange rate from CO2 to CH 2O (carbohydrates, "sugars"). Part of thesecarbohydrates is lost immediately to maintenance respiration while the rest is distributed amongthe plant organs, according to the prevailing allocation scheme. But even the actual incorporationof those carbohydrates comes at a cost, growth respiration, before the remainder is finally boundas plant biomass. All this logic can be expressed straightforwardly in C++, as will be shown inthe following.

6.2. Light absorption refactored

We view a multispecies plant community as a composition of structural levels: community,plant populations, plant organs and organ sub-components. This example shows the resultinghierarchy in a community of just two populations, a crop and a weed:

community

wheat

height leaves

area mass

stem

area mass

grains

area mass

root

mass

cheal

height leaves

area mass

stem

area mass

root

mass

Each of the boxes correspond to an object in the running model, and each arrow denotea parent-child relationship. In this case the crop is composed of four organs and the weed ofthree organs. The green organs each hold an object representing its area. All organs in additionholds a mass. Both plants also hold an object to keep track of plant height. The areas have beenemphasized with a green background.

If we look at the classes these objects belong to, we can see that we need a total of six classesto define this model (Community, Plant, Height, Organ, Area and Mass):

Community

Plant

Height Organ

Area Mass

Organ

Area Mass

Organ

Area Mass

Organ

Mass

Plant

Height Organ

Area Mass

Organ

Area Mass

Organ

Mass

To be continued …

Page 100: Unisim Explained 2015-06-08

Chapter 7. Student projects

The student projects are the results of the students’ efforts to build their own plugin models forUniversal Simulator under the supervision of Niels Holst, Aarhus University, Denmark. Themodels are documented here in the students’own words and are all easily accessible, as they formpart of the standard installation of Universal Simulator.

Note: My original thought was that all student models eventually would be added to thischapter. I have since then realised that this leads to update problems that cannot be resolved. So,here are two models presented by the brave students attending the first year (2011) the modellingcourse was run.

7.1. Lake oxygen model

Anders Nielsen,Aarhus University,Denmark [[email protected]]

7.1.1. Introduction

Net community production (NCP), defined as the difference between gross primary production(GP) and total (algal (RA) plus heterotrophic (RH)) community respiration (RT), derives definesthe metabolism of a biological community (Wetzel 2001). Unfortunately, measurements ofGP and RT and the derived NCP is relatively time consuming. For that reason empirical orstatistical relationships between easily and low cost measurements and NCP is of particularinterest. Such empirical relations have been developed in oceanography (see Serret et al. 2009),whereas compilation of similar relations for freshwater lakes according to our literature reviewis very limited. We have conducted a statistical analysis of a comprehensive high frequency dataset from 24 mesocosms including easily obtainable measurements and NCP and compiled anempirical relation to derive NCP for a given lake. The statistical analysis is still in progress andcalculations of NCP by the UniSim plug-in should only be trusted as a broad term estimate.

Data for the statistical analysis is based on work conducted by Liboriussen et al. 2010,where GP and RT haves been calculated on a 30 minute time step for a 5 year period from 2003to 2008. Data has been sampled from 24 mesocosms designed as cylindrical stainless steel tanks1.9 m in diameter and a water depth of 1 m simulating 2 nutrient levels with 3 temperatures in 4replicates. More details about design and set up of the mesocosms, see Liboriussen et al. 2005.

7.1.2. Calculations

In the following a brief description of the calculations and description of required variableswhen using the UniSim plug-in is presented. For overview of the different required variables seeTable 7.1. The variables must be given on a daily time step.

Dissolved Oxygen Concentration Saturation Percentage

The saturation concentration of oxygen is a function of primarily temperature. Calculation of

94

Page 101: Unisim Explained 2015-06-08

7.1. Lake oxygen model 95

Table 7.1. Variables necessary as input to perform calculations. An example of the input textfile is given in the UniSim weather folder (LakedataOBS2004-2005.txt).

Name Unit Variable name

Date [dd/mm/yyyy] date

LakeID [-] LakeID (ignored)

Oxygen concentration [mg -1l ] obsDO

Water temperature [°C] tempw

Daily Light Integral [mol -2m -1d ] obsDLI

Wind speed -1m wind

saturation concentration is done according to American Society of Civil Engineering Committeeon Sanitary Engineering Research (1960):

DOsat = 14.652 − 0.41022Tw + 0.0079910 2Tw − 0.000077774 3Tw

Where

DOsat: Dissolved oxygen saturation concentration [g -3m ]

Tw: Water temperature [°C]

Percentage of Saturation

Afterwards the percentage of saturation for a given observed dissolved oxygen concentration iscalculated according to the following simple equation:

DOsat,obs = 100DOobs

DOsat

PAR (Photosynthetically Active Radiation)

PAR (Photosynthetically Active Radiation), wavelength 400-700 nm [μmol -2m -1sec ] is a key pa-rameter in plant growth through the processes of chlorophyll synthesis and photosynthesis whichresult in the conversion of radiant energy into chemical energy. Thus availability of PAR radi-ation is an important factor for primary production in aquatic systems like lakes (Wetzel 2001).Unfortunately PAR is often not available as a widespread measurement at any spatial location.However PAR can be calculated as a constant ratio or function of the broadband solar radiationif no measurements are available (Jellison & Melack 1993, Alados & Alados-Arboledas 1999,Udo & Aro 1999). The UniSim plug-in needs information about PAR given as Daily Light Inte-gral [mol -2m -1d ]

Day Length

The day length is calculated in the UniSim package by the Calendar model (see page 145) as

Page 102: Unisim Explained 2015-06-08

96 Chapter 7. Student projects

a function of day number of the year (Julian day) and the latitude. The user of the lake oxygenplug-in needs to specify the latitude of location in the xml file. For further information aboutcalculation of the day length, see Kropff & Laar 1993.

Net Community Production Equation

Based on a statistical analysis we have compiled a multiple linear regression with satisfactorysignificant explained variation 2(R =0.253, N=24,738, F=4190, P<0.001). The equation ispresented below:

NCP = 0.014DOsat,obs + 0.0022DLI − 0.081DayLength − 0.787

Where

NCP: Net Community Production [gO2-2m -1d ]

DOsat,obs: Dissolved Oxygen Concentration Saturation Percentage [%]

DLI: Daily Light Integral [mol -2m -1d ]

DayLength: [hours]

This prediction equation is implemented into the UniSim lake plug-in and calculates the NCPbased on lake specific inputs.

7.1.3. Predicting NCP in Real Lakes

When extrapolating the NCP model from mesocosms to real lake data, changes in system propor-tions and factors controlling governing processes must be considered. One process is the systemexchange of oxygen between water column and overlaying atmosphere (Odum 1956). Lake oxy-gen reaeration is primarily controlled by wind speed (Banks & Herrera 1977, Gelda et al. 1996),while the mesocosms reaeration are generated from constantly mixing by artificial steering(Liboriussen et al. 2005). The UniSim lake oxygen plug-in is developed to calculate the NCP forreal lake and not mesocosms, thus we have implemented the opportunity for the user to adjustthe reaeration coefficient to fit a given lake.

Several empirical relations has been publish where reaeration coefficientis estimated from wind speed as only important parameter (Liss 1973, Emerson 1975,Banks & Herrera 1977, Deacon 1977, Mattingly 1977, O’Connor 1983, Wanninkhof et al. 1985,Boyd & Teichert-Coddington 1992, Livingstone & Imboden 1993, Portielje & Lijklema 1995,Gelda et al. 1996, Gelda & Effler 2002, Crusius & Wanninkhof 2003). Thus, we have used theempirical relation published by (Banks & Herrera 1977). Based on this relation the UniSim plug-in calculates a lake specific reaeration coefficient from wind speed (see Table 7.1).

The system reaeration coefficient for the mesocosms in Lemming (KL,mes) is estimated to

0.22 m -1d by Liboriussen et al. 2010. The Plug-in then use linear scaling, computed from theratio KL,lake / KL,mes between mesocosms system reaeration coefficient and the individual lakespecific reaeration coefficient (KL,lake) estimated from wind speed, to correct our NCP model to

Page 103: Unisim Explained 2015-06-08

7.1. Lake oxygen model 97

individual lakes.

Furthermore the user can specify a range for the KL,lake parameter used as input to astochastic number generator generating the coefficient KL,lake,Random. This coefficient is alsoused to calculate a NCP from linear scaling by the ratio KL,lake,Random/KL,mes. Thus the user canview different estimations of the NCP where uncertainty on the reaeration coefficient implicitis included.

If the user has limited knowledge about a lake specific system reaeration coefficient,estimations from wind is the best approach. For that reason we derive the average reaerationcoefficient estimated from wind speed and present it in a plot (see section about plotting). Basedon this particular plot, the user can set the ranges for the stochastic number generator and therebyquantify the NCP in a broader range and implicit account for uncertainty.

The reason why so much effort is put into this module is that the reaeration coefficient asparameter is difficult to measure directly and thereby is uncertain to estimate as well.

7.1.4. Unit of output

Daily accumulated NCP is default calculated as mass oxygen production per square metersurface area per day [gO2

-2m -1day ], however, the user can choose to change the unit to carboninstead by taking into account the difference in atom mass between oxygen and carbon. This iseasily done by simply changing the parameter unit from 1 (oxygen) to 0 (carbon) in the modelXML file.

7.1.5. Setting the stochastic sampling number

In the model XML file the user can specify the number of iterations one batch model runperforms. Control of this parameter is of use if any post hoc statistical analysis is conducted.By default the model performs 30 single runs in each batch where the reaeration coefficient ischanged each time within the user specified range (min and max for the stochastic samplingrange is also set in the XML file).

7.1.6. Plotting

WHen the simulation is run, output appears in several plots on the screen. Below their meaningis explained.

Lake environment

Lake environment is an overview of the observed parameters: Daily Light Integral (DLI), windspeed and Day length, variables classified as outer variables in respect to the lake as system. Theplot is simply graphs drawn from the input file where all variables are given on a daily time step,but is presented to give the user overview.

Observations

Observations is an overview of the in-lake observed parameters: oxygen [mg -1l ] and watertemperature [°C] read from the input file and given on a daily time step.

Averaged estimated reaeration coefficient (from wind speed)

Page 104: Unisim Explained 2015-06-08

98 Chapter 7. Student projects

If the user has no knowledge about the reaeration coefficient for a specific lake, a value computedfrom wind speed is the best estimate. Thus by looking at the average plot the user can then gethelp to estimate the stochastic sampling range for the reaeration coefficient.

Net community production

Net community production presents two graphs (1) NCP (KL estimated from wind) and (2) NCP(KL stochastic). (1) is the NCP where corrections in respect to reaeration coefficient is computedfrom wind speed (see Table 7.1) whereas (2) is the NCP where corrections in respect to reaerationcoefficient is computed as and stochastic sampling process based on a user defined range.

Parameter

The stochastic sampling of parameter values for the reaeration coefficient based on a userdefined range is presented in the Parameter plot where each individually sampled value is plotted,thus the user can view the actually sampled values.

Accumulated Net Community Production

The UniSim lake oxygen plug-in calculates NCP on a daily basis. However, for comparablereasons the present calculations is summarize from daily values to an accumulated yearly netcommunity production. Following the curve, the accumulation is reset at the first of January eachyear and thereby gives the yearly calendar net community production.

7.1.7. Output from the model

In the XML file output from the lake oxygen model is specified. The model automatically createsan output file containing all parameters necessary for the calculations as well as calculated valuesof dissolved oxygen concentration saturation percentage, net community production (both withcorrections where reaeration coefficients are estimated from stochastic sampling and from windspeed, respectively). The UniSim model creates one file for each stochastic parameter estimate,which can be used for post hoc statistical analysis.

Page 105: Unisim Explained 2015-06-08

7.2. Microbial community model 99

7.2. Microbial community model

Yun-Feng (Kevin) Duan,Aarhus University,Denmark [[email protected]]

7.2.1. Introduction

Microbial community model simulates the composition and activity of microbial communities.It is composed of a series of sub models, each simulating one aspect of the complex of microbialcommunity. For example, population model mimics the population of a microbial species andits growth, competition model imitates the competition for common resources, reaction modelsemulates microbial metabolic activities, and effect model reproduces the effect of environmentalfactors. These models can be combined together to simulates the facets of interest of themicrobial community under study. Furthermore, microbial community model offers the abilityto construct communities stochastically. This feature is very useful in exploring how communitystructure affects community function and response to stress.

7.2.2. Population model

Population is the basic structural unit of a community. Similarly, the Population model is thebasic building block of more complicated community models. Population model describessome of the important parameters of a microbial population, e.g. species name, initial density,growth rate, mortality rate, metabolic dynamics, etc., and these parameters are used by othermodels to simulate microbial activities.

Prerequisite

A UniSim::Calendar model with the name calendar must be placed in the XML file. Thismodel is required by Population model.

7.2.3. Population Growth

The Populationmodel is to be used in combination with other models, so it cannot do anythingon its own, except for growth. The growth of a population is characterized by parametersGrowthRate (g) and MortalityRate (m), and the observed growth rate is:

ΔnΔt

= n × (g − m)

where n is the current density of the population. As long as g > m, the growth will follow anexponential curve (Fig. 7.1, Left).

In real world situations, the growth of a population is limited by available environmentalresources so the population cannot grow indefinitely and will eventually reach a plateau (Fig. 7.1,Right). This kind of growth is called logistic growth, and can be easily simulated by introducinga new parameter CarryingCapacity (C). In that case, the observed growth rate becomes:

ΔnΔt

= n × [g × (1 − n/C) − m]

Page 106: Unisim Explained 2015-06-08

100 Chapter 7. Student projects

When CarryingCapacity is set to a positive value, the Population model would behaveaccording to logistic growth; when it´s set to 0 or a negative value, exponential growth will bepresented instead. Note that Population model assumes infinite supply of resource duringgrowth (which means you will never see a decrease of density as long as g>m); to simulategrowth under limited resource, a Competition model should be introduced.

Demonstration

Model definition file Demo_PopulationGrowth.xml demonstrates exponential and logisticpopulation growth.

Model Parameter Value Remarks

Population InitialDensity 1000

Growthrate 0.03

MortalityRate 0.01

CarryingCapacity 0 For exponential growth

CarryingCapacity 10000 For logistic growth

Figure 7.1. Simulated population growth. Left: exponential growth; Right: logistic growth.

7.2.4. Competition Model

Competition model simulates the growth of one or more populations under competition for acommon resource of limited supply. To enable the model, simply set parameter EnableCompe-tition to True, and define the amount of available resource at the beginning of competition inparameter InitialResource. It is possible in future development to select what competitionmodel to be used, but for now only one model (the Gutierrez-Baumgärtner functional responsemodel) is available. Each population is considered a consumer for the common resource in thecompetition.For each consumer to sustain itself, a certain amount of resource is required,and this

Page 107: Unisim Explained 2015-06-08

7.2. Microbial community model 101

is called "demand".Demand of the i´th consumer (ΔDi) in time Δt is dependent on the populationdensity (ni) and the demand rate (δi), and is defined as:

ΔDi = ni δi Δt

However, in a limited environment, the demand of each consumer may not be realized due to theconsumer´s inability to acquire resource or the insufficiency of resource. So, in the case of nointerspecific competition, the actual resource consumed by the i´th consumer (ˆconsumption˜,noted as Δ Ri), is dependent on the consumer´s ability to find the resource (determined bysearch rate αi), and the available resource in the environment (R). ΔRi can be modelled by theGutierrez-Baumgärtner functional response model (Gutierrez 1992):

ΔRi = Di × (1 −−αiR

ΔDie )So, the actual growth of the i´th consumer is now dependent on its demand and consumption,which can be characterized by the supply/demand ratio:

φi =ΔRi

ΔDi= 1 −

−αiR

ΔDie

And the observed growth rate for the i´th consumer becomes:

Δni

Δt= ni × (gi × φi − mi )

Note that in the presence of a Competition model, the carrying capacity for a population isimplicitly determined by the available resource S which is determined by the Competition

model, so exponential instead of logistic growth would be used.

With the introduction of supply/demand ratio φ, the observed growth rate could nowbecome negative, indicating decrease of population density (Fig. 7.2). It should be noted thatwhen the calculated population density drops below 1, Population model will return 0 as theoutput value. This ensures that population can "extinct"during competition since mathematicallythe progressive decrease of density would only approximate zero indefinitly but never reallyreach it. The total consumption of all consumers is:

ΔRtotal = ∑i

ΔRi

Page 108: Unisim Explained 2015-06-08

102 Chapter 7. Student projects

And the remaining resource R is updated in each step as:

R ← R − ΔRtotal

When R approaches zero, the calculated ΔRtotal could become greater than R. In that case weassume that the consumers exhaust the resource completely, dividing the remaining resourceamong them in proportion to ΔRi:

ΔRi ←ΔRi

ΔRtotal × R

Demand rate (δ) and search rate (a) are defined in Population model as parameters Deman-dRate and SearchRate; Competition model will try to inquire their values as well as thevalue of pull variable Density from Population model during simulation. Supply/demandratio (φ) is calculated by Competition model and sent back to Population model, and can beaccessed through pull variable SupplyDemandRatio. Remaining resource (R) can be accessedthrough pull variable AvailableResource from Competition model.

Demonstration

Model definition file Demo_PopulationGrowth.xml demonstrates exponential and logisticpopulation growth.

Model Parameter Value Remarks

Population InitialResource 10000

Population_1 InitialDensity 500

Growthrate 0.04

MortalityRate 0.01

SearchRate 0.01

DemandRate 0.02

Population_2 InitialDensity 1000

Growthrate 0.03

MortalityRate 0.01

SearchRate 0.015

DemandRate 0.03

7.2.5. Reaction Models

Examining the dynamics of microbial metabolic activities is an important part of microbialecology studies. Although the real situation could very well be much more complicated, in many

Page 109: Unisim Explained 2015-06-08

7.2. Microbial community model 103

Figure 7.2. Simulated competition of 2 populations. Left: the change of population (red and blue) andcommunity density (yellow); Right: the decrease of available resource

cases, these activities are reduced to simple enzymatic or chemical reactions, and they can besimulated by reaction models.

There is a group of different reaction models to suit different senarios. All reaction modelstake only one parameter InitialSubstrate. But during simulation, they will also try toinquire parameter values describing metabolic dynamics from Population models. Eachreaction model would inquire parameter(s) from Population model during simulation, and this isdescribed in each section respectively.

Reaction models send current reaction rate and substrate concentration as output and theycan be accessed through pull variables Velocity and Substrate respectively.

NOTICE: A model of the type MicrobialCommunity::Reaction does exist, but it isonly meant as the base model for implementation.The model Reaction should never be used inthe simulation.

EnzymaticReaction Model

The metabolic activities of microorganisms are catalyzed by enzymes, so the EnzymaticReac-tion model is the fundament of all other Reaction models.

An enzyme catalyzed reaction could take several substrates, but in studies ususally onlyone substrate is considered the limiting factor. For example, the monooxygenase in methane-ox-idizing bacteria (MOB) oxidizes methane to formaldehyde through a reaction that also requiresoxygen. But in an aerobic environment where MOBs are most active, oxygen is ample and theavailability of methane limits the reaction. So, in situations like this, the dynamics of microbialmetabolic activity can be simplified to single-substrate enzymatic dynamics,and can be describedby Michaelis-Menten equation (Fig. 3, Up-left):

V = ΔSDelatt

=Vmax × SKm + S

Page 110: Unisim Explained 2015-06-08

104 Chapter 7. Student projects

where V is the velocity of reaction,S is the substrate concentration,Vmax is the maximum velocityand Km is the Michaelis-Menten constant.

The integrated form of Michaelis-Menten equation describes how substrate concentrationdecreases over time (Fig. 3, Bottom-right, Red):

(S0 − S) + Km × ln(S0S ) = Vmax × t

EnzymaticReaction model would inquire two parameters from Population model:MaximumVelocity, which is corresponding to Vmax, and MichaelisMentenConstant,corresponding to Km.

ZeroOrderReaction Model

In certain cases, Michaelis-Menten equation can be approximated to simpler forms. If substrateconcentration S >> sKm, then V ≈Vmax, and Michaelis-Menten equation can be approximated tothe rate equation of zero-order reaction (Fig. 3, Up-right):

ΔSΔt

= k0 where k0 = Vmax

In a zero-order reaction, the substrate concentration decreases linearly over time (Fig. 3,Bottom-right, Blue):

S = S0 − k0t

ZeroOrderReaction model would inquire parameter ZeroOrderRateConstant (k0) fromPopulation model.

FirstOrderReaction Model

On the other hand, if S << Km, then V ≈Vmax

KmS, and Michaelis-Menten equation can be approx-

imated to the rate equation of first-order reaction (Fig. 3, Bottom-left):

ΔSΔt

= k1S where k1 =Vmax

Km

In a first-order reaction, the substrate concentration decreases along an exponential decay curveover time (Fig. 3, Bottom-right, Yellow):

Page 111: Unisim Explained 2015-06-08

7.2. Microbial community model 105

S = S0 × −k1te

FirstOrderReaction model would inquire parameter FirstOrderRateConstant (k1)from Population model.

Reaction by Several Populations

When there are several populations present in the environment that ultilize the same substrate, thechange of substrate concentration is simply calculated by adding together the substrate uptakeof each population:

ΔS = ∑i

ΔSi

Reaction with Changing Population Density

During prolonged experiment, the density of microbial population will likely to change. Forexample, in a incubation trial of MOB with methane for several weeks, MOB populations willgrow in numbers and this will lead to increased rate of methane oxidation. Reaction models cantake the change of population density into account and run simulations as accurate as possible.

Let´s say the initial population density is n0, and after time t the density becomes nt,and the change of density is Δ n. Since population density is positively correlated to enzymeconcentration, we can simplify the situation by treating density as enzyme cancentration directly.Then, by deducing Michaelis-Menten equation, we have:

V(n0)=

kn0 × S

Km + S

V(nt)=

knt × SKm + S

(Note: kn = Vmax)

From which we can define a density-activity coefficient ρ:

ρ =V(nt)

V(n0)

=nt

n0= 1 + Δn

n0

It is easy to see that in an enzyme catalyzed reaction, change of population density will affectVmax but not Km; and in zero- and first-order reactions, the effect is on k0 and k1.

It should be noted that the change of population is dependent on population growth.

Page 112: Unisim Explained 2015-06-08

106 Chapter 7. Student projects

Logistic growth or growth under competition should be used instead of exponential growth,which might generate unrealistic results.

In the case of changing population density, current reaction rate and substrate concentrationshould be accessed through pull variables VelocityPDD and SubstratePDD respectively.PDD stands for ˆPopulation Density Dependent˜.

Demonstration

Model definition file Demo_Reaction.xml demonstrates the activity of methane oxidationby a MOB population. Population density dependent reaction is demonstrated in a separate fileDemo_Reaction_PDD.xml, the result of which is not shown below.

Model Parameter Value Remarks

Population InitialDensity 1000

ZeroOrderRateConstant 25

FirstOrderRateConstant 0.004

MichaelisMentenConstant 800

MaximumVelocity 30

EnzymaticReaction InitialSubstrate 10000

ZeroOrderReaction InitialSubstrate 10000

FirstOrderReaction InitialSubstrate 10000

7.2.6. GeneralEffect Model

In microbial ecology studies, it is often to examine the effect of environmental factors onmicrobial activities, which could be either stimulative or inhibitory. Simulation of these effect isachieved by including an effect model.

To activate an effect model, the value of parameter EnableEffect should be set to True;then, parameter TargetPopulations determines the populations affected under the effect.TargetPopulations is flexible and can take several forms of input to suit different needs:

• All (or simply *): all populations are affected.

• AllBut:{List_of_Population_Models}: all populations are affected, except forthose given in the list.

• Specified:{List_of_Population_Models}: only those populations given in the listare affected. E.g. Specified:{Bacterium_1, Bacterium_2, Bacterium_3}.

• Random:{List_of_Population_Models}: a random group from those populationsgiven in the list are affected.

• Random:{Min, Max}: a random group from all populations with size ranging from Min

to Max are affected.Min must be equal to or greater than 1.

Page 113: Unisim Explained 2015-06-08

7.2. Microbial community model 107

Figure 7.3. Simulated microbial methane oxidation. Up-left, Up-rightBottom-left: dependence ofreaction rate on substrate concentration (enzymatic, zero order, and first order reaction); Bottom-right: thedecrease of methane concentration over time (Red:enzymatic reaction, Blue: zero order reaction, Yellow:first order reaction).

• Random:{All} or Random:{*}: a random group from all populations are affected. Thisis equivalent to Random:{1, Number_of_Populations}.

In each implementation of individual effect model, additional parameters are required in orderto perform respective simulation, and this is described in each section of the model.

NOTICE: A model of the type MicrobialCommunity::Effect does exist, but it isonly meant as the base model for implementation. The model Effect should never be used inthe simulation.

GeneralEffect Model

GeneralEffect is a simple implementation of Effectmodel which simulates the effect of anenvironmental factor on the properties of populations. A simple usage of the GeneralEffectmodel is to simulate the effect of temperature on the growth of microorganisms.

GeneralEffect has two additional parameters:TargetParameter and EffectRatio.TargetParameter determines which parameter of the Population models is affected, e.g.GrowthRate, MortalityRate, or MichaelisMentenConstant. The strength of the effect

Page 114: Unisim Explained 2015-06-08

108 Chapter 7. Student projects

is determined by EffectRatio, which can take the following forms of input:

• Uniform:{Value}: the strength is uniform among all populations and takes the valuespecified in the curly brackets.

• Range:{Min, Max}: the strength takes a random number between Min and Max.

• specified:{List_of_Values}: this can only be used when TargetPopulations

is set to Specified, and the list of values must contain the same number of items as thelist in TargetPopulations. Each affected population will take one value in the order ofappearance. You can even define a range for the value, but slightly different from the above,it should be written in the form of min-max. E.g. Specified:{0.2, 0.3-0.5, 0.6}.

Effect ratio is defined as the ratio of the parameter value under effect to the value without effect.So, effect ratio less than 1means the factor is inhibitory,while ratio greater than 1means the factoris stimulative, and equal to 1 means there´s no effect at all.

CompetitiveInhibition Model

CompetitiveInhibition implements the effect of a competitive inhibitor on enzyme-cat-alyzed reactions. Competitive inhibitor competes with the substrate for the active site of an en-zyme. In the presence of a competitive inhibitor, the Michaelis-Menten equation becomes:

V =Vmax × S

λKm + Swhere λ = 1 + [I]

KI

[I] is the concentration of the competitive inhibitor, and KI is the inhibition constant. As a result,CompetitiveInhibition model has two corresponding parameters: InhibitorConcen-tration and InhibitionConstant. It can be used, for example, to simulate the competitiveeffect of ammonium on methane oxidation by MOBs.

7.2.7. Community Model

The Community model provides a realistic way to simulate real world situations. In mostcases, it is recommended to use Community model as a container to hold other models suchas Population, Competition, Reaction, and Effect. This not only simplifies the modeldefinition in the XML file, but also presents a more flexible way to run the simulation.

As already discussed above, Competition, Reaction and Effect models can interactwith Population models during the simulation, by either inquiring parameter values, or affectthe behavior of Populationmodels. It should be noted by now that Competition,Reactionand Effect models only interact with Population models that are on the same level asthemselves. For example, consider the following structure of models:

<Community_1><Competition_1 /><Population_1 /><Population_2 />

Page 115: Unisim Explained 2015-06-08

7.2. Microbial community model 109

</Community_1><Community_2>

<Effect_1 /><Population_3 /><Population_4 />

</Community_2>

Competition_1 only affects Population_1 and Population_2, since they are all onthe same level (contained in Community_1); while Effect_1 only has an effect on Popula-tion_3 and Population_4. This behavior makes it possible to include several Communitymodels with different combination of submodels in one simulation and they can be insulatedfrom each other.

Stochastic Community

Another powerful feature of Community model is that it can stochastically select Populationmodels into the simulation. Coupled with UniSim´s RunIterator and random parameterfeatures, Community model provides an automated way to explore the effect of communitystructure on community functions,

To generate stochastic communities, the parameter EnableStochasticCommunity

should be set to True. Then Community model takes three parameters to determine how thestochastic communities are constructed:

• MinPopulations: the minimum number of populations in the community;

• MaxPopulations: the maximum number of populations in the community;

• AlwaysIncludedPopulations: a list of Population models that should always beincluded in the community.

When constructing a stochastic community, Community model flows the following steps:

1. A random number between the values of MinPopulations and MaxPopulations wasgenerated, which determines how many populations will be selected into the community.

2. Population models specified in AlwaysIncludedPopulations are entered withpriority. If there are more items in AlwaysIncludedPopulations than the numbergenerated in step 1, then those items will be selected randomly. To avoid this situation, setMinPopulations to the number of items in AlwaysIncludedPopulations.

3. If after step 2 there´re still empty slots left, the rest of the Population models will beselected randomly until all slots are filled.

Model Output

Community model can calculate a list of indices that describe the properties of the community,

Page 116: Unisim Explained 2015-06-08

110 Chapter 7. Student projects

including species richness (Richness), Simpson´s index (SimpsonIndex), Shannon-Wienerindex (ShannonIndex), evenness (Evenness), and Gini coefficient (GiniCoefficient).All indicies are calculated in real-time, that means, for example, if the density of one populationdecreases to 0 during the simulation, the value of richness will decrease by 1. This allows aglimpse into the detailed dynamics of community structural change instead of comparing statusat the beginning and the end of the simulation.

Page 117: Unisim Explained 2015-06-08

Appendix A. Plug-ins ReferenceThis appendix was generated directly from the source code of the UniSim plugins. Thus itslistings of model parameters, push and pull parameters are up-to-date with the code versiongiven below.

The Appendix is out-dated. In the current revision of the Universal Simulator software,documentation will instead be generated as HTML documents that can be browsed (andupdated) moreeasily.

Version: 1.43.

A.1. awe plugin

The awe plugin contains an unpublished model of annual weed population dynamics in thecrop rotation. It was developed as a teaching tool for the ENDURE Summer School 2009 inVolterra, Italy.

Author: Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.1.1. awe::Crop

The Crop model is quite simple as it does not contain a dynamic formulation of growht anddevelopment. Rather, the crop is modelled only by its leaf area index (LAI) which follows a fixedschedule according to the temperature sum (day-degrees above ˚C) since sowing.

PARAMETERS

sowingDay 1 Day in month of sowing.sowingMonth 4 Month of sowing.harvestDay 1 Day in month of harvest.harvestMonth 8 Month of harvest.weedExchangeRate 0.6 Final biomass of weeds as a proportion of yield

loss (g/g).maxYield 800 Weed-free yield 2(g/m ).maxYieldLossPct 60 Maximum yield loss (%) caused by weeds

(Cousens’s a).slopeYield-

LossPct

0.5 Initial yield loss per weed (% per weed densityequivalent) caused by weeds (Cousens’s i).

111

Page 118: Unisim Explained 2015-06-08

112 Appendix A. Plug-ins Reference

laiCalendar ((0 0)(110

0)(210

0.3)(310

0.8)(410

1.6)(510

2.9)(610

5)(1000

5)(1200

5)(1650 2))

Calendar for leaf area index (LAI) running on tem-perature sum since sowing (day-degrees above ˚C).Defined as a list of (temperature-sum LAI) pairs.

VARIABLES

lai double Leaf area index 2(m 2/m ).Tsum double Temperature sum since sowing (day-degrees above

˚C).

A.1.2. awe::InstantMortality

Once per year, at the given month and day, an InstantMortality object effectuates givenmortalities on one or more PlantGrowhtStage models. This can be used to simulate discretemortaly events caused by field operations, for example, spraying or soil cultivation.

It is natural to create InstantMortality objects as descendants (or, ’inside’) of a Cropmodel. The mortalities will then only be in effect when that crop is current in the Rotation.

PARAMETERS

day 1 Day in month of imposed mortality.month 6 Month of imposed mortality.mortalities empty string List of instant mortalities (0-100%) applied to the

different weed growth stages. Defined as a listof (growth stage mortality) pairs. For example,((seedling 100) (juvenile 80) (mature10)), which will apply the respectivemortalities to all PlantGrowhtStage modelsnamed seedling, juvenile and mature.

A.1.3. awe::PlantGrowthStage

A PlantGrowthStage holds two UniSim::Stage models inside, represing plant densityboth as plants per 2m and density equivalents per 2m . One density eqivalent corresponds to thedensity of one plant that emerged simultaneouly with the crop. Later emerging plant counts asless than one density equivalent per plant. Thus ’equivalence” is meant as equivalent in terms ofcompetitiveness towards the crop

PARAMETERS

Page 119: Unisim Explained 2015-06-08

A.1. awe plugin 113

inflowAsDensity 0 Number of plants to enter this growth stage in thenext update (i.e. time step) (plants per 2m per day).

inflowAsDensi-

tyEqs

0 Number of density equivalents to enter this growthstage in the next update (i.e. time step) (densityequivalents per 2m per day).

instantMortality 0 Instant mortality (0-100%) to apply to this growthstage in the next update.

VARIABLES

outflowAsDensity double Number of plants that emerged from this growthstage during the last update (i.e. time step) (plantsper 2m per day).

outflowAsDensi-

tyEqs

double Number of density equivalents that emerged fromthis growth stage during the last update (i.e. timestep) (density equivalents per 2m per day).

A.1.4. awe::Rotation

The Rotation model holds as children the Crop models that are part of the rotation. It keepscheck of the current crop according to cropping sequence and the harvest and sowing eventspertaining to Crop models.

PARAMETERS

crops empty string Sequence of crops in rotation. For example,(maize wheat wheat), in which maize is fol-lowed by two crops of wheat. The crop names mustrefer to names of Crop models that are children ofRotation.

VARIABLES

lai double Leaf area index 2(m 2/m ) of the current crop.

A.1.5. awe::SeedBank

The SeedBank model holds the density of seeds in the soil 2(per ). Seeds are divide into twogroups: dormant and non-dormant. Newly produced seeds enter the seed bank as dormant. Dor-mancy is lost on 1 January every year, and all dormant seeds are then movedinto the non-dor-mant group.

PARAMETERS

initialDensity 1000 Initial density of the seeds in the seed bank (seedsper 2m .

Page 120: Unisim Explained 2015-06-08

114 Appendix A. Plug-ins Reference

emergenceCalen-

dar

(0 0 5 10 20

40 10 5 0 0

0 0)

The calendar shows the relative emergence ofseedlings per month in a scenario where no shadeis causing a reduction in emergence. The scale isrelative and needs not add up to a total of, e.g., 1 or100. A daily calendar with values fordailyEmergenceRatioPotential is con-structed from this calendar and the yearlyEmer-genceRate.

yearlyEmer-

genceRate

0.2 The proportion [0..1] of the seed bank that wouldpotentially emerge if no crop reduced emergenceby shading.

yearlyMortali-

tyRate

0.1 The mortality [0..1] of the seed bank per year.

cropLaiExp 0.04282 Exponent a in the equation to calculate cropEf-

fectOnEmergence, y = exp( −52ax ), where x is

the leaf area index of the current Crop.dormantInflow 0 Use this to set the daily inflow of dormant seeds

into the seed bank (seeds per 2m per day). You can-not put non-dormant seeds into the seed bank.

instantMortality 0 The mortality (%) will be applied once in the nexttime step, before new seeds of dormantInfloware added. Dormant and non-dormant seeds will beaffected alike.

VARIABLES

number double Total number of seeds (dormant + non-dormant) inthe soil (seeds per 2m ).

dormant double Number of dormant seeds in the soil (seeds per2m ).

nonDormant double Number of non-dormant seeds in the soil (seeds per2m ).

dailyEmergenceR-

atio

double Ratio [0..1] of seedlings emerging in this time step(per day).

totalEmergenceR-

atio

double Accumulated ratio [0..1] of seedlings that haveemerged since 1 January.

dailyEmergence-

Density

double Density of seedlings emerging in this time step(seedlings per 2m per day).

totalEmergence-

Density

double Accumulated density of seedlings emerged since 1January (seedlings per 2m ).

cropEffectOnE-

mergence

double The effect [0..1] is a scaling factor applied to thedailyEmergenceRatioPotential to achievethe realised dailyEmergenceRatio.

Page 121: Unisim Explained 2015-06-08

A.1. awe plugin 115

dailyEmergenceR-

atioPotential

double Potential ratio [0..1] of seedlings emerging in thistime step (per day). The realised ratio dailyE-mergenceRatio depends on the shading effect ofthe crop.

A.1.6. awe::Weather

The Weather model produces data for daily average temperature, assuming a sine curverelationover the year, y = a + b(π x

365 + c 2) , where x is the day of the year [0..365].

PARAMETERS

a -0.75 Parameter a of yearly sine curve for temperature(˚C).

b 17.2 Parameter b of yearly sine curve for temperature(˚C).

VARIABLES

T double Daily average temperature (˚ C).Tavg double Same as T.Tsum double Temperature sum since 1 January Day-degrees

above 0 ˚C.

A.1.7. awe::Weed

The Weed model holds the SeedBank model, PlantGrowthStage models for seedling,juvenile and mature stages, and a UniSim::Stage model to represent seeds on the plant.

The Weed model orchestrates the progressive flow of weed individuals through thesemodels. For the PlantGrowthStage models there are parallel flows of density equivalents.

PARAMETERS

c1 6.904 Parameter in the equation that calculates densityequivalents from density, y = exp{c1[exp( − x

c2) − 1

]} − exp( − c1), where x is crop leaf area index.

c2 0.7491 See c1.seedProdSlope 2 Slope a (seeds per bg ) in the equation relating seed

production to final weed biomass, y = bax where x isweed biomass (g).

seedProdExp 1 Exponent b in the equation relating seed produc-tion to final weed biomass, y = bax where x is weedbiomass (g).

VARIABLES

Page 122: Unisim Explained 2015-06-08

116 Appendix A. Plug-ins Reference

projectedDeqs double The projected number of density equivalents (per2m ) is the final density equivalentsexpected, if there

will be no mortality applied to any growth stages.projectedYield-

LossPct

double The projected yield loss (%) is calculated fromprojectedDeqs by way of the Cousens equa-tion.

projectedMass double The projected weed biomass 2(g/m ) is calculatedfrom projectedYieldLossPct applying theweed/yield biomass exchange rate pertinent to theCrop.

seedsDropping double The number of seeds (per 2m per day) dropping tothe ground during this time step. These originatefrom the seedsOnPlant model.

g double Current seed multiplication rate for the seedsOn-Plant model. Works by unpublished mechanism.

Page 123: Unisim Explained 2015-06-08

A.1. awe plugin 117

A.2. conductance plugin

The conductance plugin is an implementation of the Conductance model for plant growthand competition, as described by Benjamin & Park (2007) and references cited therein. TheConductance model always holds three child models, representing calendar, weather and plantcommunity, respectively. The community model again holds one or two plant models.

Authors: Niels Holst, Aarhus University, Flakkebjerg, Denmark.

Mette Sønderskov, Aarhus University, Flakkebjerg, Denmark.

Gionata Bocci, Scuola Superiore di Studi Universitari e di Perfezionamento Sant’Anna,Pisa, Italy.

A.2.1. conductance::Community

A Community object holds one or two Plant objects. It governs the passage of the plant(s)through the three stages of competition:Unlimited, UnderCompression, and WeightPro-portional.

VARIABLES

sum_sz double Total crown zone area of the one or two plantspresent 2(m ground area owned per 2m ground areaavailable).

A.2.2. conductance::Plant

A Plant object grows, in terms of biomass, leaf area and crown zone area, according to itscurrent competition phase

PARAMETERS

initWeight 2 Initial plant weight at time zero (g per plant).initDay 0 Day of month when growth begins and weight

is set to initWeight. Use together with init-Month. If initDay or initMonth is zero,theyare not used and growth will start on day 1 in thesimulation.

initMonth 0 See initDay.A 0.03 Coefficient in allometric relation for crown zone

area: A ϕw .phi 0.67 Exponent in allometric relation for crown zone

area: A ϕw .F 0.01 Coefficient in allometric relation for plant leaf

area: F θw .

Page 124: Unisim Explained 2015-06-08

118 Appendix A. Plug-ins Reference

theta 0.9 Exponent in allometric relation for plant leaf area:F θw .

k 0.6 Light extinction coefficient of foliage [0..1].eps 1 Light use efficiency (g/MJ) of global irradiation.n 20 Plant density (plants per 2m ).

VARIABLES

weight double Plant weight (g per plant).totalWeight double Total population plant weight 2(g/m ground area

available).sz double Crown zone area per plant 2(m ground area owned

per per plant).total_sz double Total population crown zone area 2(m ground area

owned per 2m ground area available).Lz double Leaf area index within the crown zone area 2(m

leaf area per 2m ground area owned).fz double Fraction of light intercepted [0..1].LA_per_plant double Leaf area per plant 2(m leaf area per plant).dweight double Latest increment in plant weight over time step dt

(g per plant per day).phase int Competition phase: Unlimited, UnderCom-

pression or WeightProportional.LAI double Leaf area index of whole population 2(m leaf area

per 2m ground area available).

A.2.3. conductance::Weather

This Weather object holds fixed values for global irradiation and daily average temperature.

PARAMETERS

irradiation 10 Global irradiation 2(MJ/m /d).

Page 125: Unisim Explained 2015-06-08

A.2. conductance plugin 119

A.3. dynamic_photosynthesis plugin

The dynamic_photosynthesis plug-in contains just one model Leaf, which modelsphotosynthesis based on induction state.

Authors: Isik Ozturk, Aarhus University, Årslev, Denmark.

Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.3.1. dynamic_photosynthesis::Leaf

To simulate leaf photosynthesis in C3 plants

PARAMETERS

Sini 0 Initial induction state, Mmol 2m -1s .alpha 0.007 Response of Seq to PAR, no dimension.S0 1 Asymptotic Seq with respect to PAR, Mmol 2m -1s .a 0.27 Asymptotic regression coefficient for S60, Mmol

2m -1s .b 0.017 Regression coefficient for S60, no dimension.c 0.007 Regression coefficient for S60, no dimension.gSini 250 Initial stomatal conductance, mmol 2m -1s .PARmin 1 Value of PAR when measured PAR is zero, Mmol

2m -1s .tm 30 location of the peak response on the x axis, ˚ C.ts 45 controls the width of the bell, no dimension.useTemperature no controls the effect of temperature.A0 12 Max assimilation rate, Mmol 2m -1s .theta 0.0035 Regression coefficient for photosynthesis, Mmol

2m -1s .

VARIABLES

S double Induction state, Mmol 2m -1s .Seq double Equilibrium state of induction, Mmol 2m -1s .S60 double Induction state after 60 seconds, Mmol 2m -1s .Ar double Photosynthesis rate, Mmol 2m -1s .

Page 126: Unisim Explained 2015-06-08

120 Appendix A. Plug-ins Reference

A.4. ecotox plugin

A collection of models to simulate deposition of a substance around a source, for instance, GMpollen or a pesticide. The current naming of models implies GM pollen.

Author: Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.4.1. ecotox::DepositionFlush

With this model deposition comes in a flush. The daily deposition rate follows a parabolic curveduring the deposition period. The flush starts on a date sampled randomly from a seasonal depo-sition curve, which must be defined in a sibling model called depositionRate. This can, forexample, be one of the models DepositionMonotonicSampled or DepositionMonoton-icWeibull.

PARAMETERS

duration 14 Duration (days) of pollen release from crop.onsetFileName empty string Optional file with dates of pollen onset. Date will

be picked at random within calendar year.

VARIABLES

value double Deposition rate (0..1).total double Accumulated deposition total (0..1).

A.4.2. ecotox::DepositionMonotonicSampled

Seasonal deposition curve sampled from an empirical distribution, beginning at value zero andending at value one at the end of the season. The distribution data must be supplied as a columnin the records of the weather model.

VARIABLES

value double Deposition rate (0..1).total double Accumulated deposition total (0..1).

A.4.3. ecotox::DepositionMonotonicWeibull

Seasonal deposition curve described by a Weibull curve

PARAMETERS

alpha 21.54 Pollen phenology shape parameter.beta 1.868 Pollen phenology shape parameter.

Page 127: Unisim Explained 2015-06-08

A.4. ecotox plugin 121

c 1 Pollen phenology compression. c < 1 prolongs theperiod of pollen deposition. c > 1 shortens the pe-riod.

dateMax 31/7/2011 Date when pollen deposition peaks.dateShift 0 Shift dateMax by this number of days. Usefull for

stochastic modelling.

VARIABLES

value double Deposition rate (0..1).total double Accumulated deposition total (0..1).

A.4.4. ecotox::LogLogistic

The log-logistic dose-response curve described by

y = ymin −(ymax − ymin)

1 + −slopexED50

The value of the dose x is given by the parameter dose below. As for any other parameter,you can either set this to a fixed or a variable value. For dose you most often want a vari-able value supplied from another model. If you set dose to pollen[pollenDensity]

then the response will reflect current pollen density. Other possible measures includepollen[stdPollenDensity] and pollen[toxinDensity], see Pollen on page 121.

PARAMETERS

dose 0 Dose for which response will be calculated. Youcan use this also as a push variable.

lower 0 Asymptotic response at low dose.upper 1 Asymptotic response at high dose.ED50 10 Dose giving average response (lower + up-

per)/2.slope 2 Slope of sigmoid curve. The curve is rising from

lower to upper, if slope is positive.And, thecurve is falling from upper to lower, if slopeis negative.

VARIABLES

value double Response at current dose.

A.4.5. ecotox::Pollen

This model must be composed of two models, depositionRate and lossRate, and possiblya third model, depositionFlush. Its parameters determine the total deposition and the

Page 128: Unisim Explained 2015-06-08

122 Appendix A. Plug-ins Reference

distance from the source.

The LogLogistic dose-response model can pull the current dose from Pollen as pollen-Density, toxinDensity or stdPollenDensity.The exchange rate between these differentunits of density is determined by the parameters pollenMass and toxinConc, which set themass and toxin concentration for the crop at hand, and stdPollenMass and stdToxinConc,which set the corresponding values for a standard reference crop. The transformations are

toxinDensity = pollenDensity*pollenMass*toxinConc

and

stdPollenDensity =

pollenDensity*pollenMass/stdPollenMass*toxinConc/stdToxinConc

PARAMETERS

distance 0 Distance to maize field (m).distanceExp -0.548 Pollen deposition declines with the distance from

the maize field. This is described as a power func-tion with the exponent distanceExp.

distanceMin 0.3 Minimum distance of pollen dispersion mod-el (m).

Npeak 1750 Peak average density of pollen deposited on foodplant (pollen per 2cm ) at field edge, i.e. at dis-tance <= distanceMin.

VARIABLES

pollenDeposi-

tionRate

double Current pollen deposition rate (per day per 2cm ).

pollenDeposi-

tionTotal

double Total pollen deposition (per 2cm ).

pollenDensity double Current pollen density (per 2cm ).

A.4.6. ecotox::PollenLossConstant

With a constant rate of pollen loss, pollen disappears following a negetive exponential curve.

PARAMETERS

rate 0.01 Fraction of pollen lost per day. Set this to zero ifpollen is not lost.

VARIABLES

value double Fraction of pollen lost per day.

Page 129: Unisim Explained 2015-06-08

A.4. ecotox plugin 123

A.4.7. ecotox::PollenLossSampled

With sampled loss rate, the daily loss rate is determind by picking a value at random from thesupplied list of loss rates.

PARAMETERS

rates (0 0.5 0.9) List of daily loss rates from which one is drawn atrandom every day. A value of (0 0.5 0.9), forexample, results in a daily loss rate of either 0, 50%or 90% with equal probability.

VARIABLES

value double Pollen survival rate (per day).

Page 130: Unisim Explained 2015-06-08

124 Appendix A. Plug-ins Reference

A.5. intercom plugin

The intercom plugin is an implementation of the INTERCOM model for plant growth andcompetition, as described by Kropff & Laar (1993).

Authors: Niels Holst, Aarhus University, Flakkebjerg, Denmark.

Marleen Riemens, Plant Research International, Wageningen, Netherlands.

Jonathan Storkey, Rothamsted Research, UK.

A.5.1. intercom::Area

An Area object keeps track of the area 2(cm per plant) which carries out photosynthesisaccording to its parameters and sub-models. It must hold three sub-models as children, nameddensity, amax and lightUseEfficiency. The latter two specify the shape of the lightresponse curve and the first the shape of the canopy.

PARAMETERS

scatteringCoeff 0.2 Light scattering coefficient. Usually the defaultvalue is used.

kDiffuse 0.7 Light extinction coefficient of diffuse light.writeTestOutput no Write detailed output? The resulting file has a name

that begins witharea_test followed by the full nameof the Area object.

allocation 0 Allocated dry matter (g per plant per day) to beconverted into area.

VARIABLES

value double The area of this organ per plant 2(cm per plant).LAI double Leaf area index of this organ.lightAbsorption double Light absorbed by this area (W per 2m ground

per day).CO2Assimilation double CO2 assimilated by this area (kg CO2 per ha ground

per day).grossProduction double Carbohydrates produced by this area (kg CH2O per

ha ground per day).

A.5.2. intercom::AreaDensityEven

This model can serve as a density sub-model for an Area object. The density is the same at allheights from zero to canopy height.

Page 131: Unisim Explained 2015-06-08

A.5. intercom plugin 125

A.5.3. intercom::AreaDensitySymmetric

This model can serve as a density sub-model for an Area object. The density is parabolic fromzero to canopy height.

A.5.4. intercom::AreaDensityTapering

This model can serve as a density sub-model for an Area object.The density increases linearlyfrom zero at canopy height to its maximum at zero height.

A.5.5. intercom::AreaDensityTopheavy

This model can serve as a density sub-model for an Area object. The density increasesnon-linearly from zero to canopy height, resulting in a topheavy shape typical of flowers

A.5.6. intercom::AssimilationMaxGivenTemp

This model can serve as the amax sub-model of an Area object. Based on the Tday variable ofweather model, it calculates the maximum assimilation rate as maxAmax(1 − Tday)radix

PARAMETERS

radix 0.882 Radix in the empirical equation.maxAmax 50 Asymptotic max CO2 assimilation rate at high

temperature [kg CO2 per ha leaf per hour].

VARIABLES

value double Max CO2 assimilation rate [kg CO2 per ha leafper hour].

A.5.7. intercom::Community

A Community model holds one or more Plant child models. It resolves the competition forlight in daily time steps, calculating total light absorption and CO2 assimilation of the wholecanopy (i.e. of all its Plant objects) and dividing the resulting total among its Plant objects.

If more than one Community object is present they will work in parallel without any in-terference (e.g. competition for light). Thus different scenarios can be compared in one simula-tion run.

PARAMETERS

early-

GrowthThreshold

1 Threshold (LAI) for applying the early exponentialgrowth model.

Page 132: Unisim Explained 2015-06-08

126 Appendix A. Plug-ins Reference

testMode no In test mode, the plants stop growing after early-GrowthThreshold has been reached. Daily pho-tosynthesis is calculated but not allocated.

VARIABLES

isInEarlyGrowth bool Is the community it its early growth phase?.LAI double Leaf area index of whole community 2(m plant

area per 2m ground).lightAbsorption double Absorbed light (W per 2m ground per day).CO2Assimilation double Assimilated kg CO2 per ha ground per day.

grossProduction double Produced kg CH2O per ha ground per day.

A.5.8. intercom::EarlyGrowth

The EarlyGrowth model is a simple expontial curve based on photothermal time. A pho-tothermal time model must be available as a sibling.

PARAMETERS

initialArea 0.05 Area at time zero 2(cm per plant).growthRate 1 Exponential growth rate 2(m per 2m per photother-

mal time unit.

VARIABLES

area double Current area 2(cm per plant).

A.5.9. intercom::Height

A Plant model must have one child model named height with a height pull variablereturning the height. The Height class provides the standard height model of INTERCOMwhich is a logistic growth curve working on photothermal time.

height(t) = h0 + hmax − h01 + exp( − slope(t − tm))

The height model looks for the nearest model named time to provide the daily time increment.A UniSim::PhotoThermalTime model can be used for this purpose (see page 152).

PARAMETERS

h0 0.05 Height at time zero (m).hmax 1 Maximum height (m).slope 0.0085 Growth rate (per photothermal time unit).tm 624 Time when height = h0 + (hmax − h0)/2.

Page 133: Unisim Explained 2015-06-08

A.5. intercom plugin 127

VARIABLES

height double Current height (m).

A.5.10. intercom::InstantMortality

List of instant mortalities [0;1] applied on a certain day and month to the listed plant organs, forexample,((leaves 0)(stem 0.05)(flowers 0)). Plant organs not mentioned will not beafflicted. Those mentioned must exist inside Plant.

PARAMETERS

day 0 Day of month when survival will be applied.month 0 Month when survival will be applied.survival empty string List of survival rates, max. one for each Stage

defined for the Plant.

A.5.11. intercom::LightUseEfficiencyGivenTemp

This model can serve as the lightUseEfficiency child model of an Area object. It calculateslight use (or light conversion) effiency as a linear relation on Tday of the weather model

PARAMETERS

slope -0.0095 Slope of the line (kg CO2 per ha leaf per hour per(W per 2m leaf) per °C).

intercept 0.635 Intercept of the line (kg CO2 per ha leaf per hourper (W per 2m leaf)’).

VARIABLES

value double Light use efficiency, ε (kg CO2 per ha leaf per hourper (W per 2m leaf)’).

A.5.12. intercom::Mass

This model can serve as a mass child model of an Organ model. It holds iself a mass childmodel to hold the actual mass (g/plant) which is usually of the UniSim::Stage class to simulatean ageing mass

PARAMETERS

allocation 0 Allocated dry matter (g per plant per day) to beadded to mass.

VARIABLES

value double The mass of this organ per plant (g per plant).

Page 134: Unisim Explained 2015-06-08

128 Appendix A. Plug-ins Reference

allocationRate double The mass just allocated to this organ per plant (gper plant per day).

currentPartition double The proportion [0;1] that this mass consistutes outof the plant total.

A.5.13. intercom::Organ

An Organ model is a child of a Plant model. It contains one child model called mass andoptionally an additional model of the Area class

PARAMETERS

maintenanceCoeff 0.03 Maintenance coefficient (g/g/day) at 20 °C.CH2ORequirement 1.5 Carbohydrate requirement g CH2 O per g biomass.

VARIABLES

lightAbsorption double Absorbed light (W per 2m ground per day).CO2Assimilation double Assimilated kg CO2 per ha ground per day.

grossProduction double Produced kg CH2O per ha ground per day.

maintenanceResp double Maintenance respiration (kg CH2 O per ha groundper day).

growthResp double Growth respiration (kg CH2 O per ha ground perday).

netAllocation double Net allocation rate, the daily increment to organ-biomass (kg CH2 O per ha ground per day).

allocatedPer-

Plant

double Net biomass allocated to this organ per plant (g perplant per day).

propAllocated-

PerPlant

double Proportion biomass allocated to this organ amongall the plant’s organs [0;1].

A.5.14. intercom::PartitioningFixed

This model supplies a partitioning coefficient with a fixed value

PARAMETERS

value 1 Fixed partitioning coefficient.They must sum up toone for a Plant object.

Page 135: Unisim Explained 2015-06-08

A.5. intercom plugin 129

A.5.15. intercom::PartitioningFixedByStage

Pending

PARAMETERS

value 1 Fixed partitioning coefficient.They must sum up toone for a Plant object.

values empty string Fixed partitioning coefficient for each plant growthstage, for example, (vegetative 0.5)(flowering 0.2).

A.5.16. intercom::Phenology

The model of plant phenology must be a child of a Plant model. It may consist of any numberof UniSim::Stage models

VARIABLES

alive double Proportion of plant population still alive [0;1], i.e.the proportion that has not yet developed past thelast stage defined as child of Phenology.

A.5.17. intercom::Plant

A Plant model is a child of the Community model. It holds one or more Organ child modelsand additional child models called time, height and earlyGrowth.

PARAMETERS

density 100 Plants per 2m .

VARIABLES

mass double Mass of one plant (g per plant).LAI double Leaf area index of whole plant 2(m plant area per

2m ground).lightAbsorption double Absorbed light (W per 2m ground per day).allocatedPer-

Plant

double Net allocation rate, the daily increment to plantmass (g per plant per day).

CO2Assimilation double Assimilated CO2 (kg CO2 per ha ground per day.

grossProduction double Produced kg CH2O per ha ground per day.

maintenanceResp double Maintenance respiration (kg CH2O per ha groundper day).

Page 136: Unisim Explained 2015-06-08

130 Appendix A. Plug-ins Reference

growthResp double Growth respiration (kg CH2 O per ha ground perday).

availableProduc-

tion

double The available production is gross production minusmaintenance respiration (kg CH2O per ha groundper day).

netAllocation double Net allocation rate, the daily increment to plantpopulation mass (kg CH2O per ha ground perday).

A.5.18. intercom::SpecificLeafArea

This can serve as the specificLeafAreamodel of an Areamodel. It models specific leaf area2(m /g) as a linear relation on photothermal time, supplied by the nearest model called time, for

example a UniSim::PhotoThermalTime model.

PARAMETERS

initial 240 Initial specific leaf area at time zero 2(cm /g).slope -0.075 Slope on photothermal time 2((cm /g/°D)).

VARIABLES

value double Specific leaf area 2(cm /g).

A.5.19. intercom::Weather

The model named weather of this class must be present, as several other models rely on dailyweather recordings. The weather model holds a UniSim::Records inside which managesthe daily readings from a weather file. This weather file must hold at least four columns labelled:Date, Tmin, Tmax and irradiationMJ. In addition to these four, Weather itself adds additionalpull variables.

Values of irradiation rates pertain to the current time of the day, as set by the clock

object

VARIABLES

Tavg double Daily average temperature calculated as the aver-age of Tmin and Tmax (°C).

Tday double Daily day temperature calculated as Tmax minusone quarter of the span between Tmax and Tmin

(°C).irradiation double Daily total irradiation. Same as irradiationMJ

read from weather records but with adjusted units2(W/m ).

Page 137: Unisim Explained 2015-06-08

A.5. intercom plugin 131

parTotal double Total PAR irradiation rate at current time of day2(W/m ).

parDiffuse double Diffuse component of total PAR irradiation atcurrent time of day 2(W/m ).

parDirect double Direct componente of total PAR irradiation at cur-rent time of day 2(W/m ).

Page 138: Unisim Explained 2015-06-08

132 Appendix A. Plug-ins Reference

A.6. MicrobialCommunity plugin

Description of MicrobialCommunity.

Authors: Kevin, Yun-Feng Duan, Aarhus University, Foulum, Denmark.

Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.6.1. MicrobialCommunity::Community

Description pending

PARAMETERS

EnableStochas-

ticCommunity

no A switch indicating whether stochastic communityis enabled.

MinPopulations 1 Minimum number of populations entered in thestochastic community.

MaxPopulations 1 Maximum number of populations entered in thestochastic community.

AlwaysIncluded-

Populationsempty string A list of populations that will always be entered in

the stochastic community.

VARIABLES

Density double Total density of the community.Richness int Community richness.SimpsonIndex double Simpson’s Index.ShannonIndex double Shannon-Wiener Index.Evenness double Community evenness.GiniCoefficient double Gini coefficient.

A.6.2. MicrobialCommunity::Competition

Description pending

PARAMETERS

EnableCompeti-

tion

yes A switch indicating whether competition modelis enabled.

InitialResource 1 Initial resource.CompetitionModel default Define the competition model used in the simu-

lation.

VARIABLES

Page 139: Unisim Explained 2015-06-08

A.6. MicrobialCommunity plugin 133

AvailableRe-

source

double Description.

A.6.3. MicrobialCommunity::CompetitiveInhibition

Description pending

PARAMETERS

EnableEffect yes Enable the effect.TargetPopula-

tionsempty string The Population models that are affected under

this effect.InhibitionCon-

stant

1 Inhibition constant.

InhibitorConcen-

tration

0 Concentration of inhibitor.

A.6.4. MicrobialCommunity::Effect

Description pending

PARAMETERS

EnableEffect yes Enable the effect.TargetPopula-

tionsempty string The Population models that are affected under

this effect.

A.6.5. MicrobialCommunity::EnzymaticReaction

Description pending

PARAMETERS

InitialSubstrate 100 Initial concentration of substrate.VARIABLES

Substrate double Concentration of substrate.SubstratePDD double Concentration of substrate, population density de-

pendent.Velocity double Reaction velocity.VelocityPDD double Reaction velocity, population density dependent.

Page 140: Unisim Explained 2015-06-08

134 Appendix A. Plug-ins Reference

A.6.6. MicrobialCommunity::FirstOrderReaction

Description pending

PARAMETERS

InitialSubstrate 100 Initial concentration of substrate.VARIABLES

Substrate double Concentration of substrate.SubstratePDD double Concentration of substrate, population density de-

pendent.Velocity double Reaction velocity.VelocityPDD double Reaction velocity, population density dependent.

A.6.7. MicrobialCommunity::GeneralEffect

Description pending

PARAMETERS

EnableEffect yes Enable the effect.TargetPopula-

tionsempty string The Population models that are affected under

this effect.TargetParameter empty string The parameter of Population model that is affected

by this factor.EffectRatio empty string The effect ratio of this factor.

A.6.8. MicrobialCommunity::Population

Description pending

PARAMETERS

SpeciesName Bacterium Name of the microbial species.IsActive yes A switch indicating whether this population is

active in a stochastic community.InitialDensity 0 Initial density.CarryingCapacity 0 Carrying capacity.LagPhase 0 Lag phase.GrowthRate 0 Growth rate.MortalityRate 0 Mortality rate.SearchRate 0 Search rate.

Page 141: Unisim Explained 2015-06-08

A.6. MicrobialCommunity plugin 135

DemandRate 0 Demand rate.ZeroOrderRate-

Constant

0 Zero-order rate constant.

FirstOrderRate-

Constant

0 First-order rate constant.

MichaelisMenten-

Constant

0 Michaelis-Menten constant (Km) for the enzyme.

MaximumVelocity 0 Maximum velocity of the enzyme-catalyzed re-action.

SupplyDemandRa-

tio

1 Supply-demand ratio.

VARIABLES

Density double Population density.DensityActivity-

Coefficient

double Bacterial density-activity coefficient.

A.6.9. MicrobialCommunity::Reaction

Description pending

PARAMETERS

InitialSubstrate 100 Initial concentration of substrate.VARIABLES

Substrate double Concentration of substrate.SubstratePDD double Concentration of substrate, population density de-

pendent.Velocity double Reaction velocity.VelocityPDD double Reaction velocity, population density dependent.

A.6.10. MicrobialCommunity::ZeroOrderReaction

Description pending

PARAMETERS

InitialSubstrate 100 Initial concentration of substrate.VARIABLES

Substrate double Concentration of substrate.SubstratePDD double Concentration of substrate, population density de-

pendent.Velocity double Reaction velocity.

Page 142: Unisim Explained 2015-06-08

136 Appendix A. Plug-ins Reference

VelocityPDD double Reaction velocity, population density dependent.

Page 143: Unisim Explained 2015-06-08

A.6. MicrobialCommunity plugin 137

A.7. mussel_bed plugin

The mussel_bed plugin includes models for creatures on a mussel bed.

Authors: Antonio Agüera, Wageningen University, Netherlands.

Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.7.1. mussel_bed::HydrodynamicSRScale

Scaling searching rate of starfish by hydrodynamic regime in the area. Yields a number [0;1]

PARAMETERS

maxflow 0 desc.VARIABLES

value double desc.

A.7.2. mussel_bed::Mussel

Mussel population model

PARAMETERS

initialDensity 3 Observed density at t0 as kg/m2.initialN 1000 Observed density at t0 as numbers/m2.LossB 0 losses in mussel biomass as kg/m2.LossN 0 losses in mussel numbers as kg/m2.growthRate 0.3 mussel growth rate (only in biomass).

VARIABLES

N double current density at step, numbers/m2.density double current density at step, kg/m2.

A.7.3. mussel_bed::MusselGrowthRate

Mussel population growth rate model

PARAMETERS

intrinsicRate 0.019 Intrinsic rate of increase (% per day), maximumgrowth observed in the Wadden Sea for youngmussels.

carryingCapacity 15 Carrying capacity (kg/m2), obtained from field ob-servations.

Page 144: Unisim Explained 2015-06-08

138 Appendix A. Plug-ins Reference

density 3 current mussel density at step(kg/m2).

VARIABLES

value double total growth rate for the current density, tempera-ture and salinity (kg/m2).

A.7.4. mussel_bed::SalinityScale

Scaling of growth rate by Salinity. Yields a number [0;1]

PARAMETERS

Smax 30 salinity at high tide.Smin 24 salinity at low tide.

VARIABLES

value double mussel growth scaling factor.

A.7.5. mussel_bed::SalinitySRScale

Scaling searching rate of starfish by average salinity. Yields a number [0;1]

PARAMETERS

Smax 31 desc.Smin 10 desc.

VARIABLES

value double desc.

A.7.6. mussel_bed::searchrate

estimating appearance for fResp

PARAMETERS

maxSR 1 maximum search rate m2/day, from Wong et al,2006.

VARIABLES

value double search rate or appearance.

A.7.7. mussel_bed::Starfish

starfish population model

PARAMETERS

Page 145: Unisim Explained 2015-06-08

A.7. mussel_bed plugin 139

inDensity 0.3 Starfish density at t0 (kg/m2.mortality 0 Starfish mortality at step (kg).stgrowthRate 0.12 Starfish population increase in biomass (kg) at

current step.

VARIABLES

stdensity double current step starfish density (kg/m2).

A.7.8. mussel_bed::StarfishFeedingRate

Scaled Feeding rate of starfish

PARAMETERS

stdensity 0.3 current starfish density Kg/m2.

VARIABLES

value double total demand for the current density kg/m2 of mus-sel flesh.

A.7.9. mussel_bed::StarfishGrowthRate

transform feeding rate into new starfish biomass

PARAMETERS

supply 0.007 total amount of mussel flesh consumed kg/m2.stDensity 0.3 current starfish density kg/m2.temperature 13 current temperature degrees celsius.

VARIABLES

value double total increase in starfish biomass at step kg/m2.

A.7.10. mussel_bed::StarfishSalMortality

Starfish mortality produced by salinity changes

PARAMETERS

Smax 28 maximum salinity at day.Smin 12 minimum salinity at day.

VARIABLES

value double desc.

Page 146: Unisim Explained 2015-06-08

140 Appendix A. Plug-ins Reference

A.7.11. mussel_bed::TemperatureScale

Scaling of growth rate by temperature. Yields a number [0;1]

PARAMETERS

temperature 12 current step temperature in degree Celsius.avgs 0.005 average individual weight at current step.

VARIABLES

value double scaling parameter at current temperature.

A.7.12. mussel_bed::TemperatureStScale

Scaling of feeding rate of starfish by Temperature. Yields a number [0;1]

PARAMETERS

temperature 15 current temperature degree celsius.

VARIABLES

value double scaling factor for feeding rate.

A.7.13. mussel_bed::thinning

stimate loss rate considering also self thinning rule

PARAMETERS

Density 1 current mussel density biomass kg/m2.N 1 current mussel density numbers n/m2.supply 0 biomass of mussesl consumed by starfish kg/m2.

VARIABLES

thin double loss casused by thinning as kg/m2.LossN double mussel loss as numbers n/m2.LossB double mussel loss as biomass kg/m2.avgs double current mussel mean individual weight.maxN double maximum density in numbers/m2 for the current

avgs.

Page 147: Unisim Explained 2015-06-08

A.7. mussel_bed plugin 141

A.8. rvf plugin

The rvf plugin includes models for the epidemics of Rift Valley Virus (RVF).

Author: Clement Mweya, National Institute for Medical Research, Tanzania.

A.8.1. rvf::Adult

Adult mosquitoes laying eggs.

PARAMETERS

sexRatio 0.5 Proportion of females.density 1 Density of adults.fecundity 20 Eggs laid per female per day.proportionEg-

gsInWater

20 desc.

VARIABLES

eggsLaidInWater double Number of eggs laid in water.eggsLaidOnGround double Number of eggs laid on dry ground.

A.8.2. rvf::Egg

Mosquitoes eggs in water

VARIABLES

totalEggsInflow double desc.

A.8.3. rvf::InactiveEgg

Inactive eggs laid on the ground.

PARAMETERS

initialDensity 0 desc.lossRate 20 desc.activationRate 20 desc.inflow 0 desc.

VARIABLES

density double desc.eggsLost double desc.eggsActivated double desc.

Page 148: Unisim Explained 2015-06-08

142 Appendix A. Plug-ins Reference

A.8.4. rvf::MosquitoFecundity

Daily egg-laying rate of adult mosquitoes. Depends on water level

PARAMETERS

waterLevel 0 desc.water-

LevelThreshold

20 desc.

dailyFecundity 20 desc.

VARIABLES

value double desc.

A.8.5. rvf::WaterLevel

Water level in the environment.

PARAMETERS

initialValue 100 desc.dailyRainfall 2 desc.dailyLoss 10 desc.

VARIABLES

value double desc.

Page 149: Unisim Explained 2015-06-08

A.8. rvf plugin 143

A.9. seed_emergence plugin

The seed_emergence plugin provides a CumulativeEmergencemodel which models emer-gence as a Gompertz curve running on hydrothermal time.The Unisim::HydrothermalTimemodel calculates time from weather input provided on a file with hourly readings of soil temper-ature and soil water potential.

Authors: Niels Holst, Aarhus University, Flakkebjerg, Denmark.

Roberta Masin, Consiglio Nazionale delle Ricerche, Padova, Italy.

A.9.1. seed_emergence::CumulativeEmergence

Cumulative emergence (%) modelled as a Gompertz curve.

PARAMETERS

a 10 Gompertz curve a parameter.b 0.008 Gompertz curve b parameter.

VARIABLES

accumulated double Current accumulated emergence (%).

A.9.2. seed_emergence::Weather

Converts units of soil water potential from kPa to MPa.

VARIABLES

Tavg double Soil temperature (°C).SWP double Soil water potential in MPa.

Page 150: Unisim Explained 2015-06-08

144 Appendix A. Plug-ins Reference

A.10. strawberry plugin

The strawberry plugin models powdery mildew in strawberries.

Author: Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.10.1. strawberry::Infection

Computes daily infection rate of leaves

PARAMETERS

inoculumDensity 0 desc.infectionRate 0 desc.sourceModel empty string desc.targetModel empty string desc.

VARIABLES

leavesInfected double Number of new leaves infected (latent) per day.

A.10.2. strawberry::LeafProduction

Computes daily production of new leaves

PARAMETERS

productionRate 0.1 Number of leaves produced per day.

VARIABLES

value double desc.

Page 151: Unisim Explained 2015-06-08

A.10. strawberry plugin 145

A.11. UniSim plugin

The UniSim plugin contains a collection of models of general utility.

Author: Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.11.1. UniSim::Anonymous

An Anonymous model simply acts as a container of other models

A.11.2. UniSim::AsymptoticDecreasing

Asymptotic curve which begins at a value of max at x=0and decreases to min as a lowerasymtote ar large x. The slope parameter determines the curvature

PARAMETERS

x 0 x for which to calculate the value.min 1 Asymptotic minimum value attained at large $F x.max 0 Maximum value attained at x=0.slope 0.5 Slope of curve in the invert units of x.

VARIABLES

value double Value calculated from x.

A.11.3. UniSim::AsymptoticIncreasing

Asymptotic curve which begins at a value of min at x=0and increases to max as an upperasymtote ar large x. The slope parameter determines the curvature

PARAMETERS

x 0 x for which to calculate the value.min 0 Minimum value attained at x=0.max 1 Asymptotic maximum value attained at large $F x.slope 0.5 Slope of curve in the invert units of x.

VARIABLES

value double Value calculated from x.

A.11.4. UniSim::Calendar

The Calendar model keeps track of the date. Since latitude is one of its parameters, it alsoknows of the current day length. Solar elevation is calculated every time the hour of the day isset by a tick of the global clock object. For example,

Page 152: Unisim Explained 2015-06-08

146 Appendix A. Plug-ins Reference

#include <usbase/clock.h>double hour = 12.5; // Half-past noonclock()->doTick(hour);

PARAMETERS

latitude 52 Latitude of simulated system.initialDate 1/1/2000 Initial date of simulation. You should perform a

deepReset on your Calendar object after push-ing a new value to initialDate.

initialTimeOfDay 0:0:0 Initial time of day of simulation. Default is mid-night. You should perform a deepReset on yourCalendar object after pushing a new value toinitialDate.

timeStep 1 Duration of one integration time step in units deter-mined by timeUnit.

timeUnit d Time unit of timeStep: s)econds, m)inutes,h)ours, d)ays or y)ears.

timeStepOffset -1 The first values are reported to plot and table out-puts after one time step. With the default value of -1for timeStepOffset, the first output will occurat time zero, defined by initialDay and ini-tialTimeOfDay. Often this is whatis intuitively expected. With a timeStepOffset

value of zero the first output will occur one timestep after time zero.

VARIABLES

date date Current date.timeOfDay time Current time of day.dateTime datetime Current date and time.timeStepSecs double Duration of timeStep in seconds.totalTimeSteps int Total number of time steps performed since begin-

ning of simulation.totalTime int Total time, in units determined by timeUnit.

passed since beginning of simulation.totalDays double Total days passed since beginning of simulation.dayOfYear int Day number in year, also known as Julian day.day int Current day in month (1..31).month int Current month (1..12).year int Current year.hour int Current hour of the day (0..23).

Page 153: Unisim Explained 2015-06-08

A.11. UniSim plugin 147

minute int Current minute of the hour (0..59).second int Current second of the minute (0..59).dateAsReal double Date as a real number measured in years.dayLength double Current day length (hours).sinb double Sine of sun elevation, updated by the tick event

of the clock object.sinLD double Intermediate variable in astronomic calculations,

updated by the tick event of the clock object.cosLD double Intermediate variable in astronomic calculations,

updated by the tick event of the clock object.

A.11.5. UniSim::CrossTab

Output class. Description pending

PARAMETERS

fileName output.txt Name of output file.

A.11.6. UniSim::DayDegrees

This is a standard day-degree model. It obtains the daily average temperature from the weatherobject, which must exist as Model named weather having a pull variable named Tavg. Thedaily increment in day-degrees increases linerly above T0 until Topt. Above Tops it decreaseslinearly until Tmax.

The DayDegree model is derived from the PhysiologicalTime base class, like thealternatives: Days, HydroThermalTime, LactinTime and PhotoThermalTime. Theyall start updating right from the beginning, or when triggered by a child model, for example aTriggerByDate model.

PARAMETERS

T0 0 Lower temperature threshold for development(˚C).

Topt 100 Optimum temperature for development (˚C).Tmax 100 Upper temperature threshold for development

(˚C).T 0 weather[Tavg].

VARIABLES

step double Duration of latest time step (physiological timeunits).

Page 154: Unisim Explained 2015-06-08

148 Appendix A. Plug-ins Reference

total double Total duration since beginning of simulation (inphysiological time units) or since most recent trig-ger event (see e.g. TriggerByDate).

A.11.7. UniSim::Days

This model has the same pull variables as the DayDegrees model but it works in simplechronological time counting every day as just that, one day.

VARIABLES

step double Duration of latest time step (physiological timeunits).

total double Total duration since beginning of simulation (inphysiological time units) or since most recent trig-ger event (see e.g. TriggerByDate).

A.11.8. UniSim::Exponential

Simple exponential growth model, y = exp(rt ), where t is taken from the nearest model calledtime.

PARAMETERS

initialValue 0.05 Value at time zero (size or density units).growthRate 1 Exponential growth rate (size or density units per

time unit.

VARIABLES

value double Current value (size or density units).increment double Increment in value during the latest time step (size

or density units).

A.11.9. UniSim::Fixed

Often used for test purposes, or an initial version of a model, a Fixed model sets up fixedvalues for chosen parameters, and push and pull variables. The only type of values currentlysupported is double. Note that these ’artifical’ parameters and variables are not created untilinitialize() of Fixed is called. This is unlike their real counterparts which are alwayscreated in the model’s constructor

PARAMETERS

parameters () Parameters as name value pairs. E.g., ((Tavg22.5)(I 40)).

Page 155: Unisim Explained 2015-06-08

A.11. UniSim plugin 149

A.11.10. UniSim::FunctionalResponseGB

The Gutierrez-Baumgaertner functional response model, including the energy budget foregestion and respiration

PARAMETERS

apparancy 1 The apparancy of the resource, also known as at-tack rate or search rate.

resourceDensity 100 The density of the resource (prey, host).demand 1 The finite demand rate of the consumer (predator,

parasitoid) population.egestionRatio 0 Egestion fraction of consumption.respiration 0 Demand to cover respiration costs.

VARIABLES

supply double The net supply obtained (net resource consump-tion, parasitoids infected [0; demand].

sdRatio double The supply/demand ratio [0;1].totalDemand double Total demand obtained to cover net supply,egestion

and respiration.totalSupply double Total supply obtained to cover net supply, egestion

and respiration.egestion double Amount of totalSupply lost to egestion.attacksPerHost double Amount of totalSupply lost to egestion.numHostsAttacked double Amount of totalSupply lost to egestion.propHostsAt-

tacked

double Amount of totalSupply lost to egestion.

A.11.11. UniSim::HydroThermalTime

Hydrothermal time accounts for temperature and soil water potential at the same time. In thisimplementation the daily increment, as calculated by the DayDegrees model, is set to zero ifsoil water potential is less than the threshold,otherwise the daily increment is unaltered.A Model

named weather with a pull variable named SWP must exist to supply HydroThermalTime

with soil water potential.

PARAMETERS

T0 0 Lower temperature threshold for development(˚C).

Topt 100 Optimum temperature for development (˚C).Tmax 100 Upper temperature threshold for development

(˚C).

Page 156: Unisim Explained 2015-06-08

150 Appendix A. Plug-ins Reference

T 0 weather[Tavg].SWP0 0 Soil water potential threshold (MPa).SWPTopt 100 Temperature optimum (˚C). Above this value, the

soil water potential threshold increases linearly byKt.

Kt 0 Rate of increase (MPa/˚C) in soil water potentialthreshold above SWPTOpt.

VARIABLES

step double Duration of latest time step (physiological timeunits).

total double Total duration since beginning of simulation (inphysiological time units) or since most recent trig-ger event (see e.g. TriggerByDate).

swpThreshold double Actual soil water potential threshold for germina-tion (MPa).

A.11.12. UniSim::Inachis

A stage-structured model of the Nymphalid butterfly Inachis io.

PARAMETERS

sexRatio 0.5 Proportion females.eggProduction 100 Lifetime egg production of one female.

A.11.13. UniSim::Infection

Multi-way infection based upon Predation model.

PARAMETERS

apparencyMatrix empty string File with references to predator demands and ap-parency value for each predator x prey combi-nation.

A.11.14. UniSim::InsectLifeCycle

A stage-structured insect model. Under development

VARIABLES

eclosedReproduc-

tiveAdults

double Number of individuals just eclosed and enteringthe reproductive adult stage.

Page 157: Unisim Explained 2015-06-08

A.11. UniSim plugin 151

adultsToHiberna-

tion

double Number of individuals entering the hibernatingadult stage.

deadAdults double Number of individuals dead from senescence.

A.11.15. UniSim::LactinTime

This is the physiological time scale of Lactin et al. (reference to be added). It pulls the dailyaverage temperature from the weather object just like the DayDegrees model. The equationused to calculate the daily increment in physiological time is exp(ax) − exp(ab − (b − x)⁄ c) + d,where x is daily average temperature.

PARAMETERS

a 0.13 Equation parameter.b 42 Equation parameter.c 8 Equation parameter.d -0.1 Equation parameter.

VARIABLES

step double Duration of latest time step (physiological timeunits).

total double Total duration since beginning of simulation (inphysiological time units) or since most recent trig-ger event (see e.g. TriggerByDate).

A.11.16. UniSim::Map

Creates output as an animated map. The output element must hold exactly one Trace el-ement.

PARAMETERS

fileName output.txt Name of output file.range (0 100) Range of trace values on colour ramp. Use log-

transformed range values if log10 is set to true.steps 7 Number of steps on colour ramp.log10 no Log-transform trace values?.

Page 158: Unisim Explained 2015-06-08

152 Appendix A. Plug-ins Reference

A.11.17. UniSim::PhotoThermalTime

Photothermal time accounts for temperature and day length at the same time. In this implemen-tation the daily increment, as calculated by the DayDegrees model, is multiplied by day lengthin hours (acquired from the calendar object) divided by 24 hours.

PARAMETERS

T0 0 Lower temperature threshold for development(˚C).

Topt 100 Optimum temperature for development (˚C).Tmax 100 Upper temperature threshold for development

(˚C).T 0 weather[Tavg].

VARIABLES

step double Duration of latest time step (physiological timeunits).

total double Total duration since beginning of simulation (inphysiological time units) or since most recent trig-ger event (see e.g. TriggerByDate).

A.11.18. UniSim::Plot

Output class. Description pending

PARAMETERS

title empty string Title of plot shown in window top bar.logy no Log-transform y-axis? Log base 10 is used.ymin NA Minimum value displayed on y-axis. Write as log-

transformed value if logy.ymax NA Maximum value displayed on y-axis. Write as

log-transformed value if logy.penWidth 2 Pen width for curves and symbols.symbolSize 6 Size of symbols.

A.11.19. UniSim::Predation

Multi-way predation based upon FunctionalResponseGB model.

PARAMETERS

Page 159: Unisim Explained 2015-06-08

A.11. UniSim plugin 153

apparencyMatrix empty string File with references to predator demands and ap-parency value for each predator x prey combi-nation.

A.11.20. UniSim::RandomLognormal

The model maintains a random variable with a log-normal distribution.

PARAMETERS

minValue NA Minimum random value.maxValue NA Maximum random value.maxTries 100 Maximum number of tries to find a number inside

the interval minValue to maxValue. An excep-tion is cast if exceeded.

mean 10 Mean of log-normal distribution.sd 2 Standard deviation of log-normal distribution.

VARIABLES

value double Random value.

A.11.21. UniSim::RandomNormal

The model maintains a random variable with a normal distribution.

PARAMETERS

minValue NA Minimum random value.maxValue NA Maximum random value.maxTries 100 Maximum number of tries to find a number inside

the interval minValue to maxValue. An excep-tion is cast if exceeded.

mean 10 Mean of normal distribution.sd 2 Standard deviation of normal distribution.

VARIABLES

value double Random value.

A.11.22. UniSim::RandomPoisson

The model maintains a random variable with a Poisson distribution.

PARAMETERS

minValue NA Minimum random value.maxValue NA Maximum random value.

Page 160: Unisim Explained 2015-06-08

154 Appendix A. Plug-ins Reference

maxTries 100 Maximum number of tries to find a number insidethe interval minValue to maxValue. An excep-tion is cast if exceeded.

mean 10 Mean of Poisson distribution.

VARIABLES

value double Random value.

A.11.23. UniSim::RandomUniform

The model maintains a random variable with uniform (i.e. flat) distribution.

PARAMETERS

minValue NA Minimum random value.maxValue NA Maximum random value.maxTries 100 Maximum number of tries to find a number inside

the interval minValue to maxValue. An excep-tion is cast if exceeded.

VARIABLES

value double Random value.

A.11.24. UniSim::Range

The model produces equally spaced numbers inside a [min,max] range.

PARAMETERS

progress 0 steps[progress].min 0 Minimum value in range.max 100 Maximum value in range.scale linear Scale is either linear or log10. With a log10

scale, min=-2 and max=3, values in the range[0.01,1000] will result.

VARIABLES

value double Current value in range.

A.11.25. UniSim::Records

A Records model reads input from a text file formatted in columns with labels in the first line.Columns can be separated by spaces or tab characters. Labels may not contain spaces. A pullvariable will be created for every column in the input file, named after the column label. Therecan be more than one Records model present in a simulation.

Columns named date and time have special meanings, as they are used to synchronize

Page 161: Unisim Explained 2015-06-08

A.11. UniSim plugin 155

the readings from the input file with the calendar model. If you have either a date or a timecolumn, or both, then the calendar model will be reset to the time indicated in the first line ofrecords, before the simulation begins. While this is the behaviour usually wanted, you can alsochange this by setting imposeInitialDateTime to no.

The pull variables for date and time are mostly used for test purposes. If you need to knowabout the current date and time of day, you should pull this information from the calender

model. See page 145.

PARAMETERS

fileName records.txt Name of input file. If date and time are included,their column titles must be date and time.

fileLocation input Valid locations are the standard folders:input andplugins. The standard folders can be set from theFile|Locations menu.

imposeInitial-

DateTime

yes Impose the first date and time on calendar.Eitheror both, date and time, are imposed; it depends onwhich are included in the file. If neither is includ-ed, there is no effect of setting imposeInitial-DateTime to yes.

randomizeInitia-

lYear

no Pick a random initial year from the years availablein the records file.

VARIABLES

currentDateTime datetime The date and time of the current line in the inputfile. The calendar date and time will be at orpast this.

nextDateTime datetime The date and time of the next line in the input file.The calendar date and time will be at or be-fore this.

firstDateTime datetime The date and time of the first line in the input file.lastDateTime datetime The date and time of the last line in the input file.currentDate date The date part of currentDateTime.nextDate date The date part of nextDateTime.currentTime time The time part of currentDateTime.nextTime time The time part of nextDateTime.

A.11.26. UniSim::RunIteratorFixed

The model increments itsiteration counter for every update. Its value remains true as longas iteration ≤ numIterations.

PARAMETERS

numIterations 10 Number of iterations to count.

Page 162: Unisim Explained 2015-06-08

156 Appendix A. Plug-ins Reference

VARIABLES

value bool Is current iteration within the set number of iter-ations?.

iteration int Number of current iteration.

A.11.27. UniSim::Scenarios

The Scenarios model is used to iterate through several parameter settings. Descrip-tion pending…

PARAMETERS

fileName scenar-

ios.txtColumn-oriented text file with scenarios, line byline.

VARIABLES

iteration int Number of current iteration.numIterations int Number of current iteration.value bool Is current iteration within the set number of iter-

ations?.

A.11.28. UniSim::Scheduled

A Scheduled model produces canned data which are derived from a list of time value pairs,e.g., ((10.2 14.6) (45.1 32.3) (57.1 24.43)). Values are interpolated from thecurrent time which is taken from the nearest model called time. At times outside the rangecovered by the list (outside [10.2;57.1], in this case) values are extrapolated (to 14.6 or 24.43, inthis case).

PARAMETERS

schedule empty string Schedule as (time value) pairs. For example, ((010)(20.5 30)(65 48.6)).

VARIABLES

value double Current value.increment double Increment in value during the latest time step.

A.11.29. UniSim::SensitivityAnalysis

Integrator class. Description pending

PARAMETERS

maxSteps 100 description.factor -1 description.

Page 163: Unisim Explained 2015-06-08

A.11. UniSim plugin 157

relative -1 description.absolute -1 description.days 10 description.seconds 60 description.

VARIABLES

stepNumber int Number of current time step in this iteration.progress double Progress of current iteration [0,1].runNumber int Number of current iteration.

A.11.30. UniSim::Stage

The Stage model implements a distributed delay (Manetsch 1976, Vansickle 1977). The imple-mentation follows the original FORTRAN code of Abkin & Wolf (1976). The two parametersduration and k determine the average and variance of stage duration with variance equal to

2duration / 2k . The time scale used by the Stage model is determined by the nearest modelcalled time.

PARAMETERS

k 30 The number of age classes in the stage. The fewerage classes, the larger the variance on duration.

duration 100 The average duration of the stage: an inflow willemerge as an outflow dispersed over time, with adelay of duration on average and a variance of

2duration / 2k (Manetsch 1976).growthRate 1 For every quantity x that enters as in-

flow, growthRate*x will emerge as outflow.growthRate can be changed during the simula-tion but must be larger than zero. Use small values(e.g., −610 ) instead of zero. growthRate is also apull/push variable.

sdRatio 1 Supply/Demand ratio.instantMortality 0 Mortality [0..100] will be applied in the next time

step, before inflow is added.instantLossRate 0 Works just like mortality except the scale is a

ratio [0..1].phaseInflow 0 Inflow of dimension k.inflow 0 Number of units to be put into the stage in the next

time step.initialInflow 0 The initialInflow is entered as inflow at time

0.

Page 164: Unisim Explained 2015-06-08

158 Appendix A. Plug-ins Reference

phaseOutflowPro-

portion

0 Proportion that will change phase in next timestep.

VARIABLES

value double Number of units (e.g. individuals) in stage.number double Synonymous with value.inflowTotal double Total inflow into the stage since beginning of the

simulation.outflowTotal double Total outflow from the stage since beginning of

the simulation.phaseInflowTotal double Total phase change inflow into the stage since be-

ginning of the simulation.phaseOutflowTo-

tal

double Total phase change outflow from the stage sincebeginning of the simulation.

growthIncrement double Increment realised in this integration step.phaseOutflow QVec-

tor<double>Outflow of dimension k.

latestInflow double Inflow into the stage in latest time step.outflow double Outflow from the stage in latest time step.timeStep double The latest time step applied to the stage.

A.11.31. UniSim::StageAndPhase

The StageAndPhase model simulates a population undergoing two processes at the same, forinstancephysiological development (ageing) and incubation (after being infected). The discernthe two, the first is called a stage and the second, a phase. Phase change is characterisedby theparameters phaseL and phaseK with the same meaning as L and k in the Stage class.

PARAMETERS

k 30 The number of age classes in the stage. The fewerage classes, the larger the variance on duration.

duration 100 The average duration of the stage: an inflow willemerge as an outflow dispersed over time, with adelay of duration on average and a variance of

2duration / 2k (Manetsch 1976).growthRate 1 For every quantity x that enters as in-

flow, growthRate*x will emerge as outflow.growthRate can be changed during the simula-tion but must be larger than zero. Use small values(e.g., −610 ) instead of zero. growthRate is also apull/push variable.

sdRatio 1 Supply/Demand ratio.

Page 165: Unisim Explained 2015-06-08

A.11. UniSim plugin 159

instantMortality 0 Mortality [0..100] will be applied in the next timestep, before inflow is added.

instantLossRate 0 Works just like mortality except the scale is aratio [0..1].

phaseInflow 0 Inflow of dimension k.phaseK 30 Works like k but in the change phase process.phaseDuration 100 Works like duration but in the change phase

process.inflow 0 Number of units to be put into the stage in the next

time step.timeStep 1 Time step for stage development, for example, in

days or day-degrees.phaseTimeStep 1 Time step for phase development, for example, in

days or day-degrees.

VARIABLES

value double Number of units (e.g. individuals) in stage.number double Synonymous with value.inflowTotal double Total inflow into the stage since beginning of the

simulation.outflowTotal double Total outflow from the stage since beginning of

the simulation.phaseInflowTotal double Total phase change inflow into the stage since be-

ginning of the simulation.phaseOutflowTo-

tal

double Total phase change outflow from the stage sincebeginning of the simulation.

growthIncrement double Increment realised in this integration step.phaseOutflow QVec-

tor<double>Outflow of dimension k.

latestInflow QVec-

tor<double>Inflow into the stage in latest time step.

outflow QVec-

tor<double>Outflow from the stage in latest time step.

A.11.32. UniSim::StageDemand

This model calculates the growth demand of the stage, identified by stage, which must be oftype UniSim::Stage.The stage’s growthDemand method is used for the calculation.

PARAMETERS

stage empty string Name of stage from which the current demand isrequested by the growthDemand method.

Page 166: Unisim Explained 2015-06-08

160 Appendix A. Plug-ins Reference

VARIABLES

value double Current demand of stage.

A.11.33. UniSim::Steps

Integrator class. Description pending

PARAMETERS

maxSteps 100 description.

VARIABLES

stepNumber int Number of current time step in this iteration.progress double Progress of current iteration [0,1].runNumber int Number of current iteration.

A.11.34. UniSim::Sum

Calculates sum of variables supplied as a list of references. The variables must all be oftype double.

PARAMETERS

toAdd empty string List of references to add, e.g. (lion[density]leopard[density]).

VARIABLES

value double Sum of values in list.

A.11.35. UniSim::Table

Output class. Description pending

PARAMETERS

fileName output.txt Name of output file.

A.11.36. UniSim::TimeLimited

Integrator class. Description pending

PARAMETERS

maxTime 30 description.

VARIABLES

stepNumber int Number of current time step in this iteration.

Page 167: Unisim Explained 2015-06-08

A.11. UniSim plugin 161

progress double Progress of current iteration [0,1].runNumber int Number of current iteration.

A.11.37. UniSim::TriggerByDate

The TriggerByDate model can be used by other models to trigger changes in theirbehaviour.

PARAMETERS

fromDate 1/1/1900 The trigger will be true between fromDate andtoDate at the specified frequency.

dateShift 0 The value of dateShift is added to fromDate,This is useful for adding stochasticity.

toDate 1/1/1900 The trigger will be true between fromDate andtoDate at the specified frequency.

frequency Yearly Frequency of trigger (Daily or Yearly: Daily oryearly in date interval.

triggerAtReset yes Always trigger when model is reset?.

VARIABLES

value bool Triggered? Updated for every time step accordingto the rules set by the parameters.

A.11.38. UniSim::Weather

This Weather model simply supplies a daily reading from a Records child model. If therecords file contains a column named Tavg then that colum is used.Otherwise, if columns namedTmin and Tmax are present then Tavg is calculated as the average of those

VARIABLES

Tavg double Daily average temperature, either read fromrecords file, or calculated as the daily average ofminimum and maximum temperature. Must have achild model called records.

Page 168: Unisim Explained 2015-06-08

162 Appendix A. Plug-ins Reference

A.12. vg plugin

Virtual greenhouse.

Authors: Oliver Körner, AgroTech, Denmark.

Niels Holst, Aarhus University, Flakkebjerg, Denmark.

A.12.1. vg::AirInfiltration

Desc

PARAMETERS

timeStepSecs 0 calendar[timeStepSecs].height 0 construction[height].roofRatio 0 construction[roofRatio].sideRatio 0 construction[sideRatio].windspeed 0 environment[windspeed].screensAirTrans-

mission

0 screens[airTransmission].

leakage 0.5 Air exchange through leakage (m3 air/m3 green-house/h.

VARIABLES

value double Greenhouse air infiltration (m3 air/m2 green-house/s).

A.12.2. vg::BlackoutScreenController

Desc

PARAMETERS

fromTime 0:0:0 Screen is fully drawn after this time.toTime 0:0:0 Screen is fully drawn until this time.maxSignalHighHu-

midity

0.95 Maximum signal to screen at high humidity [0;1].

radiationThresh-

old

0 Radiation threshold for using blackout screen(W/m2).

followEner-

gyScreen

yes If the energy screen signal is larger than this, willthe blackout screen use that signal instead?.

time NA calendar[timeOfDay].radiation 0 environment[radiation].

Page 169: Unisim Explained 2015-06-08

A.12. vg plugin 163

isHumidityHigh no climate/humidity[isHigh].

VARIABLES

signal double Signal to shade screen [0;1].

A.12.3. vg::BoundaryLayerResistance

Desc

PARAMETERS

windSpeed 0 environment[windspeed].ventilation 0 greenhouse/ventilation[value].

VARIABLES

value double Boundary layer resistance against water vapour(s/m).

A.12.4. vg::ControlElement

Desc

PARAMETERS

signal 0 ..[signal].timeStepSecs 0 calendar[timeStepSecs].initState 0 Initial value of state.rate 0.1 Rate at which state approaches signal (per

minute).

VARIABLES

state double Current state of control element.course int Current course of change: Decreasing, Stable

or Increasing.

A.12.5. vg::ControlElementAsym

Desc

PARAMETERS

signal 0 ..[signal].timeStepSecs 0 calendar[timeStepSecs].initState 0 Initial value of state.

Page 170: Unisim Explained 2015-06-08

164 Appendix A. Plug-ins Reference

rateUp 0.1 Rate at which state approaches signal (per minute),when state is going up towards signal.

rateDown 0.01 Rate at which state approaches signal (per minute),when state is going down towards signal.

VARIABLES

state double Current state of control element.course int Current course of change: Decreasing, Stable

or Increasing.

A.12.6. vg::CoverDew

Desc

PARAMETERS

timeStepSecs 0 calendar[timeStepSecs].numTimeSteps 0 calendar[totalTimeSteps].coverArea 0 greenhouse/construction[coverArea].groundArea 0 greenhouse/construction[groundArea].Tcover 0 ../temperature[value].mcIndoors 0 climate/humidity[mc].dewScreen 0 regulation/screens[dew].

VARIABLES

value double Dew formation on greenhouse cover (g/m2/s).

A.12.7. vg::CoverTemperature

Desc

PARAMETERS

Tindoors 0 climate/temperature[value].Toutdoors 0 environment[temperature].Tsky 0 environment[skyTemperature].windspeed 0 environment[windspeed].latcov 0 greenhouse/construction[latcov].

VARIABLES

value double Cover temperature (oC).

Page 171: Unisim Explained 2015-06-08

A.12. vg plugin 165

A.12.8. vg::CoverVapourFlux

Desc

PARAMETERS

Tindoors 0 climate/temperature[value].mcIndoors 0 climate/humidity[mc].diffuseRadiation 0 climate/radiation[diffuse].rbH2O 0 crop/rbH2O[value].

VARIABLES

value double Vapour flux from cover (i.e. glass and screens)(kg/m2/s).

A.12.9. vg::Crop

Desc

PARAMETERS

kdiff 0.8 Extinction coefficient for diffuse light (-).coverage 0.1 Proportion of floor covered by crop [0;1].

VARIABLES

absorbedRadia-

tion

double Total radiation absorbed by crop (W/m2).

temperature double Average temperature of crop (oC).surfaceMoisture-

Content

double Average air moisture content at leaf surface(g/m3).

transpira-

tionConductance

double Total transpiration conductance of leaves (m/s).

latentHeatFlux double Average latent heat flux of crop (W/m2).dew double Total dew formation rate on crop (kg/m2/s).

A.12.10. vg::CropLayer

Desc

PARAMETERS

Tindoors 0 climate/temperature[value].mcIndoors 0 climate/humidity[mc].vpIndoors 0 climate/humidity[vp].vpdIndoors 0 climate/humidity[vpd].

Page 172: Unisim Explained 2015-06-08

166 Appendix A. Plug-ins Reference

diffuseRadiation 0 climate/radiation[diffuse].cropLai 0 crop/growth[lai].lowerPipeHeat-

Flux

0 pipes/lower[heatFlux].

kDiff 0 crop[kDiff].riH2O 0 crop/riH2O[value].rbH2O 0 crop/rbH2O[value].longWaveAbsorp-

tion

0 crop/radiationAbsorption[longWave].

VARIABLES

absorbedRadia-

tion

double Radiation absorbed by crop layer (W/m2).

temperature double Temperature of crop layer (oC).surfaceMoisture-

Content

double Air moisture content at leaf surface (g/m3).

transpira-

tionConductance

double Transpiration conductance of leaves (m/s).

latentHeatFlux double Latent heat flux of crop layer (W/m2).dew double Dew formation rate on crop (g/m2/s).

A.12.11. vg::CropRadiationAbsorption

Desc

PARAMETERS

Tindoors 0 climate/temperature[value].diffuseRadiation 0 climate/radiation[diffuse].screenTransmis-

sion

0 regulation/screens[lightTransmission].

lampLongWaveE-

mission

0 regulation/light/attributes[longWaveEmission].

lampShortWaveE-

mission

0 regulation/light/attributes[shortWaveEmission].

VARIABLES

longWave double Long wave absorption (thermal radiation, Bn)(W/m2).

shortWave double Short wave absorption (visible light, Rn) (W/m2).

Page 173: Unisim Explained 2015-06-08

A.12. vg plugin 167

A.12.12. vg::EnergyScreenBalance

Desc

PARAMETERS

indoorsDirectRa-

diation

0 climate/radiation[direct].

indoorsTempera-

ture

0 climate/temperature[value].

outdoorsTempera-

ture

0 environment[temperature].

KCover 0 construction[KCover].

VARIABLES

value double Value of energy balance (W/m2).

A.12.13. vg::EnergyScreenController

Desc

PARAMETERS

maxSignalHighHu-

midity

0.95 Maximum signal to screen at high humidity [0;1].

radiationThresh-

old

10 Radiation threshold for using energy screen(W/m2).

radiation 0 environment[radiation].isHumidityHigh no climate/humidity[isHigh].

VARIABLES

signal double Signal to shade screen [0;1].

A.12.14. vg::Environment

Desc

PARAMETERS

co2 350 CO2 concentration(ppm).windDirection 0 Wind direction [0;360].temperature 0 ./records[Tair].rh 0 ./records[RHair].radiation 0 ./records[GlobRad].diffuseRadiation 0 ./records[DifRad].windSpeed 0 ./records[WindSpeed].

Page 174: Unisim Explained 2015-06-08

168 Appendix A. Plug-ins Reference

skyTemperature 0 ./records[Tsky].

VARIABLES

directRadiation double Direct global radiation (W/m2).vp double Water vapour pressure (Pa).mc double Moisture content (g/m3).

A.12.15. vg::GreenhouseConstruction

Desc

PARAMETERS

width 50 Width (m).length 50 Length (m).height 4 Height (m).roofRatio 1 Roof/Side wall ratio (-).sideRatio 1 Side ratio ? (-).windowLength 2 Window length (m).windowHeight 0.825 Window height (m).fractionWindows 0.078 Fraction windows [0;1].alphaVentila-

tionMax

44 Max. ventilation opening (degrees).

latcov 35 Lat cover (degrees).Kcover 7.9 K value of greenhouse cover (W/m2/K).floorHec 6 Heat capacity of the floor (?).glassType single Possible values: double, hortiplus, single.lampType HPSL Possible values: hpsl, led.

VARIABLES

iGlassType int Glass type as integer.iLampType int Lamp type as integer.volume double Volume (m3).groundArea double Area of ground covered (m2).coverArea double Area of greenhouse cover (m2).averageHeight double Average height of greenhouse (m).

Page 175: Unisim Explained 2015-06-08

A.12. vg plugin 169

A.12.16. vg::GreenhouseEnergetics

Desc

PARAMETERS

coverDew 0 greenhouse/cover/dew[value].screenDew 0 regulation/screens[dew].cropDew 0 crop[dew].ventilation 0 greenhouse/ventilation[value].energyScreen-

State

0 screens/energy/control[state].

longWaveLight 0 light/attributes[longWaveEmission].shortWaveLight 0 light/attributes[shortWaveEmission].lampHeat 0 light/attributes[heatEmission].Toutdoors 0 environment[temperature].Tfloor 0 floor/temperature[state].cropLatentHeat-

Flux

0 crop[latentHeatFlux].

KScreenEnergy 5.2 K-value for energy screen (W/m2/K).KCover 7.9 K-value for greenhouse cover (W/m2/K).floorHec 6 Heat capacity of the floor (W/m2/K).

VARIABLES

energyBalance double Energy balance of greenhouse (W/m2).heatCapacity double Heat capacity of greenhouse (W/m2/K).Tunheated double Greenhouse temperature if not heated (oC).dewHeat double Heat generated from dew condensation (W/m2).outdoorsHeat double Heat from outside (W/m2).floorHeat double Heat from floor (W/m2).

A.12.17. vg::GreenhouseVentilation

Desc

VARIABLES

value double Total ventilation rate (m3/m2/s.

Page 176: Unisim Explained 2015-06-08

170 Appendix A. Plug-ins Reference

A.12.18. vg::HeatingDemand

Desc

PARAMETERS

Tminimum 0 setpoints/temperature[minimum].energyBalance 0 greenhouse/energetics[energyBalance].heatCapacity 0 greenhouse/energetics[heatCapacity].

VARIABLES

total double Total heat needed to reach desired minimum tem-perature (W/m2).

perPipe double total divided by number of pipes (W/m2).

A.12.19. vg::HumiditySetpoints

Desc

PARAMETERS

radiation 0 environment[radiation].daylightThresh-

old

10 Global radiation threshold for daylight (W/m2).

maxRHDay 80 Setpoint for relative humidity during the day (%).maxRHNight 90 Setpoint for relative humidity during the night

(%).minDeltaXBasis 1 Setpoint for delta x (g/m3).

VARIABLES

maxRH double Setpoint for maximum relative humidity (%).minDeltaX double Setpoint for minimum delta x (g/m3).

A.12.20. vg::IndoorsRadiation

Desc

PARAMETERS

glassType 0 construction[iGlassType].sinb 0 calendar[sinb].outdoorsDirec-

tRadiation

0 environment[directRadiation].

outdoorsDif-

fuseRadiation

0 environment[diffuseRadiation].

Page 177: Unisim Explained 2015-06-08

A.12. vg plugin 171

diffuseTransmis-

sion

0.79 Transmission of diffuse light through greenhouseconstruction [0;1].

VARIABLES

direct double Direct light transmitted through greenhouse con-struction (W/m2).

diffuse double Diffuse light transmitted through greenhouse con-struction (W/m2).

A.12.21. vg::LampAttributes

Desc

PARAMETERS

lampType 0 construction[iLampType].capacity 40 Capacity of installed lamps (W/m2).ballastCorrec-

tion

1 Set to >1 (e.g, 1.15) if capacity includes ballast.

VARIABLES

heatEmission double Convective heat emission (W/m2).longWaveEmission double Long wave emission (thermal radiation, Bn)

(W/m2).shortWaveEmis-

sion

double Short wave emission (visible light, Rn) (W/m2).

parEmission double PAR radiation (W/m2).energyUse double Energy used (W/m2).

A.12.22. vg::LightController

Desc

PARAMETERS

onDay 300 Julian day when to switch on (1..365).offDay 60 Julian day when to switch off (1..365).onTime 0:0:0 Time when to switch on.offTime NA Time when to switch off.onRadiation 0 Outdoors radiation when to switch on (W/m2).offRadiation 20 Outdoors radiation when to switch on (W/m2).day 0 calendar[dayOfyear].time NA calendar[timeOfDay].

Page 178: Unisim Explained 2015-06-08

172 Appendix A. Plug-ins Reference

radiation 0 environment[radiation].

VARIABLES

signal double Signal to lamp (0 or 1).signalDay bool Switch on according to day?.signalTime bool Switch on according to time of day?.signalRadiation bool Switch on according to outdoors radiation?.

A.12.23. vg::MicroclimateHumidity

Desc

PARAMETERS

timeStepSecs 0 calendar[timeStepSecs].mcOutdoors 0 environment[mc].height 0 greenhouse/construction[averageHeight].ventilation 0 greenhouse/ventilation[value].temperature 0 ../temperature[value].mcCropSurface 0 crop[surfaceMoistureContent].cropTranspira-

tionConductance

0 crop[transpirationConductance].

screenState 0 screens/energy/control[state].Tscreen 0 screens/energy/temperature[value].Tcover 0 greenhouse/cover/temperature[value].maxRH 0 setpoints/humidity[maxRH].minDeltaX 0 setpoints/humidity[minDeltaX].

VARIABLES

rh double Relative humidity (%).prevRh double Relative humidity (%).vp double Water vapour pressure (Pa).vpd double Water vapour pressure deficit (Pa).mc double Moisture content (g/m3).moistureDeficit double Absolute humidity deficit (g/kg).isHigh bool Is humidity above setpoints?.

A.12.24. vg::MicroclimateTemperature

Desc

Page 179: Unisim Explained 2015-06-08

A.12. vg plugin 173

PARAMETERS

energyBalance 0

heatCapacity 0

pipesHeatFlux 0

VARIABLES

value double

A.12.25. vg::PidControl

Desc

PARAMETERS

direction ceiling Is target value a lower (floor) or upper (ceiling)limit? Possible values: ceiling, floor.

timeStepSecs 0 calendar[timeStepSecs].actualValue 20 Current value being regulated.targetValue 20 Value to regulate towards.initSignal 0 Initial value of signal.Kp 1 Proportional gain.Ti 1000000 Integral time.Td 0 Derivative time.

VARIABLES

signal double Response of PID control.

A.12.26. vg::Pipe

Desc

PARAMETERS

pipeType s51 Possible values: p25, s26, s33, s51.heatingDemand 0 heating/demand/pipe[signal].Tunheated 0 greenhouse/energetics[Tunheated].energyScreen-

Course

0 screens/energy/control[course].

Tminimum 0 setpoints/temperature[minimum].Tindoors 0 climate/temperature[value].actualTpipe 0 ./control[state].pipeLength 1.822 Pipe length (m/m2).

Page 180: Unisim Explained 2015-06-08

174 Appendix A. Plug-ins Reference

TmaxPipe 70 Max pipe temperature (oC).

VARIABLES

signal double Desired pipe temperature (oC).heatFlux double Heat flux from pipe (W/m2).

A.12.27. vg::Pipes

Desc

PARAMETERS

timeStepsSecs 0 calendar[timeStepSecs].

VARIABLES

heatFlux double Total heat transfered from all pipes (W/m2).energyUsed double Accumulated energy used for heating (MJ/m2).

A.12.28. vg::ProportionalControl

Desc

PARAMETERS

direction ceiling Is target value a lower (floor) or upper (ceiling)limit? Possible values: ceiling, floor.

actualValue 20 Current value being regulated.targetValue 20 Value to regulate towards.gapMultiplier 1 Multiplier on gap between actualValue and

targetValue.pBand 5 Proportional band of response.maxSignal 100 Maximum absolute value of signal.signalNotNega-

tive

yes Should a negative signal be set to zero?.

VARIABLES

signal double Response between zero and maxSignal, increas-ing with increasing difference between actual-Value and targetValue, positive or negative ac-cording to direction of change and setting of sig-nalNotNegative flag.

Page 181: Unisim Explained 2015-06-08

A.12. vg plugin 175

A.12.29. vg::ScreenDew

Desc

PARAMETERS

timeStepSecs 0 calendar[timeStepSecs].numTimeSteps 0 calendar[totalTimeSteps].state 0 ../control[state].Tscreen 0 ../temperature[value].mcIndoors 0 climate/humidity[mc].

VARIABLES

value double Dew formation at all screens (g/m2/s).

A.12.30. vg::Screens

Desc

VARIABLES

temperature double Average temperature of screens [oC].airTransmission double Transmission of air through all screens [0;1].lightTransmis-

sion

double Transmission of light through all screens [0;1].

dew double Dew formation at all screens (kg/m2/s).

A.12.31. vg::ScreenTemperature

Desc

PARAMETERS

Tindoors 0 climate/temperature[value].Tcover 0 greenhouse/cover/temperature[value].

VARIABLES

value double Screen temperature (oC).

A.12.32. vg::ScreenTransmission

Desc

PARAMETERS

screenState 0 ../control[state].

Page 182: Unisim Explained 2015-06-08

176 Appendix A. Plug-ins Reference

ratio 0.3 Ratio of transmission [0;1].

VARIABLES

value double Screen transmission [0;1].

A.12.33. vg::ShadeScreenController

Desc

PARAMETERS

maxSignalHighHu-

midity

0.95 Maximum signal to screen at high humidity [0;1].

radiationThresh-

old

10 Radiation threshold for using shade screen(W/m2).

tempera-

tureThreshold

28 Temperature threshold for using shade screen(oC).

tolerance 2000 Low tolerance gives steep reaction and high tol-erance gives gentle reaction, when threshold iscrossed (>=0.

followEner-

gyScreen

yes If the energy screen signal is larger than this, willthe blackout screen use that signal instead?.

radiation 0 environment[radiation].temperature 0 climate/temperature[value].isHumidityHigh no climate/humidity[isHigh].

VARIABLES

signal double Signal to shade screen [0;1].

A.12.34. vg::StomatalResistance

Desc

PARAMETERS

rh 0 climate/humidity[rh].co2 0 climate/co2/[value].PgcMol 0 crop/photosynthesis[PgcMol].rbH2O 0 crop/rbH2O[value].

VARIABLES

value double Stomatal resistance against water vapour (s/m).

Page 183: Unisim Explained 2015-06-08

A.12. vg plugin 177

A.12.35. vg::TemperatureSetpoints

Desc

PARAMETERS

humidityIncre-

ment

0 ./humidityIncrement[signal].

humidityDecre-

ment

0 ./humidityDecrement[signal].

setMinimum 20 Desired minimum temperature, which may beincreased by humidity (oC).

setMaximum 27 Desired maximum temperature, which may belowered by humidity (oC).

VARIABLES

minimum double Desired minimum temperature, corrected for hu-midity (oC).

maximum double Desired maximum temperature, corrected for hu-midity (oC).

A.12.36. vg::VentilationByTemperatureDiff

Desc

PARAMETERS

indoorsTempera-

ture

0 climate/temperature[value].

outdoorsTempera-

ture

0 environment[temperature].

ventilationMax 0 ../maximum[signal].

VARIABLES

signal double The desired ventilation opening [0;100].

A.12.37. vg::VentilationController

Desc

PARAMETERS

windSidePropor-

tion

0.75 The wind side signal as a proportion of the lee sidesignal [0;1].

indoorsTempera-

ture

0 climate/temperature[value].

Page 184: Unisim Explained 2015-06-08

178 Appendix A. Plug-ins Reference

outdoorsTempera-

ture

0 environment[temperature].

maxTemperature 0 setpoints/temperature[maximum].windSpeed 0 environment[windspeed].byTemperature 0 ./byTemperature[signal].byTemperatureD-

iff

0 ./byTemperatureDiff[signal].

byHumidity 0 ./byHumidity[signal].maxSignal 0 ./maximum[signal].

VARIABLES

signal double Synonym for leeSideSignal.leeSideSignal double Ventilation opening on the lee side [0;100].windSideSignal double Ventilation opening on the wind side [0;100].

A.12.38. vg::VentilationLatentEnergyBalance

Desc

PARAMETERS

timeStepSecs 0 calendar[timeStepSecs].groundArea 0 greenhouse/construction[groundArea].height 0 greenhouse/construction[averageHeight].ventilation 0 greenhouse/ventilation[value].mcIndoors 0 climate/humidity[mc].mcOutdoors 0 environment[mc].

VARIABLES

value double Balance of latent heat by ventilation (W/m2).totalLoss double Total latent heat lost through ventilation (MJ/m2).

A.12.39. vg::VentilationMax

Desc

PARAMETERS

radiation 0 environment[radiation].thresholdRadia-

tion

10 Threshold radiation day vs. night (W/m2).

dayMax 100 Max. ventilation opening in the day [0;100].

Page 185: Unisim Explained 2015-06-08

A.12. vg plugin 179

nightMax 5 Max. ventilation opening in the night [0;100].

VARIABLES

signal double Max. ventilation opening [0;100].

A.12.40. vg::WindowsVentilation

Desc

PARAMETERS

Tindoors 0 climate/temperature[value].Toutdoors 0 environment[temperature].windspeed 0 environment[windspeed].windowLength 0 construction[windowLength].alphaVentila-

tionMax

0 construction[alphaVentilationMax].

fractionWindows 0 construction[fractionWindows].ventilationLee-

Side

0 regulation/ventilation/leeSideControl[state].

ventilationWind-

Side

0 regulation/ventilation/windSideControl[state].

VARIABLES

value double Greenhouse ventilation rate through windows (m3air/m2 greenhouse/s.

Page 186: Unisim Explained 2015-06-08

180 Appendix A. Plug-ins Reference

Page 187: Unisim Explained 2015-06-08

ReferencesAbkin MH & Wolf C. Computer library for agricultural systems simulation. Distributed delayroutines: DEL, DELS, DELF, DELLF, DELVF, DELLVF, pages 1-88. Tech. Rep. CLASS-8(1976), Department of Agricultural Economics, Michigan State University.

Alados I & Alados-Arboledas L. Validation of an empirical model for photosynthetically activeradiation. International Journal of Climatology 19, 1145-1152 (1999).

Banks RB & Herrera FF. Effect of wind and rain on surface reaeration. Journal of theHydraulics Division 103, 489-504 (1977).

Benjamin LR & Park SE. The Conductance model of plant growth and competition inmonoculture and species mixtures: a review. Weed Research 47, 284-298 (2007).

Boyd CE & Teichert-Coddington D. Relationship between wind speed and reaeration in smallaquaculture ponds. Aquacultural Engineering 11, 121-131 (1992).

Crusius J & Wanninkhof R. Gas transfer velocities measured at low wind speed over a lake.Limnology and Oceanography 48, 1010-1017 (2003).

Deacon 1977. Gas transfer to and across an air-water interface. Tellus 29, 363-374 (1977).

Emerson S. Gas exchange rates in small Canadian shield lakes. Limnology and Oceanography20, 754-761 (1975).

Gelda RK, Auer MT, Effler SW, Chapra SC & Storey ML. Determination of reaeration coeffi-cients: whole-lake approach. Journal of Environmental Engineering 122, 269-275 (1996).

Gelda RK & Effler SW. Estimating oxygen exchange across the air˘water interface of ahypereutrophic lake. Hydrobiologia 487, 243-254 (2002).

Holst N, Lang A, Gabor LOtto M. Increased mortality is predicted of Inachis io larvae causedby Bt-maize pollen in European farmland. Ecological Modelling,250, 126-133 (2013).

Jellison R & Melack JM. Meromixis in hypersaline Mono Lake, California. 1. Stratificationand vertical mixing during the onset, persistence, and breakdown of meromixis. Limnology andOceanography 38, 1008-1019 (1993).

Kropff MJ & van Laar HH. Modelling Crop-Weed Interactions, pages 1-274. CAB Internation-al, Wallingford, UK and International Rice Research Institute, Manila, The Philippinnes, 1993.

Liboriussen L, Landkildehus F et al.. Global warming: Design of a flow-through shallow lakemesocosm climate experiment. Limnol.Oceanogr.: Methods 3, 1-9 (2005).

Liboriussen L, Lauridsen TL F et al.. Effects of warming and nutrients on sediment communityrespiration in shallow lakes: an outdoor mesocosm experiment. Freshwater Biology ?, ?-?

181

Page 188: Unisim Explained 2015-06-08

182 References

(2010).

Liss PS. Processes of gas exchange across an air-water interface. Deep Sea Research andOceanographic Abstracts 20, 221-238. (1973).

Livingstone DM & Imboden DM. The non-linear influence of wind-speed variability on gastransfer in lakes. Tellus B 45, 275-295 (1993).

Manetsch TJ. Time-varying distributed delays and their use in aggregate models of largesystems. IEEE Transactions on Systems,Man and Cybernetics 6, 547-553 (1976).

Mattingly GE. Experimental study of wind effects on reaeration. Journal of the HydraulicsDivision 103, 311-323 (1977).

O’Connor DJ. Wind effects on gas-liquid transfer coefficients. Journal of EnvironmentalEngineering 109, 731-752 (1983).

Odum HT. Primary production in flowing waters. Limnology and Oceanography 1, 102-117(1956).

Park SE, Benjamin LR, Aikman DP & Watkinson AR. Predicting the growth interactionsbetween plants in mixed species stands using a simple mechanistic model. Annals of Botany 87,523-536 (2001).

Portielje R & Lijklema L. The effect of reaeration and benthic algae on the oxygen balance ofan artificial ditch. Ecological Modelling 79, 35-48 (1995).

Serret P, Robinson C, Fernández E, Teira E, Tilstone G & Pérez V. Predicting plankton netcommunity production in the Atlantic Ocean. Deep Sea Research Part II: Topical Studies inOceanography 56, 941-953. (2009).

Storkey J. Modelling assimilation rates of 14 temperate arable weed species as a function of theenvironment and leaf traits. Weed Research 45, 361-370 (2005).

Udo SO & Aro TO. Global PAR related to global solar radiation for central Nigeria. Agricultur-al and Forest Meteorology 97, 21-31 (1999).

Vansickle J. Attrition in distributed delay models. IEEE Transactions on Systems, Man andCybernetics 7, 635-638 (1977).

Wanninkhof RIK, Ledwell JR & Broecker WS. Gas exchange-wind speed relation measuredwith sulfur hexafluoride on a lake. Science 227, 1224-1226 (1985).

Wetzel RG. Limnology.Lake and River Ecosystems. Academic Press, San Diego, 2001.

Page 189: Unisim Explained 2015-06-08

Indexa A, 115, 117, 119, 143, 151A0, 119absolute, 157absorbedRadiation, 165, 166accumulated, 143activationRate, 141actualTpipe, 173actualValue, 173, 174Adult, 141adultsToHibernation, 151AirInfiltration, 162airTransmission, 175alive, 129allocatedPerPlant, 128, 129allocation, 124, 127allocationRate, 128alpha, 119, 120alphaVentilationMax, 168, 179AlwaysIncludedPopulations, 132Anonymous, 145apparancy, 149apparencyMatrix, 150, 153Ar, 119Area area, 124, 126AreaDensityEven, 124AreaDensitySymmetric, 125AreaDensityTapering, 125AreaDensityTopheavy, 125AssimilationMaxGivenTemp, 125AsymptoticDecreasing, 145AsymptoticIncreasing, 145attacksPerHost, 149availableProduction, 130AvailableResource, 133averageHeight, 168avgs, 140awe, 111b, 115, 119, 143, 151ballastCorrection, 171beta, 120BlackoutScreenController, 162

BoundaryLayerResistance, 163byHumidity, 178byTemperature, 178byTemperatureDiff, 178c, 119, 121, 151c1, 115c2, 115Calendar, 145capacity, 171CarryingCapacity carryingCapacity, 134,

137CH2ORequirement, 128co2, 167, 176CO2Assimilation, 124, 126, 128, 129Community, 117, 125, 132Competition, 132CompetitionModel, 132CompetitiveInhibition, 133conductance, 117ControlElement, 163ControlElementAsym, 163cosLD, 147course, 163, 164coverage, 165coverArea, 164, 168CoverDew coverDew, 164, 169CoverTemperature, 164CoverVapourFlux, 165Crop, 111, 165cropDew, 169cropEffectOnEmergence, 114cropLai, 166cropLaiExp, 114cropLatentHeatFlux, 169CropLayer, 165CropRadiationAbsorption, 166crops, 113cropTranspirationConductance, 172CrossTab, 147CumulativeEmergence, 143currentDate, 155

183

Page 190: Unisim Explained 2015-06-08

184 Index

currentDateTime, 155currentPartition, 128currentTime, 155d, 151dailyEmergenceDensity, 114dailyEmergenceRatio, 114dailyEmergenceRatioPotential, 115dailyFecundity, 142dailyLoss, 142dailyRainfall, 142date, 146dateAsReal, 147dateMax, 121dateShift, 121, 161dateTime, 146day, 112, 127, 146, 171DayDegrees, 147dayLength, 147daylightThreshold, 170dayMax, 178dayOfYear, 146Days days, 148, 157deadAdults, 151demand, 149DemandRate, 135density Density density, 129, 132, 135, 137,

138, 140, 141DensityActivityCoefficient, 135DepositionFlush, 120DepositionMonotonicSampled, 120DepositionMonotonicWeibull, 120dew, 165, 166, 175dewHeat, 169dewScreen, 164diffuse, 171diffuseRadiation, 165, 166, 167diffuseTransmission, 171direct, 171direction, 173, 174directRadiation, 168distance, 122distanceExp, 122distanceMin, 122dormant, 114dormantInflow, 114dose, 121

duration, 120, 157, 158dweight, 118dynamic_photosynthesis, 119EarlyGrowth, 126earlyGrowthThreshold, 125eclosedReproductiveAdults, 150ecotox, 120ED50, 121Effect, 133EffectRatio, 134egestion, 149egestionRatio, 149Egg, 141eggProduction, 150eggsActivated, 141eggsLaidInWater, 141eggsLaidOnGround, 141eggsLost, 141emergenceCalendar, 114EnableCompetition, 132EnableEffect, 133, 134EnableStochasticCommunity, 132energyBalance, 169, 170, 173EnergyScreenBalance, 167EnergyScreenController, 167energyScreenCourse, 173energyScreenState, 169energyUse, 171energyUsed, 174Environment, 167EnzymaticReaction, 133eps, 118Evenness, 132Exponential, 148F, 117factor, 156fecundity, 141fileLocation, 155fileName, 147, 151, 155, 156, 160firstDateTime, 155FirstOrderRateConstant, 135FirstOrderReaction, 134Fixed, 148floorHeat, 169floorHec, 168, 169followEnergyScreen, 162, 176

Page 191: Unisim Explained 2015-06-08

Index 185

fractionWindows, 168, 179frequency, 161fromDate, 161fromTime, 162FunctionalResponseGB, 149fz, 118g, 116gapMultiplier, 174GeneralEffect, 134GiniCoefficient, 132glassType, 168, 170GreenhouseConstruction, 168GreenhouseEnergetics, 169GreenhouseVentilation, 169grossProduction, 124, 126, 128, 129groundArea, 164, 168, 178growthIncrement, 158, 159GrowthRate growthRate, 126, 134, 137, 148,

157, 158growthResp, 128, 130gSini, 1190, 126harvestDay, 111harvestMonth, 111heatCapacity, 169, 170, 173heatEmission, 171heatFlux, 174HeatingDemand heatingDemand, 170, 173Height height, 126, 127, 162, 168, 172, 178hmax, 126hour, 146humidityDecrement, 177humidityIncrement, 177HumiditySetpoints, 170HydrodynamicSRScale, 137HydroThermalTime, 149iGlassType, 168iLampType, 168imposeInitialDateTime, 155Inachis, 150InactiveEgg, 141increment, 148, 156inDensity, 139indoorsDirectRadiation, 167IndoorsRadiation, 170indoorsTemperature, 167, 177

Infection, 144, 150infectionRate, 144inflow, 141, 157, 159inflowAsDensity, 113inflowAsDensityEqs, 113inflowTotal, 158, 159InhibitionConstant, 133InhibitorConcentration, 133initDay, 117initial, 130initialArea, 126initialDate, 146initialDensity InitialDensity, 113, 134, 137,

141initialInflow, 157initialN, 137InitialResource, 132InitialSubstrate, 133, 134, 135initialTimeOfDay, 146initialValue, 142, 148initMonth, 117initSignal, 173initState, 163initWeight, 117inoculumDensity, 144InsectLifeCycle, 150instantLossRate, 157, 159InstantMortality instantMortality, 112, 113,

114, 127, 157, 159intercept, 127intercom, 124intrinsicRate, 137irradiation, 118, 130IsActive, 134isHigh, 172isHumidityHigh, 163, 167, 176isInEarlyGrowth, 126iteration, 156k, 118, 157, 158Kcover KCover, 167, 168, 169kdiff kDiff, 165, 166kDiffuse, 124Kp, 173KScreenEnergy, 169Kt, 150LA_per_plant, 118

Page 192: Unisim Explained 2015-06-08

186 Index

LactinTime, 151LagPhase, 134lai LAI, 112, 113, 118, 124, 126, 129laiCalendar, 112LampAttributes, 171lampHeat, 169lampLongWaveEmission, 166lampShortWaveEmission, 166lampType, 168, 171lastDateTime, 155latcov, 164, 168latentHeatFlux, 165, 166latestInflow, 158, 159latitude, 146Leaf, 119LeafProduction, 144leakage, 162leavesInfected, 144leeSideSignal, 178length, 168lightAbsorption, 124, 126, 128, 129LightController, 171lightTransmission, 175LightUseEfficiencyGivenTemp, 127log10, 151LogLogistic, 121logy, 152longWave, 166longWaveAbsorption, 166longWaveEmission, 171longWaveLight, 169LossB, 137, 140LossN, 137, 140lossRate, 141lower, 121lowerPipeHeatFlux, 166Lz, 118maintenanceCoeff, 128maintenanceResp, 128, 129Map, 151Mass mass, 127, 129max, 145, 154maxAmax, 125maxflow, 137maximum, 177MaximumVelocity, 135

maxN, 140MaxPopulations, 132maxRH, 170, 172maxRHDay, 170maxRHNight, 170maxSignal, 174, 178maxSignalHighHumidity, 162, 167, 176maxSR, 138maxSteps, 156, 160maxTemperature, 178maxTime, 160maxTries, 153, 154maxValue, 153, 154maxYield, 111maxYieldLossPct, 111mc, 168, 172mcCropSurface, 172mcIndoors, 164, 165, 175, 178mcOutdoors, 172, 178mean, 153, 154MichaelisMentenConstant, 135MicrobialCommunity, 132MicroclimateHumidity, 172MicroclimateTemperature, 172min, 145, 154minDeltaX, 170, 172minDeltaXBasis, 170minimum, 177MinPopulations, 132minute, 147minValue, 153, 154moistureDeficit, 172month, 112, 127, 146mortalities, 112mortality, 139MortalityRate, 134MosquitoFecundity, 142Mussel, 137mussel_bed, 137MusselGrowthRate, 137n N, 118, 137, 140netAllocation, 128, 130nextDate, 155nextDateTime, 155nextTime, 155nightMax, 179

Page 193: Unisim Explained 2015-06-08

Index 187

nonDormant, 114Npeak, 122number, 114, 158, 159numHostsAttacked, 149numIterations, 155, 156numTimeSteps, 164, 175offDay, 171offRadiation, 171offTime, 171onDay, 171onRadiation, 171onsetFileName, 120onTime, 171Organ, 128outdoorsDiffuseRadiation, 170outdoorsDirectRadiation, 170outdoorsHeat, 169outdoorsTemperature, 167, 177, 178outflow, 158, 159outflowAsDensity, 113outflowAsDensityEqs, 113outflowTotal, 158, 159parameters, 148parDiffuse, 131parDirect, 131parEmission, 171PARmin, 119PartitioningFixed, 128PartitioningFixedByStage, 129parTotal, 131pBand, 174penWidth, 152perPipe, 170PgcMol, 176phase, 118phaseDuration, 159phaseInflow, 157, 159phaseInflowTotal, 158, 159phaseK, 159phaseOutflow, 158, 159phaseOutflowProportion, 158phaseOutflowTotal, 158, 159phaseTimeStep, 159Phenology, 129phi, 117PhotoThermalTime, 152

PidControl, 173Pipe, 173pipeLength, 173Pipes, 174pipesHeatFlux, 173pipeType, 173Plant, 117, 129PlantGrowthStage, 112Plot, 152Pollen, 121pollenDensity, 122pollenDepositionRate, 122pollenDepositionTotal, 122PollenLossConstant, 122PollenLossSampled, 123Population, 134Predation, 152prevRh, 172productionRate, 144progress, 154, 157, 160, 161projectedDeqs, 116projectedMass, 116projectedYieldLossPct, 116propAllocatedPerPlant, 128propHostsAttacked, 149ProportionalControl, 174proportionEggsInWater, 141radiation, 162, 167, 170, 172, 176, 178radiationThreshold, 162, 167, 176radix, 125randomizeInitialYear, 155RandomLognormal, 153RandomNormal, 153RandomPoisson, 153RandomUniform, 154range Range, 151, 154rate, 122, 163rateDown, 164rates, 123rateUp, 164ratio, 176rbH2O, 165, 166, 176Reaction, 135Records, 154relative, 157resourceDensity, 149

Page 194: Unisim Explained 2015-06-08

188 Index

respiration, 149rh, 167, 172, 176Richness, 132riH2O, 166roofRatio, 162, 168Rotation, 113RunIteratorFixed, 155runNumber, 157, 160, 161rvf, 141S, 119S0, 119S60, 119SalinityScale, 138SalinitySRScale, 138scale, 154scatteringCoeff, 124Scenarios, 156schedule, 156Scheduled, 156screenDew ScreenDew, 169, 175Screens, 175screensAirTransmission, 162screenState, 172, 175ScreenTemperature, 175screenTransmission ScreenTransmission,

166, 175sd, 153sdRatio, 149, 157, 158SearchRate searchrate, 134, 138second, 147seconds, 157seed_emergence, 143SeedBank, 113seedProdExp, 115seedProdSlope, 115seedsDropping, 116SensitivityAnalysis, 156Seq, 119setMaximum, 177setMinimum, 177sexRatio, 141, 150ShadeScreenController, 176ShannonIndex, 132shortWave, 166shortWaveEmission, 171shortWaveLight, 169

sideRatio, 162, 168signal, 163, 167, 172, 173, 174, 176, 177, 178,

179signalDay, 172signalNotNegative, 174signalRadiation, 172signalTime, 172SimpsonIndex, 132sinb, 147, 170Sini, 119sinLD, 147skyTemperature, 168slope, 121, 126, 127, 130, 145slopeYieldLossPct, 111Smax, 138, 139Smin, 138, 139sourceModel, 144sowingDay, 111sowingMonth, 111SpeciesName, 134SpecificLeafArea, 130Stage stage, 157, 159StageAndPhase, 158StageDemand, 159Starfish, 138StarfishFeedingRate, 139StarfishGrowthRate, 139StarfishSalMortality, 139state, 163, 164, 175stdensity stDensity, 139, 139step, 147, 148, 150, 151, 152stepNumber, 157, 160steps Steps, 151, 160stgrowthRate, 139StomatalResistance, 176strawberry, 144Substrate, 133, 134, 135SubstratePDD, 133, 134, 135Sum, 160sum_sz, 117supply, 139, 140, 149SupplyDemandRatio, 135surfaceMoistureContent, 165, 166survival, 127SWP, 143SWP0, 150

Page 195: Unisim Explained 2015-06-08

Index 189

swpThreshold, 150SWPTopt, 150symbolSize, 152sz, 118T, 115, 147, 150, 152T0, 147, 149, 152Table, 160targetModel, 144TargetParameter, 134TargetPopulations, 133, 134targetValue, 173, 174Tavg, 115, 130, 143, 161Tcover, 164, 172, 175Td, 173Tday, 130temperature, 139, 140, 165, 166, 167, 172,

175, 176TemperatureScale, 140TemperatureSetpoints, 177TemperatureStScale, 140temperatureThreshold, 176testMode, 126Tfloor, 169theta, 118, 119thin, 140thinning, 140thresholdRadiation, 178Ti, 173time, 162, 171TimeLimited, 160timeOfDay, 146timeStep, 146, 158, 159timeStepOffset, 146timeStepSecs, 146, 162, 163, 164, 172, 173,

175, 178timeStepsSecs, 174timeUnit, 146Tindoors, 164, 165, 166, 173, 175, 179title, 152tm, 119, 126Tmax, 147, 149, 152TmaxPipe, 174Tminimum, 170, 173toAdd, 160toDate, 161tolerance, 176

Topt, 147, 149, 152total, 120, 121, 148, 150, 151, 152, 170total_sz, 118totalDays, 146totalDemand, 149totalEggsInflow, 141totalEmergenceDensity, 114totalEmergenceRatio, 114totalLoss, 178totalSupply, 149totalTime, 146totalTimeSteps, 146totalWeight, 118toTime, 162Toutdoors, 164, 169, 179transpirationConductance, 165, 166triggerAtReset, 161TriggerByDate, 161ts, 119Tscreen, 172, 175Tsky, 164Tsum, 112, 115Tunheated, 169, 173UniSim, 145upper, 121useTemperature, 119value, 120, 121, 122, 123, 124, 125, 127, 128,

129, 130, 137, 138, 139, 140, 142, 144,145, 148, 153, 154, 156, 158, 159, 160,161, 162, 163, 164, 165, 167, 169, 173,175, 176, 178, 179

values, 129Velocity, 133, 134, 135VelocityPDD, 133, 134, 135, 136ventilation, 163, 169, 172, 178VentilationByTemperatureDiff, 177VentilationController, 177VentilationLatentEnergyBalance, 178ventilationLeeSide, 179ventilationMax VentilationMax, 177, 178ventilationWindSide, 179vg, 162volume, 168vp, 168, 172vpd, 172vpdIndoors, 165

Page 196: Unisim Explained 2015-06-08

190 Index

vpIndoors, 165waterLevel WaterLevel, 142, 142waterLevelThreshold, 142Weather, 115, 118, 130, 143, 161Weed, 115weedExchangeRate, 111weight, 118width, 168windDirection, 167windowHeight, 168windowLength, 168, 179WindowsVentilation, 179windSideProportion, 177windSideSignal, 178windSpeed windspeed, 162, 163, 164, 167,

178, 179writeTestOutput, 124x, 145year, 146yearlyEmergenceRate, 114yearlyMortalityRate, 114ymax, 152ymin, 152ZeroOrderRateConstant, 135ZeroOrderReaction, 135