User and Programmers Guide to the Neutron Ray-Tracing Package McStas, version 3.8.6

3.5  Using simulation front-ends

McStas includes a number of front-end programs that extend the functionality of the simulations. A front-end program is an interface between the user and the simulations, running the simulations and presenting the output in various ways to the user.

The list of available McStas front-end programs is (see mcdoc --tools, or run any tool with -h for its specific help):

1    McStas Tools 
2       mcstas         Main instrument compiler 
3       mcrun          Instrument build and execution utility 
4       mcgui          Graphical User Interface instrument builder 
5       mcdoc          Component library documentation generator/viewer 
6       mcplot         Simulation result viewer (default: pyqtgraph backend) 
7       mcplot-html     Simulation result viewer, in a web browser (D3.js) 
8       mcplotdiff-html Difference plot between two simulation results, in a browser 
9       mccoplot-html   Overlay (co-plot) of two simulation results 1D monitors 
10       mcdisplay       Instrument geometry viewer (default: pyqtgraph backend) 
11       mcresplot       Instrument resolution function viewer (Python/matplotlib) 
12       mctest         Self-test / benchmark of the current McStas installation 
13       mcviewtest      Viewer for mctest results, with mcplotdiff-html comparisons 
14    Each tool also exists in dedicated *-matplotlib, *-pyqtgraph, *-html, 
15    *-webgl or *-webgl-classic variants where applicable, see sections below. 
16    DOC:      Please visit https://www.mcstas.org

3.5.1  The graphical user interface (mcgui)

The front-end mcgui provides a graphical user interface that interfaces the various parts of the McStas package. It may be started with the single command

1    mcgui

The mcgui program may optionally be given the name of the instrument file to use.

Dependencies: As of McStas 3.x, mcgui is a pure Python/Qt application (PyQt), bundled with the standard conda-forge McStas package; no separate Perl, Tk, or PGPLOT installation is required.

The menus

When the front-end is started the main window is opened (see figure 3.2). This window displays the output from compiling and running simulations, and contains a few menus and buttons for easy navigation. The main purpose of the front-end is to edit and compile instrument definitions, run the simulations, and visualize the results.

The File menu has the following features:

File/Open instrument

selects the name of an instrument file to be used.

File/Edit current

opens a simple editor window with McStas syntax highlighting for editing the current instrument definition. This function is also available from the Edit button to the right of the name of the instrument definition in the main window.

File/Spawn editor

This starts the editor defined in the environment variable VISUAL or EDITOR on the current instrument file. It is also possible to start an external editor manually; in any case mcgui will recompile instrument definitions as necessary based on the modification dates of the files on the disk.

File/Compile instrument

forces a recompile of the instrument definition, regardless of file dates. This is for example useful to pick up changes in component definitions, which the front-end will not notice automatically. This might also be required when choosing MPI and NeXus options.

File/Save log file

saves the text in the window showing output of compilations and simulations into a file.

File/Clear output

erases all text in the window showing output of compilations and simulations.

File/Preferences

Opens the configuration dialog shown in figure 3.3. Several settings can be chosen here:

  • Selection of the desired plotting/display backend (pyqtgraph, matplotlib, html, …) for mcplot and mcdisplay.

  • Choice of code generator (mccode or mccode-antlr, see section 3.3.1.0).

  • Choice of editor to use when editing instrument files.

  • Automatic quotation of strings when inserting in the built-in editor.

  • Possibility to not optimize when compiling the generated c-code. This is very handy when setting up an instrument model, which requires regular compilations.

To save the chosen settings for your next McStas run, use Save Configuration in the File menu.

File/Save configuration

saves user settings from Configuration options and Run dialogue to disk.

File/Quit

exits the graphical user interface front-end.

The Simulation menu has the following features:

Simulation/Read old simulation

prompts for the name of a file from a previous run of a McStas simulation (usually called mccode.sim). The file will be read and any detector data plotted using the mcplot front-end. The parameters used in the simulation will also be made the defaults for the next simulation run. This function is also available using the “Read” button to the right of the name of the current simulation data.

Simulation/Run simulation

opens the run dialog window, explained further below.

Simulation/Plot results

plots (using mcplot) the results of the last simulation run or spawns a load dialogue to load a set of results.


PIC


Figure 3.3.: The “configuration options” dialog in mcgui.


The New from Template menu (known as “Neutron site” in older McStas releases) contains a list of template and example instruments as found in the McStas library, sorted by category/facility (e.g. Templates, ILL, ISIS, ESS, Union_demos, …– see chapter 8 for a curated tour). When selecting one of these, a local copy of the instrument description is transferred to the active directory (so that users have modification rights) and loaded. One may then view its source (Edit) and use it directly for simulations/trace (3D View).
 

The Tools menu gathers minor tools.

Tools/Plot current/other results

Plot current simulation results and other results.

Tools/Dataset convert/merge

Opens a GUI to merge scattered data sets (e.g. from successive runs or an MPI job) or assemble scan sets.

Tools/Shortcut keys

displays the shortcut keys used for running and editing instruments.

The Help menu has the following features, through use of mcdoc and a web browser. To customize the used web browser, set the BROWSER environment variable. If BROWSER is not set, mcgui uses netscape/mozilla/firefox on Unix/Linux and the default browser on Windows.

Help/McStas User manual

calls mcdoc --manual, brings up the local pdf version of this manual, using a web browser.

Help/McStas Component manual

calls mcdoc --comps, brings up the local pdf version of the component manual, using a web browser.

Help/Component library index

displays the component documentation using the component index.html index file.

Help/McStas web page

calls mcdoc --web, brings up the McStas website in a web browser.

Help/Tutorial

opens the McStas tutorial for a quick start.

Help/Current instrument info

generates a description web-page of the current edited instrument.

Help/Test McStas installation

launches mctest to check that the McStas package is installed properly and generates accurate results (see section 3.5).

Help/Generate component index

(re-)generates locally the component index.html.

The run dialog


PIC


Figure 3.4.: The run dialog in mcgui.


The run dialog is used to run simulations. It allows the entry of instrument parameters as well as the specifications of options for running the simulation (see section 3.4 for details). It also allows to run the mcdisplay (section 3.5.4) and mcplot (section 3.5.5) front-ends together with the simulation.

The meaning of the different fields is as follows:

Run:Instrument parameters

allows the setting of the values for the input parameters of the instrument. The type of each instrument parameter is given in parenthesis after each name. Floating point numbers are denoted by (D) (for the C type “double”), (I) denotes integer parameters, and (S) denotes strings. For parameter scans and optimizations, enter the minimum and maximum values to scan/optimize, separated by a comma, e.g. 1,10 and do not forget to set the # Scanpoints to more than 1.

Run:Output to

allows the entry of a directory for storage of the resulting data files in (like the --dir option). If no name is given, the results are stored in the current directory, to be overwritten by the next simulation.

Run:Force

Forces McStas to overwrite existing data files

Neutron count

sets the number of neutron rays to simulate (the --ncount option).

Run:Gravity

Activates gravitation handling. Not all components full support the use of gravitation, but all transport in “free space” using the PROP_DT, PROP_Z0 etc. macros will include propagation with gravity. Only local, internal component propagation without the PROP routines will be gravity-less. As a conclusion it is considered safe and to high precision correct to apply the gravitation setting if one takes care to use the Guide_gravity component and other gravity-supporting guide types in combination with non-gravity components that are “small” in size, i.e. samples, lenses, etc.

Run:Random seed/Set seed to

selects between using a random seed (different in each simulation) for the random number generator, or using a fixed seed (to reproduce results for debugging).

Run:Simulate/Trace (3D)/Optimize

selects between several modes of running the simulation:

  • Simulate: perform a normal simulation or a scan when #steps is set to non-zero value

  • Trace (3D view): View the instrument in 3D tracing individual neutrons through the instrument

  • Optimize: find the optimum value of the simulation parameters in the given ranges (see section 3.4.5).

  • Backgrounding (bg): Simulate or Optimize in the background.

Run:# steps / # optim

sets the number of simulation to run when performing a parameter scan or the number of iterations to perform in optimization mode.

Run:Plot results

– if checked, the mcplot front-end will be run after the simulation has finished, and the plot dialog will appear (see below).

Run:Format

quick selection of output format (McCode or NeXus).

Run:Clustering method

selects between running locally or via MPI. See section 3.7 on parallel computing for more informations.

Run:Number of nodes

sets the number of MPI nodes to use.

Run:Inspect component

(Trace mode) will trace only neutron trajectories that reach a given component (e.g. sample or detector).

Run:First component

(Trace mode) seletcs the first component to plot (default is first) in order to define a region of interest.

Run:Last component

(Trace mode) seletcs the last component to plot (default is first) in order to define a region of interest.

Run:Maximize monitor

(Optimization mode) seletcs up to three monitors which integral value should be maximized, varying instrument parameters. If no monitor is selected, the sum of all monitors is optimized.

Run:Start

runs the simulation.

Run:Cancel

aborts the dialog.

Most of the settings on the run dialog can be saved for your next McStas run using ’Save configuration’ in the File menu.

Before running the simulation, the instrument definition is automatically compiled if it is newer than the generated C file (or if the C file is newer than the executable). The executable is assumed to have a .out suffix in the filename. NB: If components are changed, automatic compilation is not performed. Instead, use the File/Compile menu item in mcgui.

The editor window

The editor window provides a simple editor for creating and modifying instrument definitions. Apart from the usual editor functions, the “Insert” menu provides some functions that aid in the construction of the instrument definitions:

Editor Insert/Instrument template

inserts the text for a simple instrument skeleton in the editor window.

Editor Insert/Component

opens up a dialog window with a list of all the components available for use in McStas. Selecting a component will display a description. Double-clicking will open up a dialog window allowing the entry of the values of all the parameters for the component (figure 3.5). See section 4.3 for details of the meaning of the different fields.

The dialog will also pick up those of the users own components that are present in the current directory when mcgui is started. See section 4.7 for how to write components to integrate well with this facility.

Editor Insert/Type

These menu entries give quick access to the entry dialog for the various component types available, i.e. Sources, Optics, Samples, Monitors, Misc, Contrib and Obsolete.


PIC

Figure 3.5.: Component parameter entry dialog.


3.5.2  Running simulations on the commandline (mcrun)

The mcrun front-end provides a convenient command-line interface for running simulations with the same automatic compilation features available in the mcgui front-end. It also provides a facility for running a series of simulations while varying an input parameter.

The command

1mcrun sim args ...
 
2

will compile the instrument definition sim.instr (if necessary) into an executable simulation sim.out. It will then run sim.out, passing the argument list args

The possible arguments are the same as those accepted by the simulations themselves as described in section 3.4, with the following extensions:

The -h option will list valid options; see also Table 3.1 for the complete, current option list.

3.5.3  GPU acceleration via OpenACC

McStas 3.x supports GPU-accelerated simulations through the OpenACC framework, enabling substantial speed-ups over CPU-only execution on compatible NVIDIA hardware.

Requirements

Running a GPU-accelerated simulation

Pass the --openacc flag to mcrun:

  mcrun --openacc MyInstrument.instr -n 1e9

Combined multi-core + GPU execution. It is also possible to use both CPU cores and the GPU simultaneously. Enable this by adding the following to the OACCFLAGS field of your mccode_config.json:

  "OACCFLAGS": "-fast -Minfo=accel -acc=gpu,multicore
                -gpu=managed -DOPENACC -DMULTICORE"

Further information

GPU terminology specific to McStas/McXtrace 3 and detailed debugging tips are documented on the McCode wiki:

3.5.4  Graphical display of simulations (mcdisplay)

The front-end mcdisplay is a graphical visualization tool, very useful for debugging. It presents a schematic drawing of the instrument definition, showing the position of the components and the paths of the simulated neutrons through the instrument. It is thus very useful for debugging a simulation, for example to spot components in the wrong position or to find out where neutrons are getting lost.

To use the mcdisplay front-end with a simulation, run it as follows:

1mcdisplay sim args ...
 
2

where sim is the name of either the instrument source sim.instr or the simulation program sim.out generated by mcstas, and args are the normal command line arguments for the simulation, as explained above. The -h option will list valid options.

The drawing back-end may be selected by invoking one of the dedicated front-ends directly:

For instance, calling

1mcdisplay-webgl BNL_H8.instr lambda=2.36
 
2

will open a WebGL view of the instrument in a browser tab. The mcdisplay front-end can also be run from the mcgui front-end.

The (default, PyQtGraph) front-end accepts the following options, amongst others – run mcdisplay --help for the complete, current list:

When debugging trajectories through a long or complex instrument, combining --inspect with a modest --ncount typically gives the clearest, fastest picture of what is happening around a particular component.

3.5.5  Plotting the results of a simulation (mcplot)

The front-end mcplot is a program that produces plots of all the monitors in a simulation, and it is thus useful to get a quick overview of the simulation results.

In the simplest case, the front-end is run simply by typing

1    mcplot
 
2

This will plot any simulation data stored in the current directory, which is where simulations store their results by default. If the --dir or --file options have been used (see section 3.4), the name of the file or directory should be passed to mcplot, e.g. mcplot dir ” or “mcplot file ”. It is also possible to plot one single text (not binary) data file from a given monitor, passing its name to mcplot.

As with mcdisplay (section 3.5.4), the drawing back-end may be selected by invoking the dedicated front-end directly: mcplot-pyqtgraph (the default), mcplot-matplotlib, or mcplot-html (renders an interactive, self-contained web page using D3.js, see section 3.4.2), or by setting the MCSTAS_FORMAT environment variable.

All plotters read the plain-text McStas/McCode data format (section 3.6); NeXus files are not currently read back by the plotters.

The mcplot front-end can also be run from the mcgui front-end.

The initial display shows plots for each detector in the simulation.

Comparing two simulation results: mcplotdiff-html and mccoplot-html. Two companion browser-based tools reuse mcplot-html’s plotting code to compare a pair of simulation results (two output directories, or two single monitor files), matching monitors by output filename:

Both accept -A LABEL_A/-B LABEL_B to control the labels used for each input, and -o OUTPUT to control the output directory name; run either with --help for the complete option list. mcplotdiff-html is also used internally by mcviewtest (section 3.5) to compare test runs against a reference.

3.5.6  Plotting resolution functions (mcresplot)

The mcresplot front-end is used to plot the resolution function, particularly for triple-axis spectrometers, as calculated by the Res_sample component or TOF_Res_sample for time-of-flight instruments. It requires to have a Res_monitor (or TOF_Res_monitor) component further in the instrument description (at the detector position).

As of McStas 3.x, mcresplot is a pure Python tool built around a covariance-matrix method (rather than reading a resolution ellipsoid directly out of the simulation), following the approach implemented in the Takin2 package [Web20]. Neutron events collected by the Res_monitor are loaded with NumPy, the weighted covariance matrix of the \((\boldsymbol {Q},\omega )\) four-vectors is computed and inverted to obtain the resolution matrix, and the resulting ellipsoids are drawn with matplotlib (2D projections and slices, plus a 3D view).

The mcresplot front-end is launched with the command

1mcresplot outfile

Here, outfile is the name of a file output from a simulation using the Res_monitor component. Useful options include --QEfile (if the event file is in the \(h\,k\,l\,E\,w\) format rather than the default \(\mathbf {k}_i\,\mathbf {k}_f\,w_i\,w_f\) format), --centreonQ (center plots on the mean \(\boldsymbol {Q}\) rather than the origin), --save=file (save the plots to a file instead of, or in addition to, showing them interactively), --noplot (compute and print the resolution matrices only, without opening a plot window) and --tex (use LaTeX for axis labels). Run mcresplot --help for the full, current option list.

The front-end will open a window displaying projections of the 4-dimensional resolution function \(R(\boldsymbol {Q}, \omega )\), measured at a particular choice of \(\boldsymbol {Q}\) and \(\omega \), see the component manual. The covariance matrix of the resolution function, the resolution along each projection axis and the resulting resolution matrix are also shown, as well as the instrument name and parameters used for the simulation.

To use the mcresplot front-end, a Python installation with NumPy and matplotlib is required (both are part of the standard McStas conda-forge environment).

3.5.7  Creating and viewing the library, component/instrument help and Manuals (mcdoc)

McStas provides an easy way to generate automatically an HTML help page about a given component or instrument, or the whole McStas library.

1mcdoc 
2mcdoc searchterm 
3mcdoc file.comp

The first example generates an index.html catalog file using the available components and instruments (both locally, and in the McStas library), and browses it using the BROWSER environment variable (e.g. firefox, chromium, …). Alternatively, if a search term or a file.comp/file.instr path is given, mcdoc will search within the library and open documentation for all matching entries.

Additional options include --install/-i (regenerate the local installation-wide index), --dir=DIR/-d (add search results from a given directory), and --verbose/-v (print a parsing log). The options --manual/-m, --comps/-c and --web/-w will open the User Manual (this document), the Component Manual, and the McStas web site, respectively, all requiring BROWSER to be defined. Finally, the --help option will display the command help, as usual.

See section 4.7 for more details about the McDoc usage and header format. mcdoc is a pure Python tool, part of the standard McStas conda-forge package.

Online wiki. In addition to this manual, extensive and frequently updated documentation is maintained on the McCode GitHub wiki [Wik]:

https://github.com/mccode-dev/McCode/wiki

The wiki includes end-user guides, component development howtos, GPU acceleration information, and migration guides from McStas 2.x to 3.x.

3.5.8  Self-testing the installation (mctest, mcviewtest)

McStas ships with a Python self-test/benchmark harness, replacing the earlier mcrun --test command. mctest compiles and runs a selection (or all) of the example instruments found under the current installation(s), and stores each run’s results (including any test-defined %Example reference values) in a timestamped output folder. Useful options include --ncount, --mpi and --openacc (forwarded to mcrun for every tested instrument), --config=LABEL (test only a specific McCode installation/config), --instr=REGEX (test only matching instrument names), and --limit=N (test only the first N instruments per version); run mctest --help for the full list.

mcviewtest then generates an HTML report of one or more mctest runs found in a given folder (the current directory by default). When more than one run is present (e.g. a reference run and a run on a different platform, GPU vs. CPU, or a different McStas branch), it takes the oldest subfolder as the reference column, and additionally runs mcplotdiff-html (section 3.5.5) between each other column’s monitor output and the reference’s, adding a DIFF [vs ref] link next to each such row in the report. These comparisons are cached on disk and generated in parallel (--diffworkers), so re-running mcviewtest is fast; use --nodiff to skip generating them entirely, or --diff-errors-only to only diff rows that already show a discrepancy.