% +-======-+ 
%  Copyright (c) 2003-2007 United States Government as represented by 
%  the Admistrator of the National Aeronautics and Space Administration.  
%  All Rights Reserved.
%  
%  THIS OPEN  SOURCE  AGREEMENT  ("AGREEMENT") DEFINES  THE  RIGHTS  OF USE,
%  REPRODUCTION,  DISTRIBUTION,  MODIFICATION AND REDISTRIBUTION OF CERTAIN 
%  COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE UNITED STATES GOVERNMENT AS 
%  REPRESENTED BY THE GOVERNMENT AGENCY LISTED BELOW ("GOVERNMENT AGENCY").  
%  THE UNITED STATES GOVERNMENT, AS REPRESENTED BY GOVERNMENT AGENCY, IS AN 
%  INTENDED  THIRD-PARTY  BENEFICIARY  OF  ALL  SUBSEQUENT DISTRIBUTIONS OR 
%  REDISTRIBUTIONS  OF THE  SUBJECT  SOFTWARE.  ANYONE WHO USES, REPRODUCES, 
%  DISTRIBUTES, MODIFIES  OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED 
%  HEREIN, OR ANY PART THEREOF,  IS,  BY THAT ACTION, ACCEPTING IN FULL THE 
%  RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
%  
%  Government Agency: National Aeronautics and Space Administration
%  Government Agency Original Software Designation: GSC-15354-1
%  Government Agency Original Software Title:  GEOS-5 GCM Modeling Software
%  User Registration Requested.  Please Visit http://opensource.gsfc.nasa.gov
%  Government Agency Point of Contact for Original Software:  
%  			Dale Hithon, SRA Assistant, (301) 286-2691
%  
% +-======-+ 

\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage{epsfig}
\usepackage{hangcaption}
\textheight     9in
\topmargin      0pt
\headsep        1cm
\headheight     0pt
\textwidth      6in
\oddsidemargin  0in
\evensidemargin 0in
\marginparpush  0pt
\pagestyle{myheadings}
\markboth{}{}
%-------------------------------------------------------------
\setlength{\parskip}{12pt}
\setlength{\parindent}{0pt}
\setlength{\baselineskip}{11pt}
 
%--------------------- SHORT-HAND MACROS ----------------------
\def\bv{\begin{verbatim}}
\def\ev{\end{verbatim}}
\def\be{\begin{equation}}
\def\ee{\end{equation}}
\def\bea{\begin{eqnarray}}
\def\eea{\end{eqnarray}}
\def\bi{\begin{itemize}}
\def\ei{\end{itemize}}
\def\bn{\begin{enumerate}}
\def\en{\end{enumerate}}
\def\bd{\begin{description}}
\def\ed{\end{description}}
\def\({\left (}
\def\){\right )}
\def\[{\left [}
\def\]{\right ]}
\def\<{\left  \langle}
\def\>{\right \rangle}
\def\cI{{\cal I}}
\def\diag{\mathop{\rm diag}}
\def\tr{\mathop{\rm tr}}
%-------------------------

\newcommand{\ggn}{{\em MAPL}}
\newcommand{\bdl}{{\tt ESMF\_Bundle}}
\newcommand{\fld}{{\tt ESMF\_Field}}
\newcommand{\stt}{{\tt ESMF\_State}}
\newcommand{\grd}{{\tt ESMF\_Grid}}
\newcommand{\loc}{{\tt MAPL\_LocationStream}}
\newcommand{\ssv}{{\tt SetServices}}
\newcommand{\egc}{{\tt ESMF\_GriddedComponent}}
\newcommand{\ggc}{{\tt MAPL\_GriddedComponent}}
\newcommand{\gssv}{{\tt MAPL\_GenericSetServices}}
\newcommand{\gint}{{\tt MAPL\_GenericInitialize}}
\newcommand{\gfin}{{\tt MAPL\_GenericFinalize}}
\newcommand{\ptx}{{\tt protex}}

\newcounter{genct}
\newcounter{grdct}
\newcounter{sttct}
\setcounter{genct}{1}
\setcounter{grdct}{1}
\setcounter{sttct}{1}

\title{An Introduction to  \ggn}  

\author{Max Suarez, Atanas Trayanov, Arlindo da Silva, Chris Hill, Paul Schopf}

\date{\today}

\setlength{\parskip}{12pt}

\begin{document}

\maketitle

% $Id: MAPL_Intro.tex,v 1.1 2008-10-30 15:55:35 dasilva Exp $
%=========================================================================

\section{Introduction}

This document describes \ggn, a software layer that
establishes usage standards and
software tools for building ESMF compliant components. This package
(1) facilitates the porting of existing codes to ESMF, (2) provides
tools and a straightforward recipe for building new ESMF components,
and (3) provides much greater interoperability between compliant
components than between current ESMF compliant components.

As the Earth System Modeling Framework (ESMF)
has become available, several groups have been involved in prototyping
its use in climate and weather prediction models and in data
assimilation systems.  Existing programs have been converted to use
the superstructure of the framework at MIT, NCAR, GFDL, Goddard,
NCEP and the DoD. (see {\tt http://www.esmf.ucar.edu/impacts}).
One of the
most complete attempts to use ESMF has been the development of the
GEOS-5 AGCM, a model targeted by the MAP announcement. GEOS-5 has been
built ``from the ground up'' using the latest available versions of
ESMF superstructure and infrastructure.

All of these efforts have produced much constructive feedback to the
ESMF core development team, and have helped refine the design and
improve the implementation of the framework. They have also served to
identify the most important directions for future extensions.
Comparing the various implementations leads to two seemingly
contradictory conclusions: that all implementations are different and
that much of what they do is the same.  Both conclusions were
anticipated, since ESMF is a general framework designed to meet a wide
variety of needs.  This generality is an important strength of the
ESMF design, but it also implies that there are many different ways of
using ESMF---even when performing very similar tasks. Other
observations from this early experience were that each group, within
its own implementations, repeatedly needed functions that provided
higher level functionality than that provided by the basic ESMF tools,
and that the core methods of ESMF components (Run, Initialize, and
Finalize) looked very similar in all their implementations.

The \ggn\   package arose as a response to this early
experience, particularly during the construction of GEOS-5.
It is based on the observation that much of the work done in these initial
implementations can be standardized; thus, reducing the labor of
constructing ESMF applications in the future, as well as increasing
their interoperability. In its initial implementation, \ggn\  
provides:

\begin{itemize}

\item Specific conventions and best practices for the utilization 
of ESMF in climate models

\item  A middleware layer (i.e., between the model and ESMF) that
facilitates the adoption of ESMF by climate models.

\end{itemize}

This enhancement in usability of ESMF must come at the cost of reduced
generality. To make the framework more usable for our applications, we
make assumptions and place requirements on the applications that ESMF,
with its goal of generality, could not. \ggn\   does this 
``on top of'' ESMF and as a separate layer through which the
application uses ESMF for some of its functions (although for most
things, applications will continue to use ESMF directly). We feel that
this middleware-layer approach is the right way to get the usability
and interoperability that climate model components require of the
framework, without sacrificing ESMF's generality and extensibility.


%=========================================================================
\section{Review of Relevant Aspects of ESMF}

The Earth System Modeling Framework (ESMF) (DeLuca et al, 2004) is a
software package designed to provide some of essential functions
needed by parallel, scalable earth system models in a
machine-independent way. ESMF is implemented as a collection of very
general programming classes that can be used both to construct ESMF
components (infrastructure layer) and to connect them to one another
(superstructure layer). These classes thus support modelers in
building interoperable and portable codes. This design is illustrated
by the ESMF ``sandwich'' diagram, where the user's computational code
sits between the two ESMF layers.

The simplest ESMF implementations consist of building a Gridded
Component (an ESMF superstructure class) that encapsulates the user
code, interfacing it to the framework by defining the ESMF callable
methods (Initialize, Run and Finalize, hereafter, IRF methods). This
can be done making little or no use of the ESMF Infrastructure---a
strategy that fails to capitalize on some of ESMF's greatest
strengths. Such ``encapsulation'' implementations have dominated the early
adoptions of ESMF.

More sophisticated implementations put user data in ESMF
Infrastructure objects (primarily \fld s) which can then be
manipulated by a wide array of ESMF methods to facilitate the coupling
of components with different data structures (i.e., that are on
different grids) and to insulate the user
from the architecture-specific implementation layers that are used for
inter-process or inter-processor communication, I/O, etc.

In designing ESMF, a deliberate decision was made to have the
framework provide these services in a very general way, and not to
prejudge how future models would use it or what programming models
would best suit future computer architectures. This generality is an
important strength of ESMF, but it is also an impediment to many users
that would prefer a more specific formulation for porting existing
codes or a better defined recipe for building new codes with ESMF. The
generality also impacts the interoperability of applications, since
the ESMF interfaces to the IRF methods are general purpose, and they
carry little information (other than the grid definition) about the
physical content of the data moving in and out of the gridded
component.  

The middleware layer implemented in \ggn\  
includes the following design elements:

\begin{enumerate}

\item Provide easy-to-use tools for describing the contents of a
component's import and export states, as well as adopting conventions for what
must be described. But in no way specifying what the contents must be.

\item Facilitate the coupling of components into complex applications. This
requires a means of describing the connectivity between components and
of using the description of the import and export states to couple
components.

\item Provide aids in constructing a component's IRF methods

\item Facilitate the use of \fld s and thus of the ESMF 
Infrastructure layer

\item Extend the \stt\  concept to a component's internal state, and
help it manage its persistent data.  

\end{enumerate}



Two other ESMF concepts are worth highlighting: the hierarchical
organization of gridded components and the coupler component.
ESMF gridded components can be, as described above, simple containers
for user code. But ESMF also allows gridded components to contain
other gridded components. These {\em composite
components} can themselves contain user code or can simply serve
as a way of grouping closely related components. The notion of
composite components allows a straightforward way of organizing
applications as a hierarchy of components. ESMF does not
require a hierarchical organization, but it
is the most natural way of connecting ESMF components. 
ESMF also defines the notion of
Coupler Components. These are similar to gridded components, but are
not intended for user code; rather, they house the transformations
necessary to convert between exports of one component and imports of
another. \ggn\  adopts the hierarchical organization as its architecture
for making complex applications and uses both composite gridded components
 and ESMF coupler components to establish connections between 
members of the hierarchy.


%=========================================================================
\section{Overview of \ggn}

We organize the \ggn\   description around how it deals with the
relevant design elements discussed, even though there is not a one-to-one
correspondence between these elements and the actual \ggn\  code.

The first of these we refer to as \ggn\_Core. This includes those elements
useful in building a single \ggn\  gridded component. In particular,
it includes the means of describing a component's Import and Exports states.
Having a component built in this ways, with well described states, 
allows us to use the second element, \ggn\_Connect to organize them
into a hierarchy. The distinction between these two elements, which in
the \ggn\  code are mostly within the \ggn\_Generic module, is important.
One may use \ggn\_Core alone as a means of facilitating the introduction
of ESMF, with no intention of ever coupling the component to a 
\ggn\  hierarchy. A component so contructed is a perfectly good
ESMF component, and other than having to access the \ggn\  library
to build and execute, it is not special in any way. The code in 
an application instanciating  it would not need to know it was built 
with \ggn\  machinery.

A third element is \ggn\_History, which is an ESMF gridded component that
sits inside MAPL and can be instanciated to provide data writing services
for a \ggn\  hierarchy. \ggn\_Utils is a set of support utilities 
for tasks commonly needed in global models. \ggn\  itself uses some of
these, but, like \ggn\_History,  \ggn\  components or application
need not use them.

Finally, \ggn\_CFIO is a partial I/O layer for ESMF components. 
It relies internally on \ggn , and so must be built with it, but it
can be used even if one is not using the rest of \ggn . \ggn\_History
is built on top of \ggn\_CFIO.

\subsection{Building a \ggn\  Gridded Component: \ggn\_Core}


\ggn 's initial intention, and still its core function, is
to provide assistance in writing ESMF Gridded components. It does this
in the following ways:

\begin{itemize} 

\item It makes it easier to write the component's IRF methods. In fact
in some cases they need not be written at all.

\item It adds an Internal ESMF\_State to the component, supplementing the 
Import and Export states required by ESMF.

\item It provides a means of describing the contents of the three states
   so that \ggn\  can help manage them.

\item It adopts groundrules for the behavior of a component 
and its treatment of the three states.

\item It defines a standard recipe for writing 
 \ggn -based ESMF Gridded Components.

\end{itemize} 


{\em Wrting the IRF method:} 
After writing a few gridded components, one realizes that, except for
the actual insertion of the user code, most SetServices and IRF
methods are very similar, and that it would be economical to
generalize this ``boilerplate'' code. \ggn\   provides
three ways of doing this.

The first way is to use the generic versions of 
\ssv\  and of the three IRF methods provided by \ggn\  as the 
component's methods. When \gssv\  is
invoked, it registers the three Generic IRF methods. If not overridden,
these become the component's actual methods.

A second way of using \ggn\  is to simply call the generic
versions of the methods from the component-specific versions, allowing
them to perform the boilerplate functions. 

A third way is to simply use the source code
of the generic versions as templates for the specific versions.
Taking this approach is dangerous and not allowed for \ggn-compliant components. 

So what do the Generic IRF methods do? This will be described in detail
in subsequent sections, but simply stated, they manage the
IM/EX States and a third \stt that we will be discussing
below, the {\tt Generic\_Internal} state. We will refer to these three
state as the IM/EX/IN states. Note that they are all ordinary \stt s.
From the description of the three states provided in the data
services, \ggn\  is able to create, allocate, initialize,
and destroy all items in these states; it can also checkpoint and
restart the internal and import states. The IRF methods also implement the
connectivity of children components, creating the appropriate
couplers, registering their services, and executing their IRF methods.


{\em The new Internal State:}
In the spirit of having as unintrusive a design as possible, ESMF says
nothing about a component's internal state. But, since
it is desirable that gridded components themselves be as
object-oriented as possible, the framework has to allow them to be fully
instanciatable. This requires that whatever the component defines as
its internal state be attached to the \egc\ 
instance. ESMF provides such a mechanism---effectively a hook on which
a component can hang the current instance of its internal state.

\ggn\   maintains this approach, but in addition allows the
component to place some parts of its true internal state in an \stt
analogous to the IM/EX states. This new state
does not appear explicitly in the argument
list of IRF methods, as is the case with
the IM/EX states; instead it is attached to the \egc\  and, in
principle, is accessible only through \ggn.

All of the mechanisms for registering and manipulating data that are
already available in \ggn\  for the IM/EX States, are
extended to the new Internal state. The default accessibility rules
for this state are that its items can be written only by the component
and can be read only by its parent. All data registered in this state
by the component's \ssv\  are, of course, automatically
allocated, checkpointed, and restarted by the \ggn\   Initialize and Finalize
methods.



{\em Description of State contents:} 
As discussed above, the simplest ESFM gridded component consists of the
IRF methods encapsulating the user's computational code. These
methods are private to the component, but are callable by the
framework; in fact, they can only be called by the framework. This
is accomplished by having in each component a public method
(\ssv) that tells the framework what functions it can perform
(initialize the component, run it, etc.). The framework can then
invoke these functional services when they are required.


The interface to these services is prescribed by ESMF and includes
Import and Export (IM/EX) States, through which all data exchange
between the components occurs. These states can contain only ESMF
objects (primarily \fld s and other \stt s), but ESMF says
nothing about how they are to be used.  \ggn\   assumes that
IM/EX states consist only of Fields and other States. It also adopts
the convention that, by default, items in its Export state are not
modified by other components and that it cannot modify items in its
Import state.

A major innovation in \ggn\   is a means of describing the
contents of the IM/EX states. \ggn\   takes the view that a
component, in addition to giving the framework access to its
functional services, should also tell the framework about its data
services, i.e., what it needs from others and what it can provide.
\ggn\   extends the use of \ssv\   to accomplish this. The
\ssv\   method of a \ggn-based gridded component will
contain {\em spec calls} like the following:

\begin{verbatim}
     call MAPL_AddImportSpec(STATE,       		&
          SHORT_NAME         = 'PLE',                   &
          LONG_NAME          = 'air_pressure',          &
          UNITS              = 'Pa',                    &
          DIMS               = MAPL_DimsHorzVert,      	&
          VLOCATION          = MAPL_VLocationEdge, 	&
                                             RC=STATUS  )
\end{verbatim}

Note That some of the attributes being set for this Field, such as
units are likely reflect assumptions made by the
component and are usually static; others may be set at run time, say from
a configuration file.

The information provided in setting data
services is used by \ggn, to allocate and initialize the
states, to couple to other components, and to help build the
component's IRF methods, as we will see below.


{\em Rules for Components:}

The first thing to clarify is what we mean by a \ggn -based \egc.
The following general rules apply to \ggn -compliant components:
%
\begin{quote}
\begin{itemize}
\item[{\bf Rule \thegenct}] The component must be a fully-compliant \egc.
  This implies that its only public object is \ssv\  and it registers
  IRF methods with ESMF.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Associated with each instance of a \ggn-compliant
  \egc\  there is an \grd that \ggn\  will use to allocate data.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Every \egc  has a configuration. A \ggn\  gridded
 component will expect it to be open when \ssv  is called.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Components can be run sequentially or
  concurrently; however, their Run methods must return control at {\tt
  RUN\_DT} intervals.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}]  A \ggn -compliant \egc\  can be simple or composite.
\addtocounter{genct}{1}

\item[{\bf Rule \thegenct}] The component must obey all \ggn\   rules 
  pertaining to its grid, as defined below.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] The component must obey all \ggn\  access rules
 to the IM/EX/IN  states, as defined below.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] The {\tt MAPL\_GenericSetServices}, 
  {\tt MAPL\_GenericInitialize}, and {\tt MAPL\_GenericFinalize}
  methods must be invoked once, and only once, for each instance of
  the gridded component.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Component instances must have unique names 
   of the form: ``first[:last]''. Neither first nor last name can have a
  colon. Example: {\tt Ens01:TURBULENCE}.
\addtocounter{genct}{1}
%
\end{itemize}
\end{quote}

The following {\tt Fortran 95} module
shows the simplest \ggn\  component. This is a fully-compliant \egc.
It has a public \ssv\  taken from \ggn, and this is its only
public object. Of course, it does nothing; but it can be run as a null
component anywhere an \egc\  can be run. Since it uses the generic IRF
methods, it has a single stage of each. The rules about grids and
states are not too relevant, but it has a a natural grid---the \grd
we assume was given to it when the instance of the \egc\  is created.
It has IM/EX/IN states, which are silently created by the implicit
generic methods; but all three state are empty.

\subsection{\em Example 1: Using the Generic Component}

\ggn  has built-in \egc s. The most fundaments of these is the 
{\em MAPL\_Generic} component, whose \ssv  and IRF methods we normally
use in building other components. It is possible, however, to instantiate
{\em MAPL\_Generic} itself. Currently such an instance is useful only
as a null leaf component, which does nothing. Nevertheless, it is a
perfectly valid \egc. The example is a main program that runs     
{\em MAPL\_Generic} for a year. It also illustrates the basic steps
that an ESMF main program (or Cap) contains. As one can see, even
this basic program is fairly complex. We will see later how 
\ggn  can also help in reducing this complexity. 

\footnotesize

\begin{verbatim}
  Program Example1
   use ESMF_Mod
   use MAPL_Mod, only: SetServices => MAPL_GenericSetServices
   type(ESMF_GridComp)    :: GC
   type(ESMF_State)       :: Import, Export
   type(ESMF_Clock)       :: Clock
   type(ESMF_Time)        :: StartTime
   type(ESMF_Time)        :: StopTime
   type(ESMF_TimeInterval):: DT
   integer                :: RC
   rc = ESMF_SUCCESS

! Initialize ESMF
!----------------
   call ESMF_Initialize (defaultCalendar=ESMF_CAL_GREGORIAN, rc=rc)
   if(RC==ESMF_FAILURE) call exit(RC)

! Initial and final time of run and time step
!--------------------------------------------
   call ESMF_TimeSet( StartTime, YY = 2007, rc=RC   )
   if(RC==ESMF_FAILURE) call exit(RC)
   call ESMF_TimeSet( StopTime, YY = 2008, rc=RC    )
   if(RC==ESMF_FAILURE) call exit(RC)
   call ESMF_TimeIntervalSet( DT, S=1800,    rc=RC  )
   if(RC==ESMF_FAILURE) call exit(RC)

! Create the Clock
!-----------------
   clock = ESMF_ClockCreate( 'MyClock', DT, StartTime, StopTime, rc=RC )
   if(RC==ESMF_FAILURE) call exit(RC)

! Create the gridded component
!-----------------------------
   GC = ESMF_GridCompCreate(name='ExampleGC', rc=rc)
   if(RC==ESMF_FAILURE) call exit(RC)

! SetServices
!------------
   call ESMF_GridCompSetServices ( GC, SetServices,            RC)
   if(RC==ESMF_FAILURE) call exit(RC)

! Initialize
!-----------
   call ESMF_GridCompInitialize ( GC, Import, Export, Clock, RC)
   if(RC==ESMF_FAILURE) call exit(RC)

   do while (.not. ESMF_ClockIsDone(Clock))
! Run
!----
      call ESMF_GridCompRun       ( GC, Import, Export, Clock, RC)
      if(RC==ESMF_FAILURE) call exit(RC)

! Tick the Clock
!---------------
     call ESMF_ClockAdvance(Clock, rc=RC)
     if(RC==ESMF_FAILURE) call exit(RC)
   enddo

! Finalize
!---------
   call ESMF_GridCompFinalize    ( GC, Import, Export, Clock, RC)
   if(RC==ESMF_FAILURE) call exit(RC)

! Finalize ESMF
!--------------
   call ESMF_Finalize (rc=rc)
   if(RC==ESMF_FAILURE) call exit(RC)

! All Done
!---------
   call exit(RC)
  end Program Example1
\end{verbatim}
\normalsize



\centerline{\rule{2in}{1pt}}


\subsection{\em Example 2: HelloWorldMod}

The second example illustrates a more typical use of \ggn 
to help write a gridded component. 

\footnotesize
\begin{verbatim}
  module HelloWorldMod

! We always have this preamble
!-----------------------------
       use ESMF_Mod
       use MAPL_Mod
       implicit none

! Make sure only SetServices id public.
! This is a hallmark of ESMF gridded components.
!-----------------------------------------------
       private
       public SetServices
    contains

! We write a simple SetServices to register our custom
! run method with MAPL. We rely on MAPL_GenericSetServices
! to do the heavu work. Normally, we would also register
! data and connectivities at this point, but in this example
! we have none.
!-----------------------------------------------------------
       subroutine SetServices(GC,RC)
         type(ESMF_GridComp), intent(INOUT) :: GC
         integer, optional,    intent( OUT) :: RC
         call MAPL_GridCompSetEntryPoint ( GC, ESMF_SETRUN, Run, RC )
         call MAPL_GenericSetServices    ( GC, RC )
       end subroutine SetServices

! The Run method
!---------------
       subroutine Run (GC, IMPORT, EXPORT, CLOCK, RC )
         type(ESMF_GridComp), intent(INOUT)  :: GC
         type(ESMF_State),     intent(INOUT) :: IMPORT
         type(ESMF_State),     intent(INOUT) :: EXPORT
         type(ESMF_Clock),     intent(INOUT) :: CLOCK
         integer, optional,    intent( OUT)  :: RC
         type(ESMF_Config)                   :: CF
         character(len=ESMF_MAXSTR)          :: COMP_NAME
         real                                :: DT
         call ESMF_GridCompGet        ( GC, NAME=COMP_NAME, config=CF)
         call ESMF_ConfigGetAttribute( CF, DT, Label='RUN_DT:')
         print *, 'Hello World. I am ', trim(COMP_NAME), &
                  ', and my timestep is ',DT
         RC = ESMF_SUCCESS
       end subroutine Run
  end module HelloWorldMod
\end{verbatim}
\normalsize

Crucial to the successful use of this and other examples is the
Configuration (see section \ref{sec:Configuration}).  MAPL 
requires certain configuration variables to be set in order 
to properly execute any application.

\centerline{\rule{2in}{1pt}}

This example needs a custom a Run method.
Since this method can only be registered in a \ssv 
that is in the module, we must also write an explicit \ssv.
Notice that the registration of the Run method is with \ggn ,
not directly with ESMF. 
The component does not explicitly register Initialize and Finalize
methods, so the generic ones will be used.
Notice also that 
\gssv\  is called at the end, after all registration with \ggn\ 
is completed.

The Run method is simple,
but it does illustrate that every instance of an \egc\  has a name,
and the IRF methods can access it to know which instance they are
working on. Notice also that we have assumed that there is an 
open configuration in the gridded component, from which we are 
getting the time step. This is also typical of \ggn  components.
\ggn  treats the configuration in the component object like an
environment from which it can always query for predefined
metadata.

The situation illustrated by this example is quite common. Most simple
components will follow this template: defining a Run method, having a
\ssv\  that registers it and calls \gssv, and
defaulting the Initialize and Finalize methods.

{\em Additional Rules for Grids and States}

Most \ggc  gridded components will receive a fully populated grid from
its parent. Some, however, may need be written to receive an empty
grid that they popolate themselves or to replace the grid they receive
with one of their own creation.

Its it current implementation, \ggn   severely restricts the nature
of \grd s reflecting in part the state of ESMF's own development.
We will discuss this at length later.

The following are some of the grid related rules:
%
\begin{quote}
\begin{itemize}
\item[{\bf Rule \thegenct}] A component's grid must be fully formed 
  when {\tt MAPL\_GenericInitialize} is invoked.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Once {\tt MAPL\_GenericInitialize} is invoked, 
  the grid may not be changed and must remain as the instance's \grd.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] An instance's grid can be either an \grd or a
  \loc that has an associated \grd. Thus there is always an \grd
  associated with the each instance of a \ggn-compliant \egc.
\addtocounter{genct}{1}
\end{itemize}
\end{quote}

A component can operate on
data on various grids. These can be \grd s or grids defined with the
user's own conventions and ESMF Infrasructure can be used to
manipulate this data internally. But to the outside world and to \ggn\ 
a \ggn-compliant component should ``look'' as though it has only one
grid.

The following are the state related rules:
%
\begin{quote}
\begin{itemize}
\item[{\bf Rule \thegenct}] Items in  the IM/EX/IN states must be either
  \stt s, \bdl s, or  \fld s.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] A \ggn\  places items in the IM/EX/IN states only 
  through appropriate ``spec'' calls from its \ssv.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] All items the component places in the IM/EX/IN states
  must be defined on its grid. If the grid is a \loc, these items
  can be either at locations or on the associated \grd. Only in this sense
  can a component appear to expose two grids. 
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] In addition to the ESMF internal state that \ggn\ 
  places in the component, a component can have any number of privately 
  defined ``internal'' states. We will refer to these as the component's 
  {\em private} states.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] The private states, together with IN, fully define the
  component's instanciatable state. Private states must, therefore, be
  attached to the \egc.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Private states must be ``named'' states when attached
  to the \egc. \ggn\  used the unnamed internal state in the component for its
  own purposes.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Items in the IM/EX/IN states may have \ggn\  and
  user attributes. 
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Items in the Internal state can be given a
  FRIENDLY\_TO \ggn\  attribute that consists of a list of other
  component's names. \ggn  then places these items in the component's
  Export state, and it is an error to add another item with the same name
  to the Export.  
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Items in the IM state are ``read-only'' to the
  component, unless the component's name appears in the item's FRIENDLY\_TO
  attribute.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Items in the EX state can be assumed to be
  ``read-only'' to  other components, unless a non-empty FRIENDLY\_TO
   is present.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Components can only create or modify the FRIENDLY\_TO
  attribute of items in its Import state.
\addtocounter{genct}{1}
%
\item[{\bf Rule \thegenct}] Values of all \ggn\  attributes can be set only
  in \ssv.
\addtocounter{genct}{1}
%
\end{itemize}
\end{quote}

Note that the restriction on items being on the component;s grid applies only
to the items explicitly placed in the states by the component; \ggn\  itself 
may place other items in these states that are not ``visible'' to
the component. It is in this sense that the component
``looks'' as though it has a single grid, even when its children use 
different grids.


%=========================================================================


{\em The recipe for writing a \ggn\ :}

Writing an \egc\  consists of writing a \ssv and at least one 
phse of each of the registered IRF methods. \ggn  provides
a recipe for each of these tasks. We will focus first on the
writing of a leaf component and defer the discussion of how to
extend the recipe to composite components and to putting together
hierarchies to the \ggn \_Connect section. 

\subsection{Writing a \ssv}


Every non-trivial \ggn\  has a \ssv\  from which \gssv\  is called, 
as illustrated in Example 2. In this section we provide a complete
recipe for writing \ssv\  and explain exactly what \gssv\  does.

The minimum we must do in \ssv\  is 
registering any private IRF methods we are writing (Run in Example 2) and then
calling \gssv. Everything else is optional. The following is a complete list
in the order in which they would normally appear:

\begin{enumerate}
\item Get instance name and set-up traceback handle  (\ggn \_Util)
\begin{quote} 
{\em This is only for using the optional error handling.}
\end{quote}
%
\item If it is using a private internal state, allocate it and put it
  in the gridded component with a unique name.
%
\item Register any custom IRF methods with \ggn\ . \ggn\  will register
them with ESMF.
\begin{quote}
{\em This step is present in practically all components.}
\end{quote}
%
\item Set Data Services for the GC
\begin{quote} 
 {\em Data services are the heart of \ggn\  and practically all 
 components will have to do some state description. An exception would be
 a composite component that serves only as a container for its
 children. We will explain the setting of data services in detail on
 the following sections. }  
\end{quote}
%
\item Call \gssv.
\begin{quote} 
{\em This is required. We discuss what it does in the next paragraph.}
\end{quote}
%
\item Set the Profiling timers (\ggn \_Util)
\begin{quote} {\em This, of course, is optional.}  \end{quote}
\end{enumerate}

\subsubsection{What \gssv\  Does}

 As we showed in Example 1, \gssv, can be used as a component's \ssv,
 but this is not very useful. Its usual use is as a set-up routine 
 for \ggn\  called as one of the last things from the component's 
 own \ssv\ (step 5 above).

 {\tt MAPL\_GenericSetServices} performs the following tasks:
%
\begin{itemize}
%
\item
  If the \ggn  object does not exists in the component, it
  allocates it and places it in the component.
  Usually the object already exists at this point.
%
\item
  Sets the any of the \egc's IRF methods that have not been
  registered to the generic versions.
%
\item
  Deals with the children. This is discussed in \ggn \_Connect.
\end{itemize}

Most of this is straightforward, but a few points merit further
discussion, especially the setting of data services and the 
treatment of the children.

\subsubsection{Data Services}

A crucial aspect of writing a \ggn component is describing the three
states (Import/Export/Internal --{\tt IM/EX/IN}). These are all \stt s.
The {\tt IM/EX} states
are those passed in the calls to the IRF methods. The {\tt IN}
state is attached to the \ggn\  object by \ggn. In \ssv  we must describe all
items in all three states. This will allow \ggn\  to create,
initialze, and otherwise manipulate these data.

\ggn  assumes that items in these states are either \fld s  or \bdl s.
Each item is described by a call to {\tt MAPL\_AddXXXSpec}, where
'{\tt XXX}' stands for either {\tt Import, Export} or {\tt
  Internal}. These calls do not modify these states or create the
items; they merely update tables of item {\em specifications} for the
three states. The interface is as follows:

\begin{verbatim}
  subroutine MAPL_AddInternalSpec(MAPL ,                   &
                                       SHORT_NAME,         &
                                       LONG_NAME,          &
                                       UNITS,              &
                                       DIMS,               &
                                       VLOCATION,          &
                                       DATATYPE,           &
                                       REFRESH_INTERVAL,   &
                                       AVERAGING_INTERVAL, &
                                       DEFAULT,            &
                                       HALOWIDTH,          &
                                       PRECISION,          &
                                       FRIENDLYTO,         &
                                                       RC  )


    type (MAPL_MetaComp)            , intent(INOUT)   :: MAPL
    character (len=*)               , intent(IN)      :: SHORT_NAME
    character (len=*)  , optional   , intent(IN)      :: LONG_NAME
    character (len=*)  , optional   , intent(IN)      :: UNITS		    
    integer            , optional   , intent(IN)      :: DIMS		    
    integer            , optional   , intent(IN)      :: DATATYPE
    integer            , optional   , intent(IN)      :: VLOCATION	    
    integer            , optional   , intent(IN)      :: REFRESH_INTERVAL   
    integer            , optional   , intent(IN)      :: AVERAGING_INTERVAL
    integer            , optional   , intent(IN)      :: PRECISION
    real               , optional   , intent(IN)      :: DEFAULT
    character (len=*)  , optional   , intent(IN)      :: HALOWIDTH
    character (len=*)  , optional   , intent(IN)      :: FRIENDLYTO
    integer            , optional   , intent(OUT)     :: RC         
\end{verbatim}
 
Only the \ggn  object {\tt MAPL} and the {\tt SHORT\_NAME} are required. The
latter is the handle used to access the variable; it is also the name
used for the variable by \ggn\  in checkpoint files. The remaining,
optional argumsnts are as follows:

\begin{quote}
\makebox[2in][l]{\bf \sc \small LONG\_NAME}
                   \parbox[t]{3.5in}{A longer descriptive name; we try
       to use the CF standard name. Default: (empty string)}

\makebox[2in][l]{\bf \sc \small UNITS		    }
         \parbox[t]{3.5in}{ Default:  (empty string) }

\makebox[2in][l]{\bf \sc \small DIMS		    }
         \parbox[t]{3.5in}{This describes the structure of the
  arrays. It can take on any of the following integer values:
\begin{description}
\item{\tt MAPL\_DimsUnknown}          
\item{\tt MAPL\_DimsHorzOnly}    1- or 2-D arrays in the horizontal
\item{\tt MAPL\_DimsVertOnly}    1-D arrays in the vertical
\item{\tt MAPL\_DimsHorzVert}    2- or 3-D arrays with one or two
    horizontal dimensions and a vertical dimension. Because of
    temporary ESMF constraints, the vertical dimension is assumed
    to be the last. This constraint will be removed later. 
\item{\tt MAPL\_DimsTileOnly}    1-D array of ``tile'' or location
    stream variables.
\item{\tt MAPL\_DimsTileTile}    2-D array of tile by subtile variabled.
\item Default: {none}
\end{description}
Eventhough DIMD is optional, it make little sense not to specify it.
}

\makebox[2in][l]{\bf \sc \small DATATYPE	}
  \parbox[t]{3.5in}{This is the type of item. It can be
    any of the following integer values:	    
\begin{description}
\item{\tt MAPL\_FieldItem}          
\item{\tt MAPL\_BundleItem}
\item       Default: {\tt MAPL\_FieldItem}
\end{description}
}

\makebox[2in][l]{\bf \sc \small VLOCATION	    }
         \parbox[t]{3.5in}{Location of the variable in a vertically
 staggered grid. Edge variables will be dimensioned starting at 0.
 It can take on the following integer values:
\begin{description}
\item{\tt MAPL\_VLocationNone}         
\item{\tt MAPL\_VLocationEdge}         
\item{\tt MAPL\_VLocationCenter}       
\item Default: {\tt MAPL\_VLocationNone}
\end{description}
}

\makebox[2in][l]{\bf \sc \small REFRESH\_INTERVAL  }
         \parbox[t]{3.5in}{For IMPORT variables only. Data will be
    valid  only on this interval, given in integer seconds. Currently the time origin is the
     the time when this call is made; in future this should be defined
     in the argument list. Default: 0}

\makebox[2in][l]{\bf \sc \small AVERAGING\_INTERVAL}
         \parbox[t]{3.5in}{For IMPORT variables only. Data will be
     an average over this interval immediately preceeding the valid time. 
     This is also in integer seconds. If zero, the value will be
     instantaneous. What is meant by ``preceeding'' is a bit tricky,
    since it may or may not include the update for the current
    timestep, depending on whether the source component(s) were
    already called or not. This is discussed further in the 
    checkpointing and coupling sections. Default: 0}

\makebox[2in][l]{\bf \sc \small DEFAULT	    }
         \parbox[t]{3.5in}{Value to which variable is set when allocated. Default: 0.0 }

\makebox[2in][l]{\bf \sc \small HALOWIDTH	    }
         \parbox[t]{3.5in}{The width of the halo region. Currently it is the same
         on all dimensions. Note that ``haloing'' is
         currently defined only for variables with two horizontal 
         dimensions.  Default:'0' }

\makebox[2in][l]{\bf \sc \small FRIENDLYTO        }
         \parbox[t]{3.5in}{For INTERNAL variables
         only. A colon separated list of component types
         that the variable is ``Friendly'' to.  Default: (blank string) }
\end{quote}
%=========================================================================

\subsection{Writing an Initialize Method}

Every \ggn\  component must make a call to \gint. This can be done by
letting the method default or by writing a component-specific
Initialize method that invoked \gint.  In this section we provide a
complete recipe for writing an Initialize and explain exactly what
\gint\  does.

The main reason to write a component-specific Initalize is to handle a
private internal state. If all internal state variables can be put in
the \ggn\  {\tt INTERNAL} and checkpointed, using \gint\  should
suffice, at least for a simple component. A composite component may
have other considerations; these will be discussed in later
sections.

\begin{enumerate}
\item Get the name from the \egc\  and set-up traceback handle (\ggn \_Utils)
\begin{quote}
{\em This is only for using the optional error handling.}
\end{quote}

\item Get the \ggn\  object from the \egc
\begin{quote} 
{\em It will almost certainly be convenient to query
    this object during Initialization.}
\end{quote}

\item If you are doing profiling turn on timer  (\ggn \_Utils)


\item If you will use the configuration, get it from the \egc
\begin{quote} {\em The configuration is to a component what the
    environment is to a UNIX process. We use it to keep all
    parameters, and so it is likely to be needed in Initalize.}
\end{quote}

\item Get the component's private internal state from the \egc
\begin{quote} {\em If you are writing your own Initialize you will
    almost certainly be using a private internal state.}
\end{quote}


\item If you are changing the grid, it has to be done before invoking
  \gint.
\begin{quote} {\em Remember, by default the component's natural grid
  will be the one it was given at creation. If an {\tt INTERNAL}
  and/or an {\tt IMPORT} state is being restarted (as described in the
  next section), the grids on those restarts will overide whatever is
  present when \gint\  is called in the next step. So it only makes
  sense to change the grid if you are {\em not} doing restarts in
  \gint. After returning from \gint, the natural grid cannot be changed.}
    \end{quote}

\item Invoke \gint
\begin{quote} {\em This will do the automatic state initializations as
  described below. In the case of a composite component, it will also
  initialize the children.}
    \end{quote}

\item If you have put items that need to be explicitly initialized in
  the \ggn\  {\tt INTERNAL} state, get it from the \ggn\  object
\begin{quote} {\em Items in the  \ggn\  {\tt INTERNAL} state that were
  checkpointed will be restored by \gint; other items will be set to
  their {\tt DEFAULT} value. We need access to {\tt INTERNAL} only if
  we wish to overide these in Initialize. An example of this would be
  setting static arrays, like map factors, Coriolis, etc.}
    \end{quote}

\item Query the \ggn\  object for information you need to do initialization
\begin{quote} {\em You probably need to know what the world looks
    like, so get {\tt LATS} and {\tt LONS}.} \end{quote}

\item Query the configuration for parameters you need to do initialization

\item Get pointers from the \ggn\  {\tt INTERNAL} and/or the private internal states. 
\begin{quote} {\em These are the quantities you need to initialize.} \end{quote}

\item Do the Initialization
\begin{quote} {\em For {\tt INTERNAL} items, you are overriding 
    \ggn 's initialization, which was either from a restart or a default; for a
    private state you are on your own.} \end{quote}

\item If you are profiling, turn off timer
\begin{quote} {\em } \end{quote}

\end{enumerate}

\subsection{What \gint\  Does}

\gint\  does most of the instance-specific initializations of
the \ggn\  objects. It also creates, an possibly allocates and
initializes, items in the IM/EX/IN states. \gint\  also makes the
final decision on what will be the natural grid. And, as is the
case for all generic IRF methods, it calls the children's Initialize.
The following list discusses these tasks in more detail:


\subsubsection{Writing a Finalize Method}

Finalize parallels the Initialize. It is usually only needed if there is a 
private internal state.

\subsubsection{What \gfin\  Does}

\gfin\  does most of the instance-specific finalizations of
the \ggn\  objects. It checkpoints the Import and Export states if
a checkpoint file has been provided. 
It also destroys, an possibly deallocates items in the IM/IN states.
 \gint\  also makes the
It calls the children's Finalize.

\section{Building complex applications: \ggn\_Connect}

\ggn\   adopts ESMF's natural hierarchical topology for
component connectivity, following the model illustrated in Figure 3. In
a typical application, the leaf components at the bottom of he figure
contain the bulk of the computational code. These are things like
physical parameterizations or dynamical cores, and they are grouped in
composite components (their {\em parents}), where the physical coupling
is performed. Each parent's constituent components (its {\em children})
can be connected to each other by ESMF couplers. It is in these
couplers that the more automatable coupling functions, such as grid
transformation, accumulation, etc., are performed.

Note that in this hierarchical scheme all coupling, whether physical
or automatable, occurs between {\em siblings}. This simplifies the
placement of couplers, which is important to us because we want this
to be done automatically by \ggn, but it does require some
means of making connections between ``cousins.'' This is done by
adopting some rules that define the parent-child relationship. Since a
parent component's ``owns'' its children components and their IM/EX
states (it declares them), it has access to them. In \ggn, we
take advantage of this by having the parent explicitly declare what
connections it wants between its children's import and export
states. Once again, this is done in \ssv. The following call,
which is made by the parent of \egc s called 
{\em SURFACE} and {\em MOIST}, would let \ggn\   know that it needs
certain connectivity services between these children; \ggn\  
will provide these by automatically generating the appropriate
couplers, extracting some of the needed information from the data
services provided by the children.

\begin{verbatim}
	call MAPL_AddConnectivity ( GC,    			  &
                SRC_NAME = ('PCU', 'PLS', 'SNO' /),   		  &
                DST_NAME = (/'CU_prec ', 'LS_prec ', 'SnowFall'/),&
                SRC_ID   = 'SURFACE',          			  &
                DST_ID   = 'MOIST',         			  &
                RC       = STATUS  )
\end{verbatim}

After all connections between the children are processed, their import
states may still contain some unsatisfied items (such as those that
would be provided by cousins). \ggn\   adds these to the
parent's Import state. This occurs recursively up the hierarchy
until, in a well-coupled application, all imports are satisfied.  In
order to have the cousin's export available to the parents, \ggn
places all of the children's exports in the parent's Export
state. This also continues recursively up the hierarchy.

\subsection{What \gssv\  Does with the Children}



\begin{itemize}
\item
   Allocates an \egc\  and an IMPORT and EXPORT state for each child
\item
   Creates each child's \egc\  using the inherited grid and
   configuration. The Ith child is named {\tt GCNames(I)}.
\item
   Creates each child's Import and Export states. These are named
   {\tt GCNames(I)//"\_IMPORT"} and {\tt GCNames(I)//"\_EXPORT"}
\item
   Invokes each child's set services. These are chosen from the five possible
   externals specified, depending on the value of {\tt SSptr(I)}. By convention,
   if {\tt SSptr} is not present, there can be at most as many children as
   optional externals, and these are associated in the order they appear in
   {\tt GCNames} and the argument list.
\item
   ``Wires'' the children. This resolve all child imports that are satisfied
   by siblings. All such connections must have been added explicitly
   in \ssv\  (step 4 above).
\item
   Propoagates each child's export state to the component's export state.
\item
   Propagated the childrens's unresolved imports to the component's import state. 
\end{itemize}

\subsection{Rules for the Application}


\begin{quote}
\begin{itemize}
\item[{\bf Rule \thegenct}] Every \ggn  application will have one and only
  one {\em Root} component, which will be an ancestor of every
  component except the {\em History} component.
\addtocounter{genct}{1}

\item[{\bf Rule \thegenct}] The {\em Cap} component is the
  main program; it has no parent and exactly two children: {\em Root}
  and {\em History}. The application component creates and
  initializes the configuration.
\addtocounter{genct}{1}
\end{itemize}
\end{quote}


\subsection{The Configuration}  \label{sec:Configuration}

\ggn\  requires that the application's configuration be propagated down
from parents to children, and that it be present in the component as
soon as the component is created. It effectively treats the configuration as
though it was a UNIX environment available to all components in an
application.

The configuration may be obtained from the \egc\  and
queried using the standard ESMF interface, as shown in the run method
of Example 2.
It can also be queried through the \ggn\  object by calling {\tt  MAPL\_GetResource} , and
this is the prefered way of doing it. When the configuration is
queried this way, \ggn\  first tries to match a label that has been made
instance-specific by prepending the instance's full name and an underscore
to the specified label; in Example 2, \ggn\  would first look for {\tt
  trim(COMP\_NAME)//'\_DT:'}. If this is not found, it would then look for
a type-specific label by prepending only the last name, if the
instance has one. If this fails, it would look for the
unqualified label, {\tt DT:}; finally, if this also failed, it would
set it to the default value, which in the example is the application's
time step, {\tt RUN\_DT}.

An example configuration file ({\tt CAP.rc}) for Example 2 is:

\footnotesize
\begin{verbatim}
NX: 2
NY: 2
IM: 72
JM: 46
LM: 72

ROOT_RC_FILE: HelloWorld.rc

BEG_YY: 1991
BEG_MM: 03
BEG_DD: 01
BEG_H: 0

END_YY: 1991
END_MM: 03
END_DD: 02
END_H: 0

RUN_DT:   1800

\end{verbatim}
\normalsize

This would perform a one day simulation with 30 minute time steps
on a $4^{\circ} \times 5^{\circ}$ grid, using a $2 \times 2$
decomposition element layout.

An example {\tt HelloWorld.rc} configuration file is simply:

\footnotesize
\begin{verbatim}
RUN_DT:   1800
\end{verbatim}
\normalsize

%=========================================================================
\section{Doing Diagnostics: \ggn\_History}

\input{TeX/HistoryIntro}

%=========================================================================

\section{Doing I/O: \ggn\_CFIO}


      {\tt MAPL\_CFIO}  interfaces CFIO to the ESMF data types.
      It currently includes read-write support for ESMF Fields and States,
      and read support for ESMF Fields and Fortran arrays. It has only four methods:
      MAPL\_CFIOCreate, MAPL\_CFIOWrite, MAPL\_CFIORead, MAPL\_CFIODestroy. Except
      for MAPL\_Read, all work on the MAPL\_CFIO object. Reading is done
      directly from a file to the appropriate ESMF object.

      {\tt MAPL\_CFIO} is designed for two modes of I/O: self-describing formats (SDF),
      of which it supports HDF-4 and netcdf-3, and flat files, which includes support
      for GrADS readable files. The GrADS support is still und4er construction. There
      are also plans to add GRIB support. 

      In SDF mode, capability of {\tt MAPL\_CFIO} depends on which library (HDF or netcdf)
      is linked with the application, since both cannot be used because
      name conflicts between these two libraries. If netcdf is linked, only netcdf 
      files may be read or written. If HDF is linked, both HDF and netcdf files may
      be read, but only HDF files may be written.
      

%=========================================================================

\section{Miscellaneous Features: \ggn\_{Utils}}


Many aspects of the ESMF infrastructure, such as those dealing with
time management, error logging, etc., can easily be used directly by
modelers. Elements of the infrastructure that involve interfaces to
ESMF's communications layer, which are intended to be among ESMF most
powerful methods, are not as easy to adopt. The major hurdle to using
these elements of the ESMF infrastructure is that the user pretty much
has to put his data into \fld s, which are the main objects on
which the ESMF communication methods work. \ggn\  facilitates this by
creating all elements described in data services as \fld s or \bdl s
within the three states. In user code these can be extracted directly
and manipulated as \fld s when using ESMF infrastructure,
or one extract fortran pointers to the data when interfacing to 
existing user code. 


\ggn\  provides several features that are not central to its main 
goals, but which can be very handy. Some of these provide
functionality in and instance-specific way by saving metadata in the
\ggn\  object. This save the user the need to deal with such things in
his private internal state. The main support is for profiling, error
handling, and astronomy. These are very simple and we expect that
eventually they will be superceded by ESMF utilities, or remain as
simple interfaces to them.

\subsection{Error Handling}
The error handling utility consists of the three macros:
\begin{verbatim}
    VERIFY_(STATUS)
    RETURN_(ESMF_Success|ESMF_Failure)
    ASSERT_(logical expr)
\end{verbatim}

These are used by setting the local character string variable {\tt Iam} to
the soubroutine name, where possible qualified by the instance's name,
and then using {\tt VERIFY\_} to test ESMF and \ggn\  return codes, {\tt
  RETURN\_} to exit routines, and {\tt  ASSERT\_} for conditional aborts. 

\subsection{Profiling}
The API of the profiling utility consists three subroutines:
\begin{verbatim}
 MAPL_TimerAdd(MAPL, NAME, RC)
 MAPL_TimerOn (MAPL, NAME, RC)
 MAPL_TimerOff(MAPL, NAME, RC)
\end{verbatim}
where {\tt MAPL} is the \ggn\  object and {\tt NAME} is the string
name of a performance meter. Meters are usually registered in \ssv\
with {\tt Add} and can then be turned on and off throughout the user
code. In generic finalize the results are reported to standard
out. Even if the user registers no meters, the performance of the
generic IRF methods is reported.

\subsection{Astronomy}
 The astronomy is also simple and easy to use. At any time after the
 \ggn\ object is created (i.e., after the call to \gssv) it can be
 queried for an opaque object of type {\tt MAPL\_SunOrbit}.
 This orbit object can
 then be used to get the insolation at the top of the atmosphere
 through the following API:
\begin{verbatim}
 MAPL_SunGetInsolation(LONS, LATS, ORBIT,ZTH,SLR,INTV,CLOCK,TIME,RC)
\end{verbatim}
  where {\tt LONS} and {\tt LATS} can be either one- or two-dimensional
  Fortran arrays or general ESMF arrays with one or two horizontal
  dimensions, {\tt ORBIT} is the predefined object of type {\tt
  MAPL\_SunOrbit}, and {\tt ZTH} and {\tt SLR} are the cosine of the solar zenith angle
  and the TOA insolation at the given latitudes and longitudes; these are,
  of course, declared in the same way as  {\tt LONS} and {\tt LATS}. The
  remaining arguments are optional and their use is explained in Part II.

  By default the orbit created by \ggn\  uses late 20$^{th}$ century
  orbital parameters. These can be
  overidden in the configuration by specifying {\tt ECCENTRICITY:},
  {\tt OBLIQUITY}, {\tt PERIHELION:}, AND {\tt EQUINOX:}. The meaning
  of these, as well as more complex uses of the astronomy are also explained
  in the prologues of {\tt MAPL\_SunMod} in Part II.

\subsection{Universal Constants}
The following universal constants are defined when {\tt MAPLMod} is
used:

 \makebox[2in][l]{MAPL\_PI     }\makebox[2.5in][l] {\bf \tt  3.14159265358979323846}
  \makebox[2in][l] {--}
 \makebox[2in][l]{MAPL\_GRAV   }\makebox[2.5in][l] {\bf \tt  9.80}
  \makebox[2in][l] {m s$^{-2}$}
 \makebox[2in][l]{MAPL\_RADIUS }\makebox[2.5in][l]{\bf \tt  6376.0E3 }
\makebox[2in][l]{m}
 \makebox[2in][l]{MAPL\_OMEGA  }\makebox[2.5in][l]{\bf \tt  2.0*MAPL\_PI$/$86164.0 }
  \makebox[2in][l]{s$^{-1}$}
 \makebox[2in][l]{MAPL\_ALHL   }\makebox[2.5in][l]{\bf \tt  2.4548E6 }
  \makebox[2in][l]{J kg$^{-1}$}
 \makebox[2in][l]{MAPL\_ALHS   }\makebox[2.5in][l]{\bf \tt  2.8368E6 }
  \makebox[2in][l]{J kg$^{-1}$}
 \makebox[2in][l]{MAPL\_ALHF   }\makebox[2.5in][l]{\bf \tt  MAPL\_ALHS$-$MAPL\_ALHL }
  \makebox[2in][l]{J kg$^{-1}$}
 \makebox[2in][l]{MAPL\_STFBOL }\makebox[2.5in][l]{\bf \tt  5.6734E-8 }
  \makebox[2in][l]{W m$^{-2}$ K$^{-4}$}
 \makebox[2in][l]{MAPL\_AIRMW  }\makebox[2.5in][l]{\bf \tt  28.97 }
  \makebox[2in][l]{kg Kmole$^{-1}$}
 \makebox[2in][l]{MAPL\_H2OMW  }\makebox[2.5in][l]{\bf \tt  18.01 }
  \makebox[2in][l]{kg Kmole$^{-1}$}
 \makebox[2in][l]{MAPL\_RUNIV  }\makebox[2.5in][l]{\bf \tt  8314.3 }
  \makebox[2in][l]{J Kmole$^{-1}$ K$^{-1}$}
 \makebox[2in][l]{MAPL\_KAPPA  }\makebox[2.5in][l]{\bf \tt  2.0/7.0 }
  \makebox[2in][l] {--}
 \makebox[2in][l]{MAPL\_RVAP   }\makebox[2.5in][l]{\bf \tt
  MAPL\_RUNIV/MAPL\_H2OMW}
\makebox[2in][l]{J K$^{-1}$ kg$^{-1}$}
 \makebox[2in][l]{MAPL\_RGAS   }\makebox[2.5in][l]{\bf \tt
  MAPL\_RUNIV/MAPL\_AIRMW}
\makebox[2in][l]{J K$^{-1}$ kg$^{-1}$}
 \makebox[2in][l]{MAPL\_CP     }\makebox[2.5in][l]{\bf \tt
  MAPL\_RGAS/MAPL\_KAPPA }
\makebox[2in][l]{J K$^{-1}$ kg$^{-1}$}
 \makebox[2in][l]{MAPL\_P00    }\makebox[2.5in][l]{\bf \tt
  100000.0 }              
\makebox[2in][l]{Pa}
 \makebox[2in][l]{MAPL\_CAPWTR }\makebox[2.5in][l]{\bf \tt  4218. }
  \makebox[2in][l]{J K$^{-1}$ kg$^{-1}$}
 \makebox[2in][l]{MAPL\_RHOWTR }\makebox[2.5in][l]{\bf \tt  1000. }
  \makebox[2in][l]{kg m$^{-3}$}
 \makebox[2in][l]{MAPL\_NUAIR  }\makebox[2.5in][l]{\bf \tt  1.533E-5 }
  \makebox[2in][l]{m$^2$ S$^{-1}$ (@ 18C)}
 \makebox[2in][l]{MAPL\_TICE   }\makebox[2.5in][l]{\bf \tt
  273.16 }                
\makebox[2in][l]{K}
 \makebox[2in][l]{MAPL\_UNDEF  }\makebox[2.5in][l]{\bf \tt  -999.0 }
  \makebox[2in][l] {--}
 \makebox[2in][l]{MAPL\_SRFPRS }\makebox[2.5in][l]{\bf \tt
  98470 }                 
\makebox[2in][l]{Pa}
 \makebox[2in][l]{MAPL\_KARMAN }\makebox[2.5in][l]{\bf \tt  0.40 }
  \makebox[2in][l] {--}
 \makebox[2in][l]{MAPL\_USMIN  }\makebox[2.5in][l]{\bf \tt  1.00 }
  \makebox[2in][l]{m s$^{-1}$}
 \makebox[2in][l]{MAPL\_VIREPS }\makebox[2.5in][l]{\bf \tt  MAPL\_AIRMW/MAPL\_H2OMW-1.0 }
  \makebox[2in][l] {--}



%.........................................................................
\newpage

{\Large \bf References}

\addcontentsline{toc}{section}{References}

\begin{description}

\item DeLuca, C. and the ESMF Joint Specification Team, Earth System
Modeling Framework Project Plan 2005-2010, http://www.esmf.ucar.edu.

\item Hill, C., C. DeLuca, V. Balaji, M. Suarez, A. da Silva, The
Architecture of the Earth System Modeling Framework, {\em Computing in
Science and Engineering}, Vol. 11, No. 6, January/February 2004,
pp.18-28.

\item Held, I.M. and M.J. Suarez. A proposal for the intercomparison
  of the dynamical cores of atmospheric general circulation
  models. {\em Bulletin of the American Meteorological Society}, 
 {\bf 75(10)}:1825-1830, 1994.
 
\end{description}


\end{document}
%..........................................................................

