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

% This file is part of Code_Saturne, a general-purpose CFD tool.
%
% Copyright (C) 1998-2018 EDF S.A.
%
% This program is free software; you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation; either version 2 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
% Street, Fifth Floor, Boston, MA 02110-1301, USA.

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Short doc CS class corresponding to article
\documentclass[a4paper,10pt,twoside]{csshortdoc}
% MACROS SUPPLEMENTAIRES
\usepackage{csmacros}
\usepackage{longtable}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PACKAGES ET COMMANDES POUR LE DOCUMENTS PDF ET LES HYPERLIENS
\hypersetup{%
  pdftitle = {CodeSaturne studymanager},
  pdfauthor = {MFEE},
  pdfpagemode = UseOutlines
}
\pdfinfo{/CreationDate (D:20110704000000-01 00 )}
%
% To have thumbnails upon opening the document under ACROREAD
% pdfpagemode = UseThumbs
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INFO POUR PAGES DE GARDES
\titreCS{\CS version~\verscs: studymanager}

\docassociesCS{}
\resumeCS{This document presents the tool studymanager. The aim of this script
is to drive \CS's cases automatically, to compare checkpoint files and
to display results.

\CS version~\verscs.

\begin{center}
\large{WORK IN PROGRESS}
\end{center}
}
%
\lstset{language=bash,
        keywordstyle=\color{blueedf},
        basicstyle=\small\ttfamily,
        commentstyle=\ttfamily\itshape\color{gray},
        stringstyle=\ttfamily,
        showstringspaces=false,
        breaklines=true,
        frameround=ffff,
        frame=single,
        rulecolor=\color{black},
        prebreak=\textbackslash,
        breakatwhitespace=true
}
%
\makeatletter
% command \noindentgroup to be used in a group
\newcommand*\noindentgroup{\@@par   % clear parshape parameters
% fool list-awareness code (as supposedly in lstlisting, not checked)
      \@totalleftmargin\z@ \@listdepth\z@ \rightmargin\z@
}
\makeatother
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DEBUT DU DOCUMENT
\begin{document}

\def\contentsname{\textbf{\normalsize TABLE OF CONTENTS}\pdfbookmark[1]{Table of
contents}{contents}}

\renewcommand{\logocs}{cs_logo_wave}

\pdfbookmark[1]{Flyleaf}{pdg}
\large
\makepdgCS
\normalsize

\passepage

\begin{center}\begin{singlespace}
\tableofcontents
\end{singlespace}\end{center}
%
\section{Introduction}

\textsc{studymanager} is a small framework to automate the launch of \CS
computations and do some operations on new results.

The script needs a directory of previous \CS cases which are candidates to be
duplicated. This directory is called \textbf{repository}. The duplication is
done in a new directory which is called the \textbf{destination}.

For each duplicated case, \textsc{studymanager} is able to compile the user
files, to run the case, to compare the obtained checkpoint file with the
previous one from the \textbf{repository}, and to plot curves in order to
illustrate the computations.

For all these steps, \textsc{studymanager} generate two reports,
a global report which summarizes the status of each case, and a detailed report
which gives the
differences between the new results and the previous ones in the
\textbf{repository}, and display the defined plots.

In the \textbf{repository}, previous results of computations are required only
for checkpoint files comparison purpose. They can be also useful, if the user
needs to run specific scripts.

\section{Installation and prerequisites}

\textsc{studymanager} does not need a specific installation: the related files
are installed with the other Python scripts of \CS. Nevertheless, additional
prerequisites required are:
\begin{list}{$\bullet$}{}
\item \texttt{numpy},
\item \texttt{matplotlib},
\end{list}

\section{Command line options}

The command line options can be found with the command: \texttt{code\_saturne
studymanager -h}.

\begin{list}{$\bullet$}{}
\item \texttt{-h, --help}: show the help message and exit
\item \texttt{-f FILE, --file=FILE}: give the file of parameters for
\textsc{studymanager}. This file is mandatory, and therefore this option must be
completed
\item \texttt{-q, --quiet}: do not print status messages to stdout
\item \texttt{-u, --update}: update installation pathes in scripts (i.e. \texttt{SaturneGUI} and
  \texttt{runcase}) only in the repository, reinitialize XML files of parameters and compile
\item \texttt{-x, --update-xml}: update only XML files in the repository
\item \texttt{-t, --test-compile}: compile all cases
\item \texttt{-r, --run}: run all cases
\item \texttt{-n N\_ITERATIONS, --n-iterations=N\_ITERATIONS}: maximum number of iterations for cases of the study
\item \texttt{-c, --compare}: compare chekpoint files between \textbf{repository} and \textbf{destination}
\item \texttt{-d REFERENCE, --ref-dir=REFERENCE}: absolute reference directory to compare dest with
\item \texttt{-p, --post}: postprocess results of computations
\item \texttt{-m ADDRESS1 ADDRESS2 ..., --mail=ADDRESS1 ADDRESS2 ...}: addresses for sending the reports
\item \texttt{-l LOG\_FILE, --log=LOG\_FILE}: name of studymanager log file (default value is 'studymanager.log')
\item \texttt{-z, --disable-tex}: disable text rendering with \LaTeX when plotting with Matplotlib. It then uses Mathtext instead which is less complete
\item \texttt{--rm}: remove all existing run directories in destination directory
\item \texttt{--fow}: overwrite files in MESH and POST directories in destination directory
\item \texttt{-s, --skip-pdflatex}: disable tex reports compilation with pdflatex
\item \texttt{--fmt=DEFAULT\_FMT}: set the global format for exporting matplotlib figure (default is pdf)
\item \texttt{--repo=REPO\_PATH}: force the path to the repository directory
\item \texttt{--dest=DEST\_PATH}: force the path to the destination directory
\item \texttt{-g, --debug}: activate debugging mode
\item \texttt{--with-tags=WITH\_TAGS}: only process runs with all specified tags (separated by commas)
\item \texttt{--without-tags=WITHOUT\_TAGS}: exclude any run with one of specified tags (separated by commas)
\end{list}

\underline{Examples:}

\begin{list}{$\bullet$}{}
\item duplicates all cases from the \textbf{repository} in the \textbf{destination}, compile all user files and exits;
{\noindentgroup\begin{lstlisting}
$ code_saturne studymanager -f sample.xml
\end{lstlisting}}

\item as above, and run all cases if defined in \texttt{sample.xml}
{\noindentgroup\begin{lstlisting}
$ code_saturne studymanager -f sample.xml -r
\end{lstlisting}}

\item as above, and compares all new checkpoint files with those from the \textbf{repository} if defined in \texttt{sample.xml}
{\noindentgroup\begin{lstlisting}
$ code\_saturne smgr -f sample.xml -r -c
\end{lstlisting}}

\item as above, and plots results if defined in \texttt{sample.xml}
{\noindentgroup\begin{lstlisting}
$ code_saturne smgr -f sample.xml -rcp
\end{lstlisting}}

\item as above, and send the two reports
{\noindentgroup\begin{lstlisting}
$ code_saturne smgr -f sample.xml -r -c -p -m "dt@moulinsart.be dd@moulinsart.be"
\end{lstlisting}}

\item compares and plots results in the \textbf{destination} already computed
{\noindentgroup\begin{lstlisting}
$ code_saturne smgr -f sample.xml -c -p
\end{lstlisting}}

\item compares and plots results in the \textbf{destination} already computed
{\noindentgroup\begin{lstlisting}
$ code_saturne smgr -f sample.xml -c -p
\end{lstlisting}}

\item run cases tagged "coarse" (standing for coarse mesh for example) \underline{and} "hr" (standing for high Reynolds for example) only for 2 time iterations in destination directory of path \texttt{../RUNS/RIBS} (\texttt{RIBS} will be created, \texttt{RUNS} already exists). The command is launched from inside the study directory, hence the repository which has to be the directory containing the original study is simply indicated by \texttt{..}
{\noindentgroup\begin{lstlisting}
$ code_saturne smgr -f smgr_ribs.xml -r -n 2 --with-tags=coarse,hr --dest=../RUNS/RIBS --repo=..
\end{lstlisting}}
\end{list}

\underline{Note:}

The detailed report is generated only if the options \texttt{-c, --compare}
or \texttt{-p, --post} is present in the command line.

\section{File of parameters}

The file of parameters is a XML formatted ascii file.

\subsection{Begin and end of the file of parameters}

This example shows the four mandatory first lines of the file of parameters.

\small
\begin{verbatim}
<?xml version="1.0"?>
<studymanager>
    <repository>/home/dupond/codesaturne/MyRepository</repository>
    <destination>/home/dupond/codesaturne/MyDestination</destination>
\end{verbatim}
\normalsize

The third and fourth lines correspond to the definition of the
\textbf{repository} and \textbf{destination} directories.
Inside the markups \texttt{<repository>} and \texttt{<destination>} the user
must inform the related directories. If the \textbf{destination} does not exit,
the directory is created.

The last line of the file of parameters must be:

\small
\begin{verbatim}
</studymanager>
\end{verbatim}
\normalsize

\subsection{Case creation and compilation fo the user files}

When \textsc{studymanager} is launched, the file of parameters is parsed in order to
known which studies and cases from the \textbf{repository} should be duplicated
in the \textbf{destination}. The selection is done with the markups
\texttt{<study>} and \texttt{<case>} as the following example:

\small
\begin{verbatim}
<?xml version="1.0"?>
<studymanager>
    <repository>/home/dupond/codesaturne/MyRepository</repository>
    <destination>/home/dupond/codesaturne/MyDestination</destination>

    <study label="MyStudy1" status="on">
        <case label="Grid1" run_id="Grid1" status="on" compute="on" post="off"/>
        <case label="Grid2" run_id="Grid2" status="off" compute="on" post="off"/>
    </study>
    <study label="MyStudy2" status="off">
        <case label="k-eps" status="on" compute="on" post="off"/>
        <case label="Rij-eps" status="on" compute="on" post="off"/>
    </study>
</studymanager>
\end{verbatim}
\normalsize

The attributes are:
\begin{list}{$\bullet$}{}
\item \texttt{label}: the name of the file of the script;
\item \texttt{status}: must be equal to \texttt{on} or \texttt{off},
activate or deactivate the markup;
\item \texttt{compute}: must be equal to \texttt{on} or \texttt{off},
activate or deactivate the computation of the case;
\item \texttt{post}: must be equal to \texttt{on} or \texttt{off},
activate or deactivate the post-processing of the case;
\item \texttt{run\_id}: name of the run directory (sub-directory of \texttt{RESU}) in which the result
is stored. This attribute is optional. If it is not set (or if set to \texttt{run\_id=""}), an
automatic value will be proposed by the code (usually based on current date and time).
\item \texttt{tags}: possible tags distinguishing the run from the others in the same XML parameter file (ex.: \texttt{tags="coarse,high-reynolds"}).
\end{list}

Only the attributes \texttt{label}, \texttt{status}, \texttt{compute}
and \texttt{post} are mandatory.

If the directory specified by the attribute \texttt{run\_id} already exists,
the computation is not performed again. For the post-processing step, the existing
results are taken into accout only if no error file is detected in the
directory.

With the attribute \texttt{status}, a single case or a complete study can be
switched off. In the above example, only the case \texttt{Grid1} of the study
\texttt{MyStudy1} is going to be created.

After the creation of the directories in the \textbf{destination}, for each
case, all user files are compiled. The \textsc{studymanager} stops if a compilation
error occurs: neither computation nor comparison nor plot will be performed,
even if they are switched on.

\underline{Notes:}

\begin{list}{$\bullet$}{}
\item During the duplication, every files are copied, except mesh files, for
which a symbolic link is used.
\item During the duplication, if a file already exists in the
\textbf{destination}, this file is not overwritten by \textsc{studymanager} by default.
\end{list}


\subsection{Run cases}\label{sec:run}

The computations are activated if the option \texttt{-r, --run} is present in
the command line.

All cases described in the file of parameters with the attribute
\texttt{compute="on"} are taken into account.

\small
\begin{verbatim}
<?xml version="1.0"?>
<studymanager>
    <repository>/home/dupond/codesaturne/MyRepository</repository>
    <destination>/home/dupond/codesaturne/MyDestination</destination>

    <study label="MyStudy1" status="on">
        <case label="Grid1" status="on" compute="on" post="off"/>
        <case label="Grid2" status="on" compute="off" post="off"/>
    </study>
    <study label="MyStudy2" status="on">
        <case label="k-eps" status="on" compute="on" post="off"/>
        <case label="Rij-eps" status="on" compute="on" post="off"/>
    </study>
</studymanager>
\end{verbatim}
\normalsize

After the computation, if no error occurs, the attribute \texttt{compute} is set
to \texttt{"off"} in the copy of the file of parameters in the
\textbf{destination}. It is allow to restart \textsc{studymanager} without re-run
successfull previous computations.

Note that it is allowed to run several times the same case in a given study.
The case has to be repeated in the file of parameters:

\small
\begin{verbatim}
<?xml version="1.0"?>
<studymanager>
    <repository>/home/dupond/codesaturne/MyRepository</repository>
    <destination>/home/dupond/codesaturne/MyDestination</destination>

    <study label="MyStudy1" status="on">
        <case label="CASE1" run_id="Grid1" status="on" compute="on" post="on">
            <prepro label="grid.py" args="-m grid1.med -p cas.xml" status="on"/>
        </case>
        <case label="CASE1" run_id="Grid2" status="on" compute="on" post="on"/>
            <prepro label="grid.py" args="-m grid2.med -p cas.xml" status="on"/>
        </case>
    </study>
</studymanager>
\end{verbatim}
\normalsize

If nothing is done, the case is repeated without modifications. In order to modify
the setup between two runs of the same case, an external script has to be used to
change the related setup (see sections \ref{sec:prepro} and \ref{sec:tricks}).

\subsection{Compare checkpoint files}

The comparison is activated if the option \texttt{-c, --compare} is present in
the command line.

In order to compare two checkpoint files for a given case, a markup
\texttt{<compare>} has to be added as child of the considered case.
In the following exemple, a checkpoint file comparison is switched on for the
case \textit{Grid1} (for all
variables, with the default threshold), whereas no comparison is planed for
the case \textit{Grid2}. The comparison is done by the external
script \texttt{cs\_io\_dump} with the option \texttt{--diff}.

\small
\begin{verbatim}
<study label='MyStudy1' status='on'>
    <case label='Grid1' status='on' compute="on" post="off">
        <compare dest="" repo="" status="on"/>
    </case>
    <case label='Grid2' status='on' compute="off" post="off"/>
</study>
\end{verbatim}
\normalsize

The attributes are:
\begin{list}{$\bullet$}{}

\item \texttt{repo}: id of the results directory in the \textbf{repository} for
example \texttt{repo="20110704-1116"}, if there is a single results directory
in the \texttt{RESU} directory of the case, the id can be ommitted:
\texttt{repo=""};

\item \texttt{dest}: id of the results directory in the \textbf{destination}:
\begin{list}{$\rightarrow$}{}
\item if the id is not known already because the case has not yet run, just let
the attribute empty \texttt{dest=""}, the value will be updated after the run
step in the \textbf{destination} directory (see section \ref{sec:restart});
\item if \textsc{studymanager} is restarted without the run step (with the command
line \texttt{code\_saturne studymanager -f sample.xml -c} for example), the id of
the results directory in the \textbf{destination} must be given (for example
\texttt{dest="20110706-1523"}), but if there is a single results directory in
the \texttt{RESU} directory of the case, the id can be ommitted:
\texttt{dest=""}, the id will be completed automatically;
\end{list}

\item \texttt{args}: additional options for the script \texttt{cs\_io\_dump}
\begin{list}{$\diamond$}{}
\item \texttt{--section}: name of a particular variable;
\item \texttt{--threshold}: real value above which a difference is considered
significant (default: $1e-30$ for all variables);
\end{list}
\item \texttt{status}: must be equal to \texttt{on} or \texttt{off}:
activate or desactivate the markup.
\end{list}

Only the attributes \texttt{repo}, \texttt{dest} and \texttt{status} are
mandatory.

Several comparisons with different options are permitted:
\small
\begin{verbatim}
<study label='MyStudy1' status='on'>
    <case label='Grid1' status='on' compute="on" post="off">
        <compare dest="" repo="" args="--section Pressure --threshold=1000" status="on"/>
        <compare dest="" repo="" args="--section VelocityX --threshold=1e-5" status="on"/>
        <compare dest="" repo="" args="--section VelocityY --threshold=1e-3" status="on"/>
    </case>
</study>
\end{verbatim}
\normalsize

Comparisons results will be sumarized in a table in the file
\texttt{report\_detailed.pdf}  (see \ref{sec:restart}):

\begin{center}
\begin{longtable}{|l|l|l|l|}
\hline
\textbf{Variable Name} &\textbf{Diff. Max} &\textbf{Diff. Mean} &\textbf{Threshold} \\
\hline
\hline
VelocityX &0.102701 &0.00307058 &1.0e-5 \\
\hline
VelocityY &0.364351 &0.00764912 &1.0e-3 \\
\hline
\end{longtable}
\end{center}

Alternatively, in order to compare all activated cases (status at on) listed
in a \textsc{studymanager} parameter file, a reference directory can be provided
directly in the command line, as follows:

\texttt{code\_saturne studymanager -f sample.xml -c -d /scratch/***/reference\_destination\_directory}.

\subsection{Run external additional preprocessing scripts with options}\label{sec:prepro}

The markup \texttt{<prepro>} has to be added as a child of the condidered case.

\small
\begin{verbatim}
<study label='STUDY' status='on'>
    <case label='CASE1' status='on' compute="on" post="on">
        <prepro label="mesh_coarse.py" args="-n 1" status="on"/>
    </case>
</study>
\end{verbatim}
\normalsize

The attributes are:
\begin{list}{$\bullet$}{}
\item \texttt{label}: the name of the file of the considered script;
\item \texttt{status}: must be equal to \texttt{on} or \texttt{off}:
activate or desactivate the markup;
\item \texttt{args}: additional options to pass to the script.
\end{list}

Only the attributes \texttt{label} and \texttt{status} are mandatory.

An addionnal option \texttt{"-c"} (or \texttt{"--case"}) is given by
default with the path of the current case as argument (see exemple in
section \ref{sec:tricks} for decoding options).

Note that all options must be processed by the script itself.

Several calls of the same script or to different scripts are permitted:
\small
\begin{verbatim}
<study label="STUDY" status="on">
    <case label="CASE1" status="on" compute="on" post="on">
        <prepro label="script_pre1.py" args="-n 1" status="on"/>
        <prepro label="script_pre2.py" args="-n 2" status="on"/>
    </case>
</study>
\end{verbatim}
\normalsize

All preprocessing scripts are first searched in the \texttt{MESH} directory
from the current study in the \textbf{repository}. If a script is not found,
it is searched in the directories of te current case.
The main objectif of running such external scripts is to create or modify
meshes or to modify the current setup of the related case (see section
\ref{sec:tricks}).

\subsection{Run external additional postprocessing scripts with options for a case}

The launch of external scripts is activated if the option \texttt{-p, --post}
is present in the command line.

The markup \texttt{<script>} has to be added as a child of the condidered case.

\small
\begin{verbatim}
<study label='STUDY' status='on'>
    <case label='CASE1' status='on' compute="on" post="on">
        <script label="script_post.py" args="-n 1" dest="" repo="20110216-2147" status="on"/>
    </case>
</study>
\end{verbatim}
\normalsize

The attributes are:
\begin{list}{$\bullet$}{}
\item \texttt{label}: the name of the file of the considered script;
\item \texttt{status}: must be equal to \texttt{on} or \texttt{off}:
activate or desactivate the markup;
\item \texttt{args}: the arguments to pass to the script;
\item \texttt{repo} and \texttt{dest}: id of the results directory in the
\textbf{repository} or in the \textbf{destination};
\begin{list}{$\rightarrow$}{}
\item if the id is not known already because the case has not yet run, just let
the attribute empty \texttt{dest=""}, the value will be updated after the run
step in the \textbf{destination} directory (see section \ref{sec:restart});
\item if there is a single results directory in the \texttt{RESU} directory
(either in the \textbf{repository} or in the \textbf{destination}) of the case,
the id can be ommitted: \texttt{repo=""} or \texttt{dest=""}, the id will be
completed automatically.
\end{list}
If attributes \texttt{repo} and \texttt{dest} exist, their associated value
will be passed to the script as arguments, with options \texttt{"-r"} and
\texttt{"-d"} respectively.
\end{list}

Only the attributes \texttt{label} and \texttt{status} are mandatory.

Several calls of the same script or to different scripts are permitted:
\small
\begin{verbatim}
<study label="STUDY" status="on">
    <case label="CASE1" status="on" compute="on" post="on">
        <script label="script_post.py" args="-n 1" status="on"/>
        <script label="script_post.py" args="-n 2" status="on"/>
        <script label="script_post.py" args="-n 3" status="on"/>
        <script label="another_script.py" status="on"/>
    </case>
</study>
\end{verbatim}
\normalsize

All postprocessing scripts must be in the \texttt{POST} directory from
the current study in the \textbf{repository}.
The main objectif of running external scripts is to create or modify
results in order to plot them.

Example of script, which searches printed informations in the listing,
note the function to process the passed command line arguments:
\small
\begin{verbatim}
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys
import string
from optparse import OptionParser

def process_cmd_line(argv):
    """Processes the passed command line arguments."""
    parser = OptionParser(usage="usage: %prog [options]")

    parser.add_option("-r", "--repo", dest="repo", type="string",
                      help="Directory of the result in the repository")

    parser.add_option("-d", "--dest", dest="dest", type="string",
                      help="Directory of the result in the destination")

    (options, args) = parser.parse_args(argv)
    return options

def main(options):
    m = os.path.join(options.dest, "listing")
    f = open(m)
    lines = f.readlines()
    f.close()

    g = open(os.path.join(options.dest, "water_level.dat"), "w")
    g.write("# time,   h_sim,   h_th\n")
    for l in lines:
       if l.rfind("time, h_sim, h_th") == 0:
           d = l.split()
           g.write("%s  %s  %s\n" % (d[3], d[4], d[5]))
    g.close()

if __name__ == '__main__':
    options = process_cmd_line(sys.argv[1:])
    main(options)
\end{verbatim}
\normalsize

\subsection{Run external additional postprocessing scripts with options for a study}

The launch of external scripts is activated if the option \texttt{-p, --post}
is present in the command line.

The purpose of this functionality is to create new data based on several runs of
cases, and to plot them (see section \ref{sec:curves}) or to insert them in the
final detailed report (see section \ref{sec:input}).

The markup \texttt{<postpro>} has to be added as a child of the considered study.

\small
\begin{verbatim}
<study label='STUDY' status='on'>
    <case label='CASE1' status='on' compute="on" post="on"/>
    <postpro label='Grid2.py' status="on" arg="-n 100">
        <data file="profile.dat">
            <plot fig="1" xcol="1" ycol="2" legend="Grid level 2" fmt='b-p'/>
            <plot fig="2" xcol="1" ycol="3" legend="Grid level 2" fmt='b-p'/>
        </data>
    <input file="output.dat" dest=""/>
    </postpro>
</study>
\end{verbatim}
\normalsize

The attributes are:
\begin{list}{$\bullet$}{}
\item \texttt{label}: the name of the file of the considered script;
\item \texttt{status}: must be equal to \texttt{on} or \texttt{off}:
activate or desactivate the markup;
\item \texttt{args}: the additional options to pass to the script;
\end{list}

Only the attributes \texttt{label} and \texttt{status} are mandatory.

The options given to the script in the command line are:
\begin{list}{$\bullet$}{}
\item \texttt{-s} or \texttt{--study}: label of the current study;
\item \texttt{-c} or \texttt{--cases}: string which contains the list of the cases
\item \texttt{-d} or \texttt{--directories}: string which contains the list
of the directories of results.
\end{list}
Additional options can be pass to the script throught the attributes \texttt{args}.

Note that all options must be processed by the script itself.

Several calls of the same script or to different scripts are permitted.

\subsection{Post-processing: curves}\label{sec:curves}

The post-processing is activated if the option \texttt{-p, --post} is present
in the command line.

The following example shows the drawing of four curves (or plots, or 2D lines)
from two files of data (which have the same name \texttt{profile.dat}). There
are two subsets of curves (i.e. frames with axis and 2D lines), in a single
figure. The figure will be saved on the disk in a \textbf{pdf} (default)
or \textbf{png} format, in the \texttt{POST} directory of the related study
in the \textbf{destination}. Each drawing of a single curve is defined as a
markup child of a file of data inside a case. Subsets and figures are defined
as markup children of \texttt{<study>}.

\small
\begin{verbatim}
<study label='Study' status='on'>
    <case label='Grid1' status='on' compute="off" post="on">
        <data file="profile.dat" dest="">
            <plot fig="1" xcol="1" ycol="2" legend="Grid level 1" fmt='r-s'/>
            <plot fig="2" xcol="1" ycol="3" legend="Grid level 1" fmt='r-s'/>
        </data>
    </case>
    <case label='Grid2' status='on' compute="off" post="on">
        <data file="profile.dat" dest="">
            <plot fig="1" xcol="1" ycol="2" legend="Grid level 2" fmt='b-p'/>
            <plot fig="2" xcol="1" ycol="3" legend="Grid level 2" fmt='b-p'/>
        </data>
    </case>
    <subplot id="1" legstatus='on' legpos ='0.95 0.95' ylabel="U ($m/s$)" xlabel="Time ($s$)"/>
    <subplot id="2" legstatus='on' legpos ='0.95 0.95' ylabel="U ($m/s$)" xlabel="Time ($s$)"/>
    <figure name="velocity" idlist="1 2" figsize="(4,5)" format="png"/>
</study>
\end{verbatim}
\normalsize

\subsubsection{Define curves}

The curves of computational data are build from data files. These data must be
ordered as column and the files should be in results directory in the
\texttt{RESU} directory (either in the \textbf{repository} or in the
\textbf{destination}). Commentaries are allowed in the file, the head of every
commentary line must start with character \texttt{\#}.

In the file of parameters, curves are defined with two markups:
\texttt{<data>} and \texttt{<plot>}:

\begin{list}{$\bullet$}{}
\item \texttt{<data>}: child of markup \texttt{<case>}, defines a file of data;
\begin{list}{$\rightarrow$}{}
\item \texttt{file}: name of the file of data
\item \texttt{repo} or \texttt{dest}: id of the results directory either in the
\textbf{repository} or in the \textbf{destination};
\begin{list}{$\Rightarrow$}{}
\item if the id is not known already because the case has not yet run, just let
the attribute empty \texttt{dest=""}, the value will be updated after the run
step in the \textbf{destination} directory (see section \ref{sec:restart});
\item if there is a single results directory in the \texttt{RESU} directory
(either in the \textbf{repository} or in the \textbf{destination}) of the case,
the id can be ommitted: \texttt{repo=""} or \texttt{dest=""}, the id will be
completed automatically.
\end{list}
\end{list}
The attribute \texttt{file} is mandatory, and either \texttt{repo} or
\texttt{dest} must be present (but not the both) even if it is empty.

\item \texttt{<plot>}: child of markup \texttt{<data>}, defines a single
curve; the attributes are:
\begin{list}{$\rightarrow$}{}
\item \texttt{fig}: id of the subset of curves (i.e. markup \texttt{<subplot>})
where the current curve should be plotted;
\item \texttt{xcol}: number of the column in the file of data for the abscisse;
\item \texttt{ycol}: number of the column in the file of data for the ordinate;
\item \texttt{legend}: add a label to a curve;
\item \texttt{fmt}: format of the line, composed from a symbol, a color and a
linestyle, for example \texttt{fmt="r--"} for a dashed red line;
\item \texttt{xplus}: real to add to all values of the column \texttt{xcol};
\item \texttt{yplus}: real to add to all values of the column \texttt{ycol};
\item \texttt{xfois}: real to multiply to all values of the column
\texttt{xcol};
\item \texttt{yfois}: real to multiply to all values of the column
\texttt{ycol};
\item \texttt{xerr} or \texttt{xerrp}: draw horizontal error bar (see section \ref{sec:err});
\item \texttt{yerr} or \texttt{yerrp}: draw vertical error bar (see section \ref{sec:err});
\item some standard options of 2D lines can be added, for example
\texttt{markevery="2"} or \texttt{markersize="3.5"}. These options
are summarized in the table \ref{table:curves}. Note that the options
which are string of characters must be overquoted likes this:
\texttt{color="'g'"}.

\begin{table}[htbp]
\begin{center}
\begin{tabular}{|l|l|}
\hline
\textbf{Property} & \textbf{Value Type} \\
\hline
alpha & float (0.0 transparent through 1.0 opaque) \\
antialiased or aa & \texttt{True} or \texttt{False} \\
color or c & any matplotlib color \\
dash\_capstyle & \texttt{butt}; \texttt{round}; \texttt{projecting} \\
dash\_joinstyle & \texttt{miter}; \texttt{round}; \texttt{bevel} \\
dashes & sequence of on/off ink in points ex: \texttt{dashes="(5,3)"} \\
label & any string, same as legend\\
linestyle or ls &  \texttt{-}; \texttt{--}; \texttt{-.}; \texttt{:}; \texttt{steps}; ... \\
linewidth or lw & float value in points \\
marker &  \texttt{+}; \texttt{,}; \texttt{.}; \texttt{1}; \texttt{2}; \texttt{3}; \texttt{4}; ... \\
markeredgecolor or mec & any matplotlib color \\
markeredgewidth or mew & float value in points \\
markerfacecolor or mfc & any matplotlib color \\
markersize or ms & float \\
markevery & \texttt{None}; integer; (startind, stride) \\
solid\_capstyle & \texttt{butt}; \texttt{round}; \texttt{projecting} \\
solid\_joinstyle & \texttt{miter}; \texttt{round}; \texttt{bevel} \\
zorder & any number \\
\hline
\end{tabular}
\end{center}
\caption{Options authorized as attributes of the markup \texttt{plot}.}
\label{table:curves}
\end{table}

\end{list}
\end{list}

The attributes \texttt{fig} and \texttt{ycol} are mandatory.

In case a column should undergo a transformation specified by the attributes
\texttt{xfois},\texttt{yfois},\texttt{xplus},\texttt{yplus}, scale operations
take precedence over translation operations.

Details on 2D lines properties can be found in the \texttt{matplotlib}
documentation. For more advanced options see section \ref{sec:raw}.

\subsubsection{Define subsets of curves}

A subset of curves is a frame with two axis, axis labels, legend, title and
drawing of curves inside. Such subset is called subplot in the nomenclature
of \texttt{matplotlib}.

\texttt{<subplot>}: child of markup \texttt{<study>}, defines a frame with
severals curves; the attributes are:
\begin{list}{$\rightarrow$}{}
\item \texttt{id}: id of the subplot, should be an integer;
\item \texttt{legstatus}: if \texttt{"on"} display the frame of the legend;
\item \texttt{legpos}: sequence of the relative coordinates of the center of
the legend, it is possible to draw the legend outside the axis;
\item \texttt{title}: set title of the subplot;
\item \texttt{xlabel}: set label for the x axis;
\item \texttt{ylabel}: set label for the y axis;
\item \texttt{xlim}: set range for the x axis;
\item \texttt{ylim}: set range for the y axis.
\end{list}

The attributes \texttt{fig} and \texttt{ycol} are mandatory.

For more advanced options see section \ref{sec:raw}.

\subsubsection{Define figures}

Figure is a compound of subset of curves.

\texttt{<figure>}: child of markup \texttt{<study>}, defines a pictures
with a layout of frames; the attributes are:
\begin{list}{$\rightarrow$}{}
\item \texttt{name}: name of the file to be written on the disk;
\item \texttt{idlist}: list of the subplot to be displayed in the figure;
\item \texttt{title}: add a title on the top of the figure;
\item \texttt{nbrow}: impose a number of row of the layout of the subplots;
\item \texttt{nbcol}: impose a number of column of the layout of the subplots;
\item \texttt{format}: format of the file to be written on the disk,
\texttt{"pdf"} (default) or \texttt{"png"} \footnote{Other format could
be choosen (eps, ps, svg,...), but the pdf generation with pdflatex will failed.};
\item \texttt{figsize}: width x height in inches; defaults to (4,4);
\item \texttt{dpi}: resolution; defaults to 200 if format is set to pdf;
or to 800 if format is set to png; only customizable for png format.
\end{list}

The attributes \texttt{name} and \texttt{idlist} are mandatory.

\subsubsection{Experimental or analytical data}

A particular markup is provided for curves of experimental or analytical data:
\texttt{<measurement>}; the attributes are:
\begin{list}{$\rightarrow$}{}
\item \texttt{file}: name of the file to be read on the disk;
\item \texttt{path}: path of the directory where the file of data
is. the path could be ommitted (\texttt{path=""}), and in this case, the file
will be searched recursively in the directories of the considered study.
\end{list}

The attributes \texttt{file} and \texttt{path} are mandatory.

In order to draw curves of experimental or analytical data, the markup \texttt{<measurement>}
should be used with the markup \texttt{<plot>} as illustrated below:

\small
\begin{verbatim}
<study label='MyStudy' status='on'>
    <measurement file='exp1.dat' path=''>
            <plot fig='1' xcol='1' ycol='2' legend='U Experimental data'/>
            <plot fig='2' xcol='3' ycol='4' legend='V Experimental data'/>
    </measurement>
    <measurement file='exp2.dat' path =''>
            <plot fig='1' xcol='1' ycol='2' legend='U Experimental data'/>
            <plot fig='2' xcol='1' ycol='3' legend='V Experimental data'/>
    </measurement>
    <case label='Grid1' status='on' compute="off" post="on">
        <data file="profile.dat" dest="">
            <plot fig="1" xcol="1" ycol="2" legend="U computed" fmt='r-s'/>
            <plot fig="2" xcol="1" ycol="3" legend="V computed" fmt='b-s'/>
        </data>
    </case>
</study>
<subplot id="1" legstatus='on'  ylabel="U ($m/s$)" xlabel= "$r$ ($m$)" legpos ='0.05 0.1'/>
<subplot id="2" legstatus='off' ylabel="V ($m/s$)" xlabel= "$r$ ($m$)"/>
<figure name="MyFigure" idlist="1 2"  figsize="(4,4)" />
\end{verbatim}
\normalsize

\subsubsection{Curves with error bar}\label{sec:err}

In order to draw horizontal and vertical error bars, it is possible to
specify to the markup \texttt{<plot>} the attributes \texttt{xerr} and
\texttt{yerr} respectively (or \texttt{xerrp} and \texttt{yerrp}). The
value of these attributes could be:
\begin{list}{$\bullet$}{}
\item the number of the column, in the file of data, that contains the total
absolute uncertainty spans:
\small
\begin{verbatim}
<measurement file='axis.dat' path =''>
    <plot fig='1' xcol='1' ycol='3' legend='Experimental data' xerr='2' />
</measurement>
\end{verbatim}
\normalsize
\item the numbers of the two columns, in the file of data, that contain the
absolute low spans and absolute high spans of uncertainty:
\small
\begin{verbatim}
<data file='profile.dat' dest="">
    <plot fig='1' xcol='1' ycol='2' legend='computation' yerr='3 4' />
</data>
\end{verbatim}
\normalsize
\item a single real value equal to the percentage of uncertainty that should be
applied to the considered data set:
\small
\begin{verbatim}
<data file='profile.dat' dest="">
    <plot fig='1' xcol='1' ycol='2' legend='computation' yerrp='2.' />
</data>
\end{verbatim}
\normalsize
\end{list}

\subsubsection{Monitoring points or probes}

A particular markup is provided for curves of probes data:
\texttt{<probes>}; the attributes are:

\begin{list}{$\bullet$}{}
\item \texttt{file}: name of the file to be read on the disk;
\item \texttt{fig}: id of the subset of curves (i.e. markup \texttt{<subplot>})
where the current curve should be plotted;
\item \texttt{dest}: id of the results directory in the \textbf{destination}:
\begin{list}{$\rightarrow$}{}
\item if the id is not known already because the case has not yet run, just let
the attribute empty \texttt{dest=""}, the value will be updated after the run
step in the \textbf{destination} directory (see section \ref{sec:restart});
\item if \textsc{studymanager} is restarted without the run step (with the command
line \texttt{code\_saturne studymanager -f sample.xml -c} for example), the id of
the results directory in the \textbf{destination} must be given (for example
\texttt{dest="20110706-1523"}), but if there is a single results directory in
the \texttt{RESU} directory of the case, the id can be ommitted:
\texttt{dest=""}, the id will be completed automatically;
\end{list}
\end{list}

The attributes \texttt{file}, \texttt{fig} and \texttt{dest} are mandatory.

In order to draw curves of probes data, the markup \texttt{<probes>}
should be used as a child of a markup \texttt{<case>} as illustrated below:

\small
\begin{verbatim}
<study label='MyStudy' status='on'>
    <measurement file='exp1.dat' path=''>
        <plot fig='1' xcol='1' ycol='2' legend='U Experimental data'/>
    </measurement>
    <case label='Grid1' status='on' compute="off" post="on">
        <probes file="probes_U.dat" fig ="2" dest="">
        <data file="profile.dat" dest="">
            <plot fig="1" xcol="1" ycol="2" legend="U computed" fmt='r-s'/>
        </data>
    </case>
</study>
<subplot id="1" legstatus='on'  ylabel="U ($m/s$)" xlabel= "$r$ ($m$)" legpos ='0.05 0.1'/>
<subplot id="2" legstatus='on'  ylabel="U ($m/s$)" xlabel= "$time$ ($s$)" legpos ='0.05 0.1'/>
<figure title="Results" name="MyFigure" idlist="1"/>
<figure title="Grid1: probes for velocity"  name="MyProbes" idlist="2"/>
\end{verbatim}
\normalsize

\subsubsection{Matplotlib raw commands}\label{sec:raw}

The file of parameters allows to execute additional matplotlib commands (i.e
Python commands), for curves (2D lines), or subplot, or figure. For every object
drawn, \texttt{studymanager} associate a name to this object that can be reused in
standard matplotlib commands. Therefore, children markup \texttt{<plt\_command>}
could be added to \texttt{<plot>}, \texttt{<subplot>} or \texttt{<figure>}.

It is possible to add commands with \textbf{Matlab style} or \textbf{Python
style}. For the Matlab style, commands are called as methods of the module
\texttt{plt}, and for Python style commands or called as methods of the instance
of the graphical object.

Matlab style and Python style commands can be mixed.

\begin{list}{$\bullet$}{}

\item curves or 2D lines: when a curve is drawn, the associated name
are \texttt{line} and \texttt{lines} (with \texttt{line = lines[0]}).

\small
\begin{verbatim}
<plot fig="1" xcol="1" ycol="2" fmt='g^' legend="Simulated water level">
    <plt_command>plt.setp(line, color="blue")</plt_command>
    <plt_command>line.set_alpha(0.5)</plt_command>
</plot>
\end{verbatim}
\normalsize

\item subset of curves (subplot): for each subset, the associated name is \texttt{ax}:

\small
\begin{verbatim}
<subplot id="1" legend='Yes' legpos ='0.2 0.95'>
    <plt_command>plt.grid(True)</plt_command>
    <plt_command>plt.xlim(0, 20)</plt_command>
    <plt_command>ax.set_ylim(1, 3)</plt_command>
    <plt_command>plt.xlabel(r"Time ($s$)", fontsize=8)</plt_command>
    <plt_command>ax.set_ylabel(r"Level ($m$)", fontsize=8)</plt_command>
    <plt_command>for l in ax.xaxis.get_ticklabels(): l.set_fontsize(8)</plt_command>
    <plt_command>for l in ax.yaxis.get_ticklabels(): l.set_fontsize(8)</plt_command>
    <plt_command>plt.axis([-0.05, 1.6, 0.0, 0.15])</plt_command>
    <plt_command>plt.xticks([-3, -2, -1, 0, 1])</plt_command>
</subplot>
\end{verbatim}
\normalsize


\end{list}

\subsection{Post-processing: input files}\label{sec:input}

The post-processing is activated if the option \texttt{-p, --post} is present
in the command line.

\textsc{studymanager} is able to include files into the final detailed report. These
files must be in the directory of results either in the \textbf{destination} or
in the \textbf{repository}. The following example shows the inclusion of three
files: \texttt{performance.log} and \texttt{setup.log} from the
\textbf{destination}, and a \texttt{performance.log} from the \textbf{repository}:

\small
\begin{verbatim}
<case label='Grid1' status='on' compute="on" post="on">
    <input dest="" file="performance.log"/>
    <input dest="" file="setup.log"/>
    <input repo="" file="performance.log"/>
</case>
\end{verbatim}
\normalsize

Text files, \LaTeX source files, or graphical (PNG, JPEG, or PDF) files
may be included.

In the file of parameters, input files are defined with markups \texttt{<input>}
as children of a single markup \texttt{<case>}.
The attributes of \texttt{<input>} are:
\begin{list}{$\rightarrow$}{}
\item \texttt{file}: name of the file to be included
\item \texttt{repo} or \texttt{dest}: id of the results directory either in the
\textbf{repository} or in the \textbf{destination};
\begin{list}{$\Rightarrow$}{}
\item if the id is not known already because the case has not yet run, just let
the attribute empty \texttt{dest=""}, the value will be updated after the run
step in the \textbf{destination} directory (see section \ref{sec:restart});
\item if there is a single results directory in the \texttt{RESU} directory
(either in the \textbf{repository} or in the \textbf{destination}) of the case,
the id can be ommitted: \texttt{repo=""} or \texttt{dest=""}, the id will be
completed automatically.
\end{list}
\end{list}
The attribute \texttt{file} is mandatory, and either \texttt{repo} or
\texttt{dest} must be present (but not the both) even if it is empty.

\section{Output and restart}\label{sec:restart}

\textsc{studymanager} produces several files in the \textbf{destination} directory:
\begin{list}{$\bullet$}{}
\item \texttt{report.txt}: standard output of the script;
\item \texttt{auto\_vnv.log}: log of the code and the \texttt{pdflatex}
compilation;
\item \texttt{report\_global.pdf}: summary of the compilation, run, comparison,
and plot steps;
\item \texttt{report\_detailed.pdf}: details the comparison and display the
plot;
\item \texttt{sample.xml}: udpated file of parameters, useful for restart the
script if an error occurs.
\end{list}

After the computation of a case, if no error occurs, the attribute
\texttt{compute} is set to \texttt{"off"} in the copy of the file of parameters
in the \textbf{destination}. It is allow a restart of \textsc{studymanager} without
re-run successfull previous computations.
In the same manner, all empty attributes \texttt{repo=""} and \texttt{dest=""}
are completed in the udpated file of parameters.

\section{Tricks}\label{sec:tricks}
\begin{list}{$\bullet$}{}
\item How to comment markups in the file of parameter ?

The opening and closing signs for commantaries are \texttt{<!--} and
\texttt{-->}. In the following example, nothing from the study
\texttt{MyStudy2} will be read:
\small
\begin{verbatim}
<?xml version="1.0"?>
<studymanager>
    <repository>/home/dupond/codesaturne/MyRepository</repository>
    <destination>/home/dupond/codesaturne/MyDestination</destination>

    <study label="MyStudy1" status="on">
        <case label="Grid1" status="on" compute="on" post="on"/>
        <case label="Grid2" status="on" compute="off" post="on"/>
    </study>
    <!--
    <study label="MyStudy2" status="on">
        <case label="k-eps" status="on" compute="on" post="on"/>
        <case label="Rij-eps" status="on" compute="on" post="on"/>
    </study>
    -->
</studymanager>
\end{verbatim}
\normalsize

\item How to add text in a figure ?

It is possible to use raw commands:
\small
\begin{verbatim}
<subplot id='301' ylabel ='Location ($m$)' title='Before jet -0.885' legstatus='off'>
    <plt_command>plt.text(-4.2, 0.113, 'jet')</plt_command>
    <plt_command>plt.text(-4.6, 0.11, r'$\downarrow$', fontsize=15)</plt_command>
</subplot>
 \end{verbatim}
\normalsize

\item Adjust margins for layout of subplots in a figure.

You have to use the raw command \texttt{subplots\_adjust}:

\small
\begin{verbatim}
<subplot id="1" legend='Yes' legpos ='0.2 0.95'>
    <plt_command>plt.subplots_adjust(hspace=0.4, wspace=0.4, right=0.9,
                 left=0.15, bottom=0.2, top=0.9)</plt_command>
</subplot>
\end{verbatim}
\normalsize

\item How to find a syntax error in the XML file ?

When there is a misprint in the file of parameters,
\textsc{studymanager} indicates the location of the error
with the line and the column of the file:
\small
\begin{verbatim}
my_case.xml file reading error.

This file is not in accordance with XML specifications.

The parsing syntax error is:

my_case.xml:86:12: not well-formed (invalid token)
\end{verbatim}
\normalsize

\item How to render less-than and greater-than signs in legends, titles or axis labels ?

The less-than $<$ and greater-than $>$ symbols are among the five predefined
entities of the XML specification that represent special characters.

In order to have one of the five predefined entities rendered in any legend, title or axis
label, use the string ``\&name;'' . Refer to the following table \ref{table:XMLPredefEnt}
for the name of the character to be rendered:

\begin{table}[htbp]
\begin{center}
\begin{tabular}{|c|c|c|}
\hline
\textbf{name} & \textbf{character} & \textbf{description} \\
\hline
quot & ``  & double quotation mark \\
amp  & \&  & ampersand             \\
apos & '   & apostrophe            \\
lt   & $<$ & less-than sign        \\
gt   & $>$ & greater-than sign     \\
\hline
\end{tabular}
\end{center}
\caption{Some predefined entities of XML specification.}
\label{table:XMLPredefEnt}
\end{table}

For any of this predefined entities, the XML parser will first replace the string ``\&name;''
by the character, which will then allow \LaTeX (or Mathtext if \LaTeX is disabled) to process it.

For example, in order to write ``$\lambda<1$'' in a legend, the following attribute will be used:
\small
\begin{verbatim}
    <plot fig="4" fmt="k--" legend="solution for $\lambda &lt; 1$" xcol="1" ycol="2"/>
\end{verbatim}
\normalsize

\item How to set a logarithmic scale ?

The following raw commands have to be used:

\small
\begin{verbatim}
<subplot id="2" title="Grid convergence" xlabel="Number of cells" ylabel="Error (\%)">
    <plt_command>ax.set_xscale('log')</plt_command>
    <plt_command>ax.set_yscale('log')</plt_command>
</subplot>
\end{verbatim}
\normalsize

\item How to create a mesh automatically with SALOME ?

The flollowing example shows how to create a mesh with a SALOME command file:
\small
\begin{verbatim}
<study label="STUDY" status="on">
    <case label="CASE1" status="on" compute="on" post="on">
        <prepro label="salome.sh" args="-t -u my_mesh.py" status="on"/>
    </case>
</study>
\end{verbatim}
\normalsize

with the script \texttt{salome.sh} (depending of the local installation of
SALOME):
\small
\begin{verbatim}
#!/bin/bash

export ROOT_SALOME=/home/salome/salome-640/Salome-V6_4_0-c7-v2
source /home/salome/salome-640/Salome-V6_4_0-c7-v2/salome_prerequisites_V6_4_0_appli.sh
source /home/salome/salome-640/Salome-V6_4_0-c7-v2/salome_modules_V6_4_0.sh

/home/salome/salome-640/appli_V6_4_0/bin/salome/runSalome $*
\end{verbatim}
\normalsize

and the script of SALOME commands \texttt{my\_mesh.py}:
\small
\begin{verbatim}
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import geompy
import smesh

# create a box
box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
idbox = geompy.addToStudy(box, "box")

# create a mesh
tetra = smesh.Mesh(box, "MeshBox")

algo1D = tetra.Segment()
algo1D.NumberOfSegments(7)

algo2D = tetra.Triangle()
algo2D.MaxElementArea(800.)

algo3D = tetra.Tetrahedron(smesh.NETGEN)
algo3D.MaxElementVolume(900.)

# compute the mesh
tetra.Compute()

# export the mesh in a MED file
tetra.ExportMED("./my_mesh.med")
\end{verbatim}
\normalsize

\item How to carry out a grid convergence study ?

The following exemple shows how to carry out a grid convergence study by running
the same case three times and changing the parameters between each run with the
help of a prepro script.

Here the mesh, the maximum number of iterations, the reference time step and the
number of processes are modified, before each run, by the script
\texttt{prepro.py}.

The file of parameters is as follows:

\small
\begin{verbatim}
<case compute="on" label="COUETTE" post="on" run_id="21_Theta_1" status="on">
    <prepro args="-m 21_Theta_1.med -p Couette.xml -n 4000 -a 1. -t 0.01024 -u 1"
            label="prepro.py" status="on"/prepro>
    <data dest="" file="profile.dat">
        <plot fig="5" fmt="r-+" legend="21 theta 1" markersize="5.5" xcol="1" ycol="5"/>
    </data>
</case>

<case compute="on" label="COUETTE" post="on" run_id="43_Theta_05" status="on">
    <prepro args="-m 43_Theta_05.med -p Couette.xml -n 8000 -a 0.5 -t 0.00512 -u 2"
            label="prepro.py" status="on"/prepro>
    <data dest="" file="profile.dat">
        <plot fig="5" fmt="b" legend="43 Theta 05" markersize="5.5" xcol="1" ycol="5"/>
    </data>
</case>

<case compute="on" label="COUETTE" post="on" run_id="86_Theta_025" status="on">
    <prepro args="-m 86_Theta_025.med -p Couette.xml -n 16000 -a 0.25 -t 0.00256 -u 4"
            label="prepro.py" status="on" /prepro>
    <data dest="" file="profile.dat">
        <plot fig="5" fmt="g" legend="86 Theta 025" markersize="5.5" xcol="1" ycol="5"/>
    </data>
</case>
\end{verbatim}
\normalsize

Recall that the case attribute \texttt{run\_id} should be given a different
value for each run, while the \texttt{label} should stay the same and that the
prepro script should be copied in the directory \texttt{MESH} of the study or in
the directory \texttt{DATA} of the case.

The prepro script is given below. Note that it can be called inside the file of
parameters without specifying a value for each option:

\small
\begin{verbatim}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
#
#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------
# Standard modules import
#-------------------------------------------------------------------------------

import os, sys
import string
from optparse import OptionParser

#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------
# Application modules import
#-------------------------------------------------------------------------------
from Pages.ScriptRunningModel import ScriptRunningModel

#-------------------------------------------------------------------------------

def process_cmd_line(argv):
    """Processes the passed command line arguments."""
    parser = OptionParser(usage="usage: %prog [options]")

    parser.add_option("-c", "--case", dest="case", type="string",
                      help="Directory of the current case")

    parser.add_option("-p", "--param", dest="param", type="string",
                      help="Name of the file of parameters")

    parser.add_option("-m", "--mesh", dest="mesh", type="string",
                      help="Name of the new mesh")

    parser.add_option("-n", "--iter-num", dest="iterationsNumber", type="int",
                      help="New iteration number")

    parser.add_option("-u", "--n-procs", dest="n_procs", type="int",
                      help="Number of processes (units)")

    parser.add_option("-t", "--time-step", dest="timeStep", type="float",
                      help="New time step")

    parser.add_option("-a", "--perio-angle", dest="rotationAngle", type="float",
                      help="Periodicity angle")

    (options, args) = parser.parse_args(argv)

    return options

#-------------------------------------------------------------------------------

def main(options):
    from cs_package import package
    from Base.XMLengine import Case
    from Base.XMLinitialize import XMLinit
    from Pages.SolutionDomainModel import SolutionDomainModel
    from Pages.TimeStepModel import TimeStepModel
    from Pages.SteadyManagementModel import SteadyManagementModel

    fp = os.path.join(options.case, "DATA", options.param)
    if os.path.isfile(fp):
        try:
            case = Case(package = package(), file_name = fp)
        except:
            print("Parameters file reading error.\n")
            print("This file is not in accordance with XML specifications.")
            sys.exit(1)

        case['xmlfile'] = fp
        case.xmlCleanAllBlank(case.xmlRootNode())
        XMLinit(case).initialize()

        if options.mesh:
            s = SolutionDomainModel(case)
            l = s.getMeshList()
            s.delMesh(l[0])
            s.addMesh((options.mesh, None))

        if options.rotationAngle:
            s.setRotationAngle(0, options.rotationAngle)

        if (options.iterationsNumber):
            s = SteadyManagementModel(case)
            t = TimeStepModel(case)
            if s.getSteadyFlowManagement() == 'on':
                s.setNbIter(options.iterationsNumber)
            else:
                t.setIterationsNumber(options.iterationsNumber)

        if (options.TimeStep):
            t = TimeStepModel(case)
            t.setTimeStep(options.TimeStep)

        if (options.n_procs):
            mdl = ScriptRunningModel(case)
            mdl.setString('n_procs', str(options.n_procs))

        case.xmlSaveDocument()

#-------------------------------------------------------------------------------

if __name__ == '__main__':
    options = process_cmd_line(sys.argv[1:])
    main(options)

#-------------------------------------------------------------------------------
\end{verbatim}
\normalsize

\end{list}


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