Learning Python
From MantidProject
Contents |
Python in Mantid
Version
Currently Mantid requires version 2.5 of Python and will not install unless this version is available. At the time of writing Version 2.6 of python is available and Python 3.0 has been released. In the future we may migrate to these versions, but for now you need version 2.5.
On line resources
- The standard Python documentation is here http://docs.python.org/
- A bite of Python (a good resource for beginners) http://www.ibiblio.org/swaroopch/byteofpython/files/120/byteofpython_120.pdf
- Dive Into Python is a Python book for experienced programmers http://diveintopython.org/
- Thinking in Python by Bruce Eckel http://www.mindview.net/Books/TIPython
Books
We have the following books in the Mantid developers offices that you are welcome to borrow if you need to.
- Learning Python 3rd Edition
- Core Python Programming
Mantid Specifics
Both the Mantid framework itself and aspects of the graphical tool MantidPlot can be controlled using the Python interface. Here we show the common commands used to interact with the environment. In MantidPlot there is a editing window that can be used to both write and execute Python code. It can be shown/hidden using the 'Scripting' menu or by simply pressing F3. Note that once opened the scripting window stays active and clicking close (i.e. the cross or pressing F3) simply hides the window and your changes stay intact.
For a general help, simply type
mtdHelp()
and a list of the available algorithms will be printed. Each of these algorithms has a Python function of the same name associated with it. Using the help function with one of these names as an argument produces a help message specific to that algorithm, e.g.
mtdHelp("LoadRaw")
produces
Usage: LoadRaw(Filename, OutputWorkspace, spectrummin, spectrummax, spectrumlist, Cache)
Argument description:
Name: Filename, Optional: No, Direction: Input, Allowed values: RAW, raw
Name: OutputWorkspace, Optional: No, Direction: Output
Name: spectrummin, Optional: Yes, Default value: 1, Direction: Input
Name: spectrummax, Optional: Yes, Default value: 1, Direction: Input
Name: spectrumlist, Optional: Yes, Default value: , Direction: Input
Name: Cache, Optional: Yes, Default value: If slow, Direction: Input, Allowed values: Always, If slow, Never
Note 1: All arguments must be wrapped in string quotes "", regardless of their type.
Note 2: To include a particular optional argument, it should be given after the mandatory arguments in the form argumentname="value".
To run the algorithm, one simply calls the LoadRaw function with, at least, the mandatory number of arguments, i.e.
LoadRaw("c:/MantidInstall/Data/GEM38370.raw","GEM38370")
will load the 'GEM38370.raw' file and create a workspace named 'GEM38370'. Arguments can also be specified using their names as defined in the help, so running
LoadRaw(OutputWorkspace="GEM38370",Filename="c:/MantidInstall/Data/GEM38370.raw")
has the same effect as the previous command. Note:All arguments after one specified as name=value must also be specified as name=value.
The above command takes a full path to the data file but if all of the references to places where data is loaded/saved are the same, one can use the setWorkingDirectory
command to set current working directory. All paths that are given after this call are then relative to that directory, i.e.
setWorkingDirectory("C:/MantidInstall/Data")
LoadRaw("GEM38370.raw","GEM38370")
now has the same effect as the previous LoadRaw command.
Each function returns a Python object that can be used to access the properties that were set for that algorithm, i.e.
lr = LoadRaw("c:/MantidInstall/Data/GEM38370.raw","GEM38370")
workspaceName = lr.getProperty("OutputWorkspace")
will assign the value of the OutputWorkspace property, in this case 'GEM38370', to the variable workspaceName.
Another important command is the mtd.deleteWorkspace() function. This takes a workspace name as an argument and then removes it from the service allowing the memory to be used again for other operations.
Note for Linux users: Please see here for details memory management under Linux.
Workspace Interaction
To access a workspace in Python use the getMatrixWorkspace() provided by the Mantid Framework. Using the example above
raw_workspace = mantid.getMatrixWorkspace(workspaceName)
assigns a workspace to the variable raw_workspace. The data can be accessed using readX() , readY() and readZ() functions as follows
# Indices start at 0 so x_zero = raw_workspace.readX(0) # assigns a list of numbers for the first spectra in raw_workspace to x0 x_zero0 = x_zero[0] # then accesses the first number in that list.
The total number of histograms is accessed using getNumberHistograms() and together with list access in Python, it is possible to run through each value in the workspace.
for s in range(0,raw_workspace.getNumberHistograms()):
x_s = raw_workspace.readX(s)
for b in range(0, len(x_s)):
print x_s[b] + " "
print ""
MantidPlot Interaction
Dialog Boxes
Each of the functions listed with mtdHelp() has a corresponding function with the word Dialog appended to the name. Using this function brings up the properties dialog box that you would usually get by clicking on the algorithm with the mouse. This allows you to write scripts that are more reusable as you do not have to hard code things like file paths into the script. If there are properties that will be the same each time then these can be given as arguments to the function and the appropriate box in the dialog will be updated for you. For example, the LoadRaw function above could be changed to
LoadRawDialog()
which would bring up a dialog with blank fields, or
LoadRawDialog(OutputWorkspace="raw1")
which would bring up a dialog with the OutputWorkspace field set to raw1 and the box greyed out. There is also an optional argument called message that can be used to add information about what the user is supposed to enter at this point in the script, i.e.
LoadRawDialog(OutputWorkspace="raw1", message="Please enter the path to the raw file")
where this would bring up the same dialog box as above but now with the optional message string placed at the top.
In the above example, calling the dialog function with the given argument causes the control to be disabled. If this behavior is not required then a suggested value can be given and the control will remain enabled. This is achieved by prepending the ? character to the property value. For example,
LoadRawDialog("?C:/MantidInstall/Data/GEM38370.raw", "gem")
raises a dialog with the OutputWorkspace box set to gem and greyed out while the Filename argument is set to the given value but the box remains active. Note that any whitespace before or after the ? is removed
If there are already workspaces that have been created through clicking the GUI and one is highlighted in the workspace box then calling getSelectedWorkspaceName() will retrieve the name of the highlighted workspace.
1D Plots
When using the mouse, a workspace can be dragged from the workspace box to create a matrix of values and then plots can be made of various fields of the matrix. This can also be achieved through a Python script with various commands. For one-dimensional graphs there are the plotSpectrum and plotTimeBin functions that can be used to give a single spectrum or single time bin plot. The functions are used like so:
plotSpectrum("workspaceName", spectrumNumber, True or False)
plotTimeBin("workspaceName", spectrumNumber, True or False)
The final value in the function is a boolean indicating whether to show the matrix or keep it minimized on the screen. This can be left off as it has a default value of False.
There are commands available so that graphs can be manipulated, i.e. merging curves from other graphs and rescaling. As an example, assume that two data sets have been loaded and a set of algorithms have been performed on them leaving us with two workspaces focussed and stripped. If we wanted to plot spectrum 3 from each, merge both curves and then rescale the result to view an interesting point we would do the following (where # denotes a comment)
g1 = plotSpectrum("stripped",3)
# Merge the second plot onto the first
mergePlots(g1, plotSpectrum("focussed", 3))
# Rescale to an interesting point on the x-axis.
g1.activeLayer().setAxisScale(Layer.Bottom,0,2.3)
The first argument of the above setAxisScale function denotes which axis the scaling applies to:
Layer.Bottom - bottom x-axis Layer.Left - left y-axis Layer.Right - right y-axis Layer.Top - top x-axis
2D and 3D Plots
For two- and three-dimensional graphs, one must first use either the importMatrixWorkspace or getMantidMatrix functions, depending on whether a matrix has been created already, then using this a graph can be plotted, e.g.
mm = importMatrixWorkspace("GEM38370")
mm.plotGraph2D()
will show a contour plot for the workspace given in the importMatrixWorkspace and then
mm.plotGraph3D()
will show a three-dimensional graph of the given workspace.
Instrument Window
There are several commands available to interact with the instrument window. Assuming that a workspace exists, a reference to the window can be obtained using the getInstrumentView() command, where the name of the workspace must be provided.
insView = getInstrumentView("LOQTest")
So assuming that LOQTest is an existing workspace that was loaded from an LOQ file, insView can be used to manipulate the instrument window. Please note that the window will not be made visible until the showWindow() function is called like so,
insView.showWindow()
This means that the manipulations can be performed on the window before the actual object is shown and rendered. From Python, one can set a new colour map, alter the range of the colour mapping and select a bin range. For example,
insView.changeColorMap("C:/MantidInstall/colormaps/BlackBodyRadiation.MAP")
insView.setColorMapRange(10.,50.)
# Or can set a minimum and maximum separately
#insView.setColorMapMinValue(10.)
#insView.setColorMapMaxValue(50.)
# Alter the binning range
insView.setBinRange(10000,15000)
# Show the window
insView.showWindow()
There is also a command available to set the view of the instrument to a specified component, i.e. a script command substitute for clicking on something in the instrument tree. This must be done after the showWindow command so that the tree is loaded.
insView.selectComponent("HAB-module")
Note that the search simply matches to the first item that it finds and it is not case sensitive, so that insView.selectComponent("hab-module") will give the same result.
Full example
The following code demonstrates a simple use of the Python interface by performing the same operations as are detailed on the Mantid Examples page.
# Please make sure that the "GEM38370.raw" file is in the "C:/MantidInstall/Data" directory
#For convenience set a variable pointing to the Mantid path
path = "C:/MantidInstall/"
# Step (1)
LoadRaw(Filename=path+"Data/GEM38370.raw", OutputWorkspace="GEM38370")
#Step(2). Import the matrix starting at 200
gridGEM = importMatrixWorkspace("GEM38370",200)
# Step(3) - A contour plot with colour fill
gridGEM.plotGraph2D(Layer.ColorMap)
# Step(4) - Rebin the GEM data
Rebin(InputWorkspace="GEM38370", OutputWorkspace="MyWorkspace", params="0,200,20000")
# Step (5) - Create a 1D plot of a spectrum. In python this automatically creates the corresponding matrix
plotSpectrum("MyWorkspace", 10)
The above script is also included in the scripts directory of the Mantid installation and is called DIYExample.py
Error Messages
The script window within MantidPlot contains an area that used for both standard output (print commands) and also error messages. Below are examples of common errors that can occur.
# Ex. 1 - Syntax Error
# A colon is missed from the end of the for-statement line
for i in range(0,10)
print i
This produces an error of the form: Error on line 1: invalid syntax
#Ex. 2 - RuntimeError
# An error with a Mantid algorithm property
LoadRaw("path-to-nothing","result")
This produces an error of the form: RuntimeError on line 1: Invalid value for property Filename (Ss) "path-to-nothing": File "path-to-nothing" not found
# Ex. 3 - AttributeError # Try to call a function that does not exist on an object graph.testFunction() This produces an error of the form: AttributeError on line 1 : 'module' object has no attribute 'testFunction' Fix: The most likely cause of this is that the function is spelled incorrectly
# Ex. 4 - NameError # Try to call a global function that does not exist printHello() This produces an error of the form: NameError on line 14 : name 'printHello' is not defined
