WorkspaceGroup#

This is a Python binding to the C++ class Mantid::API::WorkspaceGroup.

bases: mantid.api.Workspace

A WorkspaceGroup is a group of workspaces. The WorkspaceGroup object does not hold any data itself, but instead holds a list of Workspace objects. They appear as an expandable list of workspaces in the Workspaces Toolbox in the main window (the list of workspaces is also called the ADS or AnalysisDataService). Thus, workspace groups add structure to the ADS and make it more readable and also allow algorithms to be executed over a list of workspaces contained within the group but passing the group to the algorithm.

Most algorithms can be passed a WorkspaceGroup in place of a normal workspace input, and will simply execute the algorithm on each workspace contained within the group.

Working with Group Workspaces in Python#

Creating and splitting groups#

Workspace groups can be created through the MantidWorkbench interface;

  • Select a few workspaces from the Workspaces Toolbox in the main window and click the “Group” button above the list of workspaces. The group will be named “NewGroup”.

Workspace groups can be created in a more flexible way in the Python script window using the Python API. Groups may be created via the GroupWorkspaces algorithm, This will place a workspace group directly into the ADS, and requires at least one workspace to be added to the group.

from mantid.simpleapi import *

ws1 = CreateSampleWorkspace()
ws2 = CreateSampleWorkspace()
ws3 = CreateSampleWorkspace()


# Create a group workpace
wsList = [ws1,ws2,ws3]
wsGroup = GroupWorkspaces(wsList)
# or
wsGroup = GroupWorkspaces("ws1,ws2,ws3")

print(wsGroup.getNames())

# Remove the group
# The child workspaces will be preserved
UnGroupWorkspace(wsGroup)
# Using wsGroup now will cause a runtime error
# RuntimeError: Variable invalidated, data has been deleted.

Output:

['ws1','ws2','ws3']

To avoid interaction with the ADS, a WorkspaceGroup object can be instantiated using

import mantid.api as api

ws_group = api.WorkspaceGroup()

This will not be automatically added to the ADS, to do so, use the following line

AnalysisDataService.add("name", ws_group)

the group should then appear in the ADS with the given name. Using direct instantiation; groups can be added to the ADS and then workspaces added to the group via their name and the add method;

from mantid.simpleapi import *
from mantid.api import WorkspaceGroup

mtd.clear()

ws1 = CreateSampleWorkspace()
ws2 = CreateSampleWorkspace()
ws3 = CreateSampleWorkspace()

# Create a group workspace and add to the ADS
ws_group = WorkspaceGroup()
mtd.add("group1", ws_group)

ws_group.add("ws1")
ws_group.add("ws2")
ws_group.add("ws3")

print(ws_group.getNames())

Output:

['ws1','ws2','ws3']

Alternatively, workspace group objects can be fed workspaces which are not in the ADS (in this case the addWorkspace method is used rather than add because add requires a name, and since the workspaces are not in the ADS they may not have a name)

from mantid.simpleapi import *
from mantid.api import WorkspaceGroup

mtd.clear()

ws1 = WorkspaceFactory.create("Workspace2D", 2, 2, 2)
ws2 = WorkspaceFactory.create("Workspace2D", 2, 2, 2)
ws3 = WorkspaceFactory.create("Workspace2D", 2, 2, 2)

# Create a group workspace
ws_group = WorkspaceGroup()

ws_group.addWorkspace(ws1)
ws_group.addWorkspace(ws2)
ws_group.addWorkspace(ws3)

print(ws_group.getNames())

mtd.add("group1", ws_group)

print(ws_group.getNames())

Output:

['','','']
['group1_1','group1_2','group1_3']

when adding the group to the ADS, the workspaces will also be added, and given default names. It is not recommended to add workspace to groups in this way, as much of the functionality of groups depends on workspaces having names; for example the “in” keyword.

Accessing Workspace Groups#

The methods for getting a variable to a WorkspaceGroup is the same as shown in the Workspace help page.

If you want to check if a variable points to something that is a Workspace Group you can use this:

from mantid.simpleapi import *
from mantid.api import WorkspaceGroup

ws1 = CreateSampleWorkspace()
ws2 = CreateSampleWorkspace()
wsGroup = GroupWorkspaces("ws1,ws2")

if isinstance(wsGroup, WorkspaceGroup):
    print(wsGroup.name() + " is an " + wsGroup.id())

Output:

wsGroup is an WorkspaceGroup

Looping over all of the members of a group#

from mantid.simpleapi import *

ws1 = CreateSampleWorkspace()
ws2 = CreateSampleWorkspace()
wsGroup = GroupWorkspaces("ws1,ws2")

print("Number of members: " + str(wsGroup.getNumberOfEntries()))
print("List of names: " + str(wsGroup.getNames()))

# Get the member workspaces in a loop
for i in range(wsGroup.getNumberOfEntries()):
    wsLoop = wsGroup.getItem(i)
    print("Member {0} {1}".format(i, wsLoop.name()))

Output:

Number of members: 2
List of names: ['ws1','ws2']
Member 0 ws1
Member 1 ws2

Using Workspace Groups in Algorithms#

You can pass workspace groups into any algorithm and Mantid will run that algorithm for each member of the workspace group.

from mantid.simpleapi import *

ws1 = CreateSampleWorkspace()
ws2 = CreateSampleWorkspace()
wsGroup = GroupWorkspaces("ws1,ws2")
wsGroup2 = GroupWorkspaces("ws2,ws1")

#  This will add the member workspaces in a pair like manner
wsGroup3 = wsGroup + wsGroup2

# Rebin all of wsGroup
wsRebinned = Rebin(wsGroup, Params=200)

# You can still of course refer to members of a group directly
ws1 = Rebin(ws1, Params=100)

Final words of warning:#

  • It is best to add all workspaces to the ADS before configuring the grouping structure (as in the above code); otherwise you will only be able to name the top level group when you add the structure to the ADS. All the sub-groups and workspaces not already in the ADS will be given default names which you will then have to change manually, it is much easier to name them as you go (and putting them in the ADS is the only way to name them).

  • When iterating over a WorkspaceGroup to delete its workspaces, then iterate over a list, such as:

from mantid.simpleapi import *

ws1 = CreateSampleWorkspace()
ws2 = CreateSampleWorkspace()
wsGroup = GroupWorkspaces("ws1,ws2")

for ws in list(wsGroup):
    DeleteWorkspace(ws)

otherwise indexing will be confused by each deletion.

  • To Delete an entire group, just run:

from mantid.simpleapi import *

ws1 = CreateSampleWorkspace()
ws2 = CreateSampleWorkspace()
wsGroup = GroupWorkspaces("ws1,ws2")

DeleteWorkspace(wsGroup)

Other Information on Workspaces#

  • Workspace - Overview of workspaces, which include the following classes:
    • MatrixWorkspace - A base class that contains among others:

      • WorkspaceSingleValue - Holds a single number (and X & error value, if desired). Mainly used for workspace algebra, e.g. to divide all bins in a 2D workspace by a single value.

      • Workspace2D - A workspace for holding two dimensional data in memory, this is the most commonly used workspace.

      • EventWorkspace - A workspace that retains the individual neutron event data.

    • TableWorkspace - A workspace holding data in rows of columns having a particular type (e.g. text, integer, …).

    • WorkspaceGroup - A container for a collection of workspaces. Algorithms given a group as input run sequentially on each member of the group.

Reference#

class mantid.api.WorkspaceGroup#
add((WorkspaceGroup)self, (str)workspace_name) None :#

Add a name to the group

addWorkspace((WorkspaceGroup)self, (object)workspace) None :#

Add a workspace to the group.

clone(InputWorkspace)#

Copies an existing workspace into a new one.

Property descriptions:

InputWorkspace(Input:req) Workspace Name of the input workspace. Must be a MatrixWorkspace (2D or EventWorkspace), a PeaksWorkspace or a MDEventWorkspace.

OutputWorkspace(Output:req) Workspace Name of the newly created cloned workspace.

contains((WorkspaceGroup)self, (str)workspace) bool :#

Returns true if the given name is in the group

convertUnits(InputWorkspace, Target, EMode=None, EFixed=None, AlignBins=None, ConvertFromPointData=None)#

Performs a unit change on the X values of a workspace

Property descriptions:

InputWorkspace(Input:req) MatrixWorkspace Name of the input workspace

OutputWorkspace(Output:req) MatrixWorkspace Name of the output workspace, can be the same as the input

Target(Input:req) string The name of the units to convert to (must be one of those registered in the Unit Factory)[DeltaE, DeltaE_inFrequency, DeltaE_inWavenumber, dSpacing, dSpacingPerpendicular, Energy, Energy_inWavenumber, Momentum, MomentumTransfer, QSquared, SpinEchoLength, SpinEchoTime, TOF, Wavelength]

EMode(Input) string The energy mode (default: elastic)[Elastic, Direct, Indirect]

EFixed(Input) number Value of fixed energy in meV : EI (EMode=’Direct’) or EF (EMode=’Indirect’) . Must be set if the target unit requires it (e.g. DeltaE)

AlignBins(Input) boolean If true (default is false), rebins after conversion to ensure that all spectra in the output workspace have identical bin boundaries. This option is not recommended (see http://docs.mantidproject.org/algorithms/ConvertUnits).

ConvertFromPointData(Input) boolean When checked, if the Input Workspace contains Points the algorithm ConvertToHistogram will be run to convert the Points to Bins. The Output Workspace will contains Bins.

delete(Workspace)#

Removes a workspace from memory.

Property descriptions:

Workspace(Input:req) Workspace Name of the workspace to delete.

getComment((Workspace)self) str :#

Returns the comment field on the workspace

getHistory((Workspace)self) WorkspaceHistory :#

Return read-only access to the WorkspaceHistory

getItem((WorkspaceGroup)self, (int)index) object :#

Returns the item at the given index

getMemorySize((Workspace)self) int :#

Returns the memory footprint of the workspace in KB

getName((Workspace)self) str :#

Returns the name of the workspace. This could be an empty string

getNames((WorkspaceGroup)self) mantid.kernel._kernel.std_vector_str :#

Returns the names of the entries in the group

getNumberOfEntries((WorkspaceGroup)self) int :#

Returns the number of entries in the group

getTitle((Workspace)self) str :#

Returns the title of the workspace

id((DataItem)self) str :#

The string ID of the class

isDirty((Workspace)self[, (int)n]) bool :#

True if the workspace has run more than n algorithms (Default=1)

isGroup((Workspace)self) bool :#

Returns if it is a group workspace

isMultiPeriod((WorkspaceGroup)self) bool :#

Returns true if the workspace group is multi-period

maskDetectors(Workspace, SpectraList=None, DetectorList=None, WorkspaceIndexList=None, MaskedWorkspace=None, ForceInstrumentMasking=None, StartWorkspaceIndex=None, EndWorkspaceIndex=None, ComponentList=None)#

An algorithm to mask a detector, or set of detectors, as not to be used. The workspace spectra associated with those detectors are zeroed.

Property descriptions:

Workspace(InOut:req) Workspace The name of the input and output workspace on which to perform the algorithm.

SpectraList(Input) int list A list of spectra to mask

DetectorList(Input) int list A list of detector ID’s to mask

WorkspaceIndexList(Input) unsigned int list A list of the workspace indices to mask

MaskedWorkspace(Input) MatrixWorkspace If given but not as a SpecialWorkspace2D, the masking from this workspace will be copied. If given as a SpecialWorkspace2D, the masking is read from its Y values.[]

ForceInstrumentMasking(Input) boolean Works when ‘MaskedWorkspace’ is provided and forces to use spectra-detector mapping even in case when number of spectra in ‘Workspace’ and ‘MaskedWorkspace’ are equal

StartWorkspaceIndex(Input) number If other masks fields are provided, it’s the first index of the target workspace to be allowed to be masked from by these masks, if not, its the first index of the target workspace to mask. Default value is 0 if other masking is present or ignored if not.

EndWorkspaceIndex(Input) number If other masks are provided, it’s the last index of the target workspace allowed to be masked to by these masks, if not, its the last index of the target workspace to mask. Default is number of histograms in target workspace if other masks are present or ignored if not.

ComponentList(Input) str list A list names of components to mask

name((DataItem)self) str :#

The name of the object

readLock((DataItem)self) None :#

Acquires a read lock on the data item.

remove((WorkspaceGroup)self, (str)workspace_name) None :#

Remove a name from the group

reorder((WorkspaceGroup)self, (object)indices) None :#

Reorder the group members using a list of indices

setComment((Workspace)self, (str)comment) None :#

Set the comment field of the workspace

setTitle((Workspace)self, (str)title) None :#

Set the title of the workspace

size((WorkspaceGroup)self) int :#

Returns the number of workspaces contained in the group

sortByName((WorkspaceGroup)self) None :#

Sort members by name

threadSafe((DataItem)self) bool :#

Returns true if the object can be accessed safely from multiple threads

unlock((DataItem)self) None :#

Unlocks a read or write lock on the data item.