mcstasscript.interface.instr.McCode_instr

mcstasscript.interface.instr.McCode_instr

class mcstasscript.interface.instr.McCode_instr(name, parameters=None, author=None, origin=None, ncount=None, mpi='not_set', seed=None, force_compile=None, output_path=None, increment_folder_name=None, custom_flags=None, executable_path=None, executable=None, suppress_output=None, gravity=None, input_path=None, package_path=None, checks=None, NeXus=None, openacc=None)

Main class for writing a McCode instrument using McStasScript

Initialization of McCode_instr sets the name of the instrument file and its methods are used to add all aspects of the instrument file. The class also holds methods for writing the finished instrument file to disk and to run the simulation. This is meant as a base class that McStas_instr and McXtrace_instr inherits from, these have to provide some attributes. Inherits from libpyvinyl BaseCalculator in order to harmonize input with other simulation engines.

executablestr

Name of executable, mcrun or mxrun

particlestr

Name of probe particle, “neutron” or “x-ray”

package_namestr

Name of package, “McStas” or “McXtrace”

name

name of instrument file

Type

str

author

name of user of McStasScript, written to the file

Type

str, default “Python Instrument Generator”

origin

origin of instrument file (affiliation)

Type

str, default “ESS DMSC”

input_path

directory in which simulation is executed, uses components found there

Type

str, default “.”

output_path

directory in which the data is written

Type

str

executable_path

absolute path of mcrun command, or empty if it is in path

Type

str

parameters

contains all input parameters to be written to file

Type

ParameterContainer

declare_list

contains all declare parrameters to be written to file

Type

list of DeclareVariable instances

initialize_section

string containing entire initialize section to be written

Type

str

trace_section

string containing trace section (OBSOLETE)

Type

str

finally_section

string containing entire finally section to be written

Type

str

component_list

list of components in the instrument

Type

list of component instances

component_name_list

list of names of the components in the instrument

Type

list of strings

component_class_lib

dict of custom Component classes made at run time

Type

dict

component_reader

ComponentReader instance for reading component files

Type

ComponentReader

package_path

Path to mccode package containing component folders

Type

str

run_settings

Dict of options set with settings

Type

dict

data

List of McStasData objects produced by last run

Type

list

add_parameter(*args, \*\*kwargs)

Adds input parameter to the define section

add_declare_var(type, name)

Add declared variable called name of given type to the declare section

append_declare(string)

Appends to the declare section

append_initialize(string)

Appends a string to the initialize section, then adds new line

append_initialize_no_new_line(string)

Appends a string to the initialize section

append_finally(string)

Appends a string to finally section, then adds new line

append_finally_no_new_line(string)

Appends a string to finally section

append_trace(string)

Obsolete method, add components instead (used in write_c_files)

append_trace_no_new_line(string)

Obsolete method, add components instead (used in write_c_files)

available_components(string)

Shows available components in given category

component_help(name)

Shows help on component of given name

add_component(instance_name, component_name, \*\*kwargs)

Add a component to the instrument file

copy_component(new_component_name, original_component, \*\*kwargs)

Makes a copy of original_component with new_component_name

get_component(instance_name)

Returns component instance with name instance_name

get_last_component()

Returns component instance of last component

set_component_parameter(instance_name, dict)

Adds parameters as dict to component with instance_name

set_component_AT(instance_name, AT_data, \*\*kwargs)

Sets position of component named instance_name

set_component_ROTATED(instance_name, ROTATED_data, \*\*kwargs)

Sets rotation of component named instance_name

set_component_RELATIVE(instane_name, string)

Sets position and rotation reference for named component

set_component_WHEN(instance_name, string)

Sets WHEN condition of named component, is logical c expression

set_component_GROUP(instance_name, string)

Sets GROUP name of component named instance_name

append_component_EXTEND(instance_name, string)

Appends a line to EXTEND section of named component

set_component_JUMP(instance_name, string)

Sets JUMP code for named component

set_component_SPLIT(instance_name, string)

Sets SPLIT value for named component

set_component_c_code_before(instance_name, string)

Sets c code before the component

set_component_c_code_after(instance_name, string)

Sets c code after the component

set_component_comment(instance_name, string)

Sets comment to be written before named component

print_component(instance_name)

Prints an overview of current state of named component

print_component_short(instance_name)

Prints short overview of current state of named component

show_components()

Prints overview of postion / rotation of all components

write_c_files()

Writes c files for %include in generated_includes folder

write_full_instrument()

Writes full instrument file to current directory

show_instrument()

Shows instrument using mcdisplay

set_parameters(dict)

Inherited from libpyvinyl BaseCalculator

settings(**kwargs)

Sets settings for performing simulation

backengine()

Performs simulation, saves in data attribute

run_full_instrument(**kwargs)

Depricated method for performing the simulation

interface()

Shows interface with jupyter notebook widgets

get_interface_data()

Returns data set from latest simulation in widget

__init__(name, parameters=None, author=None, origin=None, ncount=None, mpi='not_set', seed=None, force_compile=None, output_path=None, increment_folder_name=None, custom_flags=None, executable_path=None, executable=None, suppress_output=None, gravity=None, input_path=None, package_path=None, checks=None, NeXus=None, openacc=None)

Initialization of McStas Instrument

Parameters
  • name (str) – Name of project, instrument file will be name + “.instr”

  • arguments (keyword) –

    parametersParameterContainer or CalculatorParameters

    Parameters for this instrument

    authorstr

    Name of author, written in instrument file

    originstr

    Affiliation of author, written in instrument file

    input_pathstr

    Work directory, will load components from this folder

    mpiint

    Number of mpi threads to use in simulation

    output_pathstr

    Sets data_folder_name

    increment_folder_namebool

    Will update output_path if folder already exists, default True

    ncountint

    Sets ncount

    mpiint

    Sets thread count

    force_compilebool

    If True (default) new instrument file is written, otherwise not

    custom_flagsstr

    Sets custom_flags passed to mcrun

    executablestr

    Name of the executable

    executable_pathstr

    Path to mcrun command, “” if already in path

    suppress_outputbool

    Set to True to surpress output

    gravitybool

    If True, gravity will be simulated

Methods

__init__(name[, parameters, author, origin, ...])

Initialization of McStas Instrument

add_component(name[, component_name, ...])

Method for adding a new Component instance to the instrument

add_declare_var(*args, **kwargs)

Method for adding declared variable to instrument

add_parameter(*args, **kwargs)

Method for adding input parameter to instrument

add_search(statement[, SHELL])

Adds a search statement to the instrument

add_user_var(*args, **kwargs)

Method for adding user variable to instrument

append_declare(string)

Method for appending code to the declare section directly

append_finally(string)

Method for appending code to the finally section of instrument

append_finally_no_new_line(string)

Method for appending code to the finally section of instrument

append_initialize(string)

Method for appending code to the initialize section

append_initialize_no_new_line(string)

Method for appending code to the initialize section, no new line

append_trace(string)

Appends code to trace section, only used in write_c_files

append_trace_no_new_line(string)

Appends code to trace section, only used in write_c_files

available_components(*args)

Helper method that shows available components to the user

backengine()

Runs instrument with McStas / McXtrace, saves data in data attribute

check_for_errors()

Methods that checks for common McStas errors

check_for_relative_errors([start_ref, ...])

Method for checking if RELATIVE locations does not contain unknown references

clear_search()

Clears the instrument of all search statements

component_help(name, **kwargs)

Method for showing parameters for a component before adding it to the instrument

copy_component(name[, original_component, ...])

Method for adding a copy of a Component instance to the instrument

dump([fname])

Dump class instance to file.

from_dump(dumpfile)

Load a dill dump from a dumpfile.

get_component(name)

Get the component instance of component with specified name

get_component_subset_index_range([...])

Provides start and end index for components in run_from to run_to range

get_last_component()

Get the component instance of last component in the instrument

has_errors()

Method that returns true if errors are found in instrument

init_parameters()

Create empty ParameterContainer for new instrument

make_component_subset()

Uses run_from and run_to specifications to extract subset of components

move_component(name[, before, after])

Moves component with given name to before or after

move_user_vars_to_declare()

Moves all uservars to declare for compatibility with McStas 2.X

print_component(name)

Method for printing summary of contents in named component

print_component_short(name)

Method for printing summary of contents in named component

print_components([line_length])

Obsolete method, use show_components instead

read_instrument_file()

Reads current instrument file if it exists, otherwise creates one first

remove_component(name)

Removes component with given name from instrument

reset_parameters(value)

Resets the calculator parameters

reset_run_points()

Reset run_from and run_to points to the full instrument

run_from(component_ref[, run_name, tag])

Set limit for instrument, only run from given component, load MCPL ot start

run_full_instrument(**kwargs)

Runs McStas instrument described by this class, returns list of McStasData

run_to(component_ref[, run_name, comment])

Set limit for instrument, only run to given component, save MCPL there

saveH5(filename[, openpmd])

Not relevant, but required from BaseCalculator, will be removed

set_calculator_base_dir(value)

Set the calculator base directory

set_dependency(string)

Sets the DEPENDENCY line of instruments, expanding its system search

set_input(value)

Set the calculator input data.

set_instrument_base_dir(value)

Set the instrument base directory

set_output_data_types(value)

Set the calculator output data type.

set_output_filenames(value)

Set the calculator output filenames.

set_output_keys(value)

Set the calculator output keys.

set_parameters([args_as_dict])

Sets parameters contained in this calculator using dict or kwargs

settings([ncount, mpi, seed, force_compile, ...])

Sets settings for McStas run performed with backengine

settings_string()

Returns a string describing settings stored in this instrument object

show_analysis([variable])

show_components([line_length])

Method for printing overview of all components in instrument

show_diagram([analysis, variable, limits])

Shows diagram of component connections in insrument

show_dump(point[, run_name, tag])

show_dumps()

show_instrument([format, width, height, new_tab])

Uses mcdisplay to show the instrument in web browser

show_instrument_file([line_numbers])

Displays the current instrument file

show_parameters([line_length])

Method for displaying current instrument parameters

show_run_subset()

Shows current subset of instrument selected with run_from and run_to methods

show_search()

Shows all search statements on instrument level

show_settings()

Prints settings stored in this instrument object

show_variables()

Shows declared variables in instrument

subset_check(start_ref, end_ref)

Checks that when the instrument is broken into subsets, it is still valid

write_c_files()

Obsolete method for writing instrument parts to c files

write_full_instrument()

Method for writing full instrument file to disk

Attributes

base_dir

The base path for the output files of this calculator in consideration of instrument_base_dir and calculator_base_dir

calculator_base_dir

data

The alias of output.

input

instrument_base_dir

name

output

The output of this calculator

output_data_types

output_file_paths

The final output file paths considering base_dir

output_filenames

output_keys

output_path

parameters

add_component(name, component_name=None, *, before=None, after=None, AT=None, AT_RELATIVE=None, ROTATED=None, ROTATED_RELATIVE=None, RELATIVE=None, WHEN=None, EXTEND=None, GROUP=None, JUMP=None, SPLIT=None, comment=None, c_code_before=None, c_code_after=None)

Method for adding a new Component instance to the instrument

Creates a new Component instance in the instrument. This requires a unique instance name of the component to be used for future reference and the name of the McStas component to be used. The component is placed at the end of the instrument file unless otherwise specified with the after and before keywords. The Component may be initialized using other keyword arguments, but all attributes can be set with approrpiate methods.

Parameters
  • name (str) – Unique name of component instance

  • component_name (str) – Name of McStas component to create instance of

  • arguments (Keyword) –

    afterstr

    Place this component after component with given name

    beforestr

    Place this component before component with given name

    ATList of 3 floats

    Sets AT_data, position relative to reference

    AT_RELATIVEstr

    Sets reference component for postion

    ROTATEDList of 3 floats

    Sets ROTATED_data, rotation relative to reference

    ROTATED_RELATIVEstr

    Sets reference component for rotation

    RELATIVEstr

    Sets reference component for both position and rotation

    WHENstr

    Sets when condition which must be a logical c expression

    EXTENDstr

    Initialize the extend section with a line of c code

    GROUPstr

    Name of the group this component should belong to

    JUMPstr

    Set code for McStas JUMP statement

    commentstr

    Comment that will be displayed before the component

add_declare_var(*args, **kwargs)

Method for adding declared variable to instrument

Parameters
  • type (parameter) – type of input parameter

  • name (parameter) – name of parameter

  • arguments (keyword) –

    arrayint

    default 0 for scalar, if specified length of array

    valueany

    Initial value of parameter, can be list of length vector

    commentstr

    Comment displayed next to declaration of parameter

add_parameter(*args, **kwargs)

Method for adding input parameter to instrument

Type does not need to be specified, McStas considers that a floating point value with the type ‘double’. Uses libpyvinyl Parameter object.

Examples

Creates a parameter with name wavelength and associated comment add_parameter(“wavelength”, comment=”wavelength in [AA]”)

Creates a parameter with name A3 and default value add_parameter(“A3”, value=30, comment=”A3 angle in [deg]”)

Creates a parameter with type string and name sample_name add_parameter(“string”, “sample_name”)

Parameters
  • type ((optional) parameter) – type of input parameter, double, int, string

  • name (parameter) – name of parameter

  • arguments (keyword) –

    valuefloat, int or str

    Default value of parameter

    unitstr

    Unit to be displayed

    commentstr

    Comment displayed next to declaration of parameter

    optionslist or value

    list or value of allowed values for this parameter

Adds a search statement to the instrument

The dependency line can be used to tell McStas to search for files in additional locations. Double quotes are added.

Parameters
  • statement (str) – The search statement

  • SHELL (bool (default False)) – if True, shell keyword is added

add_user_var(*args, **kwargs)

Method for adding user variable to instrument

Parameters
  • type (parameter) – type of input parameter

  • name (parameter) – name of parameter

  • arguments (keyword) –

    arrayint

    default 0 for scalar, if specified length of array

    commentstr

    Comment displayed next to declaration of parameter

append_declare(string)

Method for appending code to the declare section directly

This method is not meant for declaring simple variables which should be done using add_declare_var. This method can be used to declare functions, structures and unions directly.

Parameters

string (str) – code to be added to declare section

append_finally(string)

Method for appending code to the finally section of instrument

The finally section consists of c code and will be compiled, thus any syntax errors will crash the simulation. Code is added on a new line for each call to this method.

Parameters

string (str) – code to be added to finally section

append_finally_no_new_line(string)

Method for appending code to the finally section of instrument

The finally section consists of c code and will be compiled, thus any syntax errors will crash the simulation. Code is added to the current line.

Parameters

string (str) – code to be added to finally section

append_initialize(string)

Method for appending code to the initialize section

The initialize section consists of c code and will be compiled, thus any syntax errors will crash the simulation. Code is added on a new line for each call to this method.

Parameters

string (str) – code to be added to initialize section

append_initialize_no_new_line(string)

Method for appending code to the initialize section, no new line

The initialize section consists of c code and will be compiled, thus any syntax errors will crash the simulation. Code is added to the current line.

Parameters

string (str) – code to be added to initialize section

append_trace(string)

Appends code to trace section, only used in write_c_files

The most common way to add code to the trace section is to add components using the seperate methods for this. This method is kept as is still used for writing to c files used in legacy code. Each call creates a new line.

Parameters

string (str) – code to be added to trace

append_trace_no_new_line(string)

Appends code to trace section, only used in write_c_files

The most common way to add code to the trace section is to add components using the seperate methods for this. This method is kept as is still used for writing to c files used in legacy code. No new line is made with this call.

Parameters

string (str) – code to be added to trace

available_components(*args)

Helper method that shows available components to the user

If called without any arguments it will display the available component categories. If a category is given as a string in the first input, components in that category are printed.

Parameters

(optional) (first argument) – Category that matches one of the McStas component folders

backengine()

Runs instrument with McStas / McXtrace, saves data in data attribute

This method will write the instrument to disk and then run it using the mcrun command of the system. Settings are set using settings method.

check_for_errors()

Methods that checks for common McStas errors

Currently checks for: RELATIVE for AT and ROTATED reference a component that have not yet been defined.

Using variables in components that have not been defined.

check_for_relative_errors(start_ref=None, end_ref=None, allow_absolute=True)

Method for checking if RELATIVE locations does not contain unknown references

Using the start_ref and end_ref keyword arguments, a subset of the instrument can be checked for internal consistency.

Clears the instrument of all search statements

component_help(name, **kwargs)

Method for showing parameters for a component before adding it to the instrument

keyword arguments
line_lengthint

Maximum line length in output to terminal

copy_component(name, original_component=None, *, before=None, after=None, AT=None, AT_RELATIVE=None, ROTATED=None, ROTATED_RELATIVE=None, RELATIVE=None, WHEN=None, EXTEND=None, GROUP=None, JUMP=None, SPLIT=None, comment=None, c_code_before=None, c_code_after=None)

Method for adding a copy of a Component instance to the instrument

Creates a copy of Component instance in the instrument. This requires a unique instance name of the component to be used for future reference and the name of the McStas component to be used. The component is placed at the end of the instrument file unless otherwise specified with the after and before keywords. The component may be initialized using other keyword arguments, but all attributes can be set with approrpiate methods.

Parameters
  • name (str) – Unique name of component instance

  • original_component (str) – Name of component instance to create copy of

  • arguments (Keyword) –

    afterstr

    Place this component after component with given name

    beforestr

    Place this component before component with given name

    ATList of 3 floats

    Sets AT_data, position relative to reference

    AT_RELATIVEstr

    Sets reference component for postion

    ROTATEDList of 3 floats

    Sets ROTATED_data, rotation relative to reference

    ROTATED_RELATIVEstr

    Sets reference component for rotation

    RELATIVEstr

    Sets reference component for both position and rotation

    WHENstr

    Sets when condition which must be a logical c expression

    EXTENDstr

    Initialize the extend section with a line of c code

    GROUPstr

    Name of the group this component should belong to

    JUMPstr

    Set code for McStas JUMP statement

    commentstr

    Comment that will be displayed before the component

get_component(name)

Get the component instance of component with specified name

This method is used to get direct access to any component instance in the instrument. The component instance can be manipulated in much the same way, but it is not necessary to specify the name in each call.

Parameters

name (str) – Unique name of component whose instance should be returned

get_component_subset_index_range(start_ref=None, end_ref=None)

Provides start and end index for components in run_from to run_to range

Optionally start_ref and end_ref can be given manually which would overwrite the internal run_from and run_to references.

get_last_component()

Get the component instance of last component in the instrument

This method is used to get direct access to any component instance in the instrument. The component instance can be manipulated in much the same way, but it is not necessary to specify the name in each call.

has_errors()

Method that returns true if errors are found in instrument

init_parameters()

Create empty ParameterContainer for new instrument

make_component_subset()

Uses run_from and run_to specifications to extract subset of components

Adds MCPL component at start and/or end as needed, and adjusts the surrounding components as necessary.

move_component(name, before=None, after=None)

Moves component with given name to before or after

move_user_vars_to_declare()

Moves all uservars to declare for compatibility with McStas 2.X

print_component(name)

Method for printing summary of contents in named component

Parameters

name (str) – Unique name of component to print

print_component_short(name)

Method for printing summary of contents in named component

Parameters

name (str) – Unique name of component to print

print_components(line_length=None)

Obsolete method, use show_components instead

Method for printing overview of all components in instrument

Provides overview of component names, what McStas component is used for each and their position and rotation in space.

keyword arguments: line_length : int

Maximum line length in console

read_instrument_file()

Reads current instrument file if it exists, otherwise creates one first

remove_component(name)

Removes component with given name from instrument

reset_run_points()

Reset run_from and run_to points to the full instrument

run_from(component_ref, run_name=None, tag=None, **kwargs)

Set limit for instrument, only run from given component, load MCPL ot start

The method accepts keywords for the MCPL input component allowing to set for example the smear for direction / energy / position and repeat count.

component_refstr / component object

Name of component where the instrument simulation should start

run_namestr

Run name of dump to use as starting point of simulation

taginteger

Tag of the desired dump (only allowed if run_name is given)

run_full_instrument(**kwargs)

Runs McStas instrument described by this class, returns list of McStasData

This method will write the instrument to disk and then run it using the mcrun command of the system. Options are set using keyword arguments. Some options are mandatory, for example output_path, which can not already exist, if it does data will be read from this folder. If the mcrun command is not in the path of the system, the absolute path can be given with the executable_path keyword argument. This path could also already have been set at initialization of the instrument object.

Parameters

arguments (Keyword) –

output_pathstr

Sets data_folder_name

ncountint

Sets ncount

mpiint

Sets thread count

parametersdict

Sets parameters

custom_flagsstr

Sets custom_flags passed to mcrun

force_compilebool

If True (default) new instrument file is written, otherwise not

executable_pathstr

Path to mcrun command, “” if already in path

run_to(component_ref, run_name='Run', comment=None, **kwargs)

Set limit for instrument, only run to given component, save MCPL there

The method accepts keywords for the MCPL output component allowing to store for example userflags or setting the filename directly.

component_refstr / component object

Name of component where the instrument simulation should end

run_namestr

Name associated with the generated beam dump

commentstr

Comment asscoiated with the generated beam dump

saveH5(filename: str, openpmd: bool = True)

Not relevant, but required from BaseCalculator, will be removed

set_dependency(string)

Sets the DEPENDENCY line of instruments, expanding its system search

The dependency line can be used to tell McStas to search for files in additional locations. Double quotes are added.

Parameters

string (str) – The dependency string

settings(ncount=None, mpi='not_set', seed=None, force_compile=None, output_path=None, increment_folder_name=None, custom_flags=None, executable=None, executable_path=None, suppress_output=None, gravity=None, checks=None, openacc=None, NeXus=None)

Sets settings for McStas run performed with backengine

Some options are mandatory, for example output_path, which can not already exist, if it does data will be read from this folder. If the mcrun command is not in the PATH of the system, the absolute path can be given with the executable_path keyword argument. This path could also already have been set at initialization of the instrument object.

Parameters

arguments (Keyword) –

output_pathstr

Sets data_folder_name

increment_folder_namebool

Will update output_path if folder already exists, default True

ncountint

Sets ncount

mpiint

Sets thread count

force_compilebool

If True (default) new instrument file is written, otherwise not

custom_flagsstr

Sets custom_flags passed to mcrun

executablestr

Name of the executable

executable_pathstr

Path to mcrun command, “” if already in path

suppress_outputbool

Set to True to suppress output

gravitybool

If True, gravity will be simulated

openaccbool

If True, adds –openacc to mcrun call

NeXusbool

If True, adds –format=NeXus to mcrun call

settings_string()

Returns a string describing settings stored in this instrument object

show_components(line_length=None)

Method for printing overview of all components in instrument

Provides overview of component names, what McStas component is used for each and their position and rotation in space.

keyword arguments: line_length : int

Maximum line length in console

show_diagram(analysis=False, variable=None, limits=None)

Shows diagram of component connections in insrument

Shows a diagram with all components as text fields and arrows between them showing the AT RELATIVE and ROTATED RELATIVE connections. Spatial connections are shown in blue, and rotational in red. ROTATED connections are only shown when they are specified. To see the intensity and number of rays over the course of the instrument, use analysis=True.

parameters: analysis : bool

If True, a plot of intensity and ncount over the instrument is included

show_instrument(format='webgl', width=800, height=450, new_tab=False)

Uses mcdisplay to show the instrument in web browser

If this method is performed from a jupyter notebook and use the webgl format the interface will be shown in the notebook using an IFrame.

Keyword Arguments
  • format (str) – ‘webgl’ or ‘window’ format for display

  • width (int) – width of IFrame if used in notebook

  • height (int) – height of IFrame if used in notebook

  • new_tab (bool) – Open webgl in new browser tab

show_instrument_file(line_numbers=False)

Displays the current instrument file

Parameters

line_numbers (bool) – Select whether line numbers should be displayed

show_parameters(line_length=None)

Method for displaying current instrument parameters

line_limitint

Maximum line length for terminal output

show_run_subset()

Shows current subset of instrument selected with run_from and run_to methods

Shows all search statements on instrument level

show_settings()

Prints settings stored in this instrument object

show_variables()

Shows declared variables in instrument

subset_check(start_ref, end_ref)

Checks that when the instrument is broken into subsets, it is still valid

start_refstr

Name of starting component

end_refstr

Name of end component

write_c_files()

Obsolete method for writing instrument parts to c files

It is possible to use this function to write c files to a folder called generated_includes that can then be included in the different sections of a McStas instrument. Component objects are NOT written to these files, but rather the contents of the trace_section that can be set using the append_trace method.

write_full_instrument()

Method for writing full instrument file to disk

This method writes the instrument described by the instrument objects to disk with the name specified in the initialization of the object.