\documentclass[a4,11pt,oneside,openright,titlepage]{scrbook}

%----------------------------------------------
% PACKAGE MANAGEMENT
%
\usepackage{a4}
\usepackage[latin1]{inputenc} 
\usepackage{times}
\usepackage{fancyhdr}
\usepackage{lastpage}
%\usepackage[all, light]{draftcopy}
%\usepackage{supertabular}
%\usepackage{colortbl}
%\usepackage{epsf}
\usepackage{mdwlist}
\usepackage{graphicx}

%----------------------------------------------
% Document DATE and VERSION
% set these values when releasing a new version

\def\cleanunderscore#1_#2{\expandafter #1\_#2}
\def\CVS$#1: #2 ${\expandafter\def\csname CVS#1\endcsname{\cleanunderscore#2}}

\newcommand{\documentdate}{November 29, 2011}
\newcommand{\documentversion}{1.1.2}
\newcommand{\softwareversion}{GREAT-ER 3.0.0}
\newcommand{\documentID}{}
\newcommand{\documentname}{Model Description}

%----------------------------------------------
% MACRO DEFINITION
%
%   \Fig{figure}{text}  : creates an mbox around 'figure' and
%                         writes 'text' at the bottom with leading
%                         'Fig. section.figno:'.
%                         Example:
%                         \Fig{\epsfxsize30mm \epsffile{x.png}}{the x}\\
%   \FigNoEntry{}{}     : same as above, no entry in figures list
%
%   \FigCaption{}       : line with figure caption, setting figure
%                         counter and figures list
%

%****************************************************************************
%       Figure makro for graphics continously enumerated.
%

\newcounter{FigCnt}[chapter]
\newcommand{\Fig}[3]%
{
        \refstepcounter{FigCnt}
        \addcontentsline{lof}{figure}%
                {\protect\numberline{\thechapter.\arabic{FigCnt}}{#2}}
        \mbox{#1}
\nopagebreak
        {Fig. \thechapter.\arabic{FigCnt}: #3}

}

\newcommand{\FigNoEntry}[2]%
{
        \refstepcounter{FigCnt}
        \mbox{#1}

\nopagebreak
        {Fig. \thechapter.\arabic{FigCnt}: #2}

}

\newcommand{\FigCaption}[1]%
{
        \refstepcounter{FigCnt}
        \addcontentsline{lof}{figure}%
                {\protect\numberline{\thechapter.\arabic{FigCnt}}{#1}}

        %{Figure \thechapter.\arabic{FigCnt}: #1}
}


\newcommand{\APIMethod}[1]{{\tt\small #1}}
\newcommand{\classobj}[1]{{\sffamily #1}}
\newcommand{\method}[1]{{\tt\small #1}}
\newcommand{\varname}[1]{{\tt\small #1}}
\newcommand{\varvalue}[1]{{\sl #1}}
\newcommand{\gfilename}[1]{{\sffamily #1}}
\newcommand{\gunit}[1]{\mbox{ [#1]}}

\newenvironment{methoddesc}[1]{%
\subsubsection*{\APIMethod{#1}}
}%
{
}


% typeset a parameter name
\newcommand{\parameter}[1]{{\tt\small #1}}


%
% END MACRO DEFINITION
%----------------------------------------------


%----------------------------------------------
% DOCUMENT
\begin{document}

%-----------------------------------
% HEADER/FOOTER DEFINITION
% The settings here are for single page documents (only odd page set)

% for some pages latex switches back to pagestyle plain :-(
\fancypagestyle{plain}{%
	\fancyhf{} % clear all header and footer fields
	\fancyhead[RO,LE]{\footnotesize GREAT-ER 3.0 \documentname \\ \leftmark}
	\fancyfoot[RO,LE]{\footnotesize Intevation GmbH} % Author
	\fancyfoot[CO,CE]{\footnotesize \thepage/\pageref{LastPage}}
	% set the document title for the footer here!
	\fancyfoot[LO,RE]{\footnotesize \documentdate 
	\\\documentID}
	\renewcommand{\footrulewidth}{0.4pt}
}

% and now define pagestyle fancy
\fancyhead{} % clear all fields
\fancyhead[RO,LE]{\footnotesize GREAT-ER 3.0 \documentname \\ \leftmark}
\fancyfoot[RO,LE]{\footnotesize Intevation GmbH} % Author
\fancyfoot[CO,CE]{\footnotesize \thepage/\pageref{LastPage}}
% set the document title for the footer here!
\fancyfoot[LO,RE]{\footnotesize \documentdate 
\\\documentID}

\renewcommand{\footrulewidth}{0.4pt}

\pagestyle{fancy}

%-----------------------------------

\parindent0cm

% TITLE PAGE
{

% Icon
\includegraphics[width=\textwidth]{artwork/great-er3_0-title.png}\\[4.5cm]

% Title
\begin{center}
	\sffamily\bfseries\Large 
    \Huge \documentname \\[5.5cm]
\end{center}
}
\thispagestyle{empty}

\vfill

% Author
{\sffamily\small
\begin{tabular}{p{0.3\textwidth}p{0.3\textwidth}p{0.3\textwidth}}
	\includegraphics[width=0.3\textwidth]{/home/intevation/logos/intevation/intevation_logo.png}
&
\parbox[b]{0.3\textwidth}{
Intevation GmbH\\
Neuer Graben 17\\
49074 Osnabrück\\
Germany\\
www.intevation.de
}
&
\documentdate

\end{tabular}
}

\newpage

% PAGE 4

\vfill

This document has been designed with \LaTeX{}.
It is available as source code, PDF- and HTML-format.\\

Version: \documentversion \\
Date: \documentdate \\
Author: Frank Koormann

\vfill

Related documents:
\begin{itemize}
\item GREAT-ER Manual, \\Intevation GmbH, 2011
\item GREAT-ER Model Specification, \\Intevation GmbH, 2011
\item GREAT-ER Technical Documentation - Chemical Fate Models\\
	Geert Boeije, University of Gent, 1999
\end{itemize}
\vfill

\begin{center}Copyright (c) 2011 Intevation GmbH.\end{center}

    Permission is granted to copy, distribute and/or modify this document
    under the terms of the GNU Free Documentation License, Version 1.2
    or any later version published by the Free Software Foundation;
    with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
    A copy of the license is included in the section entitled ``GNU
    Free Documentation License''.

\tableofcontents



%
%This can be used as a template for the required software description.
%
%\subsection{Network Framework}
%
%\begin{tabular}{|p{2.5cm}|p{9.5cm}|}\hline
%Name, URL:	& \\ \hline
%Version: 	& \\ \hline
%Licence:	& \\ \hline
%Description: 	& \\ \hline
%Task:		& \\ \hline
%\end{tabular}

\chapter{Introduction}
\label{chap:General}

This document aims to give an overview about the concepts and implementation of 
the GREAT-ER 3.0 Model Suite. The emphasis lies on illustrating how to implement 
new models within the Model Suite. Detailed information about the
implemented classes and methods can be found in the HTML-based 
documentation of the class hierarchy\footnote{Files: 
scheduler.html and worker.html}.

GREAT-ER is an environmental exposure assessment tool with deterministic
models. Variability and parameter uncertainty are considered by applying
the Monte-Carlo approach. 

The flexible, transparent and extensible reimplementation of the GREAT-ER
Model system was a core task of the GREAT-ER 3.0 software development project.

\section{Architecture}
\label{sec:Architecture}

The architecture of the Model Suite was designed under the requirements of
high scalability: The Suite is used in a single user desktop environment as
well as on server environments for the GREAT-ER Web Version.

Hence a two component architecture was designed with a Scheduler and a Worker.
The Scheduler controls the simulation runs, while a Worker actually performs a
simulation. Each user interface, either GREAT-ER Desktop Client or 
GREAT-ER Web (both Clients in general) are connected to one Scheduler, 
while a Scheduler can communicate with several Workers. Clients do not
communicate directly with a Worker.

This concept allows various combinations:
\begin{itemize}
	\item Scheduler and one Worker on one computer\\
		This is the usual configuration for a single user desktop
		environment. When running the GREAT-ER Desktop Client
		this combination is started automatically on authentication.
		The Model Suite can perform one simulation at time.
		\begin{center}
		\FigNoEntry{\includegraphics[width=0.9\textwidth]
			{architecture_single_user.png}}
			{GREAT-ER 3.0 Model Suite Architecture: 
			Single User Installation}
		\end{center}
	\item Scheduler and several Workers on one computer\\
		The Scheduler delegates complete simulation jobs to single 
		Workers, the Model Suite can perform as many simulations in
		parallel as Workers are running. This setup is used for 
		GREAT-ER Web. It is also usable for network installations of
		GREAT-ER, if the Clients are running on low performance
		terminals, with the Model Suite running on a computing server.
		\begin{center}
		\FigNoEntry{\includegraphics[width=0.9\textwidth]
			{architecture_computing_server.png}}
			{GREAT-ER 3.0 Model Suite Architecture: 
			Computing Server Installation}
		\end{center}

	\item One Scheduler and multiple Workers on several computers\\
		The Scheduler splits one simulation job to different
		workers (running on different computers), the Model Suite 
		can perform at least as many simulations in
		parallel as Workers are running on different computers.
		This installation can be used for highly frequented 
		GREAT-ER Web Installations or for computing farms when running
		high numbers of Monte-Carlo shots on large catchments.
		\begin{center}
		\FigNoEntry{\includegraphics[width=0.9\textwidth]
			{architecture_distributed_computing.png}}
			{GREAT-ER 3.0 Model Suite Architecture: 
			Distributed Computing Installation}
		\end{center}
\end{itemize}

\section{Scheduler Concept}
\label{sec:SchedulerConcept}

The Scheduler is designed independent of specific model implementations for 
the currently considered compartments. All model requirements are defined by
the Worker and handed over to the Scheduler on demand. 

The Scheduler performs the following actions:
\begin{itemize}
	\item Interface "required parameter" requests from a Client to a
		worker.

	\item Interface "missing parameter" requests from a Client to a worker.

	\item Run a simulation requested by a Client:
	\begin{enumerate}
		\item Request a Worker instance for a list of parameters
		to be considered as distributed (covers also correlation
		information) for the simulation run.
		\item Generate batch of Monte-Carlo shots.
		\item Delegate the simulation run to one or more Workers
		(depending on the scenario as described under 
		\ref{sec:Architecture}).
		\item During simulation collect progress information from
		Workers and report to the Client on demand.
		\item After the end of the simulation collect all results 
		and write them into the database. 
	\end{enumerate}
	\item Stop a running simulation on request.
\end{itemize}

See the document "GREAT-ER 3.0 Model Specification", section "Scheduler" 
for interface details.

\section{Worker Concept}
\label{sec:WorkerConcept}

The Worker implements the GREAT-ER Models and all information on required
parameters: 
\begin{itemize}
	\item reply on "required parameters" queries
	\item reply on "missing parameters" queries
	\item reply on "stochastic parameters" queries
	\item compute a batch of Monte-Carlo shots 
		for a specified session.
\end{itemize}

A Worker is related to one Scheduler process, both communicate via a 
perspective broker protocol. The Worker was designed to keep most of the
administrative overhead (I/O, select loops, process communication) out of the 
model implementation, which is encapsulated in the Model class 
(section \ref{sec:ModelClass}).

See the document "GREAT-ER 3.0 Model Specification", section "Worker" 
for interface details.

\section{Implemented Models}
\label{sec:Compartments}

To prove the new concept of the GREAT-ER 3.0 Model Suite the models of GREAT-ER
1.0 have been reimplemented. These cover four compartments with various levels
of model complexity:
\begin{itemize}
	\item Emission: \\
		For household chemicals the emission is calculated 
		from the number of inhabitants connected to a WWTP and the per
		year per capita consumption of a chemical. Additional inputs
		into the WWTP can be specified as mass per year separately.
	\item Sewer: \\
		A percentage removal is applied for the sewer system, the model
		can be switched off.
	\item Waste Water Treatment Plant (discharge into river):\\
		The WWTP component covers a primary settler, and a main
		processing step, either activated sludge or trickling filter.
		For both percentage removal is applied, the activated sludge 
		chain (including the primary settler) is also implemented 
		similar to the SimpleTreat model (Boeije, section 5.2).
	\item River:\\
		The river model implements an extended version of the 
		WATER model, a one-dimensional first-order elimination model.
		The elimination rate can be considered with three different
		complexities:
		\begin{enumerate}
		\item Over all elimination rate (from literature)
		\item Partitioning and separate elimination rates for 
			sorbed and dissolved fractions and volatilization.
		\item Separate processes: Hydrolysis, photolysis,
			bio-degradation, sedimentation and vola\-ti\-li\-zation.
		\end{enumerate}
\end{itemize}

Chapter \ref{chap:Examples} (page \pageref{chap:Examples}) illustrates 
by some examples how to implement a model for the GREAT-ER 3.0 Model Suite.
Details about the implemented models are described in the
"GREAT-ER Technical Documentation - Chemical Fate Models".

\section{Python}
\label{sec:Python}

Python\footnote{\tt http://www.python.org} is an object-oriented scripting
language with byte compilation available as Free Software. 
It provides multiple inheritance, overloading
of methods and operators as well as polymorphisms. Aside the usual data types
specific types as dynamic arrays, lists, tuples and dictionaries are available.

Python is an easy to learn programming language resulting in a transparent
source code due to the indention oriented structuring scheme. The basic
distribution is enhanced by numerous modules for various tasks,
partly especially for scientific computing. Python programs can be extended
with C-implemented modules for time-consuming computations.

\chapter{Structure and Helper Classes}
\label{chap:Structure}

The backbone of the system structure of GREAT-ER 1.0 was the river network.
The network is split into stretches of different types: spring, confluence,
bifurcation and discharge. Based on these elements the river network can be
seen as a directed graph, where the first three stretch types have mainly 
topological meaning. The discharge element is more special because an additional
chain of models is embedded: Emission, sewer and WWTP. However, the graph
structure is limited to the river network. 
Figure \thechapter.\ref{fig:structure_great-er_1}
illustrates the situation.

\begin{center}
\FigNoEntry{
    \includegraphics[width=0.95\textwidth]{./structure_great-er_1.png}}{
        \label{fig:structure_great-er_1} System structure GREAT-ER 1.0
    }
\end{center}

The approach for GREAT-ER 3.0 extends the segment concept to all models. The
directed graph is not limited to the river network with a static chain of
models linked to a discharge point as described above. The different models are
represented by specific segments and therewith part of the directed graph
(Figure \thechapter.\ref{fig:structure_great-er_2}).
This approach provides higher flexibility in extending and combining the model
collection. 

\begin{center}
\FigNoEntry{
    \includegraphics[width=0.95\textwidth]{./structure_great-er_2.png}}{
        \label{fig:structure_great-er_2} New system structure for GREAT-ER 3.0
    }
\end{center}

The structure implemented by two class-hierarchies, the \classobj{Segment} 
class and the \classobj{Graph} class. 

For a better understanding: Child/Parent terminology in the following section
is used with view from the graph root (which must be unique): In relation to a
given segment the child segment is the upstream segment, the parent segment is
the downstream one.

\section{Segment Class}
\label{sec:SegmentClass}

\begin{center}
\FigNoEntry{\includegraphics[scale=0.5]{dia/segment.png}}{
Class Hierarchy \classobj{Segment}}
\end{center}

The \classobj{Segment} class hierarchy implements 
the core of the directed graph, the 
segment objects, as described above. The graph is binary, therewith three 
types of segments are sufficient to build the graph: a simple segment, a
connector and a fork. The segments implementation is independent from the model
implementations following the directed graph concept.
 
\subsubsection{Segment}
\label{subsec:Segment}

The class \classobj{Segment} implements a simple segment, 
with one or none parent and one
or no child. Methods:

%
% Segment.__init__
%
\begin{methoddesc}%
	{\_\_init\_\_(self, par, model)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt \_\_init\_\_} \\ \hline

Description &
	Constructor: The \_\_init\_\_ method initializes  
	instance variables provided by the parameter dictionary and a pointer 
	to the model object depending on the segment type.
	\\ \hline
In 	&
	\parameter{par}, \parameter{model}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{par}: & Parameter dictionary \\
		\parameter{model}: & Pointer to model object
		\end{tabular}
	  } \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% Segment.PHIin
%
\begin{methoddesc}%
	{PHIin(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt PHIin} \\ \hline
Description &
	Calculate the segment mass flux input from the child segment 
	mass flux output. 
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	&
	PHIin
	\\ \hline

Return definitions	&
	Return the input mass flux of the segment.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% Segment.compute
%
\begin{methoddesc}%
	{compute(self, shot\_num)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt compute} \\ \hline
Description &
	Run the segment model and set the instance variable \varname{PHIout}.
 	\\ \hline
In 	& 
	\parameter{shot\_num}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{shot\_num}: & Number (identifier) of Monte-Carlo
						shot. \\
		\end{tabular}
	  } \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% Segment.get_results
%
\begin{methoddesc}%
	{get\_results(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt get\_results} \\ \hline

Description &
	Return the results for the segment.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	&
	Tuple (\varname{segmentid}, \varname{segment.model.results}).
	\\ \hline

Return definitions	&
	Returned is a tuple of \varname{segmentid} (which uniquely identifies
	the result set and \varname{segment.model.results} (a list of 
	\classobj{StochasticResult} objects (see
	\ref{sec:StochasticResultClass})).
	\\ \hline
\end{tabular}
\end{methoddesc}

\subsubsection{Connector}
\label{subsec:Connector}

The class Connector connects two segments (i.e. it has two children). It inherits 
from \classobj{Segment} and overrides some methods:
	
%
% Connector.__init__
%
\begin{methoddesc}%
	{\_\_init\_\_(self, par, model)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt \_\_init\_\_} \\ \hline

Description &
	Constructor: The \_\_init\_\_ method initializes  
	instance variables provided by the parameter dictionary and a pointer 
	to the model object depending on the segment type. In difference
	to \method{Segment.\_\_init\_\_} instance variables for both children are
	initialized.
	\\ \hline
In 	&
	\parameter{par}, \parameter{model}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{par}: & Parameter dictionary \\
		\parameter{model}: & Pointer to model object
		\end{tabular}
	  } \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% Connector.PHIin
%
\begin{methoddesc}%
	{PHIin(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt PHIin} \\ \hline

Description &
	Calculate the segment mass flux input as sum of the mass flux output
	of both children.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	&
	PHIin
	\\ \hline

Return definitions	&
	Return the input mass flux of the segment.
	\\ \hline
\end{tabular}
\end{methoddesc}

\newpage

\subsubsection{Fork}
\label{subsec:Fork}
The class Fork inherits from the Connector class. In combination with a 
second fork segment this class represents a bifurcation in a river network.
The segment stores a pointer to the related fork segment using the second 
child variable structures. This is similar to the data stored in the 
stretch\_tab, as a consequence a fork segment has always only one child
segment.

%
% Fork.PHIin
%
\begin{methoddesc}%
	{PHIin(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt PHIin} \\ \hline

Description &
	Calculate the segment mass flux from child segment with splitting 
	to related fork segment.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	&
	PHIin
	\\ \hline

Return definitions	&
	Return the input mass flux of the segment.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% Fork.CalculateForkRatio
%
\begin{methoddesc}%
	{CalculateForkRatio(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt CalculateForkRatio} \\ \hline

Description &
	Initially calculate fork ratio, depending on flow for the 
	two segments. The calculation has to be performed after the entire
	graph is build and all relations are determined. 
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}


\newpage

\section{Graph Class}
\label{sec:GraphClass}

\begin{center}
\FigNoEntry{\includegraphics[scale=0.5]{dia/graph.png}}{
\classobj{Graph} Class}
\end{center}

Although implementing only two methods, the \classobj{Graph} Class provides the
backbone feature of a Worker. A graph object stores the directed graph
representing the system under investigation as described above.
 
%
% Graph.__init__
%
\begin{methoddesc}%
	{\_\_init\_\_(self, session)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt \_\_init\_\_} \\ \hline

Description &
The \method{\_\_init\_\_} method initializes the graph in various steps:
\begin{itemize}
	\item Derive the list of stochastic parameters per model type.
	\item Instantiates all segments according to the structure 
	information read from the database.
	\item Bind appropriate model objects to all segments.
	\item Call the \method{setup} method of each segments model object
	(see below, section \ref{subsubsec:Model.setup}) to complete
	initialization.
	\item Link all segments with its child segments.
	\item Perform a final test on network integrity.
	\item Call the \method{CalculateForkRatio} method for all bifurcation
	segments.
	\item Derive a list representing a post-order traverse of the directed
	graph.
\end{itemize}
	\\ \hline
In 	& \parameter{session}
	\\ \hline
In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{session}: & Pointer to the \classobj{Data} object
		(see \ref{sec:DataClass}) storing the session information and
		data.\\
		\end{tabular}
	  } \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% Graph.Traverse
%
\begin{methoddesc}%
	{Traverse(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt Traverse} \\ \hline

Description &
	Return the post-order traverse for the graph.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	&
	List of \classobj{Segment} objects.
	\\ \hline

Return definitions	&
	The returned list of objects represents a post-order traverse of the
	graph.
	\\ \hline
\end{tabular}
\end{methoddesc}


Since the graph must be strictly binary, the insertion of virtual segments is
necessary during initialization, e.g. if a confluence segment 
is a river stretch receiving a discharge. Such virtual stretches are 
instantiated with a neutral model only handing over the mass flux.

The information about a segment and its model is stored in two instance
variables of a segment:
\begin{itemize}
	\item \varname{ID}: \\
	Unique string to identify the segment, combination 
	of general model type and ID as read from the database. The general
	model type can be "H" (household), "S" (sewer), "D"
	(discharge), "R" (river) or "V" (virtual). This type information is 
	evaluated when storing the simulation results (currently discharge and 
	river results).

	\item \varname{type}: \\
	A more general key storing model specific segment type information
	required while building the graph and deriving the traverse.
	\begin{tabbing}
		some more space here\=type
		\hspace*{1.5cm}\=less+some more space here\=type\kill
		Source:	 	\>0	\>Discharge:	\>4\\
		Normal Segment:	\>1	\>Sewer:	\>5\\
		Confluence: 	\>2	\>Household:	\>6\\	
		Bifurcation: 	\>-2\\
		Lake: 		\>3\\
	\end{tabbing}
\end{itemize}

\newpage

\section{Data Class}
\label{sec:DataClass}

\begin{center}
\FigNoEntry{\includegraphics[scale=0.5]{dia/data.png}}{
\classobj{Data} Class}
\end{center}

The \classobj{Data} class implements the read access to the data base.
Initialized with a session ID all required data can be loaded depending on the
requested Worker action. A worker has one \classobj{Data} object, all Model
objects store a pointer to this global source of data. The \classobj{Data}
object stores connection data and the session ID and provides a dictionary
(\varname{data}), which keys are set according to the loaded data (e.g,
'SESSION', 'STRETCH', 'DISCHARGE', 'SUBST', etc.). 

Each parameter can be identified by its BlockID, FieldID pair as used in the
database \linebreak
\varname{PARA\_TREE\_DEF\_TAB}. Tabular data can be accessed by a
BlockID, RecordID pair in combination with the needed FieldID.  Please note
that as used in this example, the \classobj{Data} object is usually stored in
the variable \varname{session}:
\begin{itemize}
	\item \varname{session.data['STRETCH'][1].q\_val}: mean flow value of the
	stretch with ID 1.
	\item \varname{session.data['SUBST']['K\_OW'].value}: $K_{OW}$ from the
	substance data.
\end{itemize}

\newpage

\section{Stochastic Result Class}
\label{sec:StochasticResultClass}

\begin{center}
\FigNoEntry{\includegraphics[scale=0.5]{dia/stochasticresult.png}}{
\classobj{StochasticResult} Class}
\end{center}

The \classobj{StochasticResult} Class implements an object to collect stochastic 
results to compute mean and standard deviation. Internally the object 
stores the number of sampled values $(n)$, 
sum of values $\left(\sum_i^n x_i{n}\right)$ 
and the sum of value squares $\left( \sum_i^n x_i^2\right)$. 

From these mean and standard deviation can be derived:
\begin{eqnarray}
\mu & = & \frac{\sum_i^n x_i}{n} \label{eqn:StochasticResult_mu}\\
\sigma & = & \sqrt{\frac{\sum_i^n x_i^2 
				- \frac{\left( \sum_i^n x_i \right)^2}{n - 1}}
			{n - 1}} \label{eqn:StochasticResult_sigma}
\end{eqnarray}

%
% StochasticResult.__init__
%
\begin{methoddesc}%
	{\_\_init\_\_(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt \_\_init\_\_} \\ \hline

Description &
	Constructor: Instantiate the \classobj{StochasticResult} object.
		\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	& -
	\parameter{}
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% StochasticResult.add
%
\begin{methoddesc}%
	{add(self, value)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt } \\ \hline

Description &
	Add a value to the collection.
	\\ \hline
In 	&
	\parameter{value}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{value}: & float value \\
		\end{tabular}
	  } \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% StochasticResult.combine
%
\begin{methoddesc}%
	{combine(self, param)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt combine} \\ \hline
Description &
	Combine two \classobj{StochasticResult} objects by adding the 
	descriptive instance variables (sampled values, 
	sum of values, sum of value squares).
	\\ \hline
In 	& \parameter{param}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{param}: & \classobj{StochasticResult} object to
					be combined with the object\\
		\end{tabular}
	  } \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% StochasticResult.get
%
\begin{methoddesc}%
	{get(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt get} \\ \hline

Description &
	Return mean, standard deviation and number of sampled values, derived 
	from instance variables as described in equations 
	\ref{eqn:StochasticResult_mu} and
	\ref{eqn:StochasticResult_sigma}
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	& 
	Tuple (\varname{mean}, \varname{stddev}, \varname{num})
	\\ \hline

Return definitions	&
	Returned are the descriptive parameters of the stochastic result: 
	Mean, standard deviation and the number of single results the
	stochastic result is based on.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% StochasticResult.get_raw
%
\begin{methoddesc}%
	{get\_raw(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt get\_raw} \\ \hline

Description &
	Return the raw sums as described above. Helpful in case combining 
	numerous stochastic results in other applications, when the 
	\classobj{StochasticResult} class is not usable.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
Return	&
	Tuple of (\parameter{sum}, \parameter{sumsqr}, \parameter{n})
	\\ \hline
Return definitions	&
	Return the sum, sum of squares and number of collected values.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% StochasticResult.reset
%
\begin{methoddesc}%
	{reset(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt reset} \\ \hline

Description &
	Reset the object to initial state (sums and numbers set back to zero).
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	  \\ \hline
	
Return	& -
	\parameter{}
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}


\section{Parameter Class}
\label{sec:ParameterClass}

\begin{center}
\FigNoEntry{\includegraphics[scale=0.5]{dia/parameter.png}}{
Parameter Class}
\end{center}

The Parameter Class encapsulates the handling of distributed parameters.
Supported are undistributed parameters, normal, logarithmic normal and uniform
distributions: 

%
% Parameter.__init__
%
\begin{methoddesc}%
	{\_\_init\_\_(self, key, parameter, 
                    stochastic\_parameter\_list,
                    stochastics, ID = None)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt \_\_init\_\_} \\ \hline

Description &
	Constructor: Initialize the parameter encapsulation as 
	normal, logarithmic normal and uniform or undistributed parameter.
	\\
	&
	If the information about distributions is incomplete on instantiation 
	an undistributed parameter is instantiated.
	\\ \hline
In 	& \parameter{key}, \parameter{parameter}, 
	  \parameter{stochastic\_parameter\_list}, 
	  \parameter{stochastics}, \parameter{ID}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{key}: & 
			Tuple (\parameter{blockid}, \parameter{fieldid})
			identifying the parameter in the session data.\\  
		\parameter{parameter}: & String representation of the 
			parameter (either single value or semicolon separated
			pair of descriptive values)\\ 
	  	\parameter{stochastic\_parameter\_list}: & \\
			&
			List of stochastic parameters (see
			\ref{subsec:Parameter} for list details). 
			The actual distribution type of the parameter is
			derived from this list (if the parameter is found).\\ 
	  	\parameter{stochastics}: & Pointer to the batch 
			(a dictionary of lists) of Monte-Carlo shot values.\\ 
		\parameter{ID}: & (optional) identifier for distinct segments.
				This can be used to use separate distributions
				for specific objects (if derived by
				\method{Model.StochasticParams}, 
				see \ref{subsec:Implemented_methods}). 
				 \\
	    \end{tabular}
	  } \\ \hline
	
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% Parameter.get
%
\begin{methoddesc}%
	{get(self, shot)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt get} \\ \hline

Description &
	Return value from the parameter for the given Monte-Carlo shot
	considering the distribution determined during instantiation.
	\\ \hline
In 	& \parameter{shot}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{shot}: & Number (identifier) of the current
					Monte Carlo shot. \\
		\end{tabular}
	  } \\ \hline
	
Return	&
	\parameter{value}
	\\ \hline

Return definitions	&
	Float value from parameter distribution for current Monte-Carlo shot.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
% CHAPTER 
% Implement a model for GREAT-ER 3.0
%
\chapter{Core Model System}
\label{chap:ModelImplementation}

As mentioned above the new GREAT-ER Model Suite has been designed to keep all
administrative tasks out of the central model implementation, to make
implementation of new models within the given framework easier. While the
previous chapter introduced some objects and methods used to implement a model 
this chapter is concentrating on the model itself.

The core of the GREAT-ER 3.0 Model Suite is 
represented in two files, \gfilename{model.py} and \gfilename{modelbase.py},
while the implementation of specific models is placed in separate files.
\begin{itemize}
	\item \gfilename{model.py}\\
	provides an unique interface to all implemented models. It imports 
	all models and lists available models in the ModelList.
	
	\item \gfilename{modelbase.py}\\
	provides the basic Model class from which all implemented models
	are inherited.
\end{itemize}

\section{The ModelList}
\label{sec:ModelList}

The \varname{ModelList} stores a list off all models implemented by the
GREAT-ER 3.0 Model Suite as a list of Python tuples. Hook in each new 
implemented model here with an entry of three values. 

The following grammar in Backus-Naur
notation describes the structure of the list:\\
 {\small\verb+[..]+} refers to 
a Python list, {\small\verb+(..)+} to a Python tuple.

{\small
\begin{verbatim}
ModelList       : [ Models ]

Models          :
                | Model, Models
                | Model

Model           : ( FlagKey, Model Name, Model Group )
\end{verbatim}
}

\begin{itemize}
	\item \varname{Flag}: String\\
	Key of item in model mode section flagging a model mode (e.g.
	'MODE\_SEWER'). If value is \varvalue{None} the model is assumed to be
	applied in any mode.

	\item \varname{Model Name}: String\\
	Name of the class implementing the given model, e.g. 'SewerMode1'.
	
	\item \varname{Model Group}: String\\
	Model group the model belongs to. Currently considered are:
	'Emission', 'Sewer', 'River', 'DischargePrimary', 'DischargeAS' and
	'DischargeTF'.
\end{itemize}

\section{The Model Class}
\label{sec:ModelClass}

\begin{center}
\FigNoEntry{\includegraphics[scale=0.5]{dia/modelclass.png}}{
Model Class}
\end{center}

The methods of the Model class fall in four groups: Initialization,
Parameter Information, Simulation and Administrative Framework. 
Depending on the specific model implementation some of the methods 
have to be overridden. The methods are discussed below followed by some
examples illustrating the implementation of models with the GREAT-ER 3.0 Model
Suite.

\subsection{Parameter information}
\label{subsec:Parameter}

The GREAT-ER 3.0 Model Suite architecture requires the parameters needed for a
simulation to be hard coded in the model. Since all model equations are 
implemented
here as well a unique location is available to store the most relevant
information on a model in one place. 

\subsubsection{Model Parameter Description}
\label{subsubsec:Model_parameter_description}

This section describes the two structures used for the parameter
description. Their interpretation in the methods to answer the Scheduler's
parameter requests are discussed below (\ref{subsec:Implemented_methods}).

\paragraph{Required parameters}
\label{paragraph:Required_parameters}
The parameters required for a model are stored in a list represented by 
the variable 
\varname{\_required\_parameters}. The list stores a sublist for each model 
implemented by a model class.

\newpage

{\small
\begin{verbatim}
_required_parameters   : [ Lists ]

Lists                  :
                       | List, Lists
                       | List

List                   : [ Mode, Parameters ]

Mode                   : ( BlockID, FieldID, value )

Parameters             : Parameter, Parameters
                       | Parameter

Parameter              : ( BlockID, FieldID )
                       | ( BlockID, FieldID, value )
\end{verbatim}
}

The parameters are represented by their
BlockID, FieldID pairs, as used also in the database 
\varname{PARA\_TREE\_DEF\_TAB}. The Mode-Descriptor 
identifies a special parameter, on which is decided if the model is used 
in the current model mode setting or not: If the identified parameter
for the current session equals the defined value, the model is to be used.

For the parameters of the blocks SUBST, ENV and MOD in addition to the simple
availability parameters can be checked for a specific value. This is defined
in the last column of the \varname{\_required\_parameters} specification.

{\bf Note:} If a model is to be used always, independent from the mode
selection, the \varname{Mode} tuple has to be set to 
\varvalue{(None, None, None)}. 

\subsubsection{Correlated parameters}
\label{paragraph:Correlated_parameters}

Similar to the \varname{\_required\_parameter} list the 
\varname{\_correlated\_parameter} list describes all parameters which are
considered as correlated by the model implementation:

{\small
\begin{verbatim}
_correlated_parameters : [ List ]

List                   :
                       | CorrelationInfo, List
                       | CorrelationInfo

CorrelationInfo        : ( Parameter, Parameter, Correlation )

Correlation            : Parameter
                       | numerical value [-1.0,1.0]

Parameter              : ( BlockID, FieldID )
\end{verbatim}
}

As described, the correlation information consists of the elements:
\begin{itemize}
	\item the correlated parameter,
	\item the parameter the current parameter is correlated with,
	\item the correlation as either a fixed value or a third parameter 
	describing the correlation.
\end{itemize}

\subsubsection{Parameter Information Output}
\label{subsubsec:Parameter_information_output}

Based on the lists described above the models parameter information methods
derive two different lists on demand.

\paragraph{Parameter List} The parameter list simply lists parameters
identified by a BlockID, FieldID tuple. Lists of this type are used for
required and missing parameters:

{\small
\begin{verbatim}
parameter_list         : [ List ]

List                   :
                       | Parameter, List
                       | Parameter

Parameter              : ( BlockID, FieldID )
\end{verbatim}
}

\paragraph{Stochastic Parameter List} is returned by the 
\method{StochasticParameters} method and lists all distributed parameters
with their correlation information:

{\small
\begin{verbatim}
stochastic_parameters  : [ List ]

List                   :
                       | StochasticParameter, List
                       | StochasticParameter

StochasticParameter    : (( BlockID, FieldID, Distribution, ObjectID ), 
                          Correlation )

Distribution           : 'none'
                       | 'normal'
                       | 'lognormal'
                       | 'uniform'

ObjectID               : '-1'
                       | Identifier of a segment

Correlation            : None
                       | Parameter
                       | numerical value [-1.0,1.0]

Parameter              : ( BlockID, FieldID )


\end{verbatim}
}

%
%\subsection{Results}
%
\subsection{Results}
\label{subsec:Results}

Results are stored in a dictionary (\varname{Results}) as pointers 
to \classobj{StochasticResult} objects (see \ref{sec:StochasticResultClass}).  
The method \method{get\_results} provides external access on the results.

%
%\subsection{Implemented methods}
%
\subsection{Implemented methods}
\label{subsec:Implemented_methods}

The Model class implements a set of generic methods necessary to provide all
model information and to run a simulation. Depending on the specific model 
various methods have to be overridden by a model implementation (as illustrated
below, section \ref{chap:Examples}), at least \method{setup} and 
\method{compute} which
implement the actual data access and model computation.
 
%
%\subsubsection{\method{\_\_init\_\_(self, session, st\_params)}}
%
\begin{methoddesc}%
	{\_\_init\_\_(self, session, st\_params)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt \_\_init\_\_} \\ \hline
\label{subsubsec:Model.__init__}

Description &
	Constructor: Called during graph initialization (\ref{sec:GraphClass}).
	The initialization is completed later with the \method{setup} method.
	The method is usually not overridden.
	\\ \hline
In 	&
	\parameter{session}, \parameter{st\_params}
	\\ \hline
In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{session}: &
			Pointer to the sessions data object 
			(\ref{sec:DataClass}) \\
		\parameter{st\_params}: & 
			Pointer to the batch of Monte-Carlo shots 
			(\ref{sec:GraphClass})
		\end{tabular}
	  } \\ \hline
Return	& -
	\parameter{}
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

 
%
%\subsubsection{\method{setup(self, segmentID)}}
%
\begin{methoddesc}%
	{setup(self, segmentID)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt setup} \\ \hline
\label{subsubsec:Model.setup}
Description &
	The \method{setup} method is used to initialize the parameters needed
	for the model for the specific segment from the \classobj{Data} object.
	The method is called with the segmentID (which is fixed at this stage) 
	as a reference to the segment in the graph. In addition the 
	\classobj{StochasticResult} objects needed by the model are 
	initialized and stored in the \varname{Result} dictionary.

	Since the generic method does not load any data it has to be 
	overridden when implementing a new model.
	\\ \hline
In 	& \parameter{segmentID}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{segmentID}: & Identifier of the graph's 
			\classobj{Segment} object 
			the \classobj{Model} object is related with.
		\end{tabular}
	  } \\ \hline
Return	& -
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsubsection{\method{compute(self, segment, shot\_num)}}
%
\begin{methoddesc}%
	{compute(self, segment, shot\_num)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt compute} \\ \hline
\label{subsubsec:Model.compute}
Description &
	The \method{compute} method finally implements the model equations. 
	\\
	&
	The generic implementation simply hands through the input mass flow, 
	hence the method has to be overridden usually.
	\\ \hline
In 	& \parameter{segment}, \parameter{shot\_num}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{segment}: & Pointer to the segment the model 
				is linked to to call the segments 
				\method{PHIin} method. \\
		\parameter{} : & Number of Monte-Carlo shot to obtain 
				the correct values from the models 
				\classobj{Parameter} objects.
		\end{tabular}
	  } \\ \hline
Return	&
	\parameter{PHIout}
	\\ \hline

Return definitions	& The model returns the mass flux out of the segment
	for the current Monte-Carlo shot.
	\\ \hline
\end{tabular}
\end{methoddesc}


%
%\subsubsection{\method{get\_results()}}
%
\begin{methoddesc}%
	{get\_results()}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt get\_results} \\ \hline
\label{subsubsec:Model.get_results}
Description &
	Return the models \classobj{StochasticResult} objects, 
	referenced in the \varname{Result} dictionary.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	   \\ \hline
Return	&
	Dictionary of \classobj{StochasticResult} objects.
	\\ \hline
Return definitions	&
	Returned is a dictionary of \classobj{StochasticResult} objects,
	from which the descriptive values can be interrogated.
	The dictionary's keys clearly identify the separate objects.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsubsection{\method{CheckRequiredParameters(self, parameter\_list=None)}}
%
\begin{methoddesc}%
	{CheckRequiredParameters(self, parameter\_list=None)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt CheckRequiredParameters} \\ \hline
\label{subsubsec:Model.CheckRequiredParameters}
Description &
On initialization of the worker the method is called to check the 
required parameter definition syntax. By default 
(\varname{parameter\_list} is \varvalue{None}) process the model's 
\varname{\_required\_parameters} list. If available the method is called 
recursively with sublists of \varname{\_required\_parameters}.
\\
& The method is usually not overridden. \\ \hline
In 	& \parameter{parameter\_list}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{parameter\_list}: & List of parameters to check\\
		\end{tabular}
	  } \\ \hline
	
Return	&
	Boolean
	\\ \hline

Return definitions	&
	The method returns a boolean value identifying correctness.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsubsection{\method{RequiredParameters(self, parameter\_list=None)}}
%
\begin{methoddesc}%
	{RequiredParameters(self, parameter\_list=None)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt RequiredParameters} \\ \hline
\label{subsubsec:Model.RequiredParameters}
Description &
Return the list of parameters required by the model according to the
model mode selections. By default 
(\varname{parameter\_list} is \varvalue{None}) process the model's 
\varname{\_required\_parameters} list. If available the method is called 
recursively with sublists of \varname{\_required\_parameters}.
\\
&Depending on the complexity of the implemented model it can be necessary to
override the \method{RequiredParameters} method (see \ref{chap:Examples}).
	\\ \hline
In 	& \parameter{parameter\_list}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{parameter\_list}: &Raw list of required parameters\\
		\end{tabular}
	  } \\ \hline
	
Return	&
	Parameter list
	\\ \hline

Return definitions	&
	A list of parameters required for the current model settings, as
	defined in section \ref{subsubsec:Parameter_information_output}.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsubsection{\method{MissingParameters(self, parameter\_list=None)}}
%
\begin{methoddesc}%
	{MissingParameters(self, parameter\_list=None)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt MissingParameters} \\ \hline
\label{subsubsec:Model.MissingParameters}
Description &
Return the list of parameters still missing in the sessions parameter sets 
according to the model mode selections. By default 
(\varname{parameter\_list} is \varvalue{None}) process the model's 
\varname{\_required\_parameters} list. If available the method is called 
recursively with sublists of \varname{\_required\_parameters}.
\\
&
If the implemented model provides parameter estimate functions the 
method has to be overridden to take these dependencies into account
(see \ref{chap:Examples}).
	\\ \hline
In 	& \parameter{parameter\_list}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{parameter\_list}: &Raw list of required parameters\\
		\end{tabular}
	  } \\ \hline
Return	&
	Parameter list
	\\ \hline

Return definitions	&
	A list of parameters required for the current model settings but not
	yet set to a valid value is returned. The format is
	defined in section \ref{subsubsec:Parameter_information_output}.
	\\ \hline
\end{tabular}
\end{methoddesc}


%
%\subsubsection{\method{StochasticParameters(self, parameter\_list=None,\\
%                          correlated\_parameters=None)}}
%
\newpage
\begin{methoddesc}%
	{StochasticParameters(self, parameter\_list=None,\\
		correlated\_parameters=None)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt StochasticParameters} \\ \hline
\label{subsubsec:Model.StochasticParameters}
Description &
Return the list of parameters considered as distributed for the specific
segment according to the model mode selections and parameter settings.
By default (\varname{parameter\_list} and \varname{correlated\_parameters} 
are \varvalue{None}) process the model's 
lists. If available the method is called 
recursively with sublists of \varname{\_required\_parameters}.
\\
&
The method calls \method{eval\_correlation} to determine correlation
dependencies. Due to its generic structure the method has usually not to be
overridden for a model implementation.
	\\ \hline
In 	& \parameter{parameter\_list}, \parameter{correlated\_parameters}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{parameter\_list}: &Raw list of required parameters\\
		\parameter{correlated\_parameters}: &\\
					&Correlation information\\
		\end{tabular}
	  } \\ \hline
Return	&
	Parameter list.
	\\ \hline
Return definitions	&
	A list of correlated parameters with correlation information according
	to the current model settings, as
	defined in section \ref{subsubsec:Parameter_information_output}.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsubsection{\method{eval\_correlation}}
%
\begin{methoddesc}%
	{eval\_correlation(self, key, correlated\_parameters)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt eval\_correlation} \\ \hline
\label{subsubsec:Model.eval_correlation}
Description &
The method is called by \method{StochasticParameters} to evaluate potential 
correlation dependencies. Since it in turn makes use of the model's 
\method{StochasticParameters} method to derive the full tuple for a stochastic
parameter description it is implemented as a class method instead of 
a simple helper function.
	\\ \hline
In 	& \parameter{key}, \parameter{correlated\_parameters}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{key}: & Tuple (\varname{blockid}, \varname{fieldid})
			to identify a parameter \\
		\parameter{correlated\_parameters}: & \\
			& List of tuples providing 
			correlation information according to 
			\ref{paragraph:Correlated_parameters}.
		\end{tabular}
	  } \\ \hline
Return	& \varvalue{None} or 
	Tuple: \\
	& ((\varname{blockid}, \varname{fieldid}, \varname{distribution}, 
		\varname{local}), \varname{correlation}) 
	\\ \hline

Return definitions	& 
	If the tested parameter is correlated with a second one, return 
        a tuple of parameter identification, distribution information and
	correlation information (as defined under 
	\ref{paragraph:Correlated_parameters}).
	\\ \hline
\end{tabular}
\end{methoddesc}
	

%
%\subsubsection{\method{Name(self)}}
%
\begin{methoddesc}%
	{Name(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt Name} \\ \hline
\label{subsubsec:Model.Name}
Description &
	Return the model name.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	\\ \hline
Return	&
	\parameter{name}
	\\ \hline
Return definitions	&
	The model name as defined in \varname{self.name}.
	\\ \hline
\end{tabular}
\end{methoddesc}


%
%\subsubsection{\method{get\_required\_parameter\_list(self)}}
%
\begin{methoddesc}%
	{get\_required\_parameter\_list(self)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt get\_required\_parameter\_list} \\ \hline
\label{subsubsec:Model.get_required_parameter_list}
Description &
	Return the required parameter definition list.
	\\ \hline
In 	& -
	\\ \hline

In definitions	& -
	\\ \hline
	
Return	&
	Parameter list.
	\\ \hline

Return definitions	&
	Return the models list of required parameters 
	(\varname{self.\_required\_parameters}).
	\\ \hline
\end{tabular}
\end{methoddesc}


%
%\subsection{Helper Functions}
%--------------------------------------------------------------------------
\subsection{Helper Functions}
\label{subsec:HelperFunctions}

In addition to the Model class the \gfilename{modelbase.py} provides 
some helper functions needed for model implementation. These functions
wrap some frequently used checks or actions to keep administrative overhead 
out of the model implementation and make it more readable.


%
%\subsubsection{eval_parameter}
%
\begin{methoddesc}%
	{eval\_parameter(data, parameter)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt eval\_parameter} \\ \hline
\label{subsubsec:eval_parameter}
Description &
	The function wraps the lengthy check if a parameter 
	(specified by a sequence of keys in the  \varname{parameter} value) 
	exists in the data dictionary.
	\\ \hline
In 	& \parameter{data}, \parameter{parameter}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{data}: & Pointer to the sessions data dictionary. \\
		\parameter{parameter}: & A tuple of 
			(\varname{BlockID}, \varname{FieldID}, \varname{value}) 
			to identify a parameter and provide access to its 
			contents. (e.g. (\varvalue{'SUBST'}, 
				\varvalue{'K\_OC'}, \varvalue{'value'}),
				to access the substance $K_{OC}$ parameter
				or (\varvalue{'SESS\_DISCH'}, 
				\varvalue{'12'}, \varvalue{'r\_wwtp'})
				to access the local $R_{WWTP}$ parameter 
				for the discharge the the ID 12.
		\\
		\end{tabular}
	  } \\ \hline
Return	&
	\parameter{Value} or \varvalue{None}
	\\ \hline

Return definitions	&
	Return parameter value as read from the data (no further
	type conversion or processing is applied) if it exists, 
	else \varvalue{None}.
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsubsection{}
%
\begin{methoddesc}%
	{remove\_parameter(parameter\_list, parameter}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt remove\_parameter} \\ \hline
\label{subsubsec:remove_parameter}
Description &
	Try to remove parameter from a list. \\
	&
	The method is frequently used in the \method{MissingParameters} methods
	if a model provides estimate functions and catches the exception 
	if the parameter does not exists in the list.
	\\ \hline
In 	& \parameter{parameter\_list}, \parameter{parameter}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{parameter\_list}: & List of parameters 
			((\varname{BlockID}, \varname{FieldID}) tuples) \\
		\parameter{parameter}: & Tuple 
			(\varname{BlockID}, \varname{FieldID}) to be 
						removed from the list.  
		\end{tabular}
	  } \\ \hline
Return	&
	-
	\\ \hline

Return definitions	& -
	\\ \hline
\end{tabular}
\end{methoddesc}


%
%\subsubsection{}
%
\begin{methoddesc}%
	{eval\_local\_setting(data, local, general)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt eval\_local\_setting} \\ \hline
\label{subsubsec:eval_local_setting}
Description &
	Test if a local setting is available which overwrites the 
	general setting (e.g. consumption data).
	\\ \hline
In 	& \parameter{data}, \parameter{local}, \parameter{general}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{data}: & Pointer to the sessions data dictionary. \\
		\parameter{local}: & Tuple 
			(\varname{BlockID}, \varname{FieldID}, \varname{value})
			identifying a potential local value. \\
		\parameter{general}: & Tuple 
			(\varname{BlockID}, \varname{FieldID}, \varname{value})
			identifying the general local value.
		\end{tabular}
	  } \\ \hline
Return	&
	Tuple (\varname{value}, \varname{flag})
	\\ \hline

Return definitions	&
	The returned tuple provides the parameter to use with some further 
	information: \varname{value} is the local value 
	if available, otherwise the general one. \varname{flag} is a boolean 
	flagging if the value is local (\varvalue{True}) or general 
	(\varvalue{False}).
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsubsection{}
%
\begin{methoddesc}%
	{eval\_local\_stochastics(status, stochastics)}
\begin{tabular}{|p{0.2\textwidth}|p{0.75\textwidth}|} \hline
{\bf Name} & {\tt eval\_local\_stochastics} \\ \hline
\label{subsubsec:eval_local_stochastics}
Description &
	Test if a distributed parameter is overwritten by a local value.  \\
	&
	The function is used in 
	combination with the Parameter Object \method{\_\_init\_\_} method.
	\\ \hline
In 	& \parameter{status}, \parameter{stochastics}
	\\ \hline

In definitions	&
	 \parbox[t]{\textwidth}{
	    \begin{tabular}[t]{p{0.18\textwidth}p{0.52\textwidth}}
		\parameter{status}: & Boolean flag, the return value of 
					\method{eval\_local\_setting} \\
		\parameter{stochastics}: & Pointer to the batch of 
						Monte-Carlo shots. 
		\end{tabular}
	  } \\ \hline
Return	&
	\varvalue{None} or \parameter{stochastics}
	\\ \hline

Return definitions	&
	The function evaluates \varname{status} and returns \varvalue{None} 
	on True, \varname{stochastics} else. 
	\\ \hline
\end{tabular}
\end{methoddesc}

%
%\subsection{Examples}
%--------------------------------------------------------------------------
\chapter{Examples}
\label{chap:Examples}

\section{Model Overview} 
Based on the Model Class and its framework the GREAT-ER 3.0 Model Suite
implements the models of GREAT-ER 1.0:

\begin{itemize}
	\item Household Emission
	\item Sewer
		\begin{itemize}
			\item No Removal
			\item Percentage Removal
		\end{itemize}
	\item Discharge
		\begin{itemize}
		    \item Primary Settler: Percentage Removal and SimpleTreat
		    \item Activated Sludge: Percentage Removal and SimpleTreat
		    \item Trickling Filter: Percentage Removal
		\end{itemize}
	\item River
		\begin{itemize}
		    \item First order elimination
		    \item First order elimination with fractioning
		    \item First order elimination with combining elimination 
				rate from detailed processes
		\end{itemize}
\end{itemize}

All models are inherited from the base Model class. Further levels of
inheritance are depending on the specific models.

\subsubsection{Household emission}

The household emission model implements an approach to calculate the emission
from annual per capita consumption and the number of inhabitants at a discharge
site.

\subsubsection{Sewer}

The sewer model is split into two modes: One with no elimination (mass flux is 
simply handed over) and a second with percentage removal.
\\
 
\begin{center}
{\FigNoEntry{\includegraphics[scale=0.25]{dia/model_emission_sewer.png}}{Class Hierarchy Model (Emission and Sewer Models)}}
\end{center}

\newpage
\subsubsection{Discharge}

The discharge model module implements various complexity modes for different
types of treatment plants: The mode 1 is implemented in a generic model 
from which the specific models Primary Settler, Activated Sludge and 
Trickling Filter are inherited. For first two also a second mode (Simple
Treat) is implemented inherited from Model with a mix-in of some helper methods
needed for both.
\\

\begin{center}
{\FigNoEntry{\includegraphics[scale=0.25]{dia/model_WWTP.png}}{Class Hierarchy
Model (Discharge Models)}}
\end{center}

\newpage
\subsubsection{River}

The three river model modes have the first order elimination approach in
common. Hence this is implemented as a method of mode 1 from which the other
two mode implementation inherit and override the elimination rate calculation.
\\

\begin{center}
{\FigNoEntry{\includegraphics[scale=0.25]{dia/model_river.png}}{Class Hierarchy
Model (River Models)}}
\end{center}

In the following some model implementation are described in detail to
illustrate the use of the classes and methods described above.

\include{emission_model}

\include{river_model}

%\chapter{Enhance GREAT-ER 3.0 with a new compartment}
%\label{chap:ModelEnhancement}

%-------------------------Appendix-------------------------------------

\begin{appendix}

\renewcommand{\documentID}{gnufdl.tex version 1.2}
\include{gnufdl}
\renewcommand{\documentID}{\CVSId}

\end{appendix}

\end{document}



