% Emacs settings: -*-mode: latex; TeX-master: "manual.tex"; -*-

\chapter{The \MCS kernel and meta-language}
\label{c:kernel}
\index{Kernel|(textbf}
\index{Meta-language}

Instrument definitions are written in a special \MCS meta-language which
is translated automatically by the compiler \mcs into a C program
which is in turn compiled to an executable that
performs the simulation. The meta-language is custom-designed for neutron
scattering and serves two main purposes: (i) to specify the interaction of a
single neutron ray with a single optical component, and (ii) to build a
simulation by constructing a complete instrument from individual
components.

For maximum flexibility and efficiency, the meta-language is based on C.
Instrument geometry, propagation of neutrons between the different
components, parameters, data input/output etc.\ is handled in the
meta-language and by the compiler \mcs. Complex calculations are written in
C embedded in the meta-language description of the
components. However, it is
possible to set up an instrument from existing components and
run a simulation without writing a single line of C code, working
entirely in the meta-language.

Apart from the meta-language, \MCS also includes a number of C library
functions and definitions that are useful for neutron ray-tracing
simulations. The definitions available for component developers are
listed in appendix~\ref{c:kernelcalls}. The list includes functions
for
\begin{itemize}
\item Computing the intersection between a flight-path and various
  objects (such as planes, cylinders, boxes and spheres)
\item Functions for generating random numbers
with various distributions
\item Functions for reading or writing information from/to data
  files
\item Convenient conversion factors between relevant units, etc.
\index{Library!run-time}
\index{Library!components!share}
\end{itemize}

The \MCS meta-language was designed to be readable, with a verbose
syntax and explicit mentioning of otherwise implicit information. The
recommended way to get started with the meta-language is to start by
looking at the examples supplied with \MCS, modifying them as necessary
for the application at hand.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Notational conventions}

Simulations generated by \MCS use a semi-classical description of the neutron
rays to compute the neutron trajectory through the instrument and its
interaction with the different components. The effect of gravity is taken into
account either in particular components (e.g. \verb+Guide_gravity+), or more
generally when setting an execution flag (\verb+-g+) to perform gravitation
computation. This latter setting is only an approximation and may produce wrong
results with some components.\index{Gravitation}

An instrument consists of a list of components through which the neutron
ray passes one after the other. The order of components is thus significant
since \mcs does not automatically check which component is the next to
interact with the neutron ray at a given point in the simulation. Note
that in case of a negative propagation time from one component to the
next, the neutron ray is by default \emph{absorbed} as this is often
an indication of unphysical conditions.

\index{Coordinate!system}
The instrument is given a global, absolute coordinate system. In
addition, every component in the instrument has its own local coordinate
system that can be given any desired position and orientation (though
the position and orientation must remain fixed for the duration of a
single simulation). 
By convention, the $z$ axis points in the direction of the beam, the $x$ axis
is perpendicular to the beam in the horizontal plane pointing left as seen
from the source, and the $y$ axis points upwards (see figure~\ref{f:axis}).
Nothing in the \MCS metalanguage enforces this convention, but if every component used
different conventions the user would be faced with a severe headache! It is
therefore necessary that this convention is followed by users implementing
new components.
\begin{figure}
  \begin{center}
    \includegraphics[width=0.8\textwidth]{figures/axis-conventions}
  \end{center}
\caption{conventions for the orientations of the axes in simulations.}
\label{f:axis}
\end{figure}

\index{Instrument definition!units|textbf}
\index{Units|textbf}
In the instrument definitions, units of length (\textit{e.g}.\ component
positions) are given in meters and units of angles (\textit{e.g}.\
rotations) are given in degrees.

\index{Neutron!state (position, velocity, time, spin, weight)|textbf}
The state of the neutron is given by
its position $(x,y,z)$ in meters, its velocity $(v_x, v_y, v_z)$ in
meters per second, the time $t$ in seconds, and the three spin parameters
$\left( s_x, s_y, s_z \right)$, and finally the neutron weight $p$ described in \ref{s:MCtechniques}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Syntactical conventions}
\label{s:syntax}

Comments follow the C and C++ syntax

\begin{mcstas}
/* C style comment  */  
// C++ style comment
\end{mcstas}

\index{Comments}

%For backward-compatibility
%with early versions, comments may also be written as a percentage sign
%followed by a space (``\verb*+% ...+''), but this is not recommended and
%will be removed in a future version.

Keywords are not case-sensitive, for example ``\verb+DEFINE+'',
``\verb+define+'', and ``\verb+dEfInE+'' are all equivalent. However, by
convention we always write keywords in uppercase to distinguish them
from identifiers and C language keywords. In contrast, \MCS
identifiers (names), like C identifiers and keywords, \emph{are} case
sensitive, another good reason to use a consistent case convention for
keywords. All \MCS keywords are reserved, and thus should not be used
as C variable names. The list of these reserved keywords is shown in table~\ref{t:keywords}.

\begin{table}
  \begin{center}
    {\let\my=\\
    \begin{tabular}{|l|c|p{0.7\textwidth}|}
      \hline
      \texttt{Keyword} & Scope & Meaning \\
      \hline
      \texttt{ABSOLUTE} & I & Indicates that the AT and ROTATED keywords are in the absolute coordinate system. \\
      \texttt{AT} & I & Indicates the position of a component in an instrument definition. \\
      \texttt{COPY}& I,C & copy/duplicate an instance or a component definition. \\
      \texttt{DECLARE} & I,C & Declares C internal variables. \\
      \texttt{DEFINE} & I,C & Starts an INSTRUMENT or COMPONENT definition. \\
      \texttt{DEFINITION} & C & Defines component parameters that are constants (\#define). \\
      \texttt{DEPENDENCY} & C,I & Indicates any library dependency required to create the instrument. \\
      \texttt{END} & I,C & Ends the instrument or component definition. \\
      \texttt{SPLIT} & I & Enhance incoming statistics by event repetition. \\
      \texttt{EXTEND} & I & Extends a component TRACE section (plug-in). \\
      \texttt{FINALLY} & I,C & Embeds C code to execute when simulation ends. \\
      \texttt{GROUP} & I & Defines an exclusive group of components. \\
      \texttt{\%include} & I,C & Imports an instrument part, a component or a piece of C code (when within embedded C). \\
      \texttt{JUMP} & I & Iterative (loops) and conditional jumps. \\
      \texttt{INITIALIZE} & I,C & Embeds C code to be executed when starting. \\
      \texttt{ITERATE} & I & Defines iteration counter for JUMP. \\
      \texttt{MCDISPLAY} & C & Embeds C code to display component geometry. \\
      \texttt{OUTPUT} & C & Defines internal variables to be public and protected symbols (usually all global variables and functions of DECLARE).\\
      \texttt{PARAMETERS} & C & Defines a class of component parameter (DEFINITION, SETTING). \\
      \texttt{PREVIOUS} & C & Refers to a previous component position/orientation.\\
      \texttt{RELATIVE} & I & Indicates that the AT and ROTATED keywords are relative to an other component. \\
      \texttt{REMOVABLE} & I & Indicates that this component will be removed when the instrument is inserted into an other one using the \texttt{\%include} keyword. \\
      \texttt{ROTATED} & I & Indicates the orientation of a component in an instrument definition. \\
      \texttt{SAVE} & I,C & Embedded C code to execute when saving data. \\
      \texttt{SETTING} & C & Defines component parameters that are
      variables. \\
      \texttt{SHARE} & C & Declares global functions and variables to be shared. \\
      \texttt{TRACE} & I,C & Defines the instrument as a the component sequence. \\
      \texttt{WHEN}  & I & Condition for component activation and JUMP.\\
      \hline
    \end{tabular}
    \caption{Reserved \MCS keywords.
    Scope is 'I' for instrument and 'C' for component definitions.
    \index{Keywords|textbf}}
    \label{t:keywords}
    }
  \end{center}
\end{table}

It is possible, and usual, to split the input instrument definition
across several different files. For example, if a component is not
explicitly defined in the instrument,
\mcs will search for a file containing the component definition in the
standard component library (as well as in the current directory and any
user-specified search directories, see section~\ref{s:files}). It is
also possible to explicitly include another file using a line of the
form \indexKW{\%include}
\begin{lstlisting}
    %include "file"
\end{lstlisting}
Beware of possible confusion with the C language ``\verb+#include+''
statement, especially when it is used in C code embedded within the
\MCS meta-language. Files referenced with ``\verb+%include+'' are read
when the instrument is translated into C by \mcs, and must
contain valid \MCS meta-language input (and possibly C code). Files referenced with
``\verb+#include+'' are read when the C compiler generates an
executable from the generated C code, and must contain valid C.

Embedded C code is used in several instances in the \MCS
meta-language. Such code is copied by \mcs into the
generated simulation C program. Embedded C code is written by putting it
between the special symbols \%{ and \%}, as follows:
\begin{lstlisting}
%{ 
// Embedded C code...
%}
\end{lstlisting} 
\index{C code!embedded}
The \%\{ and \%\} must appear on a line by themselves (do not add comments after).
Additionally, if a ``\verb+%include+'' statement is found \emph{within} an embedded C code block, the specified file will be included from the 'share' directory of the standard component library \index{Library!components!share} (or from the
current directory and any user-specified search directories) as a C library, just like the usual ``\verb+#include+'' \emph{but only once}. For instance, if many components require to read data from a file, they may all ask for ``\verb+%include "read_table-lib"+'' \index{Library!read\_table-lib} without duplicating the code of this library. If the file has no extension, both \verb+.h+ and \verb+.c+ files will be searched and included, otherwise, only the specified file will be imported. The \MCS 'run-time' shared
library is included by default (equivalent to ``\verb+%include "mcstas-r"+'' in the \texttt{DECLARE} section). \index{Library!run-time}
For an
example of \texttt{\%include}, see the monitors/Monitor\_nD component. See also section \ref{s:instrdefs-extend} for insertion of full instruments in instruments (instrument concatenation).

If the instrument description compilation fails, check that the
keywords syntax is correct, that no semi-colon (\verb+;+) sign is
missing (e.g. in C blocks and after an ABSORB macro),
\indexMCRH{ABSORB}{}
and there are no name conflicts between instrument and component instances variables.\index{Compilation!failure}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Writing instrument definitions}
\label{s:instrdefs}
\index{Instrument definition}

The purpose of the instrument definition is to specify a sequence of
components, along with their position and parameters, which together
make up an instrument. Each component is given its own local coordinate
system, the position and orientation of which may be specified by its
translation and rotation relative to another component. An example is
given in section~\ref{s:Samples_vanadium.instr} and some additional
examples of instrument definitions can be found on the \MCS
web-page~\cite{mcstas_webpage} and in the \texttt{example} directory.

As a summary, the usual grammar for instrument descriptions is
\begin{mcstas}
DEFINE INSTRUMENT name(parameters)
DECLARE C_code
INITIALIZE C_code
TRACE components
{FINALLY C_code}
END
\end{mcstas}


%-------------------------------------------------------------------------------
\subsection{The instrument definition head}

\begin{mcstas}
DEFINE INSTRUMENT name (a_1, a_2, ...)
\end{mcstas} 
\indexKW{DEFINE INSTRUMENT}

This marks the beginning of the definition. It also gives the name of
the instrument and the list of instrument parameters. Instrument
parameters describe the configuration of the instrument, and usually
correspond to setting parameters of the components, see section \ref{s:compdefs}. A motor position is
a typical example of an instrument parameter. The input parameters of
the instrument constitute the input that the user (or possibly a
front-end program) must supply when the
generated simulation is started.

\index{Parameters!Instruments}
By default, the parameters will be floating point numbers, and will have
the C type \verb+double+ (double precision floating point). The type of
each parameter may optionally be declared to be \verb+int+ for the C
integer type or \verb+char *+ for the C string type. The name
\verb+string+ may be used as a synonym for \verb+char *+, and floating
point parameters may be explicitly declared using the name
\verb+double+. The following example illustrates all possibilities:
\begin{mcstas}
DEFINE INSTRUMENT test(d1, double d2, int i, char *s1, string s2)
\end{mcstas}

Here \verb+d1+ and \verb+d2+ will be floating point parameters of C type
\verb+double+, \verb+i+ will be an integer parameter of C type \verb+int+, and
\verb+s1+ and \verb+s2+ will be string parameters of C type \verb+char *+.
\index{Parameters!optional, default value} The parameters of an instrument may
be given default values. Parameters with default values are called
\emph{optional parameters}, and need not be given an explicit value when the
instrument simulation is executed. When executed without any parameter value in
the command line (see section~\ref{s:run-sim}), the instrument asks for all
parameter values, but pressing the \verb+Return+ key selects the default value
(if any). When used with at least one parameter value in the command line, all
non specified parameters will have their value set to the default one (if
any). A parameter is given a default value using the syntax
``\textit{param}\texttt{= }\textit{value}''.  For example
\begin{mcstas}
DEFINE INSTRUMENT test(d1= 1, string s2="hello")
\end{mcstas}
Here \verb+d1+ and \verb+d2+ are optional parameters and if no
value are given explicitly, ``1'' and ``hello'' will be used.

Optional parameters can greatly increase the convenience for users of
instruments for which some parameters are seldom changed or of unclear
signification to the user. Also, if all instrument parameters have default
values, then the simple command \verb+mcdisplay+ \verb+test.instr+ will show the
instrument view without requesting any other input, which is usually a good
starting point to study the instrument design.

%-------------------------------------------------------------------------------
\subsection{The \texttt{DEPENDENCY} line}
\indexKW{DEPENDENCY}
\label{s:dependency}
\begin{mcstas}
DEPENDENCY "-lLIB1 -lLIB2 .."
\end{mcstas}

If you make use of external library calls in your instrument, you may indicate 
the dependency list to be used for the compilation of the instrument, as a single 
DEPENDENCY keyword and a string argument, all on a single line such as:
\begin{mcstas}
DEPENDENCY "-lgsl -lgslcblas"
\end{mcstas}
The concatenation of all found dependencies from the instrument, but also from 
all used components, will be printed to the terminal (stdout) as
\begin{mcstas}
CFLAGS=-lgsl -lgslcblas
\end{mcstas}
This line is interpreted by \verb+mcrun+ (see section \ref{s:mcrun}) and passed 
to the compiler. It must be indicated just before the \texttt{DECLARE} section.
This line is optional, and if omitted you may need to manually link the instrument with the libraries and add the proper library names to the MCSTAS\_CFLAGS or CFLAGS environment variables.

%-------------------------------------------------------------------------------
\subsection{The \texttt{DECLARE} section}
\indexKW{DECLARE}
\label{s:declare}

\begin{mcstas}
DECLARE
%{ 
   // C declarations of global variables etc. ...
%}
\end{mcstas} 
\index{C code!embedded}
 This gives C declarations that may be
referred to in the rest of the instrument definition. A typical use is to
declare global variables or small functions that are used elsewhere in the
instrument. The \verb+%include ''file''+ keyword may be used to import a
specific
component definition or a part of an instrument. Variables defined here are
global, and may conflict with internal \MCS variables, specially symbols like
\verb+x,y,z,sx,sy,sz,vx,vy,vz,t+ and generally all names starting with \verb+mc+
should be avoided. If you can not compile the instrument, this may be the
reason. \index{Compilation!failure}The \texttt{DECLARE} section is optional.

%-------------------------------------------------------------------------------
\subsection{The \texttt{INITIALIZE} section}
\indexKW{INITIALIZE}
\label{s:initialize}

\begin{mcstas}
INITIALIZE
%{
// C initializations. 
%}
\end{mcstas} 
\index{C code!embedded}
This gives code that is executed when the
simulation starts. This section is optional. Instrument setting parameters may
be modified in this section (e.g. doing tests or automatic settings).

%-------------------------------------------------------------------------------
\subsection{The \texttt{NEXUS} extension}
\index{NeXus!extension}
\index{Data formats}
\label{s:nexus}

The NeXus format~\cite{nexus_webpage} requires to link the simulation to
additional libraries (HDF and NeXus) which must have been
pre-installed. Preferably, \MCS should have been installed with the
\verb+./configure --with-nexus+ on Unix/Linux systems. To activate the NeXus
output, the compilation of the instrument must be done with flag
\verb+-DUSE_NEXUS+ \verb+-lNeXus+.
The resulting executable is no longer portable.

The default NeXus format is HDF5 with compression. 

You may choose the name of the output file with the \verb+-f filename+ option
from the instrument executable or \verb+mcrun+ (see Sections \ref{s:run-sim},
\ref{s:mcrun} and Table \ref{f:simoptions2}).

Then, the output format is chosen as usual with the \verb+--format=NeXus+ option
when launching the simulation. All output files are stored in the output
 \textit{filename},
as well as the instrument description itself. Other formats are
still available. When run on a distributed system (e.g. MPI), detectors are
gathered, but list of events (see e.g. component Virtual\_output) are stored as
one data set per node.

%-------------------------------------------------------------------------------
\subsection{The \texttt{TRACE} section}
\indexKW{TRACE}
\label{s:trace}


As a summary, the usual grammar for component instances within the instrument
TRACE section is
\begin{mcstas}
COMPONENT name = comp(parameters)
  AT (...) [RELATIVE [reference|PREVIOUS] | ABSOLUTE]
 {ROTATED  {RELATIVE [reference|PREVIOUS] | ABSOLUTE} }
\end{mcstas}

The \texttt{TRACE} keyword starts a section giving the list of
components that constitute the instrument.
Components are declared like this:
\begin{mcstas}
COMPONENT name = comp(p_1 = e_1, p_2 = e_2, ...)
\end{mcstas}
\index{Component!declaration (\texttt{TRACE})}
\indexKW{COMPONENT}
\index{Parameters!setting}
\index{Parameters!definition}
This declares a component named \textit{name} that is an instance of the
component definition named \textit{comp}. The parameter list gives the
setting and definition parameters for the component. The expressions $e_1,
e_2, \ldots$ define the values of the parameters. For setting parameters
arbitrary ISO-C expressions may be used, while for definition parameters
only \emph{constant} numbers, strings, names of instrument parameters, or names
of C identifiers are allowed (see section~\ref{s:comp-header} for details of
the difference between definition and setting parameters). To assign the
value of a general expression to a definition parameter, it is necessary to
declare a variable in the \texttt{DECLARE} section, assign the value to the
variable in the \texttt{INITIALIZE} section, and use the variable as the
value for the parameter.

The \MCS program takes care to rename parameters appropriately in the
output so that no conflicts occur between different component
definitions or between component and instrument definitions. It is thus
possible (and usual) to use a component definition multiple times
in an instrument description.

Beware about variable type conversion when setting numerical parameter values, as in \verb+p1=12/1000+. In this example, the parameter \verb+p1+ will be set to 0 as the division of the two integers is indeed 0. To avoid that, use explicitly floating type numbers as in \verb+p1=12.0/1000+.\index{Bugs!integer versus floating-point division}

The compiler \mcs will automatically search for a file containing a
definition of the component if it has not been declared previously. The
definition is searched for in a file called ``\textit{name\/}\texttt{.comp}''. See
section~\ref{s:files} for details on which directories are searched. This
facility is often used to refer to existing component definitions in
standard component libraries. It is also possible to write component
definitions in the main file before the instrument definitions, or to
explicitly read definitions from other files using \verb+%include+
(not within embedded C blocks).

The physical position of a component is specified using an \texttt{AT} modifier
following the component declaration:
\indexKW{AT}
\indexKW{RELATIVE}
\indexKW{ABSOLUTE}
\begin{mcstas}
  AT (x,y,z) RELATIVE name
\end{mcstas}
This places the component at position $(x,y,z)$ in the coordinate system
of the previously declared component \textit{name}. Placement may also
be absolute (not relative to any component) by writing
\begin{mcstas}
  AT (x,y,z) RELATIVE ABSOLUTE
\end{mcstas}
Any C expression may be used for $x$, $y$, and $z$. The \texttt{AT}
modifier is required.
Rotation is achieved similarly by writing
\indexKW{ROTATED}
\begin{mcstas}
  ROTATED (phi_x,phi_y,phi_z) RELATIVE name
\end{mcstas}
This will result in a coordinate system that is rotated first the angle $\phi_x$
(in degrees) around the $x$ axis, then $\phi_y$ around the $y$ axis, and finally
$\phi_z$ around the $z$ axis. Rotation may also be specified using
\texttt{ABSOLUTE} rather than \texttt{RELATIVE}. If no rotation is specified,
the default is $(0,0,0)$ using the same relative or absolute specification used
in the \texttt{AT} modifier. We \emph{strongly} recommend to apply all rotations
of an instrument description on Arm class components only, acting as
goniometers, and position the optics on top of these. This usually makes it much
easier to orient pieces of the instrument, and avoid positioning errors.

The \emph{position} of
a component is actually the origin of its local coordinate
system. Usually, this is used as the input window position (e.g. for
guide-like components), or the center position for
cylindrical/spherical components.

The \texttt{PREVIOUS}
\indexKW{PREVIOUS}
keyword is a generic name to
refer to the previous component in the simulation. Moreover, the
\texttt{PREVIOUS(n)} keyword will refer to the $n$-th previous component,
starting from the current component, so that \texttt{PREVIOUS} is equivalent to
\texttt{PREVIOUS(1)}. This keyword should be used after the \texttt{RELATIVE}
keyword, but not for the first component instance of the instrument description.
\begin{mcstas}
AT (x,y,z) RELATIVE PREVIOUS
ROTATED (phi_x, phi_y, phi_z) RELATIVE PREVIOUS(2)
\end{mcstas}
Invalid \texttt{PREVIOUS} references will be assumed to be absolute placement.

The order and position of components in the \texttt{TRACE} section does not
allow components to overlap, except for particular cases (see the \texttt{GROUP}
keyword below).  Indeed, many components of the \MCS library
\index{Library!components} start by propagating the neutron event to the
beginning of the component itself.  Anyway, when the corresponding propagation
time is found to be negative (\textit{i.e.} the neutron ray is already \emph{after}
or \emph{aside} the component, and has thus passed the 'active' position), the
neutron event is ABSORBed,
\indexMCRH{ABSORB}{}
resulting in a zero intensity and event counts after
a given position. The number of such removed neutrons is indicated at the end of
the simulation.  Getting such warning messages is an indication that either some
components overlap, or some neutrons are getting outside of the simulation, for
instance this usually happens after a monochromator, as the non-reflected beam
is indeed lost. A special warning appears when no neutron ray has reached some
part of the simulation. This is usually the sign of either overlapping
components or a very low intensity.\index{Absorption}\index{Neutron!absorption}

For experienced users, we recommend as well the usage of the \texttt{WHEN} and
\texttt{EXTEND} keywords, as well as other syntax extensions presented in
section \ref{s:instrdefs-extend} below.

%-------------------------------------------------------------------------------
\subsection{The \texttt{SAVE} section}
\indexKW{SAVE}
\label{s:save}

\begin{mcstas}
SAVE 
%{
  // C code to execute each time a temporary save is required...
%}
\end{mcstas} 

\indexSIG{USR2}{textbf}
This gives code that will be
executed when the simulation is requested to save data, for instance when
receiving a USR2 signal (on Unix systems), or using the \verb+Progress_bar+
component with intermediate savings. It is also executed when the simulation
ends. This section is optional.

%-------------------------------------------------------------------------------
\subsection{The \texttt{FINALLY} section}
\indexKW{FINALLY}
\label{s:finally}

\begin{mcstas}
FINALLY
%{
   // C code to execute at end of simulation
%}
\end{mcstas}
\indexSIG{TERM}{textbf}
\indexSIG{INT}{textbf}
This gives code that will be executed when the simulation has
ended. When existing, the \texttt{SAVE} section is first executed. The
\texttt{FINALLY} section is optional.
A simulation may be requested to end before all neutrons have been
traced when receiving a TERM or INT signal (on Unix systems), or with
Control-C, causing code in \texttt{FINALLY} to be evaluated.


%-------------------------------------------------------------------------------
\subsection{The end of the instrument definition}
\label{s:end}
\indexKW{END}

The end of the instrument definition must be explicitly marked using the keyword
\begin{lstlisting}
END
\end{lstlisting}

\subsection{Code for the instrument \texttt{vanadium\_example.instr}}
\label{s:Samples_vanadium.instr}
A commented instrument definition taken from the \texttt{examples} directory is
here shown as an example of the use of \MCS.
%FIXME \smallverbatimfile{McCode/mcstas-comps/examples/Samples_vanadium.instr}



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Writing instrument definitions - complex arrangements and syntax}
\label{s:instrdefs-extend}
\index{Instrument definition}

In this section, we describe some additional ways to build instruments using
groups, code extension, conditions, loops and duplication of components.

As a summary, the nearly complete grammar definition for component instances
within the instrument TRACE section is:

\begin{mcstas}
{SPLIT} COMPONENT name = comp(parameters) {WHEN condition}
  AT (...) [RELATIVE [reference|PREVIOUS] | ABSOLUTE]
  {ROTATED {RELATIVE [reference|PREVIOUS] | ABSOLUTE} }
  {GROUP group_name}
  {EXTEND C_code}
  {JUMP [reference|PREVIOUS|MYSELF|NEXT] [ITERATE number_of_times | WHEN condition] }
\end{mcstas}

%-------------------------------------------------------------------------------
\subsection{Embedding instruments in instruments TRACE}
\indexKW{\%include}
\label{s:instrdefs-include-instr}
The \texttt{\%include} insertion mechanism may be used within the TRACE section,
in order to concatenate instruments together. This way, each DECLARE,
INITIALIZE, SAVE, and FINALLY C blocks, as well as instrument parameters from
each part are concatenated. The TRACE section is made of inserted COMPONENTS
from each part. In principle, it is then possible to write an instrument as:
\begin{mcstas}
DEFINE concatenated()
TRACE

%include "part1.instr"
%include "part2.instr"

END
\end{mcstas}
where each inserted instrument is a valid full instrument. In order to avoid
some components to be duplicated - e.g. Sources from each part - a special
syntax in the TRACE section
\begin{mcstas}
REMOVABLE COMPONENT a=...
\end{mcstas}
marks the component \textit{a} as removable when inserted. In principle, inserted
instruments may themselves use \texttt{\%include}.

%-------------------------------------------------------------------------------
\subsection{Groups and component extensions - GROUP - EXTEND}
\indexKW{GROUP}
\indexKW{EXTEND}
\label{s:instrdefs-extend-group}

It is sometimes desirable to slightly modify an existing component of the \MCS library. One would usually make a copy of the component, and extend the code of its \texttt{TRACE} section. \MCS provides an easy way to change the behavior of existing components in an instrument definition without duplicating files, using the \texttt{EXTEND} modifier
\indexKW{EXTEND}
\begin{mcstas}
EXTEND
%{ 
// C code executed after the component TRACE section...
%}
\end{mcstas} 
\index{C code!embedded}
The embedded C code is appended to the
component \texttt{TRACE} section, and all its internal variables (as well as all
the \texttt{DECLARE} instrument variables, \emph{except} instrument parameters)
may be used. To use instrument parameters, you should copy them into global
variables in the DECLARE instrument section, and refer to these latter.  This
component declaration modifier is of course optional. You will find numerous
usage examples, and in particular in the Sources section of the Component
manual.

In some peculiar configurations it is necessary to position one or more groups
of components, nested, in parallel, or overlapping. One example is a multiple
crystal monochromator. One would then like the neutron ray to interact with
\emph{one of} the components of the group and then continue.

In order to handle such arrangements without removing neutrons, groups are
defined by the \texttt{GROUP} modifier (after the AT-ROTATED positioning):
\begin{mcstas}
GROUP name
\end{mcstas}
to all involved component declarations.
\indexKW{GROUP}
All components of
the same named group are tested one after the other, until one of them interacts
(uses the SCATTER macro\indexMCRH{SCATTER}{}). The selected component
acts on the neutron ray, and the rest of the group is skipped. Such groups are
thus exclusive (only one of the elements is active).

Within a \texttt{GROUP}, \emph{all} \texttt{EXTEND} sections of the group are
executed. In order to discriminate components that are active from those that
are skipped, one may use the SCATTERED flag, which is set to zero when entering
each component or group, and incremented when the neutron is SCATTERed, as in
the following example
\indexMCCH{SCATTERED}{}
\begin{mcstas}
COMPONENT name0 = comp (
                  p_1 = e_1, 
                  p_2 = e_2, 
                  ...)
AT (0,0,0) ABSOLUTE

COMPONENT name1 = comp... 
AT (...) ROTATED (...)

GROUP GroupName EXTEND
%{ 
   if (SCATTERED) printf("I scatter"); else printf("I do not scatter");
%}

COMPONENT} name2 = comp ...
AT (...) ROTATED (...)
GROUP GroupName
\end{mcstas}
Components \emph{name1} and \emph{name2} are at the same position. If the first
one intercepts the neutron
(and has a SCATTER\indexMCRH{SCATTER}{}
within its \texttt{TRACE}
section), the SCATTERED\indexMCCH{SCATTERED}{}
variable becomes true, the code extension will result in
printing "I scatter", and the second component will be skipped.  Thus, we
recommend to make use of the SCATTER keyword each time a component 'uses' the
neutron (scatters, detects, \ldots) within component definitions (see section
\ref{s:compdefs}). Also, the components to be grouped should be consecutive in
the TRACE section of the instrument, and the GROUPed section should not contain
components which are not part of the group.

A usage example of the GROUP keyword can be found in the \\
\verb+Neutron site/ILL/ILL_H15_IN6+ instrument from the \verb+mcgui+, to model 3 monochromators.

Combining EXTEND, GROUP and WHEN can result in unexpected behavior. Please read the related warning at the end of section \ref{s:instrdefs-extend-when}.

%-------------------------------------------------------------------------------
\subsection{Duplication of component instances - COPY}
\indexKW{COPY}
\label{s:instrdefs-extend-copy}

Often, one has a set of similar component instances in an instrument. These
could be e.g. a set of identical monochromator blades, or a set of detectors or
guide elements.  Together with JUMPs (see below), there is a way to copy a
component instance, duplicating parameter set.

Position (AT) and rotation (ROTATED) specification must
be explicitly entered in order to avoid component overlapping, and it
is futher recommended to explicitly set any EXTEND, GROUP, JUMP and
WHEN keyword to each \emph{mother} or copied instance. But \textbf{BEWARE},
advanced combinations of (many) keywords \emph{may} introduce
unexpected behaviour.

The syntax for instance copy is
\begin{mcstas}
COMPONENT name = COPY (instance_name)
\end{mcstas}
where \textit{instance\_name} is the name of a preceding component instance in the
instrument. It may be 'PREVIOUS' as well.

If you would like to change only some of the parameters in the instance copy, you may write, e.g.:

\begin{mcstas}
COMPONENT name = COPY (instance_name)(par1=0, par2=1)
\end{mcstas}

which will override the original instance parameter values. This possibility to
override parameters is very useful in case of describing e.g. sample environments
using the Isotropic\_Sqw and PowderN components, which allow \emph{concentric}
geometry (first instance must have \verb+concentric = 1+ and the second
\verb+concentric = 0+). In case EXTEND, GROUP, JUMP and WHEN keywords are
defined for the copied instance, these will override the settings from the
copied instance.


In the case where there are many duplicated components all originating from the
same instance, there is a mechanism for automating copied instance names:
\begin{mcstas}
COMPONENT COPY(root_name) = COPY(instance_name)
\end{mcstas}
will concatenate a unique number to \textit{root\_name}, avoiding name
conflicts. As a side effect, referring to this component instance (for
e.g. further positioning) is not straight forward as the name is determined by
\mcs and does not depend completely on the user's choice, even though the
PREVIOUS keyword may still be used. We thus recommend to use this naming
mechanism only for components which should not be referred to in the instrument.

This automatic naming may be used anywhere in the TRACE section of the
instrument, so that all components which do not need further referring may be
labeled as COPY(Origin).

As an example, we show how to build a guide made of equivalent elements. Only
the first instance of the Guide component is defined, whereas following
instances are copies of that definition. The instance name of Guide components
is set automatically.

\begin{mcstas}
COMPONENT CG_In = Arm() AT (...)

COMPONENT CG_1  = Guide_gravity(l=L/n, m=1, ...)
  AT (0,0,0) RELATIVE PREVIOUS

COMPONENT COPY(CG_1)  = COPY(CG_1)
  AT (0,0,L/n+d) RELATIVE PREVIOUS
  ROTATED (0, (L/n+d)/R*180/PI, 0) RELATIVE PREVIOUS

COMPONENT COPY(CG_1)  = COPY(CG_1)
  AT (0,0,L/n+d) RELATIVE PREVIOUS
  ROTATED (0, (L/n+d)/R*180/PI, 0) RELATIVE PREVIOUS
...
COMPONENT CG_Out = Arm() AT (0,0,L/n) RELATIVE PREVIOUS
\end{mcstas}

%-------------------------------------------------------------------------------
\subsection{Conditional components - WHEN}
\indexKW{WHEN}
\label{s:instrdefs-extend-when}

One of the most useful features of the extended \MCS syntax is the conditional
\texttt{WHEN} modifier. This optional keyword comes before the AT-ROTATED
positioning. It basically enables the component only when a given condition is
true (non null).

\begin{mcstas}
  COMPONENT name = comp (p_1 = e_1, p_2 = e_2, ...)
  WHEN condition
\end{mcstas}
The condition has the same scope as the EXTEND modifier, i.e. may use component
internal variables as well as all the \texttt{DECLARE} instrument variables.

Usage examples could be to have specific monitors only sensitive to selected
processes, or to have components which are only present under given
circumstances (e.g. removable guide or radial collimator), or to select a sample
among a set of choices.

In the following example, an EXTEND block sets a condition when a scattering
event is encountered, and the following monitor is then activated.
\begin{mcstas}
COMPONENT Sample = V_sample(...) AT ...
  EXTEND
  %{
    if (SCATTERED) flag=1; else flag=0;
  %}

COMPONENT MyMon = Monitor(...) WHEN (flag==1)
  AT ...
\end{mcstas}
\indexMCCH{SCATTERED}{}

The WHEN keyword only applies to the TRACE section and related EXTEND blocks of
instruments/components. Other sections (INITIALIZE, SAVE, MCDISPLAY, FINALLY)
are executed independently of the condition. As a side effect, the 3D view of
the instrument (mcdisplay) will show all components as if all conditions were
true.

Also, the \verb+WHEN+ keyword is a condition for \verb+GROUP+. This means that
when the \verb+WHEN+ is false, the component instance is not active in the
\verb+GROUP+ it belongs to.\index{Bugs!WHEN vs GROUP}

A usage example of the WHEN keyword can be found in the \\
\verb+Neutron site/ILL/ILL_TOF_Env+ instrument from the \verb+mcgui+, to monitor
neutrons depending on their fate.


\textbf{WARNING:} Combining WHEN, EXTEND and GROUP can result in unexpected behavior,
please use with caution! Let for instance a GROUP of components all have the
same WHEN condition, i.e. if the WHEN condition is false, none of the elements
SCATTER, meaning that all neutrons will be ABSORBed.
\indexMCRH{ABSORB}{}
\indexMCRH{SCATTER}{}
As a solution to this
problem, we propose to include an EXTENDed Arm component in the GROUP, but with
the opposite WHEN condition and a SCATTER keyword in the EXTEND section. This
means that when none of the other GROUP elements are present, the Arm will be
present and SCATTER.


%-------------------------------------------------------------------------------
\subsection{Component loops and non sequential propagation - JUMP}
\indexKW{JUMP}
\indexKW{ITERATE}
\indexKW{WHEN}
\label{s:instrdefs-extend-jump}

There are situations for which one would like to repeat a given component many
times, or under a given condition. The JUMP modifier is meant for that and
should be placed after the positioning, GROUP and EXTEND. This breaks the
sequential propagation along components in the instrument description. There may
be more than one JUMP per component instance.

The jump may depend on a condition:
\begin{mcstas}
COMPONENT name = comp(p_1 = e_1, p_2 = e_2, ...)
  AT (...)
  JUMP reference WHEN condition
\end{mcstas}

in which case the instrument TRACE will jump to the \textit{reference} when
\textit{condition} is true.

The \textit{reference} may be an instance name, as well as PREVIOUS, PREVIOUS($n$),
MYSELF, NEXT, and NEXT($n$), where $n$ is the index gap to the target either
backward (PREVIOUS) or forward (NEXT), so that PREVIOUS(1) is PREVIOUS and
NEXT(1) is NEXT. MYSELF means that the component will be iterated as long as the
condition is true. This may be a way to handle multiple scattering, if the
component has been designed for that.
\indexKW{PREVIOUS}
\indexKW{MYSELF}
\indexKW{NEXT}

The jump arrives directly inside the target component, in the local coordinate
system (i.e. without applying the AT and ROTATED keywords). In order to control
better the target positions, it is \emph{required} that, except for looping
MYSELF, the target component type should be an \emph{Arm}.
\indexKW{ROTATED}

There is a more general way to iterate components, which consists in repeating
the loop for a given number of times.
\begin{mcstas}
  JUMP reference ITERATE number_of_times
\end{mcstas}
This method is specially suited for very long curved guides of similar
components, but in order to take into account rotation and translation between
guide sections, the iterations are performed between Arm's.
\indexKW{ITERATE}

In the following example for a curved guide made on $n=500$ elements of length
$L$ on a curvature radius $R$, with gaps $d$ between elements, we simply write:
\begin{mcstas}
COMPONENT CG_In = Arm() AT (...)

COMPONENT CG_1  = Guide_gravity(l=L/n, m=1, ...)
  AT (0,0,0) RELATIVE PREVIOUS

COMPONENT CG_2_Position = Arm()
  AT (0,0,L/n+d) RELATIVE PREVIOUS
  ROTATED (0, (L/n+d)/R*180/PI, 0) RELATIVE PREVIOUS

COMPONENT CG_2  = Guide_gravity(l=L/n, m=1, ...)
  AT (0,0,0) RELATIVE PREVIOUS
  ROTATED (0, (L/n+d)/R*180/PI, 0) RELATIVE PREVIOUS
  JUMP CG_2_Position ITERATE n
...
COMPONENT CG_Out = Arm() AT (0,0,L/n) RELATIVE PREVIOUS
\end{mcstas}

Similarly to the \texttt{WHEN} modifier (see section
\ref{s:instrdefs-extend-when}), \texttt{JUMP} only applies within the TRACE
section of the instrument definition. Other sections (INITIALIZE, SAVE,
MCDISPLAY, FINALLY) are executed independently of the jump. As a side effect,
the 3D view of the instrument (mcdisplay) will show components as if there was
no jump. This means that in the following example, the very long guide 3D view
only shows a single guide element.

It is \emph{not} recommended to use the \verb+JUMP+ inside \verb+GROUP+s, as the
JUMP condition/counter applies to the component instance within its group.

We would like to emphasize the potential errors originating from such
jumps. Indeed, imbricating many jumps may lead to situations were it is
difficult to understand the flow of the simulation. We thus recommend the usage
of JUMPs only for experienced and cautious users.\index{Bugs!JUMPs}

%-------------------------------------------------------------------------------
\subsection{Enhancing statistics reaching components - SPLIT}
\indexKW{SPLIT}
\label{s:instrdefs-extend-enhance}

The following method applies when the incoming neutron event distribution is
considered to be representative of the real beam, but neutrons are lost in the
course of propagation (with low efficiency processes, absorption, etc). Then,
one may think that it's a pity to have so few events reaching the 'interesting'
part of the instrument (usually close to the end of the instrument description).
If some components make extensive use of random numbers (MC choices), they
shuffle this way the distributions, so that identical incoming events will not
produce the same outgoing event. In this case, you may use the \verb+SPLIT+
keyword with the syntax

\begin{mcstas}
  SPLIT r COMPONENT name = comp(...)
\end{mcstas}

where the optional number $r$ specifies the number of repetitions for each
event. Default is $r=10$.  Each neutron event reaching component \textit{name} will
be repeated $r$ times with a weight divided by $r$, so that in practice the
number of events for the remaining part of the simulation (down to the END),
will potentially have more statistics. This is only true if following components
(and preferably component \textit{name}) use random numbers. You may use this
method as many times as you wish in the same instrument, e.g. at the
monochromator and sample position. This keyword can also be used within a
GROUP. The efficiency is roughly $r$ raised to the number of occurrences in the
instrument, so that enhancing two components with the default $r=10$ will
produce at the end an enhancement effect of 100 in the number of events. The
execution time will usually get slightly longer. This technique is known as the
\emph{stratified sampling} (see Appendix \ref{s:MCtechniques}). If the
instrument makes use of global variables - e.g. in conjunction with a WHEN or
User Variable monitoring (see Monitor\_nD) - you should take care that these
variables are set properly for each SPLIT loop, which usually means that they
must be reset inside the SPLITed section and assigned/used further
on. \index{Bugs!SPLIT}

A usage example of the SPLIT keyword can be found in the \\
\verb+Neutron site/ILL/ILL_H15_IN6+ instrument from the \verb+mcgui+, to enhance
statistics for neutrons scattering on monochromators and sample.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Writing component definitions}
\label{s:compdefs}

The purpose of a \MCS component is to model the interaction of a
neutron with a physical component of a real instrument. Given the
state of the incoming neutron ray, the
component definition calculates the state of the neutron ray when it leaves
the component.  The calculation of the effect of the component on the
neutron is performed by a block of embedded C code.
One example of a component definition is given in section~\ref{s:slit}, and all
component definitions can be found on the \MCS
web-page~\cite{mcstas_webpage} and are described in the \MCS component manual.

There exists a large number of functions and constants available in
order to write efficient components. See appendix~\ref{c:kernelcalls}
for
\begin{itemize}
\item neutron propagation functions
\item geometric intersection time computations
\item mathematical functions
\item random number generation
\item physical constants
\item coordinate retrieval and operations
\item file generation routines (for monitors),
\item data file reading
\end{itemize}

%A component definition looks as follows:


%-------------------------------------------------------------------------------
\subsection{The component definition header}
\label{s:comp-header}

\begin{mcstas}
DEFINE COMPONENT name
\end{mcstas}
\indexKW{DEFINE COMPONENT}

This marks the beginning of the definition, and defines the name of the
component.
\begin{mcstas}
DEFINITION PARAMETERS (d_1, d_2, ...)
SETTING PARAMETERS (s_1, s_2, ...)
\end{mcstas}
\indexKW{DEFINITION PARAMETERS}
\indexKW{SETTING PARAMETERS}
This declares the definition and setting parameters of the component.
These parameters can be
accessed from all sections of the component (see below),
as well as in \verb+EXTEND+ sections of the instrument definition (see section~\ref{s:instrdefs}).
\index{Parameters!setting}
\index{Parameters!definition}

Setting parameters are translated into C variables usually of type
\verb+double+ in the generated simulation program, so they are usually
numbers. Definition parameters are translated into \verb+#define+ macro
definitions, and so can have any type, including strings, arrays, and
function pointers.

However, because of the use of \verb+#define+, definition parameters
suffer from the usual problems with C macro definitions. Also, it is not
possible to use a general C expression for the value of a definition
parameter in the instrument definition, only constants and variable
names may be used. For this reason, setting parameters should be used
whenever possible.

Outside the \verb+INITIALIZE+ section of components, changing setting parameter
values only affects the current section.

There are a few cases where the use of definition parameters instead of
setting parameters makes sense. If the parameter is not numeric, nor a character string ({\em i.e.} an
array, for example), a setting parameter cannot be
used. Also, because of the use of \verb+#define+, the C compiler can
treat definition parameters as constants when the simulation is
compiled. For example, if the array sizes of a multidetector are
definition parameters, the arrays can be statically allocated in the
component \verb+DECLARE+ section. If setting parameters were used, it
would be necessary to allocate the arrays dynamically using {\em e.g.}\
\verb+malloc()+.

Setting parameters may optionally be declared to be of type \verb+int+,
\verb+char *+ and \verb+string+, just as in the instrument definition (see
section~\ref{s:instrdefs}).

\begin{mcstas}
OUTPUT PARAMETERS (s_1, s_2, ...)
\end{mcstas}

\indexKW{OUTPUT PARAMETERS}
This declares a list of C identifiers (variables, functions) that are
output parameters (\textit{i.e.} global) for the
component. Output parameters are used to hold values that are computed
by the component itself, rather than being passed as input. This could
for example be a count of neutrons in a detector or a constant that is
precomputed to speed up computation.

Using \texttt{OUTPUT PARAMETERS} is \emph{strongly recommended} for
\texttt{DECLARE} and internal/global component variables and functions in order
to prevent that instances of the same component use the same variable
names. Moreover (see section \ref{s:comp-declare} below), these may be accessed
from any other instrument part (e.g. using the \verb+MC_GETPAR+ C macro).  On
the other hand, the variables from the SHARE sections should \emph{not} be
defined as OUTPUT parameters.

The \texttt{OUTPUT} \texttt{PARAMETERS} section is optional.

\subsubsection{Optional component parameters}
\index{Parameters!optional, default value}

Just as for instrument parameters, the definition and setting parameters of a
component may be given a default value. Parameters with default values are
called \emph{optional parameters}, and need not be given an explicit value when
the component is used in an instrument definition. A parameter is given a
default value using the syntax ``\textit{param}\texttt{ = }\textit{value}''.
For example
\begin{mcstas}
SETTING PARAMETERS (radius, height, pack= 1)
\end{mcstas}
Here \verb+pack+ is an optional parameter and if no value is given
explicitly, ``1'' will be used. In contrast, if no value is
  given for \texttt{radius} or \texttt{height}, an error message will
  result.

  Optional parameters can greatly increase the convenience for users of
  components with many parameters that have natural default values which are
  seldom changed. Optional parameters are also useful to preserve backwards
  compatibility with old instrument definitions when a component is updated. New
  parameters can be added with default values that correspond to the old
  behavior, and existing instrument definitions can be used with the new
  component without changes.

  However, optional parameters should not be used in cases where no general
  natural default value exists. For example, the length of a guide or the size
  of a slit should not be given default values. This would prevent the error
  messages that should be given in the common case of a user forgetting to set
  an important parameter.

%-------------------------------------------------------------------------------
\subsection{The \texttt{DEPENDENCY} line}
\indexKW{DEPENDENCY}
\label{s:comp-dependency}
\begin{mcstas}
DEPENDENCY "-lLIB1 -lLIB2 .."
\end{mcstas}
This optional line indicates any external library which are needed by the component.
It should be used when the component code calls external functions and routines
which should be available when compiling the instrument. 
This line must be indicated just before the \texttt{SHARE} and \texttt{DECLARE} sections.
Refer to the section \ref{s:dependency} for more information.

%-------------------------------------------------------------------------------
\subsection{The \texttt{DECLARE} section}
\label{s:comp-declare}
\begin{mcstas}
DECLARE
%{
// C code declarations (variables, definitions, functions)
// These are usually OUTPUT parameters to avoid name conflicts 
%}
\end{mcstas}
\indexKW{DECLARE} This gives C declarations of global variables,
functions, etc. that are used by the component code. This may for instance be
used to declare a neutron counter for a detector component. This section is
optional.

Note that any variables declared in a \verb+DECLARE+ section are
\emph{global}. Thus a name conflict may occur if two instances of a component
are used in the same instrument. To avoid this, variables declared in the
\texttt{DECLARE} section should be \texttt{OUTPUT} parameters of the component
because \MCS will then rename variables to avoid conflicts.  For example, a
simple detector might be defined as follows:

\begin{mcstas}
DEFINE COMPONENT Detector
OUTPUT PARAMETERS (counts)
DECLARE
%{
  int counts;
%}
...
\end{mcstas}

\indexKW{OUTPUT PARAMETERS}
\indexMCCH{MC\_GETPAR}{}
The idea is that the \texttt{counts} variable counts the number of neutrons detected. In
the instrument definition, the \texttt{counts} parameter may be referenced using
the \verb+MC_GETPAR+ C macro, as in the following example instrument
fragment:\label{mcgetpar}

\begin{mcstas}
COMPONENT d1 = Detector()
...
COMPONENT d2 = Detector()
...
FINALLY
%{
  printf("Detector counts: d1 = %d, d2 = %d\n",
         MC_GETPAR(d1,counts), MC_GETPAR(d2,counts));
%}
\end{mcstas}

This way, \MCS takes care to rename transparently the two 'counts'
\texttt{OUTPUT} parameters so that they are distinct, and can be accessed from
elsewhere in the instrument (EXTEND, FINALLY, SAVE, ...)  or from other
components. This particular example is outdated since \MCS monitors will
themselves output their contents.

%-------------------------------------------------------------------------------
\subsection{The \texttt{SHARE} section}
\label{s:comp-share}
\begin{mcstas}
SHARE
%{ 
// C code shared declarations (variables, definitions, functions)
// These should not be OUTPUT parameters
%}
\end{mcstas}

\indexKW{SHARE}

The \texttt{SHARE} section has the same role as \texttt{DECLARE} except that
when using more than one instance of the component, it is inserted \emph{only
  once} in the simulation code. No occurrence of the items to be shared should be
in the \texttt{OUTPUT} parameter list (not to have \MCS rename the
identifiers).  This is particularly useful when using many instances of the same
component (for instance guide elements). If the declarations were in the
\texttt{DECLARE} section, \MCS would duplicate it for each instance (making the
simulation code longer).  A typical example is to have shared variables,
functions, type and structure definitions that may be used from the component
\texttt{TRACE} section. For an example of \texttt{SHARE}, see the
samples/Single\_crystal component. The \verb+%include "file"+ keyword may be
used to import
a shared library. The \texttt{SHARE} section is optional and should be located \textit{before} the \texttt{DECLARE} section.

%-------------------------------------------------------------------------------
\subsection{The \texttt{INITIALIZE} section}
\label{s:comp-initialize}

\begin{mcstas}
INITIALIZE
%{
// C code initialization 
%}
\end{mcstas}
\indexKW{INITIALIZE} This gives C code that will be executed once at the
start of the simulation, usually to initialize any variables declared in the
\texttt{DECLARE} section. This section is optional. Component setting parameters
may be modified in this section, affecting the rest of the component.


%-------------------------------------------------------------------------------
\subsection{The \texttt{TRACE} section}
\label{s:comp-trace}

\begin{mcstas}
TRACE
%{
// C code to compute neutron interaction with component
%}
\end{mcstas}
\indexKW{TRACE}
\indexMCRH{PROP\_Z0}{}
This performs the actual computation of the interaction between the
neutron ray and the component. The C code should perform the appropriate
calculations and assign the resulting new neutron state to the state
parameters. Most components will require propagation routines to reach the component entrance/area. Special macros \verb+PROP_Z0;+ and \verb+PROP_DT();+ are provided to automate this process (see section \ref{s:calls:run-time}).

\indexMCRH{ABSORB}{textbf}
\index{Absorption}
\index{Neutron!absorption}
The C code may also execute the special macro \texttt{ABSORB} to indicate
that the neutron has been absorbed in the component and the simulation of
that neutron will be aborted.
\indexMCRH{ALLOW\_BACKPROP}{textbf}
\index{Backpropagation}
\index{Propagation!backward}
On the other hand, if the neutron event
should be \emph{allowed} be backpropagated, the special macro
\verb+ALLOW_BACKPROP;+ should precede the call to the \verb+PROP_+
call inside the component.
When the neutron state is changed or detected, for
instance if the component simulates multiple events as multiple
reflections in a guide, the
special macro \texttt{SCATTER}\indexMCRH{SCATTER}{textbf}
should be called. This does not affect the
results of the simulation in any way, but it allows the front-end
programs to visualize the scattering events properly, and to handle
component \texttt{GROUP}s in an instrument definition (see
section~\ref{s:trace}). It basically increments the SCATTERED counter.
\indexMCCH{SCATTERED}{}
The \texttt{SCATTER} macro should be called with
the state parameters set to the proper values for the scattering event, so that neutron events are displayed correctly.
For an example of \texttt{SCATTER}, see the optics/Guide
component.


%-------------------------------------------------------------------------------
\subsection{The \texttt{SAVE} section}
\label{s:comp-save}
\index{Data formats}
\indexKW{SAVE}

\begin{mcstas}
SAVE
%{
// C code to execute in order to save data 
%}
\end{mcstas}

This gives code that will be executed when the simulation ends, or is requested
to save data, for instance when receiving a USR2 signal (on Unix systems, see
section~\ref{s:run-sim}), or when triggered by the
\texttt{Progress\_bar(flag\_save=1)} component.  This might be used by monitors
and detectors in order to write results.  An extension depending on the selected
output format (see table~\ref{t:formatoptions} and section~\ref{s:run-sim}) is
automatically appended to file names, if these latter do not contain extension.

In order to work properly with the common output file format used in
\MCS, all monitor/detector components should use standard macros for
writing data in the SAVE or FINALLY section, as explained below. In the
following, we use $N = \sum_i p_i^0$ to denote the count of detected
neutron events, $p = \sum_i p_i$ to denote the sum of the weights of
detected neutrons, and $\textit{p2} = \sum_i p_i^2$ to denote the sum of
the squares of the weights, as explained in section~\ref{s:staterror}.

As a default, all monitors using the standard macros will display the
integral $p$ of the monitor bins, as well as the 2$^{nd}$ moment $\sigma$
and the number of statistical events $N$. This will result in a line such as:

\begin{mcstas}
Detector: CompName I=p CompName ERR=sigma CompNameN=N "filename"
\end{mcstas}


For 1D, 2D and 3D monitors/detectors, the data histogram store in the files is
given {\emph per bin} when the signal is the neutron intensity (\textit{i.e.} most
of the cases). Most monitors define binning for an $x_n$ axis value as the sum
of events falling into the $[ x_n x_{n+1} ]$ range, \textit{i.e} the bins are
{\emph not} centered, but left aligned.  Using the Monitor\_nD component, it is
possible to monitor other signals using the '\verb+signal=+\textit{variable\_name}'
in the 'options' parameter (refer to that component documentation).

\paragraph{Single detectors/monitors}
\label{s:DETECTOR_OUT}

\indexMCCH{DETECTOR\_OUT\_0D}{textbf}
The results of a single detector/monitor are written using the following
macro:
\begin{mcstas}
DETECTOR_OUT_0D(t, N, p, p2)
\end{mcstas}
Here, \textit{t} is a string giving a short descriptive title for the
results, {\em e.g.}\ ``Single monitor''.


\paragraph{One-dimensional detectors/monitors}

\indexMCCH{DETECTOR\_OUT\_1D}{textbf}
The results of a one-dimensional detector/\discretionary{}{}{}mon\-i\-tor are written using the
following macro:
\begin{mcstas}
DETECTOR_OUT_1D(t,
        xlabel, ylabel,
        xvar, x_min, x_max, m, 
        &N[0], &p[0], &p2[0],
       filename)
\end{mcstas}
Here,
\begin{itemize}
\item \textit{t} is a string giving a descriptive title ({\em e.g.}\ ``Energy
  monitor''),
\item \textit{xlabel} is a string giving a descriptive label for the X
  axis in a plot ({\em e.g.}\ ``Energy [meV]''),
\item \textit{ylabel} is a string giving a descriptive label for the Y
  axis of a plot ({\em e.g.}\ ``Intensity''),
\item \textit{xvar} is a string giving the name of the variable on the X
  axis ({\em e.g.}\ ``E''),
\item $x_\mathrm{min}$ is the lower limit for the X axis,
\item $x_\mathrm{max}$ is the upper limit for the X axis,
\item $m$ is the number of elements in the detector arrays,
\item $\&N[0]$ is a pointer to the first element in the array of $N$
  values for the detector component (or NULL, in which case no error
  bars will be computed),
\item $\&p[0]$ is a pointer to the first element in the array of $p$
  values for the detector component,
\item $\&\textit{p2}[0]$ is a pointer to the first element in the array of
  \textit{p2} values for the detector component (or NULL, in which case no error
  bars will be computed),
\item \textit{filename} is a string giving the name of the file in which
  to store the data.
\end{itemize}


\paragraph{Two-dimensional detectors/monitors}

\indexMCCH{DETECTOR\_OUT\_2D}{textbf}
The results of a two-dimensional detector/\discretionary{}{}{}mon\-i\-tor are written to a file using the
following macro:

\begin{mcstas}
DETECTOR_OUT_2D(t,
        xlabel, ylabel,
        x_min, x_max, y_min, y_max, m, n,
        &N[0][0], &p[0][0], &p2[0][0],
       filename)
\end{mcstas}

Here,
\begin{itemize}
\item \textit{t} is a string giving a descriptive title ({\em e.g.}\ ``PSD
  monitor''),
\item \textit{xlabel} is a string giving a descriptive label for the X
  axis in a plot ({\em e.g.}\ ``X position [cm]''),
\item \textit{ylabel} is a string giving a descriptive label for the Y
  axis of a plot ({\em e.g.}\ ``Y position [cm]''),
\item $x_\mathrm{min}$ is the lower limit for the X axis,
\item $x_\mathrm{max}$ is the upper limit for the X axis,
\item $y_\mathrm{min}$ is the lower limit for the Y axis,
\item $y_\mathrm{max}$ is the upper limit for the Y axis,
\item $m$ is the number of elements in the detector arrays along the X axis,
\item $n$ is the number of elements in the detector arrays along the Y axis,
\item $\&N[0][0]$ is a pointer to the first element in the array of $N$
  values for the detector component,
\item $\&p[0][0]$ is a pointer to the first element in the array of $p$
  values for the detector component,
\item $\&\textit{p2}[0][0]$ is a pointer to the first element in the array of
  \textit{p2} values for the detector component,
\item \textit{filename} is a string giving the name of the file in which
  to store the data.
\end{itemize}
Note that for a two-dimensional detector array, the first dimension is
along the X axis and the second dimension is along the Y axis. This
means that element $(i_x,i_y)$ can be obtained as $p[i_x*n+i_y]$ if $p$
is a pointer to the first element.

\paragraph{Three-dimensional detectors/monitors}

\indexMCCH{DETECTOR\_OUT\_3D}{textbf}
The results of a three-dimensional detector/\discretionary{}{}{}mon\-i\-tor are written to a file using the
following macro:
\begin{mcstas}
DETECTOR_OUT_3D(t,
        xlabel, ylabel,
        xvar, x_min, x_max, m, n, j,
        &N[0][0][0], &p[0][0][0], &p2[0][0][0],
       filename)
\end{mcstas}

The meaning of parameters is the same as those used in the 1D and 2D
versions of DETECTOR\_OUT. The available data format currently saves
the 3D arrays as 2D, with the 3rd dimension specified in the
\textit{type} field of the data header.

%-------------------------------------------------------------------------------
\subsection{The \texttt{FINALLY} section}
\label{s:comp-finally}
\indexKW{FINALLY}

\begin{mcstas}
FINALLY
%{
// C code to execute at end of simulation ...
%}
\end{mcstas}

This gives code that will be executed when the simulation has ended. This might
be used to free memory and print out final results from components,
\textit{e.g}.\ the simulated intensity in a detector. This section also triggers
the SAVE section to be executed.

%-------------------------------------------------------------------------------
\subsection{The \texttt{MCDISPLAY} section}
\label{s:comp-mcdisplay}
\indexKW{MCDISPLAY}

\begin{mcstas}
MCDISPLAY
%{
// C code to draw a sketch of the component ...
%}
\end{mcstas}

This gives C code that draws a sketch of the component in the plots
produced by the \verb+mcdisplay+ front-end (see
section~\ref{s:mcdisplay}). The section can contain arbitrary C code and
may refer to the parameters of the component, but usually it will
consist of a short sequence of the special commands described below that
are available only in the MCDISPLAY section.
When drawing components, all distances and positions are in meters and
specified in the local coordinate system of the component.

The MCDISPLAY section is optional. If it is omitted, \verb+mcdisplay+
will use a default symbol (a small circle) for drawing the component.

\paragraph{The \texttt{magnify} command}

This command, if present, must be the first in the section. It takes a
single argument: a string containing zero or more of the letters ``x'',
``y'' and ``z''. It causes the drawing to be enlarged along the
specified axis in case \verb+mcdisplay+ is called with the \verb+--zoom+
option. For example:
\begin{lstlisting}
    magnify("xy");
\end{lstlisting}


\paragraph{The \texttt{line} command}

The \texttt{line} command takes the following form:
\begin{lstlisting}
line(x_1, y_1, z_1, x_2, y_2, z_2)
\end{lstlisting}
It draws a line between the points $(x_1, y_1, z_1)$ and $(x_2, y_2,
z_2)$.

\paragraph{The \texttt{dashed\_line} command}

The \texttt{dashed\_line} command takes the following form:
\begin{mcstas}
dashed_line(x_1, y_1, z_1, x_2, y_2, z_2, n)
\end{mcstas}
It draws a dashed line between the points $(x_1, y_1, z_1)$ and $(x_2, y_2,
z_2)$ with $n$ equidistant spaces.


\paragraph{The \texttt{multiline} command}

The \texttt{multiline} command takes the following form:
\begin{mcstas}
  \texttt{multiline(n, x_1, y_1, z_1, ..., x_n, y_n, z_n)}
\end{mcstas}
It draws a series of lines through the $n$ points $(x_1, y_1, z_1)$,
$(x_2, y_2, z_2)$, \ldots, $(x_n, y_n, z_n)$. It thus accepts a variable
number of arguments depending on the value of $n$. This exposes
one of the nasty quirks of C since \emph{no} type checking is
performed by the C compiler. It is thus very important that all
arguments to \texttt{multiline} (except $n$) are valid numbers of type
\texttt{double}. A common mistake is to write
\begin{mcstas}
    multiline(3, x, y, 0, ...)
\end{mcstas}
which will silently produce garbage output. This must instead be
written as
\begin{mcstas}
    multiline(3, (double)x, (double)y, 0.0, ...)
\end{mcstas}

\paragraph{The \texttt{rectangle} command}

The \texttt{rectangle} command takes the following form:
\begin{mcstas}
rectangle(plane, x, y, z, width, height)
\end{mcstas}
Here \textit{plane} should be either \verb+"xy"+, \verb+"xz"+, or
\verb+"yz"+. The command draws a rectangle in the specified plane with
the center at $(x, y, z)$ and the size \textit{width} $\times$
\textit{height}.
Depending on \textit{plane} the width and height are defined as:\\
\begin{tabular} {ccc}
  \textit{plane} & \textit{width} & \textit{height} \\
  xy & x & y \\
  xz & x & z \\
  yz & y & z \\
 \end{tabular}

\paragraph{The \texttt{box} command}

The \texttt{box} command takes the following form:
\begin{lstlisting}
box(x, y, z, xwidth, yheight, zlength)
\end{lstlisting}
The command draws a box with the center at $(x, y, z)$ and the size \textit{xwidth} $\times$ \textit{yheight} $\times$ \textit{zlength}.

\paragraph{The \texttt{circle} command}

The \texttt{circle} command takes the following form:
\begin{lstlisting}
circle(plane, x, y, z, r)
\end{lstlisting}
Here \textit{plane} should be either \verb+"xy"+, \verb+"xz"+, or
\verb+"yz"+. The command draws a circle in the specified plane with the center
 at $(x, y, z)$ and the radius $r$.



%-------------------------------------------------------------------------------
\subsection{The end of the component definition}
\indexKW{END}

\begin{lstlisting}
END
\end{lstlisting}
This marks the end of the component definition.

%-------------------------------------------------------------------------------
\subsection{A component example: Slit}
\label{s:slit}
A simple example of the component \texttt{Slit} is given.

%FIXME \smallverbatimfile{McCode/mcstas-comps/optics/Slit.comp}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Extending component definitions}
\label{s:compdefs-extend}

Suppose you are interested by one component of the \MCS library, but you would
like to customize it a little. There are different ways to extend an existing
component.

%-------------------------------------------------------------------------------
\subsection{Extending from the instrument definition}
\indexKW{EXTEND}

If you only want to \emph{add} something on top of the component existing behavior, the simplest is to work from the instrument definition \texttt{TRACE} section, using the \texttt{EXTEND} modifier (see section \ref{s:instrdefs-extend-group}). You do not need to write a new component definition, but only add a piece of code to execute.

%-------------------------------------------------------------------------------
\subsection{Component heritage and duplication}
\indexKW{COPY}

There is a heritage mechanism to create children of existing components. These
are exact duplicates of the parent component, but one may override/extend
original definitions of any section.

The syntax for a full component child is
\begin{mcstas}
DEFINE COMPONENT child_name COPY parent_name
\end{mcstas}

This single line will copy all parts of the \textit{parent} into the \textit{child}, except for the documentation header.

As for normal component definitions, you may add other parameters,
\texttt{DECLARE}, \texttt{TRACE}, ... sections. Each of them will replace or
extend (be concatenated to, with the COPY/EXTEND keywords, see example below)
the corresponding \textit{parent} definition. In practice, you could copy a
component and only rewrite some of it, as in the following example:

\begin{mcstas}
DEFINE COMPONENT  child_name COPY parent_name

  SETTING PARAMETERS (newpar1, newpar2) 
  INITIALIZE COPY  parent_name EXTEND 
  %{  
// C code to be concatenated to the  parent_name INITIALIZE
  %} 
  SAVE
  %{  
// C code to replace the  parent_name SAVE 
  %} 
\end{mcstas}
where two additional parameters have been defined, and should be handled in the
extension of the original INITIALIZE section.

On the other hand, if you do not derive a component as a whole from a parent,
you may still use specific parts from any component:
\begin{mcstas}
DEFINE COMPONENT  name ...
  DECLARE COPY  parent1 
  INITIALIZE COPY  parent2 EXTEND 
%{
// C code to be concatenated to the  parent2 INITIALIZE
%}
TRACE COPY  parent3
\end{mcstas}

This mechanism may lighten the component code, but a special care should be taken in mixing bits from different sources, specially concerning variables. This may result in difficulties to compile components.\index{Compilation!failure}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{McDoc, the \MCS library documentation tool}
\label{s:mcdoc}
\index{McDoc|(textbf}

\MCS includes a facility called McDoc to help maintain good documentation of
components and instruments. In the source code, comments may be
written that follow a particular format understood by McDoc. The McDoc facility
will read these comments and automatically produce output documentation in
various forms. By using the source code itself as the source of documentation,
the documentation is much more likely to be a faithful and up-to-date
description of how the component/instrument actually works.

%-------------------------------------------------------------------------------
\subsection{Documentation generators mcdoc and mcgui}
\indexMCTOOL{mcgui}{}
\indexMCTOOL{mcdoc}{}

Two forms of documentation can be generated. One
is the component entry dialog in the \verb+mcgui+ front-end, see
section~\ref{s:mcgui}. The other is a collection of web pages documenting
the components and instruments, handled via the \verb+mcdoc+ front-end (see section~\ref{s:mcdoc-run}), and the complete documentation for all available
\MCS components and instruments may be found at the \MCS
web page~\cite{mcstas_webpage}, as well as in the \MCS library
(see~\ref{s:comp-overview}). All available \MCS documentation is accessible from the \verb+mcgui+ 'Help' menu.

Note that McDoc-compliant comments in the source code are no substitute
for a good reference manual entry. The mathematical equations describing
the physics and algorithms of the component should still be written up
carefully for inclusion in the component manual. The McDoc comments are
useful for describing the general behavior of the component, the
meaning and units of the input parameters, etc.


%-------------------------------------------------------------------------------
\subsection{The format of the comments in the library source code}

The format of the comments understood by McDoc is mostly
straight-forward, and is designed to be easily readable both by humans
and by automatic tools. McDoc has been written to be quite tolerant in
terms of how the comments may be formatted and broken across lines. A
good way to get a feeling for the format is to study some of the examples
in the existing components and instruments. Below, a few
notes are listed on the requirements for the comment headers:

\index{Keywords!McDoc|(textbf}
The comment syntax uses \verb+%IDENTIFICATION+, \verb+%DESCRIPTION+,
\verb+%PARAMETERS+, \verb+%EXAMPLE:+, \verb+%LINKS+, and \verb+%END+
keywords to mark different sections of the documentation. Keywords may
be abbreviated (except for \verb+%EXAMPLE:+), \textit{e.g.} as \verb+%IDENT+ or \verb+%I+.

Additionally, optional keys \verb+%VALIDATION+ and \verb+%BUGS+ may be found to list validation status and possible bugs in the component.
\indexDOCSEC{\%VALIDATION}{\%VALIDATION}{textbf}
\indexDOCSEC{\%BUGS}{\%BUGS}{textbf}

\begin{itemize}
\item
  \indexDOCSEC{\%IDENTIFICATION}{\%I[DENTIFICATION]}{textbf}
  \indexDOCKEY{author}{textbf}
  \indexDOCKEY{written by}{textbf}
  \indexDOCKEY{date}{textbf}
  \indexDOCKEY{version}{textbf}
  \indexDOCKEY{origin}{textbf}
  \indexDOCKEY{modified by}{textbf}
  \index{Identification!McDoc section|textbf}
  In the \verb+%IDENTIFICATION+
  section, \verb+author:+ (or \verb+written by:+ for backwards
  compatibility with old comments) denote author; \verb+date:+,
  \verb+version:+, and \verb+origin:+ are also supported. Any number of
  \verb+Modified by:+ entries may be used to give the revision history.
  The \verb+author:+, \verb+date:+, etc. entries must all
  appear on a single line of their own. Everything else in the
  identification section is part of a "short description" of the
  component.
\item
  \indexDOCSEC{\%PARAMETERS}{\%P[ARAMETERS]}{textbf}
  \index{Parameters!McDoc section|textbf}
  In the \verb+%PARAMETERS+
  section, descriptions have the form
  \hbox{``\texttt{\textit{name\/}:~[\textit{unit\/}] \textit{text\/}}''}
  or \hbox{``\texttt{\textit{name\/}:~\textit{text\/} [\textit{unit\/}]}''}.
  These may span multiple lines, but subsequent lines must be
  indented by at least four spaces. Note that square brackets \verb+[]+ should
  be used for units. Normal parentheses are also supported for backwards
  compatibility, but nested parentheses do not work well.
\item
  \indexDOCSEC{\%DESCRIPTION}{\%D[ESCRIPTION]}{textbf}
  \index{Description!McDoc section|textbf}
  The \verb+%DESCRIPTION+
  section contains text in free format. The text may contain HTML tags
  like \verb+<IMG>+ (to include pictures) and
  \verb+<A>+\ldots\verb+</A>+
  (for links to other web pages, but see also the \verb+%LINK+
  section). In the generated web documentation pages, the text is set in
  \verb+<PRE>+\ldots\verb+</PRE>+, so that the line breaks in the source
  will be obeyed.
\item 
  \indexDOCSEC{\%EXAMPLE}{\%EX[AMPLE]}{textbf}\sloppy
  \index{Example!McDoc section|textbf}
  The \verb+%EXAMPLE:+
  lines in instrument headers indicate an example parameter set or command that may be
  run to test the instrument. A following \texttt{Detector: $<$name$>$\_I=$<$value$>$}
  indicates what value should be obtained for a given monitor. More than one example
  line may be specified in instruments.
\item
  \indexDOCSEC{\%LINK}{\%L[INK]}{textbf}
  \index{Link!McDoc section|textbf}
  Any number of \verb+%LINK+
  sections may be given; each one contains HTML code that will be put in
  a list item in the link section of the description web page. This
  usually consists of an \verb+<A HREF="..."> ... </A>+ pointer to some
  other source of information.
\item
  \indexDOCSEC{\%INSTRUMENT\_SITE}{\%IN[STRUMENT\_SITE]}{textbf}
  \index{Instrument site!McDoc section|textbf}
  Optionally, an \verb+%INSTRUMENT_SITE+ section followed by a single word is used to sort \emph{instruments} by origin/location in the 'Neutron Site' menu in \verb+mcgui+.
\item  \indexDOCSEC{\%END}{\%E[ND]}{textbf}
  After \verb+%END+, no more comment text is read by McDoc.
\end{itemize}
\index{Keywords!McDoc|)}

\index{McDoc|)}
\index{Kernel|)}
