Computing for Science

The Computing for Science (CS) group supports ILL scientists, students and visitors in a number of activities including data analysis, instrument simulation and sample simulation.

Back to ILL Homepage

All Software


McStas - Tutorial

McStas - ILL- Tutorial for instrument and component design

  • B-1: Your own components. How to include them. Posting them for the community.
  • B-2: Overview of a component

Abstract

The aim of this page is to show you step by step how to describe and simulate an instrument or a component. The McStas graphic tools will also be presented. You can also look at the alternative tutorial made by the Risoe team. Refer to the McStas manual for more informations.

Other tutorials:

A - Writing an Instrument simulation

A-1: The instrument overview

We here plan to write a simple but realistic desciption of the IN14 3-axis spectrometer (TAS) at ILL, and use it with a Vanadium sample. This instrument is basically composed of :

  • the ILL horizontal cold source at the H53 guide entrance (on wich is IN14)
  • a guide 6x12 cm, lenght 15.83 m, coated Ni 58, at 2.15 m from the source
  • a PG002  monochromator (size 15x12.2 cm), at L1=16.68 m from source, rotated with angle A1
  • a 40' Soller collimator rotated with angle A2=2*A1
  • a Vanadium sample (incoherent scatterer) at L2=2.12 m from monocromator, rotated with angle A3
  • a PG002  analyzer (size 10x14 cm), at L3=1.35 m from sample, rotated with angle A5
  • a 3x4 cm slit
  • a 3He flux detector, at L4=0.7 m from analyzer, rotated with angle A6=2*A5

Of course, one can add some other components after (supermirror guide, sollers, slits, other monitors, etc...).
It here appears that you need essentially the geometrical and technical specifications of all the components of the instrument.

To top

A-2: Where to reach the McStas software

The McStas package has been installed at ILL on most Linux and SGI (Silicon Graphics-Unix) machines (such as mica) thanks to RG, as well as the required perl/pgplot extensions for design and results visualization. Scilab and Matlab viewers are also available. Of course, you can also install McStas on your own computer, but try anyway to maintain a unique component library, for portability.

Note: If you use McStas for the first time on an ILL Silicon Graphics Machine (SGI/IRIX) such as orus, mica, pandora, lotus or qaz, you have to install some environement variables for Perl and Pgplot. Refer to this matter in the installation guide.

So, just login on a machine and open a terminal/console window

xterm   for instance

From there, you need to create a text file where to describe the instrument ('in14_tut.instr' for instance); open a text editor (I recommand Nedit 5.0)

nedit in14_tut.instr    or an equivalent

Unix : syntax highlighting for McStas files

Fig 1 : A Nedit 5.0 window with highlight syntaxing for the in14_tut instrument.

You can also use the McStas GUI instrument editor by typing

mcgui <instr_name.instr>

The McStas manual may be accessed within mcgui/Help menu, or with the 'mcdoc --manual' command. Additionally, the 'mcdoc --tools' and 'mcdoc --show' will list the McStas tools, and open the Component Library help respectively. The Component manual is also available frokm there.
 

You can then begin to type in the instrument definition file, or open an already existing one (select File Menu / Open Instrument/Edit).

Fig 2 : A McGUI editor window for the in14_tut instrument.

To top

A-3: Let's start !!

Before continuing, we should wonder what parameters will be required by the instrument.

In the example that I provide,, I choosed to enter parameters

Ki  incident neutron wavevector (Angs-1),
Q exchange wavevector modulus (Angs-1) and
E exchange energy (meV)

These will be asked by the instrument simulation at computation start. You can use as many numerical parameters as you need (max is 1000 !). Character string parameters are also permitted (if you set their type to 'string' or 'char *'). The parameter values usually define the instrumental geometry and physical parameters. They may be used and modified during the simulation.

Globally, an instrument is described following the general template below. We are now going to study the IN14 instrument described in the overview.
The in14_tut.instr file begins with the DEFINE section (you can save this file as a Source/txt file from your Browser). Thus the first line of the instrument description file will be

DEFINE INSTRUMENT IN14(Ki,Q,E)

followed by comments between '/*' and '*/' to identify author, date, instrument, parameters, usage, and a typical example.
You may additionally define default parameters for the instrument with:

DEFINE INSTRUMENT IN14(Ki=2.662,Q=2,E=0)

To top

A-4: Describing the instrument structure

Each part of the instrument is indicated as a component, positioned and rotated with specified values. So, you first need to look at the component library to search if a given component already exists. If you can't find it, then you may need to write one corresponding to your needs (as we shall see further in this tutorial). In order to build the instrument simulation, McStas first looks for components in the current instrument location, and then refers to the common component library (e.g. /usr/local/lib/mcstas on Unix machines)

The description of the instrument is a sequential listing into the TRACE section. This means that you should not put two 'active' components exactly at the same place, overlap or include one into an other. Usually, you can separate them by say 1 mm if you really want to put them at 'nearly' the same place. Monitors can be positioned at the same place, as they usually do not affect the neutron beam. Anyway, you may build component groups. Look into the McStas manual for more.

Thus, we can write the skeleton of the instrument (following the informations given in the overview). The components have a generic name (from the McStas library, for instance Source_flux) and a specific name identifier, only valid for your simulation (for instance source).

TRACE
COMPONENT source = Source_flux() /* a flat constant source */
AT (0,0,0) ABSOLUTE

COMPONENT cold_guide = Guide()   /* guide between source and mono */
AT (0,0,2.15) RELATIVE source

COMPONENT mono_craddle = Arm() /* this is the monochromator craddle */
AT (0, 0, L1) RELATIVE source ROTATED (0, A1, 0) RELATIVE source

COMPONENT mono = Monochromator() /* Monochromator */
AT (0,0,0) RELATIVE mono_craddle

COMPONENT out_mono = Arm()  /* this is the mono-sample axis */
AT (0,0,0) RELATIVE mono_craddle ROTATED (0, A2, 0) RELATIVE source

COMPONENT mono_soller = Soller() /* a Soller collimator */
AT (0, 0, .9) RELATIVE out_mono

COMPONENT focus_sample = Arm()   /* this is the sample craddle */
AT (0, 0, L2) RELATIVE out_mono ROTATED (0, A3, 0) RELATIVE out_mono

COMPONENT sample = V_sample()    /* Sample */
AT (0,0,0) RELATIVE focus_sample

COMPONENT out_sample = Arm()     /* this is the sample-ana axis */
AT (0,0,0) RELATIVE focus_sample ROTATED (0, A4, 0) RELATIVE out_mono

COMPONENT focus_ana = Arm()      /* this is the analyzer craddle */
AT (0,0, L3) RELATIVE out_sample ROTATED (0, A5, 0) RELATIVE out_sample

COMPONENT ana = Monochromator()  /* Analyzer */
AT (0,0,0) RELATIVE focus_ana

COMPONENT out_ana = Arm()        /* this is the ana-det axis */
AT (0,0,0) RELATIVE focus_ana ROTATED (0, A6, 0) RELATIVE out_sample

COMPONENT focus_det = Arm()      /* this is the detector craddle */
AT (0, 0, L4) RELATIVE out_ana

COMPONENT Detector = Monitor()   /* detector */
AT(0,0,0) RELATIVE focus_det
 

Positioning components


Each component is placed (with AT) and tilted (ROTATED) with given values (in meters and degrees) or variables. The axis system is defined as

the Z-axis beeing the propagation axis (main geometrical direction)
the Y-axis is vertical
the X-axis makes the coordinate system direct

Rotations are around those axis, after the AT translation is performed. These operations are usually made in a given reference coordinate system (precised with the RELATIVE keyword, followed by one of your instrument component-identifier, such as ana or focus_det). As you can see in this skeleton, we introduced the angles A1 to A6 and the distances L1 to L4 in order to position the various components. These values must be defined somewhere. This will be explained in the computations and internal variables section below.
 

Component parameters


The components usually need some parameters to specify their behaviour (for instance the source shape and flux, the guide length, etc...). The component parameters will have to be given between the two parenthesis () following the component type, for instance

Monochromator(<my monochromator parameters=my values> , ...)

Thus when you need to use a specific component, you should first look at it's documentation or source code header, in order to look at the required parameters (in future versions, components will also have some default value parameters if not provided by user).

Here is a component parameters example for the source :

COMPONENT source = Source_flux( /* a flat constant source */
 radius = 0.20,
 dist = 2.16,
 xw = 0.06, yh = 0.12,<
 E0 = Ei,
 dE = 0.5,
 flux=1e13)
AT (0,0,0) ABSOLUTE

The component name of the parameter (left part of the =, for instace radius) is fixed by the component definition. It can not be changed in your instrument.
The values of these parameters (right part of =) can be given as a numerical (0.9), string ("my_filename", do not forget the quotes !), an instrument parameter (could be Q here) or variable (A1, but has to be defined before), and you can use mathematical expressions using internal variables, except instrument input parameters (e.g. 'A2/2' is permitted, if A2 has already been defined and is not an input component/instrument parameter). If you want to compute a numerical value (for instance A2/2), you may need to create a variable containing this value., as indicated in the computations and internal variables section below. For instance, in the source example up-there, the value of Ei should be known before the component is positioned.
The other components also need some parameters, as indicated in the TRACE section of the in14_tut.instr file. Please have a look at it.

In fact, we shall use a simple model of flat energy flux distribution for the source, flat monochromator and analyzer, and a single detector at the end. The Vanadium sample scattering is 'focussed' towards the analyzer. No need to scatter somewhere else, and loose neutrons !

Note: when using McGUI, the filenames (e.g. for monitors) should be specified between double quotes (").

To top

A-5: Internal variables and computations (embeded C code)

Defining some component parameters or variables internal to the instrument simulation is done in two steps.

If you need to use such computations (mathematical expressions), you must compute them with embeded C code before calling the component.

Obviously, computing some paranmeters needed to position, rotate and describe components is an essential point of the simulation. This is done in the DECLARE and INITIALIZE sections, before the TRACE keyword.
In this example, we need to calculate the values of

  • Ei in source : energy of neutrons produced by the source : should be set by the monochromator Bragg law.
  • L1 to L4 for AT keywords : these are fixed, but should be easely modified in the instrument
  • A1 to A6 for ROTATED keywords : these are to be computed from the instrument input parameters Ki, Q and E
  • mono_q, ana_q : are values to be computed from monochromator and analyzer crystal lattice parameters, DM and DA. These should be easely changeable by user.

The computation of these values is done in two steps.

Declaring instrument internal variables : DECLARE

In the DECLARE section, which is optional if you don't use variables in your instrument (see the in14_tut.instr file), you indicate between symbols '%{' and '}%' what C variables you are going to use.
Possible C types are
 

Data Type

Description/Example

code

double

a real in double precision

double L1 = 16.68;

int

an integer from -32768 to +32768

int ORDER = 1;

long int

an integer from -2^31 to 2^31

long int ORDER = 1;

char* (pointer to char)

a character string of 20 chars
a specific, fixed string
an variable length string

char name[20];
<char name[]=""my_name";">
char *name; or char name[];</char>

You can assign a default value in the C declaration section. The variables declared in this section are global. You can use them in the whole instrument (INITIALIZE, TRACE and FINALLY sections) as shown below.

In the case of string arrays (character strings), you may need to dynamically allocate some memory with the malloc C function. Do not forget to free the allocated memory when it is not needed anymore (with the free C funtion). Please refer for this matter to a C language book, such as the Kernigan and Richie, C language, Prentice Hall, London, 1994. An example of dynamical allocation is shown in the Monitor_nD component (which calls the MCSTAS/share/monitor_nd-lib shared library).

Now, you can look at the DECLARE section of the instrument definition file. You will see that we introduce here the variables Ei, L1 to L4, A1 to A6, mono_q and ana_q, but also some other variables (DM, DA) that can be easely changed by the user, as they are all gathered in the same zone of the instrument source file. The variables Kf and Ef are declared also in case you would need them somewhere esle in the instrument.

Computing mathematical expressions and internal variables : INITIALIZE

In the INITIALIZE section, which follows the DECLARE section, you can also declare some C variables, but these will only be valid inside the INITIALIZE section. For instance, in our example, we declare Vi, Vf and others...
The embeded C code, between symbols '%{' and '}%', is executed at the begining of each computation. It can then be used to compute the values of your instrument variables, or to open some output files, display some specific informations on screen, etc...

In a typical TAS instrument, the incident Ki, transfert Q and final Kf neutron wavevector modulus, are related to the geometrical angles A1 to A6 by classical expressions :

Bragg reflexions

2 pi/Ki = 2 DM sin (A1) and 2 pi/Kf = 2 DA sin (A5) Momentum exchange rule Q2 = Ki2 + Kf2 - 2 | Ki.Kf | cos (A4) Energy exchange rule Ef = Ei - E Geometrical relations A2 = 2*A1
A6=2*A5

with the monochromator and analyzer lattice spacings DM and DA respectively (in Angstroms). The value of A3 deends on the sample orientations. We shall use here A3=A4/2.
In our example, we check the validity of instrument parameters, by the if keywords., and display a message if they are not valid (printf). We compute the values of mono_q and ana_q :

mono_q = 2*PI*ORDER/DM;
ana_q = 2*PI*ORDER/DA;

while DM and DA have been declared and initialized in the DECLARE section. ORDER is the order of the Bragg reflexion (usually 1).
The values of PI and DEG2RAD are defined in McStas. We do also a minimal error checking (no division by 0 please).

At the end of the INITIALIZE section, all variables defined in the DECLARE section or used in the TRACE section should have been defined and assigned.

To top

A-6: The end of the simulation : END and FINALLY

At the end of the simulation file, place the keyword END. That's all.

If you want to do some stuff at the end of the computation (display some parameter values, free some C memory allocation blocks...), you are invited to do that in the FINALLY section (C code between the usual %{ and %} signs). It is executed at the end of the simulation. In our example we do not use that section.

A-7: Looking at the instrument : mcdisplay

Now that the instrument description file is complete, you can look at the instrument with the mcdisplay tool.

You need to process the in14_tut.instr through mcstas, with the trace option

mcstas --trace in14_tut.instr Compile the simulation with math library (-lm) gcc -O -o in14_tut.out in14_tut.c -lm

These two latter commands may be performed automatically with the

mcrun in14_tut.instr -n0

Then enter the instrument parameters, defining the geometry

mcdisplay in14_tut.out -n 1e6 Ki=2.662 Q=2 E=0.2

A window will pop-up, showing the whole instrument top view (from 'up-there'). Depending on the Plotter (set with the MCSTAS_FORMAT env. variable or the 'mcgui/Run menu/Choose backend') PGPLOT, Scilab and Matlab may be used.

These operations can be done in mcgui just by selecting Run Menu / Run Simulation. A parameter window will pop-up ; enter the values of Ki=2.662, Q=2 and E=0.2, click on the 'trace' option, and 'Start' button.

Fig 3 : mcdisplay : IN14 Instrument overview with mcdisplay using Scilab plotter.

You can identify on this picture the main H53 guide (cyan long rectangle), and the instrument itself on the right side. It is possible to zoom on the spectrometer with the middle mouse button. Right button resets the full view.

Fig 4 : mcdisplay : A zoom on IN14 sample area. You can identify the monochromator (left side), the soller (dark blue), sample with a magenta monitor, analyzer (yellow) and finally the detector. (right side)

The simulation should also display the message

Starting simulation 'in14_tut.out --trace -n 1e6 Ki=2.662 Q=2 E=.2' ...
IN14@ILL 3-axis spectrometer
Angles (deg) A2 = 41.190287 ; A4 = -44.287497 ; A6 = 41.486632

And you can type 'Q' in the PGPlot window to stop viewing the instrument. If you rather press the spacebar, you can look at each neutron (a moving dot on the PGPlot window) passing. The Z or middle mouse button will zoom.

Scilab and Matlab plotters will show a 3D view of the instrument. You may select a portion of the instrument to look at.

In fact, each McStas component includes a simple drawing of the component in the MCDISPLAY section.

To top

A-8: Launching a simulation and scans : mcrun

In order to perform scans on a specific parameter, you need to first compile the instrument. The 'trace' option is not needed if you don't want to view the instrument (it slowers the simulation).

 

You need to process the in14_tut.instr through mcstas

mcstas in14_tut.instr Compile the simulation with math library (-lm) gcc -O -o in14_tut.out in14_tut.c -lm You may launch a single simulation in14_tut.out -n 1e6 Ki=2.662 Q=2 E=0

These three commands may be executed automatically with

mcrun -n 1e6 in14_tut.instr Ki=2.662 Q=2 E=0

The course of the simulation will then be displayed as follows (execution takes 8 seconds on my LinuxPPC):

IN14@ILL 3-axis spectrometer
Angles (deg) A2 = 41.190287 ; A4 = -44.129900 ; A6 = 41.190287
Detector: Detector_I=4.10826 Detector_ERR=0.501173 Detector_N=368

And a mcstas.sim file containing informations about the last simulation will be created.
Then, launch a serie of scans. You need to specify how many points you want (9), how many neutrons for each point (1e6), the name of the output simulation file (in14.sim) and between which values should vary the parameters (min and max values are separated by a coma for E parameter)

mcrun -N9 -n 1e6 in14_tut.out -f in14.sim Ki=2.662 Q=2 E=-1,1

The simulation results (output of Monitor) is written in the in14.sim file, and displayed on screen. A mcstas.sim file is also gathering informations about the last performed scan. You can plot the results of the simulation with the mcplot command (see below) using the PGPLOT, Matlab and Scilab backend, or any data analysis tool, such as Our Applications for Matlab(R) or the freeware GNU Octave.

Fig 5 : mcrun/mcplot : The IN14 detector signal from Vanadium incoherent scatterer, obtained from Octave/Gnuplot.

To top

A-9: Looking at results : mcplot

The mcplot tool is designed in order to display the results of a single simulation or a full scan. It looks for the simulation file (usually called mcstas.sim) which is created for each simulation generating some output detector files. In order to test it, we add a PSD (position sensitive detector) just on the sample, in odrer to obtain a photo of the neutron beam.

Between the focus_sample and the out_sample components of the instrument TRACE section, we add :

COMPONENT PSD_sample = PSD_monitor(
  xmin = -.1, xmax = .1,
  ymin = -.1, ymax = .1,
  nx = 10, ny = 10,
  filename="sample.psd")
AT (0, 0, 0) RELATIVE focus_sample

Re-compile and run mcrun -n 1e6 in14_tut.instr Ki=2.662 Q=2 E=0

The simulation displays :

IN14@ILL 3-axis spectrometer
Angles (deg) A2 = 41.190287 ; A4 = -44.129900 ; A6 = 41.190287
Detector: PSD_sample_I=7.52492e+08 PSD_sample_ERR=2.51029e+07 PSD_sample_N=3282
Detector: Detector_I=0.274917 Detector_ERR=0.153811 Detector_N=18

Then, display the PSD photo by typing mcplot

This tool can handle all detectors installed in your simulation. With PGPLOT, type 'Q' to exit. 'P' and 'C' keys generate PS and color PS files.

Fig 6 : mcplot : the PSD beam shape on the sample using PGPLOT.

Displaying the simulation results can also be performed from the mcgui tool, just selecting the 'plot results' button in the Run Menu / Run Simulation.

The same result (PSD monitor is a x/y monitor) can be obtained with the Monitor_nD component with

COMPONENT PSD_sample = Monitor_nD(
  xmin = -.1, xmax = .1,
  ymin = -.1, ymax = .1,
  options="x y all bins=10, file=sample.psd")
AT (0, 0, 0) RELATIVE focus_sample


Of course you can also use any grapher such as Our Applications for Matlab(R) or the freeware GNU Octave. The McStas output file format is self-documented.

To top

A-10: How to improve this simulation

This tutorial has shown you how to design an already quite complex instrument. But there are a number of other additional stuff that may improve significantly the efficiency of your simulations. Look at the ILL McStas library.
 

  • For monitors, use the Monitor_nD can monitor all usual neutron parameters into 1D and 2D files.
  • For sources, use the  Source_gen component, that can describe rectrangular/circular shaped sources, flat and Maxwellian fluxes.


Using more monitors

You can use as many monitors as you want, and especially those that do not exist in reality (energy monitors, 4-D resolution ellipsoid detector...). Those can be overlapped as they do not affect the neutron beam. For instance, in the case of TAS instruments such as IN14, I recommand to install a (k,w) monitor (Monitor_nD by E.Farhi) on the final detector in order to measure the instrumental 4D resolution ellipsoid.

COMPONENT PSD_sample = Monitor_nD(
  xmin = -.1, xmax = .1,
  ymin = -.1, ymax = .1,
  options="list all neutrons kx ky kz energy file=ellipsoid")
AT (0, 0, 0) RELATIVE focus_sample

Focusing the energy of the source

In the IN14 example, we focussed the energy of the source beam on what is required by the monochromator. Thus we have computed the central incident energy Ei, and used a small dispersion around it (0.5 meV). Ei is the energy of the neutrons that will be deflected by the monochromator (from Ki value).

Using a Maxwellian source

In order to describe a real source with a better accuracy, you may use a Maxwellian model, such as the Source_Maxwell written by TH and EF. The Source_gen and Source_Maxwell_3 also includes such distributions.

Using an external file describing the flux

Also, if you have at your disposal some experimental measurements of the source characteristics, you can use the Filter_gen by EF. It does modify the beam in order to match a given distribution.
You should use first a Source_flux component, with flux=1. Then position after the Filter_gen, giving the name of the experimental data file. This file should contain the type (energy, wavevector, wavelength) of data as comments, and a two column data giving the effective flux.
You may also use a list of neutron events generated from MCNP, Vitess or McStas with the Virtual_input.

Using a flux optimizer

McStas simulations can be quite slow. In order to improve the efficiency of the Monte-Carlo shots in the instrument, one can modify the source characteristics in order to reach a specific location in the instrument with the best efficienty.
There are actually two source optimizers.

  • The Source_Optimizer , by EF is a simple component that acts directly on each neutron characteristic (speed, direction, position...), trying to maintain the energy distribution, in order to obtain the maximum flux at the Monitor_Optimizer location(s).
  • The Source_adapt , by KN, rather acts on the direction of the neutron in order to select a better direction to reach the Adapt_check component.

The typical speed-up is about 10 to 20 (10 times more neutrons arriving), and the flux is of course kept. Beware anyway the distribution changes that may arise from such optimisations. Refer to the McStas manual for comments about simulation optimisations.

Using a bent monochromator or analyzer

In the IN14 example, we used a flat monochromator. A double bent monochromator is also available (Mon_2foc by KL and PN, or the Monochromator_curved by EF), in order to focus the beam on the sample and on the detector.

To top

An instrument template for McStas

DEFINE INSTRUMENT instrument_name(instrument_parameter1, instrument_parameter2, ...)
DECLARE    /* for global definition in your instrument */
%{
/* Optional embedded C code in case you want something special */
%}
INITIALIZE
%{
/* to do at simulation start */
%}
TRACE
  COMPONENT component_id = component_name(
            component_parameter1 = {value1}, component_parameter2 = {value2}, ...)
           AT (x_position, y_position, z_position)
           ROTATED (x_tilt, y_tilt, z_tilt)
  (...)
FINALLY     /* to do at simulation end */
END
For a simple use, the DECLARE, INITIALIZE and FINALLY blocks can be empty and even omitted. They can contain embeded C code (between %{ and %}braces) for special stuff (for instance to write some informations at simulation start or send an e-mail at the end of the simulation ...)

B - Writing a new component

This section is not written yet, sorry...

To top