\(\renewcommand\AA{\unicode{x212B}}\)

Basic Algorithm Structure

Each Python algorithm within Mantid must contain a few elements in order for it to be recognised as an algorithm.

The basic layout should look like:

 1from mantid.api import AlgorithmFactory, PythonAlgorithm
 2
 3class HelloWorld(PythonAlgorithm):
 4
 5    def PyInit(self):
 6        # Declare properties
 7        pass
 8
 9    def PyExec(self):
10        # Run the algorithm
11        pass
12
13# Register algorithm with Mantid
14AlgorithmFactory.subscribe(HelloWorld)

The super class is PythonAlgorithm (alias to Algorithm), which provides a hook to allow Mantid to interact with it without knowing about it beforehand.

The functions PyInit and PyExec are called by the framework to setup properties and run the algorithm respectively and must be included.

The final line, which should be outside the class definition, registers the new algorithm class with Mantid’s AlgorithmFactory.

Each algorithm needs to belong to a category. By default a Python algorithm belongs to the “PythonAlgorithms”, but Mantid will emit a warning on registration if you leave it using the default value. To change this include the category() function in the definition, i.e.

1from mantid.api import AlgorithmFactory, PythonAlgorithm
2
3class HelloWorld(PythonAlgorithm):
4
5    def category(self):
6        return 'MyTools'
7
8    # The rest is the same as above

Subcategories can be defined using a “\\\\” (you need two \\’s as the first is the escape character) to separate the categories. You can also state that your algorithm should appear in multiple categories by separating them with a semi-colon “;”.

i.e. The following code defines that the algorithm should be stored in Useful->Tools and MyTools.

1from mantid.api import AlgorithmFactory, PythonAlgorithm
2
3class HelloWorld(PythonAlgorithm):
4
5    def category(self):
6       return 'Useful\\Tools;MyTools'
7
8    # The rest is the same as above

You are highly encouraged to stay to the list of existing categories.