source: NEMO/trunk/doc/latex/global/coding_rules.tex @ 11299

Last change on this file since 11299 was 11299, checked in by nicolasmartin, 14 months ago

Review of the coding rules chapter: convert it to a shared file for 3 manuals

  • Move annex_D.tex and NEMO_coding_conv.tex to ./latex/global
  • Rename NEMO_coding_conv.tex to coding_rules.tex and redesign it as a chapter and not a standalone document
  • Edit document.tex to include the coding rules by default at the end of the appendix
File size: 35.3 KB
Line 
1%\documentclass{article}
2
3%\usepackage{fancyhdr}
4%\usepackage{times}
5%\usepackage{graphicx}
6%\usepackage{hyperref}
7%\usepackage{minted}
8%\usepackage[normalem]{ulem}   % striketrough style with \sout{...}
9
10%\hypersetup{pdftitle={NEMO coding conventions}, pdfauthor={NEMO System Team}, colorlinks}
11%\setminted{style=emacs, breaklines, frame=leftline}
12%\newmintinline[forcode]{fortran}{fontsize=auto, frame=lines}   % \forcode{...}
13%\newminted[forlines]{fortran}{}                                % \begin{forlines}
14
15%\pagestyle{empty}
16%\setlength{\leftmargin}{1 cm}
17%\setlength{\rightmargin}{1 cm}
18%\setlength{\oddsidemargin}{0 cm}
19%\setlength{\evensidemargin}{0 cm}
20%\setlength{\topmargin}{-1cm}
21%\setlength{\textwidth}{16 cm}
22%\setlength{\textheight}{25cm}
23%\pagestyle{fancy}
24
25%\title{
26%  \includegraphics[width=0.3\textwidth]{../../../figures/NEMO_grey} \\
27%  \vspace{1.0cm} \rule{345pt}{1.5pt} \\
28%  \vspace{0.45cm} {\Huge NEMO coding conventions} \rule{345pt}{1.5pt} \\
29%}
30%\title{NEMO coding conventions}
31%\author{\Large NEMO System Team
32%  \thanks{
33%    To be completed
34%  }
35%}
36%\date{version X.X -- month year}
37
38%\begin{document}
39
40%\maketitle
41
42%\newpage
43
44%\tableofcontents
45
46%\newpage
47
48%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49\chapter{Coding Rules}
50\label{apdx:coding}
51
52\minitoc
53
54\newpage
55
56A "model life" is more than ten years.
57Its software, composed of a few hundred modules, is used by many people who are scientists or students and
58do not necessarily know every aspect of computing very well.
59Moreover, a well thought-out program is easier to read and understand, less difficult to modify,
60produces fewer bugs and is easier to maintain.
61Therefore, it is essential that the model development follows some rules:
62
63- well planned and designed
64
65- well written
66
67- well documented (both on- and off-line)
68
69- maintainable
70
71- easily portable
72
73- flexible.
74
75To satisfy part of these aims, \NEMO is written with a coding standard which is close to the ECMWF rules,
76named DOCTOR \citep{gibson_rpt86}.
77These rules present some advantages like:
78
79- to provide a well presented program
80
81- to use rules for variable names which allow recognition of their type
82(integer, real, parameter, local or shared variables, etc. ).
83
84This facilitates both the understanding and the debugging of an algorithm.
85
86\section{Introduction}
87
88This document describes conventions\index{conventions} used in NEMO coding and suggested for its development.
89The objectives are to offer a guide to all readers of the NEMO code, and to facilitate the work of
90all the developers, including the validation of their developments, and
91eventually the implementation of these developments within the NEMO platform.
92
93A first approach of these rules can be found in the code in \path{./src/OCE/module_example} where
94all the basics coding conventions are illustrated.
95More details can be found below.
96
97This work is based on the coding conventions in use for the Community Climate System Model
98\footnote {\href{http://www.cesm.ucar.edu/working_groups/Software/dev_guide/dev_guide/node7.html}{UCAR conventions}},
99the previous version of this document (``FORTRAN coding standard in the OPA System'') and
100the expertise of the NEMO System Team.
101After a general overview below, this document will describe:
102
103\begin{itemize}
104\item
105  The style rules, $i.e.$ the syntax, appearance and naming conventions chosen to improve readability of the code;
106\item
107  The content rules, $i.e.$ the conventions to improve the reliability of the different parts of the code;
108\item
109  The package rules to go a step further by improving the reliability of the whole and
110  interfaces between routines and modules.
111\end{itemize}
112
113%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114\section{Overview and general conventions}
115
116NEMO has 3 major components: ocean dynamics (\path{./src/OCE}), sea-ice (\path{./src/ICE}) and
117marine biogeochemistry (\path{./src/MBG}).
118%, linear-tangent and adjoint of the dynamics ($TAM$) each of them corresponding to a directory.
119In each directory, one will find some FORTRAN files and/or subdirectories, one per functionality of the code:
120\path{./src/OCE/BDY} (boundaries), \path{./src/OCE/DIA} (diagnostics), \path{./src/OCE/DOM} (domain),
121\path{./src/OCE/DYN} (dynamics), \path{./src/OCE/LDF} (lateral diffusion), etc... \\
122All name are chosen to be as self-explanatory as possible, in English, all prefixes are 3 digits. \\
123English is used for all variables names, comments, and documentation. \\
124Physical units are MKS. The only exception to this is the temperature, which is expressed in degrees Celsius,
125except in bulk formulae and part of SI$^3$ sea-ice model where it is in Kelvin.
126See \path{.src/OCE/DOM/phycst.F90} files for conversions.
127
128%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
129\section{Architecture}
130
131Within each directory, organisation of files is driven by orthogonality\index{orthogonality},
132$i.e.$ one functionality of the code is intended to be in one and only one directory, and
133one module and all its related routines are in one file.
134The functional modules\index{module} are:
135
136\begin{itemize}
137\item \path{SBC}             surface module
138\item \path{IOM}             management of the I/O
139\item \path{NST}             interface to AGRIF (nesting model) for dynamics and biogeochemistry
140\item \path{OBC}, \path{BDY} management of structured and unstructured open boundaries
141\item \path{C1D}             1D (vertical) configuration for dynamics, sea-ice and biogeochemistry
142\item \path{OFF}             off-line module: passive tracer or biogeochemistry alone
143\item \path{...}
144\end{itemize}
145
146For example, the file \textit{domain.F90} contains the module \texttt{domain} and all the subroutines related to
147this module (\texttt{dom\_init, dom\_nam, dom\_ctl}).
148
149%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
150\section{Style rules}
151
152%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
153\subsection{Argument list format}
154
155Routine argument lists will contain a maximum 5 variables\index{variable} per line,
156whilst continuation lines can be used.
157This applies both to the calling routine and the dummy argument list in the routine being called.
158The purpose is to simplify matching up the arguments between caller and callee.
159
160\begin{forlines}
161SUBROUTINE tra_adv_eiv( kt, pun, pvn, pwn )
162
163      CALL tra_adv_eiv( kt, zun, zvn, zwn )
164\end{forlines}
165
166%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
167\subsection{Array syntax}
168
169Except for long loops (see below), array notation should be used if possible.
170To improve readability the array shape must be shown in brackets, $e.g.$:
171
172\begin{forlines}
173onedarraya(:)   = onedarrayb(:) + onedarrayc(:)
174twodarray (:,:) = scalar * anothertwodarray(:,:)
175\end{forlines}
176
177When accessing sections of arrays, for example in finite difference equations,
178do so by using the triplet notation on the full array, $e.g.$:
179
180\begin{forlines}
181twodarray(:,2:len2) =   scalar                      &
182   &                  * ( twodarray2(:,1:len2-1 )   &
183   &                  -   twodarray2(:,2:len2 ) )
184\end{forlines}
185
186For long, complicated loops, explicitly indexed loops should be preferred.
187In general when using this syntax, the order of the loops indices should reflect the following scheme
188(for best usage of data locality):
189
190\begin{forlines}
191DO jk = 1, jpk
192   DO jj = 1, jpj
193      DO ji = 1, jpi
194         threedarray(ji,jj,jk) = ...
195      END DO
196   END DO
197END DO
198\end{forlines}
199
200%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
201\subsection{Case}
202
203All FORTRAN keywords are in capital: \forcode{DIMENSION}, \forcode{WRITE}, \forcode{DO}, \forcode{END DO},
204\forcode{NAMELIST}, ... All other parts of the NEMO code will be written in lower case.
205
206%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
207\subsection{Comments}
208
209Comments in the code are useful when reading the code and changing or developing it. \\
210The full documentation and detailed explanations are to be added in the reference manual
211(TeX files, aside from the code itself). \\
212In the code, the comments should explain variable content and describe each computational step. \\
213Comments in the header start with ``!!''.
214For more details on the content of the headers, see Content rules/Headers in this document. \\
215Comments in the code start with ``!''. \\
216All comments are indented (3, 6, or 9 blank spaces). \\
217Short comments may be included on the same line as executable code, and an additional line can be used with
218proper alignment.
219For example:
220
221\begin{forlines}
222zx = zx *zzy   ! Describe what is going on and if it is
223!              ! too long use another ! for proper
224!              ! alignment with automatic indentation
225\end{forlines}
226
227More in-depth comments should be written in the form:
228
229\begin{forlines}
230   !  Check of some namelist values
231\end{forlines}
232
233or
234
235\begin{forlines}
236!
237!     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
238!     !  Bottom boundary condition on tke
239!     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
240!
241\end{forlines}
242
243Key features of this style are
244
245\begin{enumerate}
246\item it starts with a "!" in the column required for proper indentation,
247\item the text is offset above and below by a blank line or a content line built for underlying.
248\end{enumerate}
249
250%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
251\subsection{Continuation lines}
252
253Continuation lines can be used with precise alignment for readability. For example:
254
255\begin{forlines}
256avmu(ji,jj,jk) =   avmu(ji,jj,jk) * ( un(ji,jj,jk-1) - un(ji,jj,jk) )   &
257   &                              * ( ub(ji,jj,jk-1) - ub(ji,jj,jk) )   &
258   &             / (   fse3uw_n(ji,jj,jk)                               &
259   &                 * fse3uw_b(ji,jj,jk) )
260\end{forlines}
261
262Code lines, which are continuation lines of assignment statements, must begin to the right of the column of
263the assignment operator.
264Due to the possibility of automatic indentation in some editor (emacs for example),
265use a ``\&'' as first character of the continuing lines to maintain the alignment.
266
267%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
268\subsection{Declaration of arguments and local variables}
269
270In a routine, input arguments and local variables are declared 1 per line,
271with a comment field on the same line as the declaration.
272Multiple comment lines describing a single variable are acceptable if needed.
273For example:
274
275\begin{forlines}
276INTEGER             ::   kstp   ! ocean time-step index
277\end{forlines}
278
279%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
280\subsection{F90 Standard}
281
282NEMO software adheres to the FORTRAN 95 language standard and does not rely on any specific language or
283vendor extensions.
284
285
286%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
287\subsection{Free-Form Source}
288
289Free-form source will be used.
290The F90/95 standard allows lines of up to 132 characters, but a self-imposed limit of 80 should enhance readability,
291or print source files with two columns per page.
292Multi-line comments that extend to column 100 are unacceptable.
293
294%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
295\subsection{Indentation}
296
297Code as well as comment lines within loops, if-blocks, continuation lines, \forcode{MODULE} or
298\forcode{SUBROUTINE} statements will be indented 3 characters for readability
299(except for \forcode{CONTAINS} that remains at first column).
300
301\begin{forlines}
302MODULE mod1
303   REAL(wp) xx
304CONTAINS
305   SUBROUTINE sub76( px, py, pz, pw, pa,   &
306      &              pb, pc, pd, pe          )
307      <instruction>
308   END SUBROUTINE sub76
309END MODULE mod1
310\end{forlines}
311
312%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
313\subsection{Loops}
314
315Loops, if explicit, should be structured with the do-end do construct as opposed to numbered loops.
316Nevertheless non-numeric labels can be used for a big iterative loop of a recursive algorithm.
317In the case of a long loop, a self-descriptive label can be used ($i.e.$ not just a number).
318
319%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
320\subsection{Naming Conventions: files}
321
322A file containing a module will have the same name as the module it contains
323(because dependency rules used by "make" programs are based on file names).
324\footnote{
325  For example, if routine A "\forcode{USE}"s module B, then "make" must be told of the dependency relation which
326  requires B to be compiled before A.
327  If one can assume that module B resides in file B.o,
328  building a tool to generate this dependency rule ($e.g.$ A.o: B.o) is quite simple.
329  Put another way, it is difficult (to say nothing of CPU-intensive) to search an entire source tree to
330  find the file in which module B resides for each routine or module which "\forcode{USE}"s B.
331}
332
333%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
334\subsection{Naming Conventions: modules}
335
336Use a meaningful English name and the ``3 letters'' naming convention:
337first 3 letters for the code section, and last 3 to describe the module.
338For example, zdftke, where ``zdf'' stands for vertical diffusion, and ``tke'' for turbulent kinetic energy. \\
339Note that by implication multiple modules are not allowed in a single file.
340The use of common blocks is deprecated in Fortran 90 and their use in NEMO is strongly discouraged.
341Modules are a better way to declare static data.
342Among the advantages of modules is the ability to freely mix data of various types, and
343to limit access to contained variables through the use of the \forcode{ONLY} and \forcode{PRIVATE} attributes.
344
345%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
346\subsection{Naming Conventions: variables}
347
348All variable should be named as explicitly as possible in English.
349The naming convention concerns prefix letters of these name, in order to identify the variable type and status. \\
350Never use a FORTRAN keyword as a routine or variable name. \\
351The table below lists the starting letter(s) to be used for variable naming, depending on their type and status:
352%--------------------------------------------------TABLE--------------------------------------------------
353\begin{table}[htbp]
354  \begin{center}
355    \begin{tabular}{|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|}
356      \hline
357      Type \par / Status &   integer&   real&   logical &   character&   double \par precision&   complex \\
358      \hline
359      public  \par or  \par module variable& \textbf{m n} \par \textit{but not } \par \textbf{nn\_}& \textbf{a b e f g h o} \textbf{q} \textit{to} \textbf{x} \par but not \par \textbf{fs rn\_}& \textbf{l} \par \textit{but not} \par \textbf{lp ld ll ln\_}& \textbf{c} \par \textit{but not} \par \textbf{cp cd cl cn\_}& \textbf{d} \par \textit{but not} \par \textbf{dp dd dl dn\_}& \textbf{y} \par \textit{but not} \par \textbf{yp yd yl} \\
360      \hline
361      dummy \par argument& \textbf{k} \par \textit{but not} \par \textbf{kf}& \textbf{p} \par \textit{but not}  \par \textbf{pp pf}& \textbf{ld}& \textbf{cd}& \textbf{dd}& \textbf{yd} \\
362      \hline
363      local \par variable& \textbf{i}& \textbf{z}& \textbf{ll}& \textbf{cl}& \textbf{cd}& \textbf{yl} \\
364      \hline
365      loop \par control& \textbf{j} \par \textit{but not } \par \textbf{jp}& & & & &  \\
366      \hline
367      parameter& \textbf{jp}& \textbf{pp}& \textbf{lp}& \textbf{cp}& \textbf{dp}& \textbf{yp} \\
368      \hline
369      namelist& \textbf{nn\_}& \textbf{rn\_}& \textbf{ln\_}& \textbf{cn\_}& \textbf{dn\_}& \\
370      \hline
371      CPP \par macro& \textbf{kf}& \textbf{sf} \par & & & & \\
372      \hline
373    \end{tabular}
374    \label{tab1}
375  \end{center}
376\end{table}
377%--------------------------------------------------------------------------------------------------------------
378
379%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
380\subsection{Operators}
381
382Use of the operators \texttt{<, >, <=, >=, ==, /=} is strongly recommended instead of their deprecated counterparts
383(\texttt{.lt., .gt., .le., .ge., .eq., .ne.}).
384The motivation is readability.
385In general use the notation: \\
386$<Blank><Operator><Blank>$
387%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
388\subsection{Pre processor}
389
390Where the use of a language pre-processor is required, it will be the C pre-processor (cpp). \\
391The cpp key is the main feature used, allowing to ignore some useless parts of the code at compilation step. \\
392The advantage is to reduce the memory use; the drawback is that compilation of this part of the code isn't checked. \\
393The cpp key feature should only be used for a few limited options, if it reduces the memory usage.
394In all cases, a logical variable and a FORTRAN \forcode{IF} should be preferred.
395When using a cpp key \textit{key\_optionname},
396a corresponding logical variable \textit{lk\_optionname} should be declared to
397allow FORTRAN \forcode{IF} tests in the code and
398a FORTRAN module with the same name ($i.e.$ \textit{optionname.F90}) should be defined.
399This module is the only place where a \``\#if defined'' command appears, selecting either the whole FORTRAN code or
400a dummy module.
401For example, the TKE vertical physics, the module name is \textit{zdftke.F90},
402the CPP key is \textit{key\_zdftke} and the associated logical is \textit{lk\_zdftke}.
403
404The following syntax:
405
406\begin{forlines}
407#if defined key_optionname
408!! Part of code conditionally compiled if cpp key key_optionname is active
409#endif
410\end{forlines}
411
412Is to be used rather than the \#ifdef abbreviate form since it may have conflicts with some Unix scripts.
413
414Tests on cpp keys included in NEMO at compilation step:
415
416\begin{itemize}
417\item
418  The CPP keys used are compared to the previous list of cpp keys
419  (the compilation will stop if trying to specify a non-existing key)
420\item
421  If a change occurs in the CPP keys used for a given experiment, the whole compilation phase is done again.
422\end{itemize}
423%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
424\section{Content rules}
425
426%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
427\subsection{Configurations}
428
429The configuration defines the domain and the grid on which NEMO is running.
430It may be useful to associate a cpp key and some variables to a given configuration, although
431the part of the code changed under each of those keys should be minimized.
432As an example, the "ORCA2" configuration (global ocean, 2 degrees grid size) is associated with
433the cpp key \texttt{key\_orca2} for which
434
435\begin{forlines}
436cp_cfg = "orca"
437jp_cfg = 2
438\end{forlines}
439
440%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
441\subsection{Constants}
442
443Physical constants ($e.g.$ $\pi$, gas constants) must never be hardwired into the executable portion of a code.
444Instead, a mnemonically named variable or parameter should be set to the appropriate value,
445in the setup routine for the package\index{package}.
446We realize than many parameterizations rely on empirically derived constants or fudge factors,
447which are not easy to name.
448In these cases it is not forbidden to leave such factors coded as "magic numbers" buried in executable code, but
449comments should be included referring to the source of the empirical formula.
450Hard-coded numbers should never be passed through argument lists.
451
452%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
453\subsection{Declaration for variables and constants}
454
455\subsubsection{Rules}
456
457Variables used as constants should be declared with attribute \forcode{PARAMETER} and
458used always without copying to local variables, in order to
459prevent from using different values for the same constant or changing it accidentally.
460
461\begin{itemize}
462\item
463  Usage of the \forcode{DIMENSION} statement or attribute is required in declaration statements
464\item
465  The ``::'' notation is quite useful to show that this program unit declaration part is written in
466  standard FORTRAN syntax, even if there are no attributes to clarify the declaration section.
467  Always use the notation $<$blank$>$::$<$three blanks$>$ to improve readability.
468\item
469  Declare the length of a character variable using the \forcode{CHARACTER} (len=xxx) syntax
470  \footnote {
471    The len specifier is important because it is possible to have several kinds for characters
472    ($e.g.$ Unicode using two bytes per character, or there might be a different kind for Japanese $e.g.$ NEC).
473  }
474\item
475  For all global data (in contrast to module data, that is all data that can be access by other module)
476  must be accompanied with a comment field on the same line
477  \footnote {
478    This allows a easy research of where and how a variable is declared using the unix command:
479    ``grep var *90 | grep !:''.
480  }.
481  For example:
482  \begin{forlines}
483  REAL(wp), DIMENSION(jpi,jpj,jpk) ::  ua   ! i-horizontal velocity (m/s)
484  \end{forlines}
485\end{itemize}
486
487\subsubsection{Implicit None}
488
489All subroutines and functions will include an \forcode{IMPLICIT NONE} statement.
490Thus all variables must be explicitly typed.
491It also allows the compiler to detect typographical errors in variable names.
492For modules, one \forcode{IMPLICIT NONE} statement in the modules definition section is needed.
493This also removes the need to have \forcode{IMPLICIT NONE} statements in
494any routines that are \forcode{CONTAINS}'ed in the module.
495Improper data initialisation is another common source of errors
496\footnote{
497  A variable could contain an initial value you did not expect.
498  This can happen for several reasons, $e.g.$ the variable has never been assigned a value, its value is outdated,
499  memory has been allocated for a pointer but you have forgotten to initialise the variable pointed to.
500}.
501To avoid problems, initialise variables as close as possible to where they are first used.
502
503\subsubsection{Attributes}
504
505\forcode{PRIVATE} / \forcode{PUBLIC}:
506All resources of a module are \forcode{PUBLIC} by default.
507A reason to store multiple routines and their data in a single module is that
508the scope of the data defined in the module can be limited to the routines which are in the same module.
509This is accomplished with the \forcode{PRIVATE} attribute. \\
510\forcode{INTENT}:
511All dummy arguments of a routine must include the \forcode{INTENT} clause in their declaration in order to
512improve control of variables in routine calls.
513
514%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
515\subsection{Headers}
516
517Prologues are not used in NEMO for now, although it may become an interesting tool in combination with
518ProTeX auto documentation script in the future.
519Rules to code the headers and layout of a module or a routine are illustrated in the example module available with
520the code: \path{./src/OCE/module_example}
521
522%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
523\subsection{Interface blocks}
524
525Explicit interface blocks are required between routines if optional or keyword arguments are to be used.
526They also allow the compiler to check that the type, shape and number of arguments specified in the \forcode{CALL}
527are the same as those specified in the subprogram itself.
528FORTRAN 95 compilers can automatically provide explicit interface blocks for routines contained in a module.
529
530%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
531\subsection{I/O Error Conditions}
532
533I/O statements which need to check an error condition will use the \texttt{iostat=<integer variable>} construct
534instead of the outmoded \texttt{end=} and \forcode{err=}. \\
535Note that a 0 value means success, a positive value means an error has occurred, and
536a negative value means the end of record or end of file was encountered.
537
538%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
539\subsection{PRINT - ASCII output files}
540
541Output listing and errors are directed to \texttt{numout} logical unit =6 and
542produces a file called \textit{ocean.output} (use \texttt{ln\_prt} to have one output per process in MPP).
543Logical \texttt{lwp} variable allows for less verbose outputs.
544To output an error from a routine, one can use the following template:
545
546\begin{forlines}
547IF( nstop /= 0 .AND. lwp ) THEN   ! error print
548   WRITE(numout,cform_err)
549   WRITE(numout,*) nstop, ' error have been found'
550ENDIF
551\end{forlines}
552
553%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
554\subsection{Precision}
555
556Parameterizations should not rely on vendor-supplied flags to supply a default floating point precision or
557integer size.
558The F95 \forcode{KIND} feature should be used instead.
559In order to improve portability between 32 and 64 bit platforms,
560it is necessary to make use of kinds by using a specific module \path{./src/OCE/par_kind.F90}
561declaring the "kind definitions" to obtain the required numerical precision and range as well as
562the size of \forcode{INTEGER}.
563It should be noted that numerical constants need to have a suffix of \texttt{\_kindvalue} to
564have the according size. \\
565Thus \forcode{wp} being the "working precision" as declared in \path{./src/OCE/par_kind.F90},
566declaring real array \forcode{zpc} will take the form:
567
568\begin{forlines}
569REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zpc      ! power consumption
570\end{forlines}
571
572%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
573\subsection{Structures}
574
575The \forcode{TYPE} structure allowing to declare some variables is more often used in NEMO,
576especially in the modules dealing with reading fields, or interfaces.
577For example:
578
579\begin{forlines}
580! Definition of a tracer as a structure
581TYPE PTRACER
582   CHARACTER(len = 20)  :: sname  ! short name
583   CHARACTER(len = 80 ) :: lname  ! long name
584   CHARACTER(len = 20 ) :: unit   ! unit
585   LOGICAL              :: lini   ! read in a file or not
586   LOGICAL              :: lsav   ! ouput the tracer or not
587END TYPE PTRACER
588
589TYPE(PTRACER) , DIMENSION(jptra) :: tracer
590\end{forlines}
591
592Missing rule on structure name??
593
594%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
595\section{Packages coding rules}
596
597%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
598\subsection{Bounds checking}
599
600NEMO is able to run when an array bounds checking option is enabled
601(provided the cpp key \texttt{key\_vectopt\_loop} is not defined). \\
602Thus, constructs of the following form are disallowed:
603
604\begin{forlines}
605REAL(wp) :: arr(1)
606\end{forlines}
607
608where "arr" is an input argument into which the user wishes to index beyond 1.
609Use of the (*) construct in array dimensioning is forbidden also because
610it effectively disables array bounds checking.
611
612%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
613\subsection{Communication}
614
615A package should refer only to its own modules and subprograms and to those intrinsic functions included in
616the Fortran standard. \\
617All communication with the package will be through the argument list or namelist input.
618\footnote{
619  The point behind this rule is that packages should not have to know details of
620  the surrounding model data structures, or the names of variables outside of the package.
621  A notable exception to this rule is model resolution parameters.
622  The reason for the exception is to allow compile-time array sizing inside the package.
623  This is often important for efficiency.
624}
625
626%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
627\subsection{Error conditions}
628
629When an error condition occurs inside a package, a message describing what went wrong will be printed
630(see PRINT - ASCII output files).
631The name of the routine in which the error occurred must be included.
632It is acceptable to terminate execution within a package, but
633the developer may instead wish to return an error flag through the argument list,
634see \textit{stpctl.F90}.
635
636%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
637\subsection{Memory management}
638
639The main action is to identify and declare which arrays are \forcode{PUBLIC} and which are \forcode{PRIVATE}. \\
640As of version 3.3.1 of NEMO, the use of static arrays (size fixed at compile time) has been deprecated.
641All module arrays are now declared \forcode{ALLOCATABLE} and
642allocated in either the \texttt{<module\_name>\_alloc()} or \texttt{<module\_name>\_init()} routines.
643The success or otherwise of each \forcode{ALLOCATE} must be checked using
644the \texttt{stat=<integer\ variable>} optional argument. \\
645
646In addition to arrays contained within modules, many routines in NEMO require local, ``workspace'' arrays to
647hold the intermediate results of calculations.
648In previous versions of NEMO, these arrays were declared in such a way as to be automatically allocated on
649the stack when the routine was called.
650An example of an automatic array is:
651
652\begin{forlines}
653SUBROUTINE sub(n)
654   REAL :: a(n)
655   ...
656END SUBROUTINE sub
657\end{forlines}
658
659The downside of this approach is that the program will crash if it runs out of stack space and
660the reason for the crash might not be obvious to the user.
661
662Therefore, as of version 3.3.1, the use of automatic arrays is deprecated.
663Instead, a new module, \textit{wrk\_nemo.F90}, has been introduced which
664contains 1-,2-,3- and 4-dimensional workspace arrays for use in subroutines.
665These workspace arrays should be used in preference to declaring new, local (allocatable) arrays whenever possible.
666The only exceptions to this are when workspace arrays with lower bounds other than 1 and/or
667with extent(s) greater than those in the \textit{wrk\_nemo.F90} module are required. \\
668
669The 2D, 3D and 4D workspace arrays in \textit{wrk\_nemo.F90} have extents \texttt{jpi}, \texttt{jpj},
670\texttt{jpk} and \texttt{jpts} ($x$, $y$, $z$ and tracers) in the first, second, third and fourth dimensions,
671respectively.
672The 1D arrays are allocated with extent MAX($jpi \times jpj, jpk \times jpj, jpi \times jpk$). \\
673
674The \forcode{REAL (KIND = wp)} workspace arrays in \textit{wrk\_nemo.F90}
675are named $e.g.$ \texttt{wrk\_1d\_1, wrk\_4d\_2} etc. and
676should be accessed by USE'ing the \textit{wrk\_nemo.F90} module.
677Since these arrays are available to any routine,
678some care must be taken that a given workspace array is not already being used somewhere up the call stack.
679To help with this, \textit{wrk\_nemo.F90} also contains some utility routines;
680\texttt{wrk\_in\_use()} and \texttt{wrk\_not\_released()}.
681The former first checks that the requested arrays are not already in use and then sets internal flags to show that
682they are now in use.
683The \texttt{wrk\_not\_released()} routine un-sets those internal flags.
684A subroutine using this functionality for two, 3D workspace arrays named \texttt{zwrk1} and
685\texttt{zwrk2} will look something like:
686
687\begin{forlines}
688SUBROUTINE sub()
689   USE wrk_nemo, ONLY: wrk_in_use, wrk_not_released
690   USE wrk_nemo, ONLY: zwrk1 => wrk_3d_5, zwrk2 => wrk_3d_6
691   !
692   IF(wrk_in_use(3, 5,6)THEN
693      CALL ctl_stop('sub: requested workspace arrays unavailable.')
694      RETURN
695   END IF
696   ...
697   ...
698   IF(wrk_not_released(3, 5,6)THEN
699      CALL ctl_stop('sub: failed to release workspace arrays.')
700   END IF
701   !
702END SUBROUTINE sub
703\end{forlines}
704
705The first argument to each of the utility routines is the dimensionality of the required workspace (1--4).
706Following this there must be one or more integers identifying which workspaces are to be used/released.
707Note that, in the interests of keeping the code as simple as possible,
708there is no use of \forcode{POINTER}s etc. in the \textit{wrk\_nemo.F90} module.
709Therefore it is the responsibility of the developer to ensure that the arguments to \texttt{wrk\_in\_use()} and
710\texttt{wrk\_not\_released()} match the workspace arrays actually being used by the subroutine. \\
711
712If a workspace array is required that has extent(s) less than those of the arrays in
713the \textit{wrk\_nemo.F90} module then the advantages of implicit loops and bounds checking may be retained by
714defining a pointer to a sub-array as follows:
715
716\begin{forlines}
717SUBROUTINE sub()
718   USE wrk_nemo, ONLY: wrk_in_use, wrk_not_released
719   USE wrk_nemo, ONLY: wrk_3d_5
720   !
721   REAL(wp), DIMENSION(:,:,:), POINTER :: zwrk1
722   !
723   IF(wrk_in_use(3, 5)THEN
724      CALL ctl_stop('sub: requested workspace arrays unavailable.')
725      RETURN
726   END IF
727   !
728   zwrk1 => wrk_3d_5(1:10,1:10,1:10)
729   ...
730END SUBROUTINE sub
731\end{forlines}
732
733Here, instead of ``use associating'' the variable \texttt{zwrk1} with the array \texttt{wrk\_3d\_5}
734(as in the first example), it is explicitly declared as a pointer to a 3D array.
735It is then associated with a sub-array of \texttt{wrk\_3d\_5} once the call to
736\texttt{wrk\_in\_use()} has completed successfully.
737Note that in F95 (to which NEMO conforms) it is not possible for either the upper or lower array bounds of
738the pointer object to differ from those of the target array. \\
739
740In addition to the \forcode{REAL (KIND = wp)} workspace arrays,
741\textit{wrk\_nemo.F90} also contains 2D integer arrays and 2D REAL arrays with extent (\texttt{jpi}, \texttt{jpk}),
742$i.e.$ $xz$.
743The utility routines for the integer workspaces are \texttt{iwrk\_in\_use()} and \texttt{iwrk\_not\_released()} while
744those for the $xz$ workspaces are \texttt{wrk\_in\_use\_xz()} and \texttt{wrk\_not\_released\_xz()}.
745
746Should a call to one of the \texttt{wrk\_in\_use()} family of utilities fail,
747an error message is printed along with a table showing which of the workspace arrays are currently in use.
748This should enable the developer to choose alternatives for use in the subroutine being worked on. \\
749
750When compiling NEMO for production runs,
751the calls to {\texttt{wrk\_in\_use()} / \texttt{wrk\_not\_released()} can be reduced to stubs that just
752return \forcode{.false.} by setting the cpp key \texttt{key\_no\_workspace\_check}.
753These stubs may then be inlined (and thus effectively removed altogether) by setting appropriate compiler flags
754($e.g.$ ``-finline'' for the Intel compiler or ``-Q'' for the IBM compiler).
755
756%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
757\subsection{Optimisation}
758
759Considering the new computer architecture, optimisation cannot be considered independently from the computer type.
760In NEMO, portability is a priority, before any too specific optimisation.
761
762Some tools are available to help: for vector computers, \texttt{key\_vectopt\_loop} allows to unroll a loop
763
764%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
765\subsection{Package attribute: \forcode{PRIVATE}, \forcode{PUBLIC}, \forcode{USE}, \forcode{ONLY}}
766
767Module variables and routines should be encapsulated by using the \forcode{PRIVATE} attribute.
768What shall be used outside the module can be declared \forcode{PUBLIC} instead.
769Use \forcode{USE} with the \forcode{ONLY} attribute to specify which of the variables, type definitions etc...
770defined in a module are to be made available to the using routine.
771
772%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
773\subsection {Parallelism using MPI}
774
775NEMO is written in order to be able to run on one processor, or on one or more using MPI
776($i.e.$ activating the cpp key $key\_mpp\_mpi$).
777The domain decomposition divides the global domain in cubes (see NEMO reference manual).
778Whilst coding a new development, the MPI compatibility has to be taken in account
779(see \path{./src/LBC/lib_mpp.F90}) and should be tested.
780By default, the $x$-$z$ part of the decomposition is chosen to be as square as possible.
781However, this may be overriden by specifying the number of subdomains in latitude and longitude in
782the \texttt{nammpp} section of the namelist file.
783
784%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
785\section{Features to be avoided}
786
787The code must follow the current standards of FORTRAN and ANSI C.
788In particular, the code should not produce any WARNING at compiling phase, so that
789users can be easily alerted of potential bugs when some appear in their new developments.
790Below is a list of features to avoid:
791\begin{itemize}
792\item
793  \forcode{COMMON} block
794  (use the declaration part of \forcode{MODULE} instead)
795\item
796  \forcode{EQUIVALENCE}
797  (use \forcode{POINTER} or derived data type instead to form data structure)
798\item
799  Assigned and computed \forcode{GOTO}
800  (use the \forcode{CASE} construct instead)
801\item
802  Arithmetic \forcode{IF} statement
803  (use the block \forcode{IF}, \forcode{ELSE}, \forcode{ELSEIF}, \forcode{ENDIF} or
804  \forcode{SELECT CASE} construct instead)
805\item
806  Labeled \forcode{DO} construct
807  (use unlabeled \forcode{END DO} instead)
808\item
809  \forcode{FORMAT} statement
810  (use character parameters or
811  explicit format- specifiers inside the \forcode{READ} or \forcode{WRITE} statement instead)
812\item
813  \forcode{GOTO} and \forcode{CONTINUE} statements
814  (use \forcode{IF}, \forcode{CASE}, \forcode{DO WHILE}, \forcode{EXIT} or \forcode{CYCLE} statements or
815  a contained ?)
816\item
817  \forcode{PAUSE}
818\item
819  \forcode{ENTRY} statement: a subprogram must only have one entry point.
820\item
821  \forcode{RETURN} is obsolete and so not necessary at the end of program units
822\item
823  \forcode{FUNCTION} statement
824\item
825  Avoid functions with side effects.
826  \footnote{
827    First, the code is easier to understand, if you can rely on
828    the rule that functions don't change their arguments.
829    Second, some compilers generate more efficient code for PURE functions
830    (in FORTRAN 95 there are the attributes PURE and ELEMENTAL), because
831    they can store the arguments in different places.
832    This is especially important on massive parallel and as well on vector machines.
833  }
834\item
835  \forcode{DATA} and \forcode{BLOCK DATA}
836  (use initialisers)
837\end{itemize}
838
839%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
840
841% \printindex
842% \input NEMO_coding.conv.ind
843
844%\end{document}
Note: See TracBrowser for help on using the repository browser.