Log In | Users | Register
Edit | Attach | New | Raw | Diff | Print | | Tools
You are here: CM » RcmDoc » CosmoClm » CosmoModel » CodingAdvicesCosmo2

The "COSMO rules"

The cosmo/cosmo-clm code is written in Fortran. You can find some literature about this programming language in two documents attached at the bottom of this page (one in English, one in German). Numerous books exist and useful links can be found on the web. A short reference card is also available.

1 Coding

Before starting to program the first line...

Some few rules should be observed when programming in the cosmo/cosmo-clm code.
  1. Read carefully the coding rules of DWD and the European standards for Fortran90 (both documents can be downloaded from the bottom of this page) and follow them. They constitute a prerequiste for an eventual integration of your code into an official version. A summary of the rules presented in both documents is available below.
  2. Provide a documentation of your developments (short report) and add systematically the definition of the new variables directly in the code as well as SHORT comments.
  3. Try to minimize the number of lines rather than maximize it. There are always many ways to program something and it can be worth to spend some time to find an elegant solution. You will probably spare a lot of time later...
  4. If you are developing parameterizations for new processes, adding the treatment of new chemical species, or incorporating new environment components (oceans, vegetation and so on), please do it as new modules with small and well delimited interfaces with the rest of the cosmo code if possible. It is much more easy to migrate, to use your code with other models, to be flexible.
  5. If you need some help for programming or want some help for porting your code in a newer version, don't hesitate to contact the author of this page. However, before bringing some code to port in a newer version, be sure that:
    1. Your version is stable. You are not performing some developments currently nor plan to do some soon.
    2. Your code compile and run also with debugging options.
    3. Your code complies with the requirements explained in the coding rules of DWD and the European standards for Fortran90.
    4. You have documented your work.

Good luck for your coding work!!!

Summary of the basic rules

The European standards for writing and documenting exchangeable Fortran 90 code as well as the DWD standards for model development (which is based on the first document) may be summarized as follows:

  • Write a documentation in English:
    • External documentation (outside the code). It must contains 3 elements:
      • Scientific documentation: describe the problem being solved by your code and the rationale for the method adopted. It must not refer to the code (no technical aspects).
      • Implementation documentation: describe your particular implementation of the solution method. It explains the technical aspects of the scientific problem presented in your scientific documentation. All subroutines, functions, modules, etc. have to be listed by name together with a brief description. A calling tree for routines within your code should be included.
      • User guide: describe in detail all inputs of your code (arguments, switches, namelist parameters and other "tuneable" variables). Provide also suitable default values, plausible values range, etc. if possible.
    • Internal documentation (inside the code). There are 4 types:
      • Procedure headers: Write an header for each subroutine, function, module, etc. It has to describe the function of the subroutine, function, etc. and refers to external documentation. All variables used are declared and commented. For each module, the history of the modifications has to be written in the header.
      • Section comments: Use numbered logical sections. You can also refer to external documentation if needed.
      • Other comments: Use them to simplify the understanding of your code to other persons. Place them either immediately before or on the same line as the code they are commenting.
      • Meaningful names: Use meaningful names for your functions, subroutines, variables, etc.
  • Design features:
    • External communication with your code: It can be done using arguments, a NAMELIST file read, the usage of modules among others.
    • Error handling: If an error occurs, your code should exit with the external report of the error (integer variable in the argument list) and write a diagnostic error message.
    • Resolution: Your code should be as resolution independent as possible.
    • Modularisation: Each program unit should be stored in a separated file.
  • Coding aspects:
    • Use of dynamic memory: Dynamic memory use is highly desirable. You can reach it by using automatic arrays, pointer arrays and allocatable arrays. If possible, use automatic arrays.
      • Automatic arrays: Their extent depend upon variables known at runtime (exemple: p(i,j,k,t) where i denotes the number of gridpoints in the longitude direction, j the number of gridpoints in the latitude direction, k the number of levels and t the number of time steps. i, j, k and t are defined in the different NAMELISTS and are thus not known at the compilation time but only at the runtime). You don't need to ALLOCATE and DEALLOCATE them, thus avoiding some mistakes.
      • Pointers arrays: They are declared with the POINTER attribute. You have to ALLOCATE and DEALLOCATE them.
      • Allocatable arrays: You have to ALLOCATE and DEALLOCATE them. You cannot use them inside derived data types.
    • Strictly forbidden: The use of the following commands/procedures/structures is strictly forbidden. The recommended alternative is written in brackets. COMMON blocks (use Modules), EQUIVALENCE (use POINTERS or derived data types), GO TO (use CASE), arithmetic IF statements (use the block IF construct), Labels, I/O routines End= and ERR= (use IOSTAT), FORMAT statements, PAUSE, ENTRY.
    • Free format: Use free format syntax. The maximum line length is 80 characters.
    • Implicit none: Use it in all program units.
    • Upper vs lower case: Use upper case for Fortran statements and lower or mixed case for the variables, parameters, subroutines, etc.
    • Indentation: Indent your code in the DO, DO WHILE, IF blocks, CASE, etc. by 2 characters. Indent also continuation lines and the associated comments. DO NOT use tab characters.
    • Spaces: Leave a blank space between variables and operators.
    • I/O Formatting: Don't put text inside the brackets of the I/O statements (i.e. separate the I/O content from the I/O formatting)
    • Unused header: When you are finished with the programation of a module/function/subroutine/etc., verify that all the variables declared in the header are used. If it is not the case, delete them from the header.
    • Array notation: Use array notation whenever possible (better optimization). Show the array's shape in brackets (x(:), y(:,:), pp(:,:,:,:) etc.). When accessing subsections of arrays, use this type of notation: y(:,1:rlat), pp(i:ie,j:je,ke+1,:), etc.
    • End of modules/subroutines: Always name your program units and alwys use the End program_name, End module_name, End subroutine_name, etc.
    • Logical operators: Use <,>,<=,>=,==,/= instead of .lt.,.gt.,.le.,.ge.,.eq.,.ne.
    • Multiple statements: Avoid multiple statements on one line.
    • Variable declaration: don't use the DIMENSION statement or attribute. Declare the shape and size of arrays inside brackets after the variable name in the declaration statement. Always use the :: notation even if their are no attributes. Declare the length of a character variable using the (len=) sytax.
    • Conventions for variable naming: INTEGER variables start with the letter i, j, k, m, n. LOGICAL variables start with the letter l. All other variables (REAL, CHARACTER, ...) start with any other letter except z. Local variables start with the letter z: INTEGER variables start with iz, jz, kz, mz, nz, LOGICAL variables start with lz and REAL variables simply start with z.

There are examples for the proper formatting to be used for headers, comments, etc. in both documents. Please have a look at them.

If coding errors can be difficult to find sometimes, they are generally easy to correct. It is not the case of the design errors. So please take time to well define your scientfic problem first, to check if the code is not already suited for your scientific question and if not, before starting to code a lot of lines, think about the technical implementation. It can be useful to "loose" some time at the beginning to define a good implementation.

2 Compiling

When you are making some developments in cosmo/cosmo-clm, please use some debug options to compile your code. It enables you to detect some coding errors that you would probably not detect otherwise.

In case of the PGI compiler, a meaningful set of debug options is for instance:

-O0 -c -Kieee -Mpreprocess -Mbyteswapio -Mfree -C -g -gopt -Mbounds -Mchkfpstk -Ktrap=fp -traceback -Minform=inform

(see below for the meaning of the options.)

Compile your code with this set of options or another meaningful set of debug options and RUN your code. The compilation is usually faster with the debug options and produce a little bit more verbose. The running is slower and will give you the errors if your code contains some. Don't worry if your code crashes. We all make some mistakes when coding new features. The debug options are there to help you detecting and correcting them.

Once your code crashes, try to understand and correct the error. A debugger like TotalView may help you to find the solution. You can find some documentation about TotalView at CSCS, on the COSMO page of the HYMET group (Prof. Schär) UsingTotalviewDebugger? or on the COSMO of ORGANIZATION.ORGMeteoSwiss at CSCS.

Once you have corrected all errors (i.e. your code compiles and runs after having been compiled with debug options), use optimization options again in order to produce code which runs fast.

Meaning of the proposed debug options

-O0: Specifies code optimization level (0, 1, 2, 3, or 4). For using the debug option, always use the lowest optimization level (i.e. 0).

-c: Instrument the generated executable to perform array bounds checking at runtime.

-Kieee: performs floating-point operations in strict conformance with the IEEE 754 standard.

-Mpreprocess: Run the preprocessor on the input source file regardless of the filename extension.

-Mbyteswapio: Swap bytes from big-endian to little-endian or vica versa on input and output of unformatted data.

-Mfree: Process source using Fortran 90 freeform input specifications.

-C: Generates code to check array bounds.

-g: Instructs the compiler to include symbolic debugging information in the object module.

-gopt: Instructs the compiler to include symbolic debugging information in the object file, and to generate optimized code identical to that generated when –g is not specified.

-Mbounds: Checks array bounds.

-Mchkfpstk: Checks for floating point exceptions (checks internal consistency of the x87 floating point stack in the prologue of a function and after returning from a function or subroutine call).

-Ktrap=fp: Controls the behavior of the processor when floating-point exceptions occur (fp, align, inv, denorm, divz, ovf, unf, inexact). The choice of fp traps the invalid operations, the divisions by zero and the overflows.

-traceback: Adds debug information for runtime traceback.

-Minform=inform: Specifies the minimum level of error severity that the compiler displays (fatal, file, inform, severe, warn). The choice of inform instructs the compiler to display all error messages.

If you are particularly interested in the PGI compiler, a complete documentation about the PGI compiler can be found on the PGI website. You should however not need to read it (500 pages!) before programing in cosmo/cosmo-clm. Just using the above proposed set of debug options on the Cray XT4 at CSCS should be sufficient.

-- AnneRoches - 26 May 2010

Attach
pdf
version 1 uploaded by AnneRoches on 07 Sep 2012 - 17:18
pdf
europ_sd.pdf (99.21K)
version 1 uploaded by AnneRoches on 07 Sep 2012 - 17:26
pdf
fortran.pdf (1952.10K)
version 1 uploaded by AnneRoches on 07 Sep 2012 - 17:32
spacer
This site is managed by the Center for Climate Systems Modeling (C2SM).
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors. Ideas, requests, problems? Send feedback!