%%% tutorial.tex -- A tutorial for the Daisy crop/soil system.

\documentclass[a4paper]{article}
%\usepackage{a4}
%\documentclass[11pt]{article}
\usepackage{hyperref}

\bibliographystyle{apalike}

\input{macro}

% External references.
\usepackage{xr}
\externaldocument[ref-]{reference}

\begin{document}
\sloppy

\section*{Daisy Tutorial}

\begin{abstract}
  Welcome to the Daisy tutorial.  This document is intended to
  teach the use of Daisy by example.  It is not by any stretch of
  the imagination a reference to all the features of Daisy, for
  that see~\cite{dina81}.  It also does not attempt to explain the
  mathematical and physical models implemented by the Daisy
  software, for that see~\cite{daisy-def} and~\cite{daisy-new}.
  
  I hope that you will able to get started with Daisy from these
  examples, and when you need to go beyond will be familiar enough
  with the system to make good use of the reference manual.  Daisy
  has an amazing number of adjustable dials and wheels, only a tiny
  fraction of which are explained here.  However, they are all at
  least mentioned in the reference manual, which is mostly
  automatically generated from the \texttt{daisy} executable itself.
  
  If you have questions or suggestions to either the manual or the
  Daisy system itself, feel free to contact the authors at
  \href{mailto:daisy@dina.kvl.dk}{\texttt{$<$daisy@dina.kvl.dk$>$}}.
\end{abstract}

Per Abrahamsen, \today{}.

\tableofcontents

\section{Retrieving and installing the files}
\label{sec:install}

We start by installing Daisy.  With a web browser, go to the
address~\url{http://code.google.com/p/daisy-model/}, the home page of
the Daisy project.  Follow the ``getting started'' link that is at
the beginning of the main text of the page.  Follow the instructions
on that page.

\section{Example}

The \texttt{test.dai} file contains all the information about the
simulation.  We call such a file a Daisy setup file, or a
\texttt{.dai} file for short.  By convention, we give such files the
\texttt{.dai} extension, even though Daisy doesn't care.  Teaching
you to write Daisy setup files is the main purpose of this
tutorial.

First, let's examine line by line the content of the \texttt{test.dai}
file (see appendix~\ref{app:test} for the full version).  The first
lines are

\begin{verbatim}
  ;;; test.dai -- Sample file using the Daisy libraries.

  (description "Simulation for use in tutorial.")
\end{verbatim}

Semicolons are used for comments, everything from the semicolon to the
end of the line is ignored by Daisy.  This can (and should!) be
used to put information about the simulation there for the person
reading the file.  That person may very well be you, who some month
(or years) later have forgotten about the purpose of this particular
simulation.

For the same reason, providing a description as above is also a good
idea.  The description will be written to the log files produced by
Daisy, allowing you to later see what log files come from what
simulation.

\subsection{Input files}
\label{sec:ex-input}

\begin{verbatim}
  ;; Use standard parameterizations.
  (input file "tillage.dai")
  (input file "crop.dai")
  (input file "log.dai")
\end{verbatim}

Here, we tell Daisy to read three additional files:
\texttt{tillage.dai} containing descriptions of various standard
tillage operations, such as plowing and seed bed preparation;
\texttt{crop.dai} which contains descriptions of crops like spring
barley or rye; and \texttt{log.dai} with directives for Daisy to
produce files with information about various aspects of the
simulation, such as the nitrogen or water balance.  You can read more
about input files in section~\ref{sec:files}.

\subsection{Weather}

Daisy need to know what the weather is during the simulation.  This
is usually read from a file.

\begin{verbatim}
  ;; Weather data.
  (weather default "weather.dwf")
\end{verbatim}

Here we specify where Daisy should find the weather data.  Daisy
can read weather data in several different formats, the
\texttt{default} format is \texttt{.dwf}, short for \emph{D}aisy
\emph{W}eather \emph{F}ormat.  The format is specified in an appendix
 of \cite{dina81}.

\subsection{Horizons}
\label{sec:ex-hor}

Now we get to main part of the simulation, namely the soil profile, or
\emph{column}.  In Daisy, the column is a one dimensional
description of an agricultural system, with the weather at the top and
the groundwater at the bottom.  Before coming to that, we need to
define two horizons.  A horizon is a vertical layer of soil with
similar chemical and physical properties.  If you make a vertical cut
in the soil, there is usually a clear visual distinction between the
horizons.

\begin{verbatim}
  ;; We have some very sandy soil.
(defhorizon Ap FAO3
  "Andeby top soil."
  (clay 8.0 [%])
  (silt 10.5 [%])
  (sand 81.5 [%])
  (humus 1.12 [%])
  (C_per_N 11.0 [g C/g N])
  (dry_bulk_density 1.5 [g/cm^3]))
\end{verbatim}

Here, we define a horizon named \texttt{Ap} (\texttt{defhorizon} is
short for ``define horizon'').  Like the place where we specified the
weather, the \texttt{FAO3} keyword means that we use that model for
specifying horizons.  The build-in horizon models are named after
texture classification systems\footnote{A texture classification
  system specifies how to determine whether a particle is clay, silt
  or sand.}, \texttt{FAO3} is the \textsc{fao} approved classification
system, see~\ref{ref-component:horizon} in the reference manual for a
full list of horizon models. At this point, we can only choose one of
the build-in models, but that will soon change.  The string
\texttt{"Andeby top soil."} is a description of the horizon, and is a
good place to put information about the source of data.

The first three parameters, \texttt{clay}, \texttt{silt},
\texttt{sand} together define the soil texture.  The texture affects
many aspects of the simulation, for example will the ammonium
adsorption depend on the clay content, and if not otherwise specified,
the hydraulic parameters such as soil water retention characteristics
are also estimated from the texture, a sandy soil is less capable of
storing water than a clay soil.

The fourth soil constituent is the \texttt{humus}, which among other thing
creates the background mineralization, thus providing the soil with
nitrogen.  The numbers given for the five soil constituents are
relative, that is they are weighted to the total.  So you can specify
them as fractions or percentage or whatever, as you wish.

The \texttt{C\_per\_N} parameter is the C/N ratio of the humus.  This
affects the background mineralization, a high C/N ratio will lead to
lower mineralization.  If you do not have any idea what the C/N ration
for your soil is, leave out this parameter.

The \texttt{dry\_bulk\_density} is, as the name implies, the density
of the dry soil.  It affects the hydraulic properties of the soil and
the total humus content.  If you haven't measured this value, you can
use a different function for estimating the hydraulic properties, by
replacing it with
\begin{verbatim}
  (hydraulic Cosby_at_al)
\end{verbatim}
This pedotransfer function has been developed in America, and does not
require knowledge of the dry bulk density.  Even if you know the dry
bulk density, using \texttt{Cosby\_et\_al} might be a better choice
for simulation in that continent.  The default pedotransfer function,
\texttt{hypres}, has been developed based on European (especially
North German) soil measurements.

The texture parameters all end with a \verb|[]|.  This is the
dimension surrounded by square brackets.  Since fractions are
dimensionless, there is nothing in the brackets.  The two last
parameters have the dimension $g C/g N$ and $g/cm^3$.  It is good idea
always to specify the dimension, as this will allow Daisy to check
that dimension really is what you think it is.  Misunderstandings
about dimensions are a very common source of errors.  The next horizon
is simpler.

\begin{verbatim}
(defhorizon C Ap
  "Andeby C horizon."
  (humus 0.12 []))
\end{verbatim}

Here, instead of \texttt{FAO3}, we write \texttt{Ap}.  This is the
name of the horizon we just defined, and will cause Daisy to reuse
the parameter values in the new horizon named \texttt{C} we define
here.  In particular, we give it the same texture as the \texttt{Ap}
horizon.  However, since the horizon is intended to describe lower
soil, we specify less humus.

\subsection{Column}
\label{ex:column}

Now we have described two horizons, we can describe a column.

\begin{verbatim}
  ;; We build the column from the horizons.
  (defcolumn Andeby default
    "Data collected by F.Guf at the B.And farm, Andeby, 2002."
    (Soil (horizons (-20 [cm] Ap) (-2.5 [m] C))
          (border -1 [m])
          (MaxRootingDepth 60.0 [cm]))
    (OrganicMatter original
                   (init (input 1400 [kg C/ha/y])
                         (root 480 [kg C/ha/y])
                         (end -20 [cm])))
    (Groundwater deep))
\end{verbatim}

Here, we name the column \texttt{Andeby}, and use the \texttt{default}
model for Daisy columns.  The string following the \texttt{default}
again serves as a description, and this time we use it to note who
collected the data, from where, and when.

In Daisy, a column consists of many separate subsystems.  Most of
these have default values, and does thus not need to be specified.
However, we need a description of the soil, and we need to tell
Daisy where the groundwater is.  Daisy \emph{does} contain default
values for organic matter, but these are not very useful.  Here we
specify that we should use the original\footnote{An alternative at
  this point would be to use the \texttt{none} model, which does not
  perform any calculations regarding organic matter, thus saving
  time.} model for organic matter, bit change the initialization.

See section~\ref{sec:column} for examples of other subsystems.

\subsubsection{Soil}
\label{ex:soil}

\begin{verbatim}
    (Soil (horizons (-20 [cm] Ap) (-2.5 [m] C))
\end{verbatim}
The first soil parameter, \texttt{horizons}, specify that the soil is
divided into two horizons, the first span the top 20 cm of the soil,
and the second span the soil from there down to 2.5 meters depth.
There can be as many horizons as you wish, if you had a third it might
be described as below.

\begin{verbatim}
  (horizons (-20 [cm] Ap) (-1 [m] B) (-2.5 [m] C))
\end{verbatim}

The B horizon would then span the depth from 20 cm to 1
meter.

You may note that we specify the depth in \verb|[cm]| for the first
depth, and \verb|[m]| for the next.  If you don't specify a dimension,
Daisy will expect numbers to be in centimeters, however if you
specify the dimension as \verb|[m]| knows how to convert.  

We specify a numerical border at one meter.
\begin{verbatim}
          (border -1 [m])
\end{verbatim}
The \texttt{border} parameter is optional, but when you are interested
in results for a particular interval, you should specify numerical
borders at the beginning and end of the interval in order to get exact
results.  There are automatically numeric borders between the horizons.

The other mandatory soil parameter is \texttt{MaxRootingDepth}.  This
is a soil imposed barrier for the roots, they will not penetrate below
that depth.  This doesn't mean plant root will penetrate down to that
depth, it depends on the crop.  To make writing Daisy setup files
fun, as well as to keep you alert, this number is specified as
positive depth, unlike the layer endpoints which were specified as
negative heights.  Daisy will tell you if you get it wrong.

\subsubsection{Organic Matter}
\label{ex:om}

Knowing the humus content of the soil is not enough, Daisy need know
the quality of the organic matter as well.  The quality (or lability)
of the organic matter affect how much background mineralization you
can expect, which is an important part of the total nitrogen balance.

We can estimate the quality of the soil organic matter by comparing
the humus content with the typical level of carbon input in the
decades before the beginning of the simulation.  If the carbon input
in the period before the was high compared the general level of humus,
we expect that the humus content has been growing, and much of the
humus will then be fresh and labile.  On the other hand, if the input
level is low compared to the humus content, the humus level will be
shrinking, and the most labile humus will already be gone.

It is important to understand that we are trying to estimate the
quality of the humus that exists in the system at the beginning of the
simulation period.  Therefore we are interested in how the carbon
input levels were before the simulation, not the levels during the
period we are simulating.  We specify the past input level with the
following lines.

\begin{verbatim}
    (OrganicMatter original
                   (init (input 1400 [kg C/ha/y])
                         (root 480 [kg C/ha/y])
                         (end -20 [cm])))
\end{verbatim}

Here we specify that we want to initialize the organic matter
subsystem from the carbon input.  The first line tells Daisy that the
total yearly carbon input is 1400 kg/ha.  The second line specify that
out of these 1400 kg, the 480 kg are dead roots.  The third line gives
the depth of the plowing layer, here 20 cm.  The reason we need the
two later values (\texttt{root} and \texttt{end}) is that we need to
know how the carbon input is distributed vertically.  Daisy will
assume most input is distributed evenly in the plowing layer, but that
some of the roots will reach all the way down to the depth specified
by \texttt{MaxRootingDepth}.

In section~\ref{sec:om} we describe how to estimate the carbon input,
and in section~\ref{sec:background} how to improve the initialization
of the organic matter further.

\subsubsection{Groundwater}
\label{ex:groundwater}

After specifying the soil and organic matter composition, we must tell
Daisy the location of the groundwater.  Here, we specify that the
groundwater is located so deep that it does not directly affect the
simulation.  Other options include a constant groundwater table, field
drainage, and a variable groundwater table specified in a file.  See
section~\ref{sec:groundwater} for examples.  

\subsubsection{Using it}

We have now specified a column, and given it the name \texttt{Andeby}.
Now we just need to tell Daisy to use this column for the
simulation.

\begin{verbatim}
  ;; Use it.
  (column Andeby)
\end{verbatim}

\subsection{Time}

After specifying the most complex Daisy parameter, the column, we
relax with the simplest parameter.

\begin{verbatim}
  ;; Simulation start date.
  (time 1986 12 1 1)
\end{verbatim}

As the comment say, that time we start the simulation.  The four
numbers given are year, month, day and hour in that sequence.

\subsection{Management}
\label{sec:ex-man}

Back to the complex stuff.  Daisy now knows about the piece of land
we want to simulate, the weather during the simulation, and when we
start.  However, since this is an agricultural system, we also need to
tell Daisy about the what management operations the farmer perform
during the simulation.

How to approach this problem depends on whether we are simulating a
real, already performed, experiment, or if we want to simulate a
hypothetical situation.  The difference is that in the first case, we
(hopefully) \emph{know} what the manager did, and when.  In the second
case, we need to build in some intelligence in the system, so the
actions of the hypothetical manager depend on the state of the system.
E.g.\ the manager is likely to wait for a crop to become ripe before
harvesting it.

In this example, we do both.

\begin{verbatim}
  (manager activity
    (wait (at 1987 3 20 1))
    (plowing)
    (wait (at 1987 4 4 1))
    (fertilize (mineral
                (weight 100.0 [kg N/ha])
                (NH4_fraction 0.5 [])))
    (wait (at 1987 4 5 1))
    (progn
      (sow "Grass")
      (sow "Spring Barley"))
    (wait (or (crop_ds_after "Spring Barley" 2.0)
              (at 1987 9 5 1)))
    (harvest "Spring Barley")
    (wait (at 1987 9 8 1))
    (fertilize (mineral
                (weight 80.0 [kg N/ha])
                (NH4_fraction 0.5 [])))
    (wait (at 1987 10 10 1))
    (harvest "Grass"
             (stub 8.0 [cm])              ;Leave 8 cm stub.
             (stem 1.00 []))             ;Harvest everything above stub.
    (wait (at 1988 4 1 1))
    (stop))
\end{verbatim}

First, \texttt{activity} is an order to perform the specified actions
in sequence.  When one action is done, we start the next.  Half of out
actions consist of waiting for some condition to come true.  The most
common condition is that we have reached a specific point in time.
For examples, the first line

\begin{verbatim}
    (wait (at 1987 3 20 1))
\end{verbatim}

mean wait until the simulation time is exactly 1:00~AM, March the
20th, 1987.  Our specific action is \texttt{wait} and the condition is
\texttt{at}.

The next action is \texttt{plowing}.  This happens one hour later, so
our poor farmer is out in the field plowing at 2:00~AM\@.  This activity
last (in the simulation) exactly one hour, after which he can go to
the next activity, which involves waiting once again.

I'll describe the actions used for this sample manager here, more
examples of management actions can be found in
section~\ref{sec:management}.

\begin{verbatim}
    (fertilize (mineral
                (weight 100.0 [kg N/ha])
                (NH4_fraction 0.5 [])))
\end{verbatim}

This is an order to fertilize.  The fertilization type is
\texttt{mineral}, and the amount of nitrogen is specified with the
\texttt{weight} parameter.  The nitrogen can be in the form of
ammonium (NH$_4^+$) or nitrate (NO$_3^-$).  We specify with the
\texttt{NH4\_fraction } parameter that half the nitrogen is ammonium,
and the rest is nitrate.  Read more about fertilizer types in
section~\ref{sec:fertilizer}.

\begin{verbatim}
    (progn
      (sow "Grass")
      (sow "Spring Barley"))
\end{verbatim}

Remember that \texttt{activity} was a directive to perform a list of
actions in sequence?  Well, \texttt{progn} is a directive to perform a
list of actions in parallel.  Here we sow two crops at once.  The
crops, \texttt{Grass} and \texttt{Spring Barley} are defined in the
file \texttt{crops.dai}, which we included in
section~\ref{sec:ex-input}.

\begin{verbatim}
    (wait (or (crop_ds_after "Spring Barley" 2.0)
              (at 1987 9 5 1)))
\end{verbatim}

This is the only place we wait for a condition more complex than a
specific point in time.  Actually, there are three conditions here.

\begin{verbatim}
              (at 1987 9 5 1)
\end{verbatim}

is just a point in time, as you have seen before, however

\begin{verbatim}
              (crop_ds_after "Spring Barley" 2.0)
\end{verbatim}

is new.  It is true when the development stage of a crop named
``\texttt{Spring Barley}'' is 2.0 or above.  The development stage, or
DS, is a key concept in describing the state of a crop.  It starts at
-1.0 when sowed, and increase with time.  When it reached 0.0, the
crop emerges.  At 1.0 it flowers, and at 2.0 it is ripe.   So this
condition is true when there is a ripe spring barley on the field.

The third conditions is named \texttt{or}.

\begin{verbatim}
          (or (crop_ds_after "Spring Barley" 2.0)
              (at 1987 9 5 1))
\end{verbatim}

It is true when any of the specified conditions are true.  I.e.\ it is
true when there is a ripe spring barley on the field, or when the
simulation has reached 1:00~AM, September the 5'th, 1987.

In effect, we wait for the spring barley to get ripe, but if it isn't
ripe at the specified date, we stop waiting anyway

\begin{verbatim}
    (harvest "Spring Barley")
\end{verbatim}

and harvest it.  This harvest is pretty brutal, we remove everything
above the soil, and leave only the roots to rot in the soil.  When we
later cut the grass, we are more gentle.

\begin{verbatim}
    (harvest "Grass"
             (stub 8.0 [cm])              ;Leave 8 cm stub.
             (stem 1.00 []))             ;Harvest everything above stub.
\end{verbatim}

Here, we leave 8 cm stub.  We still remove all the stem above that
height, the parameter to \texttt{stem} is the fraction to remove.  If
we remove a smaller fraction, the remainder will stay on top of the
soil as plant residuals, which will be incorporated into the soil
either gradually by earth worms and other insects, or at once by a
tillage operation.

The grass will most likely survive this cut, unlike the spring barley.

The last action, \texttt{stop}, is simply a command to stop the
simulation.

\subsection{Output}
\label{ex:output}

Now Daisy know everything it needs to know in order to run the
simulation.  We just need to tell it what information about the
simulation is should save for later processing.

\begin{verbatim}
  ;; Create these log files.
  (output harvest
          ("Field nitrogen" (when monthly))
          ("Soil nitrogen" (when daily) (from 0 [m]) (to -1 [m]))
          ("Field water" (when monthly))
          ("Soil water" (when daily) (from 0 [m]) (to -1 [m]))
          ("Crop Production"
           (crop "Spring Barley")
           (where "sbarley.dlf"))
          (checkpoint (when (at 1987 8 7 6))))

  ;;; test.dai ends here.
\end{verbatim}
%$

The first entry in the list, \texttt{harvest}, produces a
\texttt{harvest.dlf} file containing information about everything that
has been harvested during the simulation.  The \emph{D}aisy \emph{L}og
\emph{F}ormat (\texttt{.dlf}) is understood by the
\texttt{ShowDaisyOutput.exe} program, but you can also view it with an
editor or load it into a spreadsheet.  The \texttt{harvest.dlf} file,
in particular, is best viewed as plain text.  See
section~\ref{sec:plot} for more information about how to view the results.

Our next log model, \texttt{Field nitrogen}, will write enough
information about the nitrogen content of the field to calculate a
balance, in a file name \verb|field_nitrogen.dlf|.  By default, it
will write this information once a day, but by specifying
\texttt{monthly} we reduce this to once a month.  \texttt{Soil
  nitrogen} is similar, but contain information for creating a
nitrogen balance for a soil layer, rather than for the entire field.
We specify the soil layer to log to be the top meter of the soil.
q\texttt{Field water} and \texttt{Soil water} contain balances for
water instead of nitrogen, but are otherwise similar.

We have two crops simultaneously on the soil.  By default,
\texttt{Crop~Production} will add the content of both crops together,
and log it in a \texttt{crop\_prod.dlf} file.  The 
\begin{verbatim}
           (crop "Spring Barley")
\end{verbatim}
line tells Daisy to only log information about the spring barley,
and by specifying a \texttt{where} parameter we tell it to store the
information in a file named \texttt{sbarley.dlf} instead.

Note that writing these log files tend to be much slower than actually
running the simulation, to the more information you tell Daisy to
log, the slower the simulation will run.

Finally, we tell Daisy To create a checkpoint file at 6:00~AM,
August the 7'th, 1987.  This file will be named
\texttt{checkpoint-1987-8-7+6.dai}.  As the extension hints, this is
not a log file, but a setup file containing all information about the
current state of the simulation.  In fact, you can restart the
simulation by using the generated file instead of the original setup
file.  You can also browse it with a text editor to get detailed
information about the state of the simulation at that point in time.

See section~\ref{sec:output} for more information about log models,
and appendix~\ref{app:logs} for a detailed description of the files
generated by the \texttt{Field water} and \texttt{Field nitrogen} log
models.

\section{Weather}
\label{sec:weather}

It is common not to have sufficient weather data, either because there
is no access to data from a nearby weather station, or because you are
running a predictive simulating, and the data isn't available yet.
Daisy has two features for handling such cases with available
data.  

\subsection{Scaled precipitation}

Precipitation is very locale dependent, it may vary even within a
region with similar temperature and radiation.  If you know the
general monthly difference between a specific locale, and a regional
weather station, you can use the \texttt{PrecipScale} attribute:
\begin{verbatim}
  (weather default "weather.dwf"
    (PrecipScale 1.1 1.1 1.1 1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2))
\end{verbatim}
The \texttt{PrecipScale} needs 12 numbers, which will be multiplied to
all precipitation the corresponding month.  In this example, we use
the data from ``weather.dwf'', but with 10\% more precipitation from
January to March, and 20\% more the remaining 9 months.

\subsection{Missing years}

The \texttt{missing\_years} attribute allows you to reuse the weather
data for additional years.  For example, if you have weather data for
1991 to 2000 in a file named ``weather.dlf'', but want to run a
simulation from 1987 to 2001, you can specify the weather model like
this.
\begin{verbatim}
  (weather default "weather.dwf"
           (missing_years ((1987 1990) (1993 1996))
                          ((2001 2001) (1991 1991))))
\end{verbatim}
This should be read as an order to Daisy to, in the period from 1987
to 1990, use the weather data from 1993 to 1996, and for 2001 use the
weather data from 1991.

This is particularly useful for running Daisy with a ``warming up''
period where we don't have actual measurements, and for predictive
simulations, where you can run a crop rotation with many different
weather combinations.

In the example above we map two periods (1987--1990 and 2001), but you
can have as many periods as you like, so you can e.g.\ run a 100 year
simulation with just 10 years worth of climate data.

Note that Daisy will always use the actual data when available, so if
you in the example above have some data from 2001 but not all, Daisy
will not switch to 1991 data before it have used up the real data.

\section{Column}
\label{sec:column}

In this section we give examples of common customization of the
various subsystems of the column.

\subsection{Carbon Input}
\label{sec:om}

You can use Daisy to estimate the carbon input used daisy{} for
organic matter initialization (see section~\ref{ex:om}) with the
following steps.
\begin{enumerate}
\item Create a crop rotation you believe is typical for the period
  before the simulation start.
\item You use the same \texttt{Soil} and \texttt{Groundwater}
  parameters as you will for the real simulation, but omit the
  \texttt{OrganicMatter} initialization.
\item Add \texttt{"Carbon Balance"} to the output.
\item Run a simulation with that rotation repeated a couple of times,
  using meteorological data from the location.
\end{enumerate}
The \texttt{daisy.log} file will now contain lines that looks like
these near the end.

\begin{verbatim}
     Fertilizer =    0 [kg C/ha/y]
      Residuals = 1454 [kg C/ha/y]
          Roots =  651 [kg C/ha/y]
     Bioinc_CO2 = -727 [kg C/ha/y]
  --------------------------------
  Total C input = 1378 [kg C/ha/y]
                  ====
\end{verbatim}

The two values you need are ``Total C input'', which should be used
for the \texttt{input} parameter, and ``Roots'', which should be used
for the \texttt{root} parameter.  You can now add an
\texttt{OrganicMatter} initialization section, as in
section~\ref{ex:om}, and run the setup again.  The total C input
should now be slightly different in the second run.  Use this number
for the real simulation.

\subsection{Background mineralization}
\label{sec:background}

Having Daisy estimate the organic matter quality is a poor
substitution for measuring it.  While measuring it directly is hard,
it is possible to measure the background mineralization indirectly. 

The background mineralization is here defined as the difference
between the net mineralization and the amount of added organically
bound nitrogen.  The number can be both positive and negative.  A
positive number means that we get more nitrogen from mineralization
than we add to the system.  This nitrogen must come from the humus
content, which must then be decreasing for the balance to add up.
Similarly, a negative background mineralization means that some
surplus nitrogen is stored in a growing humus content.

If you look in the \texttt{daisy.log} file, you will find a line like
this
\begin{verbatim}
  Background mineralization: 4.8127 [kg N/ha/y].
\end{verbatim}
near the beginning.  This specifies that Daisy expects 5 kg N/ha to
be released from the humus every year for the current setup.  By
adding the parameter \texttt{background\_mineralization} to the
organic matter initialization, we tell Daisy to attempt to
initialize the system differently, to produce the specified level of
background mineralization.

\begin{verbatim}
    (OrganicMatter (init (input 2400 [kg C/ha/y])
                         (root 800 [kg C/ha/y])
                         (background_mineralization 30 [kg N/ha/y]) 
                         (end -20.0 [cm])))
\end{verbatim}

Here, we specify that with the given input levels, we want 30 kg N/ha
to be released from the humus every year.  It is not certain Daisy
will be able to fulfill that though, there are a number of sanity
checks build in which will limit the background mineralization can be
generated.  You can find the expected background mineralization in the
beginning of the \texttt{daisy.log} file as before.  And the
\emph{actual} background mineralization may be very different from
this, for two reasons.
\begin{enumerate}
\item The actual input levels in the simulation period can be
  different from the input levels used for the organic matter
  initialization.
\item The expected background mineralization is calculated by assuming
  the soil moisture and temperature are constant, while the simulated
  background mineralization depends on the variable simulated soil
  moisture and temperature.
\end{enumerate}
The simulated background mineralization can be found by looking at the
change in the organic nitrogen content (the \texttt{SOM} column in the
\texttt{"Soil nitrogen"} log).

If you measure how much nitrogen is removed by harvest, you can adjust
the \texttt{background\_mineralization} parameter until the simulation
gives you the same results.  However, this only works if the
background mineralization really is the only unknown.  Specifically,
you must be sure that the water balance is correct, otherwise the
amount of nitrogen lost in leaching will also be an unknown.  And you
must be sure that the crop is never nitrogen saturated.  Preferably,
you should have an unfertilized field, but if you do fertilize it must
be less than the crop is capable of taking up.

It is possible to calibrate the background mineralization from dry
matter harvest numbers, but only if you are sure the crop growth has
been nitrogen limited.

\subsection{Hydraulic properties}
\label{sec:hydraulic}

In section~\ref{sec:ex-hor}, we let Daisy guess the hydraulic
properties from the texture.  This kind of estimates (wild guessing)
are unreliable at best, and since the hydraulic properties are the key
most other aspects of the simulation depend on, getting them right
should be a priority.  Daisy supports a number of models for
hydraulic properties, the most important are listed here, more can be
found in the reference manual~\cite{dina81}.

\begin{description}
\item[\texttt{B\_BaC}] Brooks and Corey retention curve model with
  Burdine theory.
\item[\texttt{B\_C}] Campbell retention curve model with Burdine
  theory.
\item[\texttt{B\_vG}] van Genuchten retention curve model with Burdine
  theory.
\item[\texttt{M\_BaC}] Brooks and Corey retention curve model with
  Mualem theory.
\item[\texttt{M\_C}] Campbell retention curve model with Mualem
  theory.
\item[\texttt{M\_vG}] van Genuchten retention curve model with Mualem
  theory.
\end{description}

Here is an example where we specify the van Genuchten retention curve
model with Mualem theory
\begin{verbatim}
  (defhorizon B ISSS4
    (clay 8.0) (silt 10.5) (coarse_sand 65) (fine_sand 16.5)
    (humus 1.12)
    (hydraulic M_vG
               (K_sat 10 [cm/h])
               (Theta_res 5 [%])
               (Theta_sat 42.4 [%])
               (alpha 0.069 [cm^-1])
               (n 1.527)))
\end{verbatim}

The three parameters
\begin{description}
\item[\texttt{K\_sat}] Water conductivity of saturated soil.
\item[\texttt{Theta\_sat}] Saturation point (a.k.a.\ soil porosity).
\item[\texttt{Theta\_res}] Soil residual water.
\end{description}
are shared by all the models, except that \texttt{Theta\_res} must be
zero for Campbell.  The other parameters are model specific.

\subsection{Groundwater and Drainage}
\label{sec:groundwater}

Obviously, the groundwater is not always located ``far below'' the
root zone, as specified by
\begin{verbatim}
  (defcolumn Andeby default
    (Groundwater deep)
    ;; Other parameters...
\end{verbatim}
in the example.  We can therefore also specify a fixed groundwater
table as in
\begin{verbatim}
    (Groundwater fixed -100 [cm])
\end{verbatim}
where we specify groundwater in one meters depth.  Note that if we
specify a fixed groundwater table, it must be higher than our lowest
node.  A third common case is soil drainage
\begin{verbatim}
    (Groundwater pipe)
\end{verbatim}
which is often enough for drained soil.  A full specification would be
\begin{verbatim}
    (Groundwater pipe
                 (L 18 [m])
                 (x  9 [m])
                 (pipe_position -1.1 [m])
                 (K_aquitard 1e-4 [cm/h])
                 (Z_aquitard 2 [m])
                 (h_aquifer  2 [m]))
\end{verbatim}
where
\begin{description}
\item[\texttt{L}] Distance between pipes.
\item[\texttt{x}] Horizontal distance to nearest pipe. By default,
  this is $1/2 \mathtt{L}$, i.e.\ in the middle between the pipes.
\item[\texttt{pipe\_position}] Height pipes are placed in the soil.
\item[\texttt{K\_aquitard}] Conductivity of the aquitard.
\item[\texttt{Z\_aquitard}] Thickness of the aquitard.
\item[\texttt{h\_aquifer}] Pressure potential in the aquifer below the
  aquitard. By default this is equal to \texttt{Z\_aquitard}.
\end{description}
The above numbers are the default values, i.e.\ what you get if you
don't specify anything.  \texttt{L} and \texttt{pipe\_position} are
standard values for Danish fields.  The aquitard is water blocking
layer explained in~\cite{daisy-new}, the \texttt{K\_aquitard}
parameter is what you usually want to calibrate.

\textbf{Note:} When using drained soil, all numerical nodes will
contribute to the drain sink term, not just the node containing the
pipe.  This is because the pipe is assumed to be at some distance from
our node (as specified by the \texttt{x} or \texttt{L} parameter), and
the sink term is actually the simulated horizontal movement of water
towards the pipe.

\subsubsection{Aquitard horizons}
\label{sec:aquitard}

For some soils the groundwater table can fall into the aquitard on dry
years.  For this reason, Daisy will automatically add an extra
horizon below the bottom horizon you specified.  This will affect
logging, if you don't want to log the aquitard horizon you must
explicitly set the \texttt{to} parameter.

\subsection{Macropores}
\label{sec:macro}

By default, Daisy will only calculate water flow through the
matrix, not through macropores.  This is usually adequate, since the
vast amount of water travel through the matrix.  However, when
calculating leaching of nitrogen and especially pesticides, water flow
through macropores become important, because it provides a must faster
route to the groundwater.

Here is an example where we specify macropores:
\begin{verbatim}
  (defcolumn Andeby default
    (Movement original 
              (Tertiary old
                        (macro default
                               (height_start 0 [cm])
                               (height_end -200 [cm])
                               (distribution (-200 1) 
                                             ( -80 0.1) 
                                                (0 0))
                               (pressure_initiate -5 [cm])
                               (pressure_end -30 [cm])
                               (pond_max 0.5 [mm]))))
    ;; Other parameters...
\end{verbatim}

We specify that the macropores start at the soil surface, and end in 2
meters depth with \texttt{height\_start} and \texttt{height\_end}.  All
macropores are assumed to start at \texttt{height\_start}, but their
endpoints are distributed as specified by the \texttt{distribution}
parameter.  Here, we specify that all the macropores have ended at 2
meters depth, 10\% of the macropores end above 80 cm depth, and none
end above the surface (doh!).  We use linear interpolation between
these points, so we can conclude that 5\% of the macropores end above
40 cm depth.  You do not have to specify \texttt{height\_start} and
\texttt{height\_end} explicitly, if you don't, the last and first
value point of \texttt{distribution} will be used.

The macropores can be activated in two different ways.  Macropores
that, like here, reach the surface, can be activated by ponding.  The
parameter \texttt{pond\_max} specifies that the macropores will be
activated when we have half a millimeter water on the soil surface.
Once activated, the macropores will empty the pond.  The other way
macropores can be activated is if the water pressure in any node
within the region with macropores reaches above
\texttt{pressure\_initiate}.  In that case, it will be drained
immediately down to \texttt{pressure\_end}.

The water, and any solutes in it will be distributed according to
where the macropores end.  I.e.\ if the macropores was activated by
ponding, 10\% of the ponded water would have entered the matrix at 80
cm depth, and all the ponded water would have entered the matrix at 2
meters depth.

\subsection{Evapotranspiration}
\label{sec:bioclimate}

By default, Daisy will choose the best model calculating the reference
evapotranspiration based on the available data in the weather file.
You can overwrite this with the \texttt{pet} parameter.

The least demanding model in terms of access to weather data is
Makking.  It is specified as
\begin{verbatim}
  (defcolumn Andeby default
    (Bioclimate default (pet makkink))
    ;; Other parameters...
\end{verbatim}

Sometimes you have access to reference evapotranspiration data in the
weather file, in order to make Daisy use these you could specify
pet like
\begin{verbatim}
    (Bioclimate default (pet weather))
\end{verbatim}
except Daisy will automatically use the provided data for reference
evaporation when found in the weather file.

Daisy also support the more advanced model Penman-Monteith
\begin{verbatim}
    (Bioclimate default (pet PM))
\end{verbatim}
If you have reliable information about vapor pressure and wind, it is
much preferable to use Penman-Monteith over Makkink.  If the data are
missing of poor quality, the simple Makkink are more robust.

It is possible to use Penman-Monteith together with
Shuttleworth-Wallace for the most accurate model of the bioclimate
supported by Daisy.  Enable it with
\begin{verbatim}
    (Bioclimate default (pet PM) (svat PMSW))
\end{verbatim}
This requires hourly weather data to be useful.  

\subsubsection{Potential and Reference Evapotranspiration}

You may also want to change how potential evapotranspiration is
calculated from reference evapotranspiration.  Both the soil surface
and crops influence this, depending on how much of the soil is covered
by crops.  To change the soil surface factor, specify
\texttt{EpFactor} like this:
\begin{verbatim}
  (defcolumn Foulum default
    (Surface (EpFactor 1.0))
\end{verbatim}
The default value is 0.8.

For crops, derive new crop types like
\begin{verbatim}
  (defcrop "Andeby Spring Barley" "Spring Barley"
    "Spring Barley with modified EpFac as measured
  in Andeby, 2002, for the SuperGrow(TM) cooperation."
    (Canopy (EpFac 1.2)))
\end{verbatim}
overwriting the default \texttt{EpFac} of 1.0.  Remember that you need
to sow and harvest \texttt{Andeby Spring Barley} instead of
\texttt{Spring Barley}.  Or alternatively, overwrite the parameter at
the time of sowing, like this:
\begin{verbatim}
   (sow ("Spring Barley"
         (Canopy (EpFac 1.2))))
\end{verbatim}
If you want \texttt{EpFac} to depend on the development stage, specify
it like
\begin{verbatim}
   (sow ("Spring Barley"
        (Canopy (EpFacDS (0.0 1.0) (1.0 1.2) (2.0 1.0)))))
\end{verbatim}
Here, \texttt{EpFac} will be 1.0 at emergence (DS 0.0), gradually rise
to 1.2 at flowering (DS 1.0), and then fall towards 1.0 at ripeness (DS
2.0).

\subsection{Discretization}

Internally, Daisy divides the soil into a number of discrete layers.
During the simulation, it will keep track of the content (water, heat,
nitrogen, etc.) of each layer, and the flows between the layers. A
fine discretization causes more exact results, but slows down the
simulation, and very fine discretization may cause numeric problems.
The default discretion represents a balance between these concerns,
but sometimes it will be advantageous to specify it manually.

We specify the a numeric discretization of the soil with the
\texttt{zplus} parameter.  
\begin{verbatim}
  (defcolumn Andeby default
    "Data collected by F.Guf at the B.And farm, Andeby, 2002."
    (Soil (horizons (-20 [cm] Ap) (-2.5 [m] C))
          (MaxRootingDepth 60.0 [cm]))
    (Movement vertical 
      (Geometry (zplus -2.5 -5 -10 -15 -20
                       -25 -30 -40 -50 -60 -70
                       -80 -90 -100 -125 -150 -175
                       -200 -225 -250 [cm])))
    (Groundwater deep))
\end{verbatim}
Like for the horizons, we list the endpoints of each numeric layer (or
\emph{node}) from the top to the bottom.  The \verb|[cm]| at the end
of the list indicates that all the previous numbers are given in cm.

A good rule of thump is to use small intervals at the top (one or two
cm) where most of the action is, and use larger steps (dozens of cm)
near the bottom, where things are more quiet, at least with a fixed
groundwater level.

A hard rule is that numeric layers may not cross horizon boundaries,
which mean the end points in the horizon list must also be somewhere
in the zplus list.

The default discretization obey the \texttt{border} parameter, when
you specify \texttt{zplus} explicitly, \texttt{border} no longer
applies.

\subsection{Initialization of soil content}
\label{sec:init}

Daisy will be default initialize the content of the soil with
``reasonable'' values, which are most likely wrong.  So if you have
actual measurements you should use those instead.  

\subsubsection{Soil water}

You can initialize the soil water content or the soil water potential,
but not both.  The ``other one'' will be automatically initialized
from the values you provided, and the soils hydraulic properties
(section~\ref{sec:hydraulic}).  To specify initial water content, use
this: 
\begin{verbatim}
  (defcolumn Andeby default
    (SoilWater (initial_Theta (-100 [cm] 20 [%])
                              (-150 [cm] 0.1 [])))
    ;; More parameters...
\end{verbatim}
Here we specify that there are 20\% water in the first meter, and
10\% water in the next 50 cm.  The empty dimension \verb|[]| means
``fraction''.  Here we divided the soil in two layers, but you can
divide it into as many layers as you want.  

Soil water pressure is initialized like this:
\begin{verbatim}
    (SoilWater (initial_h ( -50 [cm]  -10 [kPa])
                          (-100 [cm] -100 [cm])
                          (-1.5 [m]     2 [pF])))
\end{verbatim}
Here we specify field capacity all the way, using three different
units. 

\subsubsection{Soil nitrogen}

There are three different ways to specify mineral nitrogen in the
soil.  The first is per dry soil mater.  
\begin{verbatim}
  (defcolumn JB1_init_hypres JB1_hypres 
    (Chemistry multi
               (combine (N (trace (NO3 (initial_Ms (-30 [cm] 10 [ppm])
                                                   (-70 [cm] 5  [ppm])))
                                  (NH4)))))
    ;; More parameters...
\end{verbatim}
Here we specify the weight of nitrate nitrogen (i.e.\ we ignore the
weight of the oxygen atoms) in the system (both soil and water), as a
fraction of the dry soil weight.  The idea is that you first extract
the nitrate from a measured soil sample, then weight it, compensate for
the oxygen, dry the soil sample, and weight that.  That will give you
the nitrate nitrogen fraction of the soil.  

The second method is per soil water.
\begin{verbatim}
  (defcolumn JB1_init_hypres JB1_hypres 
    (Chemistry multi
               (combine (N (trace (NO3)
                                  (NH4 (initial_C (-100 [cm] 1 [ppm])))))))
    ;; More parameters...
\end{verbatim}
Here the idea is that we extract a sample of water from the soil, and
measure the ammonium nitrogen concentration in that sample.  This will
\emph{not} give you the total amount of ammonium nitrate in the soil,
as some of is adsorbed to the soil.  That fraction will be found be
assuming the adsorbed and solved phases are in equilibrium.

The third method is to specify the total content per volume, counting
both soil, water and air. This number give a content that is
independent of the dry bulk matter density and the water content. 
\begin{verbatim}
  (defcolumn JB1_init_Cosby JB1_Cosby
    (Chemistry multi
               (combine (N (trace (NO3 (initial_M (-100 [cm] 50 [g/cm^3])))
                                  (NH4)))))
    ;; More parameters...
\end{verbatim}

\subsubsection{Soil temperature}

You can also initialize the initial temperature of the soil.
\begin{verbatim}
  (defcolumn Andeby default 
    (SoilHeat (initial_T (-100 [cm] 1 [dg C]))))
    ;; More parameters...
\end{verbatim}

\section{Management}
\label{sec:management}

Writing management specifications that behave both semi-intelligently
and robustly to the simulation state is a challenge.  However,
specifying each and every little management operation for a 30 year
run can get both tedious and error prone.

In this section, we will therefore start by introducing you to a way
to organize your manager in ``crops'' and ``rotations'', which will
save you much work, and then continue to give examples of various
common management operations.

\subsection{Crop Managements}
\label{sec:crop-man}

Our first hint is to collect all management information about a
specific crop, as in the example below.
\begin{verbatim}
  ;; Spring Barley management.
  (defaction sbarley activity
    (wait_mm_dd 3 20)
    (plowing)
    (wait_mm_dd 4 10)
    (fertilize (pig_slurry (weight 100.0 [Mg w.w./ha])))
    (wait_mm_dd 4 15)
    (seed_bed_preparation)
    (sow "Spring Barley")
    (wait_mm_dd 7 1)
    (wait (or (crop_ds_after "Spring Barley" 2.0 [])      ;Ripe
              (mm_dd 10 1)))
    (harvest "Spring Barley"))
\end{verbatim}
Here, we define a new management operation (or \emph{action}) named
\texttt{sbarley}, which can be used like any other management
operation, e.g.\ plowing, it just last a bit longer.  Specifically, it
last the good part of a year.

We define \texttt{sbarley} as an \texttt{activity}, just like in the
example in section~\ref{sec:ex-man}.  The trick is to give it a name
(\texttt{sbarley}), and specify it in a way so it can be used any
year.  The key to the later is to use
\begin{verbatim}
    (wait_mm_dd 3 20)
\end{verbatim}
which, unlike (from the example)
\begin{verbatim}
    (wait (at 1987 3 20 1))
\end{verbatim}
does not specify a year\footnote{The observant reader will notice that
  the hour isn't specified either.  You can specify the hour,
  see~\cite{dina81}, but usually the default of 8:00~AM is fine.  It
  is certainly less stressful to the farmer than the 1:00~AM we send
  him plowing earlier.}.  It matches the 20'th of March every year,
allowing us to use in any year.  Later, when waiting for the crop to
become ripe, we similarity use an \texttt{mm\_dd} condition, which
become true at 8:00~AM October the 1'st every year, instead of waiting
testing for a more specific date as in the example.

\subsubsection{Rotations}
\label{sec:rotations}

If we have defined crop management actions as in the previous section
for spring barley, rye, and grass, we can use them in a
manager specification like this
\begin{verbatim}
  (mananger activity
    sbarley sbarley grass rye)
\end{verbatim}

As you see, we only have to specify the management operations
associated with growing spring barley once, even though we grow spring
barley twice in the simulation.  We can take this one step further, by
naming and reusing specific rotations.
\begin{verbatim}
  (defaction rotation_bbgr activity
    sbarley sbarley grass rye)

  (manager activity
    rotation_bbgr rotation_bbgr rotation_bbgr rotation_bbgr rotation_bbgr)
\end{verbatim}
Here, we define and name a whole rotation containing four seasons, and
repeat that rotation five times.  All in all, we have specified
management for 20 years in two lines.

This is how I in general recommend writing management specifications.
Break it down into management specifications for individual crops,
then combine the crops into rotations.  To make sure the initial state
of Daisy is reasonable, it is a good idea to run at least one
rotation before the period you are interested in simulating.  

In the next sections I will
present more specific examples of common management operations.

\subsection{Tillage}
\label{sec:tillage}

The tillage operations defined in \texttt{tillage.dai} are
\texttt{plowing}, \texttt{rotavation}, \texttt{disk\_harrowing},
\texttt{stubble\_cultivation} and \texttt{seed\_bed\_preparation}.
You use them all like \texttt{plowing} in the example.

All the tillage operations kill any crops on the soil, and homogenize
the top soil content (be it water, organic or inorganic matter,
pesticides, or heat).  Plowing will additionally swap the content of
the top and bottom of the plowing layer.  The content on the soil
surface will be incorporated into the soil, for
\texttt{disk\_harrowing} and \texttt{stubble\_cultivation} this
incorporation will only be partial.

\subsubsection{Trafficability}
\label{sec:trafficable}

A real farmer might want to delay some operations if the soil is too
wet, or frozen.  The \texttt{trafficable} condition will test for
this.  You can use it like
\begin{verbatim}
  (wait trafficable)
  (plowing)
\end{verbatim}
but it might be a good idea to add a timeout for robustness.
\begin{verbatim}
  (wait (or trafficable (mm_dd 04 01)))
  (plowing)
\end{verbatim}
Here we wait until the soil is trafficable, or we have reached the
first of April.  This is important if we use it in a crop management
description like in section~\ref{sec:crop-man}.  Imagine we have the
following piece of management activity:
\begin{verbatim}
  (wait trafficable)
  (plowing)
  (wait_mm_dd 4 10)
\end{verbatim}
If the conditions doesn't get trafficable before the 10'th of April,
we will plow after the 10'th of April and then continue to wait for
the 10'th of April \emph{next year}.  If we only run a short
simulation, this might be OK, we can then discard the results and
investigate what went wrong.  However, if we are simulating a 30 year
period, it will be highly annoying to have to rerun because a single
year had an unusually later winter or wet spring.  For the sake of
such long simulations, it is a good idea to get in the habit of
adding timeouts to such conditions.

\subsection{Sowing and Harvesting}
\label{sec:sow}

By including the \texttt{crops.dai} file, you get access to the
following crop types: \texttt{Fodder Beet}, \texttt{Grass},
\texttt{Maize}, \texttt{Pea}, \texttt{Potato}, \texttt{Rye},
\texttt{Spring Barley}, \texttt{Spring Rape}, \texttt{Sugar Beet},
\texttt{Spring Wheat}, \texttt{Winter Barley}, \texttt{Winter Rape}
and \texttt{Winter Wheat}.

In general, creating parameterizations for new crops requires field
experiments where you carefully measure the nitrogen content during
the development with different fertilization levels.  However, making
small modifications for specific purposes is feasible, as
demonstrated in section~\ref{sec:bioclimate}.

\subsubsection{Crop Residuals}

In general, we harvest when the crop is ripe, and kill the crops in
the process. The main decision is whether to remove the crop
residuals, or leave them as litter on the field.  Here is an example
where we remove the crop residuals
\begin{verbatim}
  (harvest "Spring Barley"
           (stub 8 [cm]))
\end{verbatim}
and one where we leave them as litter on the field.
\begin{verbatim}
  (harvest "Spring Barley"
           (stub 8 [cm])
           (stem 0.0 [])
           (leaf 0.0 []))
\end{verbatim}
In both cases, we leave the stub and roots on the field, and remove
the storage organ (that is, the grains).

\subsubsection{Multiple Cuts}
\label{sec:cuts}

For some crops, like grass, we will want to harvest or cut them
multiple times.  In such cases, the stub is essential, as that
determine how much leaf area there will be left to start regrowth.  If
you don't leave any stub (the default!), the plant will be unlikely to
recover.

Writing the generic management specification for grass is a lot more
complex than for barley, because we do not know in advance how many
times we are going to cut it.  It depends on how fast it grows.
Therefore, we start by defining two simpler actions.
\begin{verbatim}
  (defaction cut_grass activity
    (wait (or (crop_ds_after "Grass" 0.7 [])
              (crop_dm_over "Grass" 4000 [kg DM/ha] (height 10.0 [cm]))))
    (cut "Grass" (stub 10.0 [cm])))
\end{verbatim}
Here, we define a \texttt{cut\_grass} operation which wait for the
grass to grow old or big enough, and then cut it.

\begin{verbatim}
  (defaction cut_grass_fertilize activity
    (cut_grass)
    (wait_days 1)
    (fertilize (N25S (weight 100.0 [kg N/ha]))))
\end{verbatim}
Here, we extend the \texttt{cut\_grass} operation by fertilizing after
the cut.

Now we can define our grass management action:
\begin{verbatim}
  (defaction grass activity
    (wait_mm_dd 3 20)
    (wait trafficable)
    (plowing)
    (wait_mm_dd 4 10)
    (fertilize (N25S (weight 100.0 [kg N/ha])))
    (wait_mm_dd 4 15)
    (seed_bed_preparation)
    (sow "Grass")
    (while (wait_mm_dd 9 1)
      (activity
        ;; Max 5 fertilized cuts.
        cut_grass_fertilize cut_grass_fertilize cut_grass_fertilize
        cut_grass_fertilize cut_grass_fertilize
        ;; As many unfertilized cuts as we want.
        (repeat cut_grass)))
    (while (wait_mm_dd 11 1)
      ;; Additional unfertilized cuts.
      (repeat cut_grass)))
\end{verbatim}
The initial part is quite conventional, as seen in
sections~\ref{sec:ex-man} and~\ref{sec:crop-man}, until the two
\texttt{while} actions.  A \texttt{while} action take two other
actions, and perform them both in parallel, until the first action is
done.  It does not matter whether the second action finish or not.

In the example above, the first action is (in both cases), a
\texttt{wait\_mm\_dd} operation.  This means that the \texttt{while}
will simply continue until we reach the specified date.  While we are
waiting for that date, it will do as specified by the second action.
This means that until the 1'st of September, we may see up to 5 cuts
followed by fertilization.  We might see less that that, if the grass
does not grow fast enough, but never more.  After the 5 fertilized
cuts, assuming it is not yet September, we may see any number of
unfertilized cuts.  The \texttt{repeat} action will perform the
specified operation over and over forever, which means it is only
useful inside a \texttt{while}, otherwise it will never break out of
the loop.

After that, we start a new round of unfertilized cuts, which last
until November.  You may wonder why we didn't just used a single
\texttt{while}, which waited until November.  What is the difference?
I'm glad you asked.  With the description above, we get a manager that
will apply fertilizer at most six times (including the initial
fertilization the 10'th of April), thus staying below a possibly
politically induced upper limit.  \emph{And}, this is the trick, never
apply fertilizer after August.  Even if we have only had, say, three
fertilized cuts before September, and later cuts will be unfertilized.
The idea being that we do not believe the grass will grow enough that
late in the year to justify the additional fertilization.

Read more about fertilization in the next section.

\subsection{Fertilization}
\label{sec:fertilizer}

We have two basic types of fertilizer, \emph{mineral} and
\emph{organic}.  These will be described in the two next sections,
followed by examples of some more advanced types of fertilization. 

\subsubsection{Mineral Fertilizer}

In section~\ref{sec:ex-man} we used mineral fertilizer, as below:
\begin{verbatim}
    (fertilize (mineral
                (weight 100.0 [kg N/ha])
                (NH4_fraction 0.5 [])))
\end{verbatim}
If we used this fertilizer type often, it might be nice to give it a
name.  We could do this with the following definition:
\begin{verbatim}
  (defam SuperGrow mineral
    (NH4_fraction 0.5 []))
\end{verbatim}
To use it, we would write:
\begin{verbatim}
  (fertilize (SuperGrow (weight 100.0 [kg N/ha])))
\end{verbatim}
It only saves one line, but the producers of SuperGrow\texttrademark{}
will be eternally grateful.  The \texttt{fertilizer.dai} file already
contain the following mineral fertilizers:
\begin{description}
\item[\texttt{Ammonia}] Pure NH$_4^+$.
\item[\texttt{AmmoniumNitrate}] A 50-50 mix of NH$_4^+$ and NO$_3^-$.
\item[\texttt{Nitrate}] Pure NO$_3^-$.
\item[\texttt{N25S}] 50.8\% NH$_4^+$.
\end{description}

\subsubsection{Organic Fertilizer}

We used organic fertilizer, specifically pig slurry, in the example in
section~\ref{sec:crop-man}.  The obvious difference is that the weight
is given in metric tons of wet weight, rather than kg nitrogen.  The
\texttt{fertilizer.dai} file contains the following ready to use
definitions of pig slurry (named \texttt{pig\_slurry}), cattle slurry
(\texttt{cattle\_slurry}), pig manure (\texttt{pig\_manure}), cattle
manure (\texttt{cattle\_manure}), and horse manure
(\texttt{horse\_manure}).

For purely hypothetical scenarios, using the predefined organic
fertilizer specifications are adequate, however, if you know more
about the system being simulated, getting a better description of the
slurry or manure being applied is important, as the quality varies a
lot.  You can define a new slurry like this:
\begin{verbatim}
  (defam Andeby_pig_slurry slurry
    "Data collected by F. Guf, 2002 at the B. And farm, Andeby."
    (dry_matter_fraction 0.073)
    (total_C_fraction 0.323)
    (total_N_fraction 0.0863)
    (NH4_fraction 0.7)
    (NO3_fraction 0.0)
    (volatilization 0.15))
\end{verbatim}
where
\begin{description}
\item[\texttt{dry\_matter\_fraction}] Dry matter fraction of total
  (wet) weight.
\item[\texttt{total\_C\_fraction}] Carbon fraction of dry matter.
\item[\texttt{total\_N\_fraction}] Nitrogen fraction of dry matter
\item[\texttt{NH4\_fraction}] Ammonium fraction of total N in
  fertilizer.
\item[\texttt{NO3\_fraction}] Nitrate fraction of total N in
  fertilizer, by default zero.
\item[\texttt{volatilization}] Fraction of NH$_4^+$ that evaporates on
  application.
\end{description}
The organic nitrogen is what is left having removed the two inorganic
fractions.

It is possible to specify other parameters such as the turnover rate
and efficiency for the organic fertilizer, but these require
specialized knowledge of both the fertilizer itself, and the organic
matter model in Daisy (see~\cite{daisy-new}).

\subsubsection{First and Second Year Utilization}

Sometimes organic fertilization plans are made from estimated first
and second year utilization of the nitrogen.  In Denmark, this even
have legal force.  None of the fertilizers in \texttt{fertilizer.dai}
contain such estimates, as they varies both in time and jurisdiction,
but you can specify them yourself, as below.
\begin{verbatim}
  (defam "Andeby Pig Slurry" pig_slurry
    (first_year_utilization 0.40)
    (second_year_utilization 0.15))
\end{verbatim}
Here, we estimate that 40\% of the nitrogen (organic or mineral) is
utilized the first year, and 15\% the second year.  The rest is
presumably lost.  Note again, that these estimates have absolutely no
effect on how much will actually be utilized during the simulation.

To use this information, we can write the following
\begin{verbatim}
  (fertilize ("Andeby Pig Slurry")
             (equivalent_weight 100.0 [kg N/ha]))
\end{verbatim}
in our management specification.  We let Daisy calculate the amount
of wet weight to apply, to get a first year utilization of 100 kg
N/ha.  Note that \texttt{equivalent\_weight} is outside the
parentheses around the \texttt{"Andeby Pig Slurry"}, unlike
\texttt{weight}.  The \texttt{weight} parameter is a property of the
fertilizer itself, while \texttt{equivalent\_weight} is a property of
the fertilize action.  Thus, the difference.

To use the \texttt{second\_year\_utilization} parameter, we should let
one harvest operation (usually the first) the next year have the form
\begin{verbatim}
  (fertilize ("Andeby Pig Slurry")
             (second_year_compensation true)
             (minimum_weight 50.0 [kg N/ha])
             (equivalent_weight 150.0 [kg N/ha]))
\end{verbatim}
The \texttt{second\_year\_compensation} directive means that Daisy
should subtract any second year effect accumulated from fertilizations
the previous year from \texttt{equivalent\_weight} before calculating
the amount of fertilizer to apply.  By specifying
\texttt{minimum\_weight} we put a minimum on the amount of fertilizer
we will bother applying.  That is, if the accumulated second year
effect is more than 100 kg N/ha, we won't fertilize at all.

\subsubsection{Precision Fertilization}

Precision fertilization allows you to let the amount of fertilizer you
apply depend on the nitrogen content of the soil in a specified zone.

\begin{verbatim}
  (fertilize (N25S)
             (precision 150.0 [kg N/ha] (from 0.0 [cm]) (to -100.0 [cm]))
             (minimum_weight 50.0 [kg N/ha]))
\end{verbatim}

Daisy will measure the amount of fertilizer in the specified zone (from
the soil surface to 1 m depth, which is also the default), and supply
enough extra nitrogen to reach the specified target (150 kg N/ha).  If
less than the specified minimum (50 kg N/ha) nitrogen is needed in
order to reach the target, no fertilizer will be applied.

You can use the \texttt{precision} parameter with organic fertilizer
as well, in that case you must also specify the
\texttt{first\_year\_utilization} fertilizer parameter.


\subsubsection{Incorporation}

By default, fertilizer will be applied directly on the soil surface.
There, organic fertilizer will be incorporated gradually by biological
means (earth worms and the like), or suddenly by mechanical means,
i.e.\ by a tillage operation.  Inorganic fertilizer will penetrate the
soil along with the rain or irrigation water.

However, if a farmer has the equipment for it, he will prefer
incorporating the fertilizer directly into the soil.  It in general
increase utilization, and decrease complaints about pig slurry smell
from neighbors.

Use the \texttt{from} and \texttt{to} fertilize parameters to specify
incorporation, as below:
\begin{verbatim}
  (fertilize (pig_slurry (weight 100.0 [Mg w.w./ha]))
             (from -5 [cm]) (to -20 [cm]))
\end{verbatim}
Again, note the extra set of parentheses that binds \texttt{weight} to
\texttt{pig\_slurry}.  Unlike \texttt{from} and \texttt{to},
\texttt{weight} is a property of the \texttt{pig\_slurry}, not of the
\texttt{fertilize} operation.

\subsection{Irrigation}
\label{sec:irrigation}

Irrigation can be applied overhead the canopy (e.g.\ in the form of
sprinklers), on the soil surface, or incorporated directly into the
soil. 

To specify overhead irrigation, write
\begin{verbatim}
  (irrigate_overhead 30 [mm/h])
\end{verbatim}
This will irrigate with 30 mm/h for one hour, giving a total of 30 mm.
The water will first hit the canopy, where some will stay until it
eventually evaporate, and some may wash down any pesticides on the
canopy.

To give the same amount of water over a timespan of 10 hours, you can
instead write 
\begin{verbatim}
  (irrigate_overhead 3 [mm/h] (hours 10))
\end{verbatim}

To specify surface irrigation, write
\begin{verbatim}
  (irrigate_surface 30 [mm/h] (temperature 10.0 [dg C]))
\end{verbatim}
Again, this will give a total of 30 mm.  The water will bypass the
canopy, and directly hit the soil surface where it might create a pond
that slowly evaporates or enter the soil.

If you don't specify the temperature parameter, as in the
\texttt{irrigate\_overhead} case, the air temperature will be used.

The syntax for incorporating the water directly into the soil is
similar, here is an example:
\begin{verbatim}
  (irrigate_subsoil 1 [mm/h] (days 1) (hours 6)
                    (from -5.0 [cm]) (to -10.0 [cm])
                    (solute (NH4 1.0 [mg N/l]) (NO3 7.0 [mg N/l])))
\end{verbatim}
Here we specify subsoil irrigation with 1 mm/h for 30 hours, giving us
a total of 30 mm.  It will be incorporated into the soil between 5 and
10 cm's depth.  We also specify a content of inorganic nitrogen in the
water, something we can also do for overhead and surface irrigation.
We do not and cannot specify the water temperature for subsoil
irrigation, it is assumed to be the same temperature as the soil
itself.

\subsubsection{Conditions}

If we know exactly when the irrigation is to be done, we can simply
wait for the date, as here
\begin{verbatim}
  (wait_mm_dd 07 15)
  (irrigate_overhead 30 [mm/h])
\end{verbatim}

However, when writing generic crop managements as in
section~\ref{sec:crop-man}, we can't use that technique.  It might
rain the first two weeks of July for all we know, which will make
irrigating rather wasteful.  Daisy therefore provides ways to test
for the soil water content.
\begin{verbatim}
  (wait (not (soil_water_pressure_above (height -30.0 [cm])
                                        (potential -1000 [cm]))))
  (irrigate_overhead 30 [mm/h])
\end{verbatim}
Here, we emulate a tensiometer placed in the field at 30 cm depth,
triggering irrigation when the potential gets below -1000 cm.


An alternative condition would be
\begin{verbatim}
  (wait (not (soil_water_content_above 200.0 [mm] 
                                       (from 0 [m]) (to 1 [m]))))
\end{verbatim}
where we wait until there is less than 200 mm water in the top meter
of the soil. 

%% TODO: water deficit condition

\subsubsection{Strategies}

However, conditions like these are not enough, since we cannot know in
advance how many times it gets necessary to irrigate, if any.  This
problem is similar to the problem of multiple cuts we had in
section~\ref{sec:cuts}, and the solution also build on our ``parallel
processing'' directive, \texttt{while}.  Imagine we already have a
crop management description, like \texttt{sbarley} in
section~\ref{sec:crop-man}.  We can then add an irrigation strategy
like this:
\begin{verbatim}
  (defaction irrigate_30 activity 
    (wait (not (soil_water_pressure_above (height -30.0 [cm])
                                          (potential -1000 [cm]))))
    (irrigate_overhead 30 [mm/h]))

  (manager activity
    (while sbarley
      (repeat irrigate_30))
    (stop))
\end{verbatim}

Here, we define a management action named \texttt{irrigate\_30}, which
consists of waiting for the soil to dry out, and then irrigating
with 30 mm.  Our management specification says that as long as we are
managing our spring barley (as defined in \texttt{sbarley}), we will
repeatedly run \texttt{irrigate\_30}, that is, wait for the soil to
dry, and then irrigate.

An advantage of implementing our irrigation strategy like this is
that we can apply the strategy on any crop.  There are, however, two
problems we need to solve before it gets useful.  First, we should only
irrigate in the growth season, even if the soil somehow dries out
during the winter.  The second is that irrigation takes one hour, but
the water may very well take longer to reach the tensiometer.  This
means that the tensiometer will keep triggering irrigation several
time, until the water finally reaches it.

We solve the first problem by adding an ``in season'' test to the wait
conditions, and the second problem by adding a delay after
irrigation. 
\begin{verbatim}
  (defaction irrigate_30 activity 
    (wait (and (after_mm_dd 5 1)
               (before_mm_dd 9 1)
               (not (soil_water_pressure_above (height -30.0 [cm])
                                               (potential -1000 [cm])))))
    (irrigate_overhead 30 [mm/h])
    (wait_days 2))
\end{verbatim}

If there are limits on the total amount of water we are allowed to use
for irrigation, we can limit the maximal number of times we irrigate,
like below.
\begin{verbatim}
  (manager activity
    (while sbarley
      (activity irrigate_30 irrigate_30 irrigate_30 irrigate_30))
    (stop))
\end{verbatim}
Here, we will at most irrigate four times.

\subsection{Pesticides}
\label{sec:pesticides}

Pesticides have no effect in Daisy (i.e. Daisy crops are immune
to everything, and weeds are something that happens to other models).
Nonetheless, Daisy allows you to apply them to the field.  Daisy
will then keep track on them, as the are transported with the water
through the system, or are removed from the system by either
decomposition, root uptake, or leaching to the groundwater.

The command to apply pesticides is
\begin{verbatim}
  (spray Bentazon 1000 [g/ha])
\end{verbatim}
with \texttt{Bentazon} being the name of the pesticide.  The currently
available pesticide parameterizations includes \texttt{Atrazine},
\texttt{Bentazon}, \texttt{IPU}, \texttt{MCPP},
\texttt{Pendimethalin}.  To use them, you must add
\begin{verbatim}
  (input file "chemistry.dai")
\end{verbatim}
to the start of the setup file.

\subsubsection{Defining New Pesticides}

You can easily introduce new pesticides by specifying a few
parameters.  The parameters may not be that easy to obtain, though.
Here is an example:
\begin{verbatim}
(defchemical Atrazine default
  "From a FAO sponsored field experiment near Andeby, 2002."
  (canopy_dissipation_rate 0.0083 [h^-1])
  (canopy_washoff_coefficient 1.0 [])
  (crop_uptake_reflection_factor 0.8 [])
  (diffusion_coefficient 4.6e-6 [cm^2/s])
  (decompose_rate 7e-5 [h^-1])
  (diffusion_coefficient 8e-6 [cm^2/s])
  (adsorption linear (K_clay 7 [cm^3/g])))
\end{verbatim}
As we have seen before, in the first line we \emph{def}ine a new
\emph{chemical} name \emph{Atrazine}, using the \emph{default} (and
currently only) model for chemicals in Daisy.  In the second line,
we put some information about this chemical so we will know later
where these numbers come from.

\subsubsection{Canopy}

The pesticide will be introduced into the system with the
\texttt{spray} command.  Some of the pesticide will land directly on
the soil surface, while other will hit the canopy, depending on how
large a fraction of the soil is covered by the crops.  The fraction
that hits the canopy is assumed to stay there, until it either
dissipate entirely out of the system, or is washed down to the soil
surface by rain or irrigation.  

The parameter \texttt{canopy\_dissipation\_rate} indicates how large a
fraction of the pesticide dissipate from the canopy each hour, while
\linebreak{}\texttt{canopy\_washoff\_coefficient} is a measure of how
the pesticide disolve in the intercepted water.  If you set it 0.0 is
does not disolve at all, and will never be washed off.  If you set it
to 1.0 it will be fully dissolved, and thus follow any water that fall
off the canopy.

\subsubsection{Soil Surface and Root Uptake}

Down on the soil surface, Daisy will pretend that the pesticide is
immediately fully dissolved in any water that hits the soil surface,
and follow the water when it enters the soil.  Nothing else will
happen to the pesticides when on the soil surface.  Pesticides in the
top of the soil can also move up to the soil surface in case of
ponding.  This effect can be significant when there are macropores
activated by the ponding, as pesticides that have already entered the
soil can later be transported with macropores from the surface.

In the soil, the pesticides can be adsorbed, transported, decomposed,
or taken up by the roots by transpiration.  The later is controlled by
\linebreak{}\texttt{crop\_uptake\_reflection\_factor}.  In the
example, we specify that 80\% of the pesticides dissolved in the water
extracted by the roots for transpiration will be reflected, that is
will stay in the soil water.  The 20\% that is uptaken will disappear
out of the system.

\subsubsection{Decomposition}

We set \texttt{decompose\_rate} to the fraction of pesticides assumed
to be decomposed each hour.  This rate is affected by a number of
factors, listed here:
\begin{description}
\item[\texttt{decompose\_heat\_factor},
  \texttt{decompose\_water\_factor}] Biological
  decomposition\linebreak{} tend to accelerate with increasing heat
  and moisture.  Unless you specify otherwise, the factors used for
  mineralization will be reused here.
\item[\texttt{decompose\_CO2\_factor}] CO$_2$ production is an
  indicator of an active soil biomass.  By specifying this parameter,
  you can let the general biological activity influence the
  decomposition. 
\item[\texttt{decompose\_conc\_factor}] Some pesticides will be hard
  to decompose at high or low concentrations, which can be specified
  with this parameter. 
\item[\texttt{decompose\_depth\_factor}] Sometimes the decompose rate
  depend on how deep in the soil we are, which is what this parameter
  is for. 
\item[\texttt{decompose\_lag\_increment}] Some pesticides require
  specialized organisms to decompose, which may take some time to
  appear.  Daisy therefore keep track of a time lag variable for
  each pesticide, which starts at zero.  When it reaches one,
  decomposition begins.  You can set this parameter to specify the
  hourly increment, as a function of the concentration in the soil.
  By default, the increment is 1, which means decompositions starts
  immediately, with no time lag.
\end{description}
See~\cite{dina81} for more specific information about each of these
factors. 

\subsubsection{Transportation}

The pesticide in the soil can be transported with convection and
diffusion.  Set \texttt{diffusion\_coefficient} to specify the later.
Finally, the pesticide may adsorb to the soil.  Daisy have a number
of advanced models for adsorption, but for pesticides it is usually
adequate to either disable adsorption \texttt{(adsorption none)}, or
use a simple linear correspondence between adsorbed and dissolved
matter, $A = K \rho C$, where $A$ is the amount of adsorbed matter,
$K$ is a pesticide and soil specific parameter, $\rho$ is the bulk
density of the soil, and $C$ is the amount of dissolved matter.  In
Daisy, we have split $K$ into a \texttt{K\_clay} parameter which is
multiplied with the clay fraction of the soil, and a \texttt{K\_OC}
parameter which is multiplied with the humus fraction of the soil.

% TODO: Transformations.

\subsubsection{Log models}

Here are some log models that are useful when dealing with pesticides:
\begin{description}
\item[\texttt{Field chemical}] Enough information to crate a balance
  for the chemical for the whole field, including what may be present
  on the surface and in the biopores. File:
  \texttt{field\_chemicals.dlf}.
\item[\texttt{Soil chemical}] Enough information to create a balance
  for a specific soil interval, only including what is present in the
  soil matrix, but not biopores or soil surface. File:
  \texttt{soil\_chemicals.dlf}.
\end{description}

The \texttt{chemical} parameter tell Daisy what pesticide to log, as
in:
\begin{verbatim}
    ("Soil chemical" (chemical Atrazine))
\end{verbatim}
Specifying this will change the default filename, so for example
instead \texttt{field\_chemicals.dlf} you will get
\texttt{field\_Atrazine.dlf}.

\section{Log Files}
\label{sec:output}

In this section I list some useful log models not listed elsewhere,
but first lets refresh the general useful parameters.  The following
two parameters can be used for almost all log models:
\begin{description}
\item[\texttt{when}] Indicates how often to log.  In theory, you can
  use any condition, like e.g.\ \texttt{crop\_dm\_over}, but in
  practice \texttt{hourly}, \texttt{daily}, \texttt{weekly},
  \texttt{monthly} and \texttt{yearly} are the most useful ones.  The
  log models will automatically accumulate flux values between time
  steps.  When not otherwise indicated, log models log every hour.
\item[\texttt{where}] Select the file in which to log the results.
\end{description}

As explained in~\ref{ex:column}, the soil is split into a large number
of numeric layers for computational purposes.  Some log models, such
as \texttt{Soil Temperature}, will log the content of a single state
variable for each of these layers.  Other log models will log many
state variables by integrating the content of the variable in for all
layers in some interval, or for flux variables, use the values at the
top or bottom of the interval.  \texttt{Soil nitrogen} is an example
of such a log model.  You can control what interval to summarize by
setting the \texttt{from} and \texttt{to} parameters.

We use all of them in this example:
\begin{verbatim}
  (output ("Soil nitrogen" (when monthly)
                           (where "nitrogen-balance.dlf")
                           (from 0 [m]) (to -1 [m])))
\end{verbatim}

\subsection{Activating output}
\label{sec:actout}

Since writing a log file tend to be as slow as running the
simulation itself, and if you specify many log files Daisy will
become very slow indeed.  It also depend on the log file, as a general
rule, large log files are much more time consuming than small log
files.  So don't ask for hourly values of daily or even monthly values
will do.  But the `harvest' log model is nearly free.  And if you are
using Daisy interactively, don't specify a log file just because
you \emph{may} need the information.  If you later discover that you
need the information in that log file, you can rerun the simulation
specifying log file only.

You can also limit the period where log file is kept, both to speed up
the simulation, and to avoid uninteresting data.  This is
especially useful in conjunction with a warmup period.  You do this by
setting \texttt{activate\_output} at the top level, like this:
\begin{verbatim}
  (activate_output (after 1997 3 31 23))
\end{verbatim}
This will activate the log files from April 1st, 1997 and to the end
of the simulation.  You can specify all the same kind of conditions as
in management.  To limit the period in both ends, you can use
\begin{verbatim}
  (activate_output (and (after 1997 3 31 23) 
                        (before 1998 4 1 0)))
\end{verbatim}
which will give you log files containing data from the hydraulic year
1997. 

\section{Plotting simulation results}
\label{sec:plot}

The \texttt{.dlf} files produced by Daisy are text files with (by
default) tab separated columns, and can be viewed by any text editor,
or by most spreadsheets.  There also exist a specialized program,
\texttt{ShowDaisyOutput}, to display the results, and Daisy has a
build in facility to covert the \texttt{.dlf} files (as well as the
related weather \texttt{(.dwf)} files and data files \texttt{.ddf}
with measurements) into commands to the general plot program
\texttt{gnuplot}. 


\subsection{Spreadsheets}

Note that Daisy uses US style numbers, that is decimal point rather
than decimal comma.  If the numbers looks weird in your spreadsheet,
check how they look in a text editor like notepad.  If the numbers are
different, you may need to change the settings of the program to
accept American style numbers.  In MS Windows, you can change the
number style from the control panel (Start $\rightarrow$ Control panel
$\rightarrow$ International).

For Excel, the easiest way to open Daisy log files are either to
drag them into a shortcut to Excel, or to associate the \texttt{.dlf}
files with Excel (right click on the file, and use ``Open with'' to
open the file with Excel).

\subsection{ShowDaisyOutput}

The ShowDaisyOutput can be fetched from the Daisy homepage.  It
only works under MS Windows.  It is very good for a fast overview of
the results, you simply drag the \texttt{.dlf} file to the
ShowDaisyOutput icon, and the program will display the first
(non-time) column.  You then have the option to display another column
from a menu, or in some versions to zoom into the data by dragging the
mouse on the plot area you want to view.  For the
\texttt{crop\_prod.dlf} file, ShowDaisyOutput is able to display all
DM at once.

For some log files, ShowDaisyOutput can display the data as a soil
profile with depth at the y-axes and value at the x-axes.  You can
then animate the data to see changes in time.

There is no printing facilities in ShowDaisyOutput, use on of the
other options for that. 

\subsection{Generating gnuplot commands from Daisy}
\label{sec:gnuplot-daisy}

The \emph{gnuplot} program build into Daisy allows you to create a
command file (name \texttt{daisy.gnuplot}) for the external
\texttt{gnuplot} (or \texttt{wgnuplot.exe}) tool, to create plots in
encapsulated postscript (\texttt{*.eps}), Acrobat Reader PDF
(\texttt{*.pdf}), LaTeX (\texttt{*.tex}) format or be shown directly
in a window.  The data to be plotted can be read from Daisy log
files (\texttt{*.dlf}), Daisy weather files (\texttt{*.dwf}) or the
Daisy data files (\texttt{*.ddf}).

The gnuplot homepage are at \url{http://www.gnuplot.info/} where you
can find versions of the program for most platforms.  You need at
least version 4.0 of gnuplot.

\subsection{Simple example}

\begin{verbatim}
  (defgnuplot test time
    (source (column (file "harvest.dlf") (tag "leaf_DM"))
            (column (file "harvest.dlf") (tag "sorg_DM"))
            (column (file "crop_prod.dlf") (tag "Leaf AI"))))

  (defprogram "Andeby Graphs" gnuplot
    (graph test))

  (run "Andeby Graphs" )
\end{verbatim}
This will create a \texttt{daisy.gnuplot} file that generates a window
with a plot of leaf and storage organ yields taken from the
\texttt{harvest.dlf} file, and LAI from the \texttt{crop\_prod.dlf}
file.

\subsection{Complex example}

\begin{verbatim}
(defgnuplot another_test time
    "Test of 'gnuplot' program."
    (ymin -1) (ymax 6) (y2min 0) (y2max 10)
    (begin 1986 9 1 0) (end 1987 11 1 0)
    (title "gnuplot demonstration")
    (size 1.0 0.5)
    (extra "set xtics rotate")
    (legend se)   
    (source (column (file "harvest.dlf")
                    (tag "leaf_DM")
                    (title "Leaf Harvest")
                    (with points)
                    (dimension "Mg DM/ha"))
            (column (file "harvest.dlf")
                    (tag "sorg_DM")
                    (title "Grain Harvest")
                    (with points)
                    (dimension "Mg DM/ha"))
            (column (file "crop_prod.dlf")
                    (filter ("day_length" "10" "8")
                    ("month" "9" "10"))
                    (style 1)
                    (tag "WLeaf"))
            (column (file "crop_prod.dlf")
                    (style 2)
                    (tag "WSOrg"))
            (column (file "crop_prod.dlf")
                    (tag "Leaf AI"))))
            
  (defprogram "Andeby Graphs" gnuplot
    (command_file "kurt.gnuplot")
    (graph (another_test)
           (test (where "test.eps"))
           (another_test (where "another-test.eps"))))
  
  (run "Andeby Graphs")
\end{verbatim}  
This example defines a gnuplot graph called ``another test''.
\begin{itemize}
\item This graph selects the range for the x-axis (begin and end)
  and both y-axes (ymin, ymax, y2min, y2max) manually, instead of
  letting gnuplot choose its own.
\item We give the graph a title, ``gnuplot demonstration''.
\item We ask for a graph with the default width, but only half the
  default height.
\item An uninterpreted gnuplot order is send via the 'extra' keyword.
  In this case in order to rotate the labels of the tics on the x axis
  90 degrees.  You can also set fonts and font sizes, ask for
  monochrome plots, and many other things.
\item We ask to get the legend in the South-East corner, instead of
  letting Daisy find the corner farthest away from an data.  
\item We use different titles and different names for the dimensions
  for the 'harvest.dlf' data, and we plot them with points instead of
  lines.  By default Daisy use points for `\texttt{*.ddf}' files, and
  lines for `\texttt{*.dlf}' and `\texttt{*.dwf}' files.
\item We only get WLeaf data from `\texttt{crop-prod.dlf}' that are
  from days with length 10 or 8, and from September or October.
\item We use the first and second style for plotting WLeaf and WSOrg
  from `\texttt{crop\_prod.dlf}', instead of letting Daisy find the
  next available style.  This means they have the same style as the
  corresponding data from `\texttt{harvest.dlf}', except that they are
  plotted as lines instead of points.
\end{itemize}
In order to actually plot the graphs we have defined, we define a
gnuplot program called ``Andeby Graphs''.  This program will generate
command in the ``\texttt{kurt.gnuplot}'' file to plot three graphs.
First the graph we just defined named ``another\_test'' with no output
file specified, meaning the graph will be shown on the screen.  Then
the program generates commands for plotting the original test graph in
a file called ``\texttt{test.eps}'', and then the new graph in the
file ``\texttt{another-test.eps}''.

\subsection{The 'arithmetic' source model}

The \texttt{arithmetic} source mode allows simple arithmetics with
columns in a single file.
\begin{verbatim}
  (defgnuplot crop time
    "Plot crop dry matter partitions."
    (source (arithmetic (file "crop_prod.dlf")
                         (expr WSOrg))
            (arithmetic (file "crop_prod.dlf")
                        (expr WRoot))
            (arithmetic (file "crop_prod.dlf")
                        (title "WShoot")
                        (expr (+ WStem WLeaf WDead)))))
\end{verbatim}
Here we plot storage organ and roots as usual, but add the stem,
leaves and dead leaves pools into a single graph named ``\emph{WShoot}''.  When
you use expressions like this, you usually will want to set the legend
title explicitly, otherwise it would have been called ``\emph{+}''.

The format of arithmetic expressions are always prefix, the name of
the operator followed by the operands.  Daisy currently understands
the following functions \texttt{+}, \texttt{-}, \texttt{*},
\texttt{/}, \texttt{min}, \texttt{max}, \texttt{pow}, \texttt{exp},
\texttt{sqrt}, \texttt{sqr}, \texttt{ln}, and \texttt{log10}.

Numbers are written as \texttt{(const \textit{val} \textit{dim})}, like
\begin{verbatim}
  (expr (+ WSOrg (const 1.0 [Mg DM/ha])))
\end{verbatim}
if we want to lie about our yield.

You can convert dimensions with \texttt{(convert \textit{expr}
  \textit{dim})} like
\begin{verbatim}
  (expr (convert WSOrg [g DM/m^2]))
\end{verbatim}
Daisy is in general unable to calculate the dimensions of the result
of some arithmetic expression, except in the most simple cases (like
\texttt{+}).  You can tell Daisy the dimension with \texttt{(dim \textit{expr} \textit{dim})}, like
\begin{verbatim}
  (expr (dim (* WSOrg (const 2.0 [])) [Mg DM/ha]))
\end{verbatim}
The difference from `\texttt{convert}' is that dim will not change the
value, only the dimension.

\subsection{Daisy Data Files (\texttt{*.ddf})}

The `\texttt{*.ddf}' files are intended for measured data.  The data
are by default plotted as points, and with the same styles as data
sources in the same sequence from `\texttt{*.dlf}' and
`\texttt{*.dwf}' files.  The idea is that you want to compare measured
and simulated numbers.

The format is:
\begin{verbatim}
  ddf-0.0 You can insert a description after the seven first letters.
  # Here you can add comments, here.
  # As long as they begin with a '#'.
  # After a line of hyphens, tab separated data should be listed.
  # The two first lines are tags and dimensions, like for '*.dlf' files.
  ------
  Date           Height
                 cm
  2005-09-24T01  20
  2005-09-24T07  21
\end{verbatim}
You can either separate year/month/mday/hour columns, as in the dlf
and dwf files, or a single Date column, with the format
`\texttt{yyyy-mm-ddThh}' (which happens to be an ISO standard).

If you don't have a dimension line, you must specify the dimension
with the \texttt{original} keyword for each source.

\section{Organizing Your Parameterizations}
\label{sec:files}

If you follow the advice in this tutorial, you will create a number of
parameterizations for things like horizons, columns, fertilizer types,
and crop management strategies.  Most likely, many of these
parameterizations will be generically useful, that is, useful in many
different simulations.  My advice is that you from the start create a
\emph{library} of such parameterizations, for later use.  This library
should be kept separate from both the standard library that comes with
Daisy, and from the files that are specific to your current
simulation.  By separate, I mean that you should keep the files in
three or more different directories.
\begin{itemize}
\item The \texttt{lib} and \texttt{sample} directories distributed
  with Daisy.  You should never change these files, and never add new
  files yourself.  If you want to add anything there, send your
  additions to
  \href{mailto:daisy@dina.kvl.dk}{\texttt{$<$daisy@dina.kvl.dk$>$}},
  and let me do it.  The advantage of this is that it will be easy to
  upgrade your Daisy installation when a new and improved version
  with new and improved features, and new and improved bugs, arrives.
  These files are closely tied to the version of Daisy they are
  distributed with.
\item A directory containing files with those parameterizations that
  are not specific to a single simulation.  In that directory you can
  organize the parameterizations by locations (e.g.\ put all horizon
  and column parameterizations containing data measured in Andeby in a
  single \texttt{andeby.dai} file) or by type (e.g.\ put all crop
  management specifications in a single \texttt{crop-man.dai} file) or
  both, depending on taste.
\item A directory for each simulation, containing a setup file, extra
  files with simulation specific parameterizations or other data, and
  all the output (\texttt{.dlf}) files produced by the simulation run.
\end{itemize}
From experience, such an organization saves time in the long run.  

\subsection{Don't Copy, Derive}

A related hint for your own parameterizations: Don't copy, derive.
For example, if you want a slightly different grass than the one
provided by the standard Daisy library, don't just copy the
definition from \texttt{grass.dai} and edit the parameter you want to
change.  And certainly don't change the \texttt{grass.dai} directly.
Instead, create a derived parameterization as we did in
section~\ref{sec:bioclimate}:
\begin{verbatim}
  (defcrop "Andeby Spring Barley" "Spring Barley"
    "Spring Barley with modified EpFac as measured
  in Andeby, 2002, for the SuperGrow(TM) cooperation."
    (Canopy (EpFac 1.2)))
\end{verbatim}
The advantage of doing it this way twofold.  First, if we fix or
improve the grass parameterization in \texttt{grass.dai}, you will
derived version will automatically get the improvements when you
install the updated Daisy version.  Furthermore, we may make
changes to the default crop model that requires corresponding changes
to the parameterizations.  Of course, we do that for the standard
parameterizations right away.  But if you have made a copy of the
parameterizations, it will break when you install the new version.

\subsection{\textsc{Daisypath}}
\label{sec:daisypath}

Now that you have followed my advice, and spread your files over three
directories, how do we tell Daisy where to find it?  Well, Daisy
uses two sources to find the files:
\begin{itemize}
\item A \emph{path} containing information about which directories to
  look, and
\item the \emph{current directory}, which is also the place it will
  put any log files.  If ``\texttt{.}'' is included in the path, Daisy
  will also look for input files here.
\end{itemize}

By default, Daisy will look for files in the current directory, as
well as in the directories distributed with Daisy (if you have used
the MS Windows installer).  You can overwrite this with the
\texttt{DAISYHOME} or \texttt{DAISYPATH} environment variable, or by
specifying path explicitly in the setup file like this:
\begin{verbatim}
  ;; Search file files these places.
  (path "." "c:/My Files/daisy/lib/" &old)
\end{verbatim}
Note that ``\texttt{.}'' means ``look in the current directory'' and
that you should use forward slashes (\verb|/|) instead of backslashes
(\verb|\|) in the path names.  The special keyword \verb|&old| means
the old value for path.  This means that Daisy will first look for
files in the current directory, then in \verb|C:\My Files\daisy\lib|,
and finally where it would have looked if you hadn't specified
anything

If you start Daisy from TextPad after following the instructions on
the home page, the current directory will be the same directory as the
active file in TextPad.  However, you can also specify it explicitly
in the setup file, like this:
\begin{verbatim}
  ;; Run program here.
  (directory "c:/My Files/Andeby/sim01")
\end{verbatim}
An advantage of doing it this way, is that you can start the simulation
by dragging the setup file to the \texttt{daisy.exe} icon in the file
manager.  If you don't specify \texttt{directory}, it will run the
program somewhere silly.

The reason I recommend the \textsc{daisypath} route, is that the setup
files become location independent.  That is, if you send it to someone
else who have installed Daisy in another location, he can still run
the setup file unchanged.  If you specify \texttt{path} in the setup
file, he has to change one line.  If you specify \texttt{directory},
he has to change two lines.  What I don't recommend is using absolute
file names.  E.g.
\begin{verbatim}
  (input file "c:/Program Files/daisy/lib/fertilizer.dai")
\end{verbatim}
It works, but gives a lot of lines that must be changed when moving
the files.

\appendix

\section{Experimental features}
\label{sec:exp}

These features are still experimental, and should not be used for
``normal'' simulations.  Use them for simulations where the main
purpose is to examine the effect of each feature.

\subsection{Ice}
\label{sec:ice}

% TODO

\subsection{Soil Compaction}
\label{sec:compact}

% TODO

\subsection{Phosphor}
\label{sec:phosphor}

% TODO: not supported, strongly adsorbed, solid, transformations.

\subsection{Dividing and Merging Fields}
\label{sec:divide}

% TODO: grazing

\subsection{Ridging}

A special tillage operation is ridging.  Ridging is common in tropical
agriculture, where it has various beneficial effects, such as
preventing erosion, controlling the soil water, and increasing the
effective rooting depth, depending on the situation.  It is also used
under temperate conditions, for example for potato farming in Denmark,
where ridging provide better growing conditions in the soil,
especially with regard to heat.

In Daisy, ridges only affects the flow of soil and surface water,
and a hard-to-penetrate crust is assumed, making it less relevant to
Danish potato farming.

You can specify that the field should contain ridges with the
\texttt{ridge} operation.
\begin{verbatim}
  (ridge (z (0.0 0.0) (0.4 0.0) (0.6 50) (1.0 50.0))
         (R_crust 50 [h]))
\end{verbatim}
where
\begin{description}
\item[\texttt{z}] The ridge height, formulated as $z (x)$, where $x$
  is the relative distance from the middle of the ridge.  $x = 0.0$ is
  in the middle of a ridge, while $x = 1.0$ is at the maximal
  distance.  The ridge is assumed to be symmetric.  $z (x)$ is
  measured in centimeter above the unridged soil surface, which means
  it is in the same reference system as the rest of the model.
\item[\texttt{R\_crust}] Resistance in crust.  Adjust this to control
  the rate in which water infiltrate.
\end{description}
The ridge must not be taller than the top horizon, as there should be
uniform hydraulic properties throughout the ridge.

To remove the ridges, specify any other tillage operation.

Technically, the ridge operation creates a special subsystem within
Daisy where water flow sideways into the ridge wall or down through
the ridge bottom.  You can log this subsystem with the following log
parameterization:
\begin{description}
\item[\texttt{Ridge}] Information about the Ridge subsystem.  File:
  \texttt{ridge.dlf}.
\end{description}

\subsection{Forced LAI}
\label{sec:forced-lai}

You can force the CAI to have a specific value for part of the year.
This is useful if you have measured the total CAI and want Daisy to
use those values for photosynthesis and transpiration (and
interception capacity).  Here is an example:
\begin{verbatim}
  (defcolumn Andeby default
    "The B.And farm, Andeby, 2003."
    (Vegetation crops
                (ForcedLAI (1987 (100 2.0) (200 4.0))
                           (1988 (100 0.0) (150 1.5) (200 5.0))))
    (Soil (horizons (-20 [cm] Ap) (-2.5 [m] C))
          (MaxRootingDepth 60.0 [cm]))
    (Groundwater deep))
\end{verbatim}
The code above should be read: In 1987 we start using forced CAI day
100 where it is 2.0 and end forced CAI in day 200 where it is 5.0.  We
use linear interpolation between these two points, so in day 150 it
will be 4.0.  Before day 100 and after day 200 we use the simulated
CAI values.  In 1988 we start day 100 at CAI 0.0, increase linearly to
1.5 day 150, and from there again linearly to 5.0 day 200, where we
switch back to using simulated CAI\@.  All other years we use simulated
LAI.

Only parameterizations of the \texttt{default} crop model will be
affected by the \texttt{ForcedLAI} attribute.

If there are multiple crops, the forced CAI will be distributed among
them corresponding to the relative size of their simulated CAI\@.  When
forced CAI is active, this is the only use of the simulated CAI\@.  

\subsubsection{Log models}

The simulated CAI will be calculated anyway and can be logged.  Most
log files will only log the CAI actually used which, when Forced LAI
is in effect, will not be the sum of Leaf, Stem and SOrg AI\@.  The
new "Forced LAI" log model will log both the used, forced and
simulated CAI\@.  By default, it will log the sum of all crops, set
\texttt{crop} to log a particular crop alone as below:

\begin{verbatim}
  (output "Forced LAI"
          ("Forced LAI"
           (crop "Spring Barley")
           (where "sbarley.dlf"))
          ("Forced LAI"
           (crop "Grass to grain")
           (where "grass.dlf")))
\end{verbatim}

\section{\texttt{test.dai}}
\label{app:test}

\begin{verbatim}
;;; test.dai -- Sample file using the Daisy libraries.

(description "Simulation for use in tutorial.")

;; Use standard parameterizations.
(input file "tillage.dai")
(input file "crop.dai")
(input file "log.dai")

;; Weather data.
(weather default "dk-taastrup.dwf")

;; We have some very sandy soil.
(defhorizon Ap FAO3
  "Andeby top soil."
  (clay 8.0 [%])
  (silt 10.5 [%])
  (sand 81.5 [%])
  (humus 1.12 [%])
  (C_per_N 11.0 [g C/g N])
  (dry_bulk_density 1.5 [g/cm^3]))

(defhorizon C Ap
  "Andeby C horizon."
  (humus 0.12 [%]))

;; We build the column from the horizons.
(defcolumn Andeby default
  "Data collected by F.Guf at the B.And farm, Andeby, 2002."
  (Soil (horizons (-20 [cm] Ap) (-2.5 [m] C))
        (border -1 [m])
        (MaxRootingDepth 60.0 [cm]))
  (OrganicMatter original
                 (init (input 1400 [kg C/ha/y])
                       (root 480 [kg C/ha/y])
                       (end -20 [cm])))
  (Groundwater deep))

;; Use it.
(column Andeby)

;; Simulation start and stop dates.
(time 1986 12 1 1)
(stop 1988 4 1 1)

(manager activity
  (wait (at 1987 3 20 1))
  (plowing)
  (wait (at 1987 4 4 1))
  (fertilize (mineral (weight 100.0 [kg N/ha])
                      (NH4_fraction 0.5 [])))
  (wait (at 1987 4 5 1))
  (progn
    (sow "Grass")
    (sow "Spring Barley"))
  (wait (or (crop_ds_after "Spring Barley" 2.0)
            (at 1987 9 5 1)))
  (harvest "Spring Barley")
  (wait (at 1987 9 8 1))
  (fertilize (mineral (weight 80.0 [kg N/ha])
                      (NH4_fraction 0.5 [])))
  (wait (at 1987 10 10 1))
  (cut "Grass"
       (stub 8.0 [cm])              ;Leave 8 cm stub.
       (stem 1.00 [])))             ;Harvest everything above stub.

;; Create these log files.
(output harvest
        ("Field nitrogen" (when monthly))
        ("Soil nitrogen" (when daily) (from 0 [m]) (to -1 [m]))
        ("Field water" (when monthly))
        ("Soil water" (when daily) (from 0 [m]) (to -1 [m]))
        ("Crop Production"
         (crop "Spring Barley")
         (where "sbarley.dlf"))
        (checkpoint (when (at 1987 8 7 6))))

;;; test.dai ends here.
\end{verbatim}

\section{Bibliography}
\bibliography{daisy}

\section{Standard log files}
\label{app:logs}

This section define the columns for the main log files.

\input{stdlog}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:
