ITableWorkspace#
This is a Python binding to the C++ class Mantid::API::ITableWorkspace.
bases: mantid.api.Workspace
Overview#
Table workspaces are general purpose workspaces for storing data of mixed types. A table workspace is organized in columns. Each column has a name and a type - the type of the data in that column. Data can be accessed by column, by row, or by cell
Working with Table Workspaces in Python#
For full details of the Table Workspaces python type itself please see this page.
Accessing Workspaces#
The methods for getting a variable to an Table Workspace is the same as shown in the Workspace help page.
If you want to check if a variable points to something that is an Table Workspace you can use this:
from mantid.api import ITableWorkspace
tableWS = CreateEmptyTableWorkspace()
if tableWS is ITableWorkspace:
print(tableWS.getName() + " is a " + tableWS.id())
Output:
tableWS is a TableWorkspace
Creating a Table Workspace in Python#
Most of the time Table workspaces are the output of certain algorithms, but you can create them yourself should you wish.
from mantid.kernel import V3D
# Create PositionTable
tableWS = CreateEmptyTableWorkspace()
# Add some columns, Recognized types are: int,float,double,bool,str,V3D,long64
tableWS.addColumn(type="int",name="Detector ID",plottype=6)
tableWS.addColumn(type="str",name="Detector Name",plottype=6)
tableWS.addColumn(type="V3D",name="Detector Position",plottype=6)
tableWS.addColumn(type='float',name="Value",plottype=2)
tableWS.addColumn(type='float',name="Error",plottype=5)
tableWS.setLinkedYCol(4, 3)
# Populate the columns for three detectors
detIDList = range(1,4)
detPosList = [ V3D(9.0,0.0,0.0), V3D(10.0,3.0,0.0), V3D(12.0,3.0,6.0)]
for j in range(len(detIDList)):
nextRow = { 'Detector ID': detIDList[j],
'Detector Name': "Detector {0}".format(detIDList[j]),
'Detector Position': detPosList[j],
'Value': 10,
'Error': 1 }
tableWS.addRow ( nextRow )
Table Workspace Properties#
#setup as above
# Rows
print("Row count: {}".format(tableWS.rowCount()))
print("Detector Position: {0}, Detector Name: {1}, Detector ID: {2}".format(
tableWS.row(0)["Detector Position"],
tableWS.row(0)["Detector Name"],
tableWS.row(0)["Detector ID"])) # row values as a dictionary
# Resize the table
tableWS.setRowCount(4)
# Add Rows
tableWS.addRow( [2, "new Detector 1", V3D(2,2,2)])
# or using a dictionary
nextRow = { 'Detector ID': 5,
'Detector Name': "new Detector 2",
'Detector Position': V3D(5,5,5) }
tableWS.addRow ( nextRow )
# Columns
print("Column count: {}".format(tableWS.columnCount()))
print("Column names: {}".format(tableWS.getColumnNames()))
columnValuesList = tableWS.column(0)
# convert table to dictionary
data = tableWS.toDict()
print("Detector names: {}".format(data['Detector Name']))
# To remove a column
tableWS.removeColumn("Detector Name")
Converting To Pandas DataFrames#
Table workspaces can be easily converted to a pandas DataFrame using the following code snippet.
import pandas as pd
df = pd.DataFrame(table.toDict())
If only a subset of the data from the table is required, or you’re working with an existing DataFrame and want to append columns from the Table workspace this can be achieved as follows.
df = pd.DataFrame()
for col in tableWS.getColumnNames():
df[col] = tableWS.column(col)
Pickling Workspaces#
A TableWorkspace may be pickled <https://docs.python.org/2/library/pickle.html/> and de-pickled in python. Users should prefer using cPickle over pickle, and make sure that the protocol option is set to the HIGHEST_PROTOCOL to ensure that the serialization/deserialization process is as fast as possible.
import cPickle as pickle
pickled = pickle.dumps(ws2d, pickle.HIGHEST_PROTOCOL)
Working with Table Workspaces in C++#
Table workspaces can be created using the workspace factory:
ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable("TableWorkspace");
Columns are added using the addColumn method:
table->addColumn("str","Parameter Name");table->addColumn("double","Value");table->addColumn("double","Error");table->addColumn("int","Index");Here the first argument is a symbolic name of the column’s data type and the second argument is the name of the column. The predefined types are:
Symbolic name |
C++ type |
|---|---|
int |
int |
float |
float |
double |
double |
bool |
bool |
str |
std::string |
V3D |
Mantid::Geometry::V3D |
long64 |
int64_t |
vector_int |
std::vector<int> |
vector_double |
std::vector<double> |
The data in the table can be accessed in a number of ways. The most simple way is to call templated method T& cell(row,col), where col is the index of the column in the workspace and row is the index of the cell in the column. Columns are indexed in the order they are created with addColumn. There are also specialized methods for four predefined data types: int& Int(row,col), double& Double(row,col), std::string& String(row,col), bool& Bool(row,col). Columns use std::vector to store the data. To get access to the vector use getVector(name). To get the column object use getColumn(name).
Only columns of type int, double and str can currently be saved to Nexus by SaveNexus or SaveNexusProcessed. Columns of other types will simply be omitted from the Nexus file without any error message.
Table rows#
Cells with the same index form a row. TableRow class represents a row. Use getRow(int) or getFirstRow() to access existing rows. For example:
std::string key;
double value;
TableRow row = table->getFirstRow();
do
{
row >> key >> value;
std::cout << "key=" << key << " value=" << value << std::endl;
}
while(row.next());
TableRow can also be use for writing into a table:
for(int i=0; i < n; ++i)
{
TableRow row = table->appendRow();
row << keys[i] << values[i];
}
Defining new column types#
Users can define new data types to be used in TableWorkspace. TableColumn.h defines macro DECLARE_TABLECOLUMN(c_plus_plus_type,symbolic_name). c_plus_plus_type must be a copyable type and operators << and >> must be defined. There is also DECLARE_TABLEPOINTERCOLUMN macro for declaring non-copyable types, but it has never been used.
Reference#
- class mantid.api.ITableWorkspace#
Most of the information from a table workspace is returned as native copies. All of the column accessors return lists while the rows return dicts. This object does support the idom ‘for row in ITableWorkspace’.
- addColumn((ITableWorkspace)self, (str)type, (str)name) bool :#
Add a named column with the given type. Recognized types are: int,float,double,bool,str,V3D,long64
- addColumn( (ITableWorkspace)self, (str)type, (str)name, (int)plottype) -> bool :
Add a named column with the given datatype (int,float,double,bool,str,V3D,long64) and plottype (0 = None, 1 = X, 2 = Y, 3 = Z, 4 = xErr, 5 = yErr, 6 = Label).
- addReadOnlyColumn((ITableWorkspace)self, (str)type, (str)name) bool :#
Add a read-only, named column with the given type. Recognized types are: int,float,double,bool,str,V3D,long64
- addRow((ITableWorkspace)self, (object)row_items_seq) None :#
Appends a row with the values from the given sequence. It it assumed that the items are in the correct order for the defined columns.
- addRow( (ITableWorkspace)self, (dict)row_items_dict) -> None :
Appends a row with the values from the dictionary.
- cell((ITableWorkspace)self, (object)value, (int)row_or_column) object :#
Return the value in the given cell. If the value argument is a number then it is interpreted as a row otherwise it is interpreted as a column name.
- 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.
- column((ITableWorkspace)self, (object)column) object :#
Return all values of a specific column as a list.
- columnArray((ITableWorkspace)self, (object)column) object :#
Return all values of a specific column (either index or name) as a numpy array.
- columnCount((ITableWorkspace)self) int :#
Returns the number of columns in the workspace.
- columnTypes((ITableWorkspace)self) list :#
Return the types of the columns as a list
- 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.
- getColumnNames((ITableWorkspace)self) numpy.ndarray :#
Return a list of the column names.
- getComment((Workspace)self) str :#
Returns the comment field on the workspace
- getHistory((Workspace)self) WorkspaceHistory :#
Return read-only access to the
WorkspaceHistory
- getLinkedYCol((ITableWorkspace)self, (object)column) int :#
Get the data column associated with a given error column.
- 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
- getPlotType((ITableWorkspace)self, (object)column) int :#
Get the plot type of given column as an integer. Accepts column name or index. Possible return values: (0 = None, 1 = X, 2 = Y, 3 = Z, 4 = xErr, 5 = yErr, 6 = Label).
- getTitle((Workspace)self) str :#
Returns the title of the workspace
- id((DataItem)self) str :#
The string ID of the class
- isColumnReadOnly((ITableWorkspace)self, (object)column) bool :#
Gets whether or not a given column of this workspace is be read-only. Columns can be selected by name or by index
- 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
- keys((ITableWorkspace)self) numpy.ndarray :#
Return a list of the column names.
- 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.
- removeColumn((ITableWorkspace)self, (str)name) None :#
Remove the named column.
- row((ITableWorkspace)self, (int)row) object :#
Return all values of a specific row as a dict.
- rowCount((ITableWorkspace)self) int :#
Returns the number of rows within the workspace.
- setCell((ITableWorkspace)self, (object)row_or_column, (int)column_or_row, (object)value[, (bool)notify_replace=True]) None :#
Sets the value of a given cell. If the row_or_column argument is a number then it is interpreted as a row otherwise it is interpreted as a column name. If notify replace is false, then the replace workspace event is not triggered.
- setColumnReadOnly((ITableWorkspace)self, (object)column, (bool)read_only) None :#
Sets whether or not a given column of this workspace should be read-only. Columns can be selected by name or by index
- setComment((Workspace)self, (str)comment) None :#
Set the comment field of the workspace
- setLinkedYCol((ITableWorkspace)self, (object)errColumn, (int)dataColumn) None :#
Set the data column associated with a given error column.
- setPlotType((ITableWorkspace)self, (object)column, (int)ptype[, (int)linkedCol=-1]) None :#
Set the plot type of given column. Accepts column name or index. Possible type values: (0 = None, 1 = X, 2 = Y, 3 = Z, 4 = xErr, 5 = yErr, 6 = Label).
- setRowCount((ITableWorkspace)self, (int)count) None :#
Resize the table to contain count rows.
- setTitle((Workspace)self, (str)title) None :#
Set the title of the workspace
- threadSafe((DataItem)self) bool :#
Returns true if the object can be accessed safely from multiple threads
- toDict((ITableWorkspace)self) dict :#
Gets the values of this workspace as a dictionary. The keys of the dictionary will be the names of the columns of the table. The values of the entries will be lists of values for each column.
- unlock((DataItem)self) None :#
Unlocks a read or write lock on the data item.