Skip to content
Snippets Groups Projects
StatisticsOfTableWorkspace.py 2.38 KiB
Newer Older
Dan Nixon's avatar
Dan Nixon committed
#pylint: disable=no-init

from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty
from mantid.kernel import Direction, Stats
import mantid.simpleapi as ms
from mantid import mtd, logger
import numpy as np


Dan Nixon's avatar
Dan Nixon committed
def _stats_to_dict(stats):
Dan Nixon's avatar
Dan Nixon committed
    Converts a Statstics object to a dictionary.
    @param stats Statistics object to convertToWaterfall
    @return Dictionary of statistics
    """
Dan Nixon's avatar
Dan Nixon committed
    stat_dict = dict()
    stat_dict['standard_deviation'] = stats.standard_deviation
    stat_dict['maximum'] = stats.maximum
    stat_dict['minimum'] = stats.minimum
    stat_dict['mean'] = stats.mean
    stat_dict['median'] = stats.median
    return stat_dict


class StatisticsOfTableWorkspace(PythonAlgorithm):

    def category(self):
        return 'DataHandling'


    def summary(self):
        return 'Calcuates columns statistics of a table workspace.'


    def PyInit(self):
        self.declareProperty(ITableWorkspaceProperty('InputWorkspace', '', Direction.Input),
                             doc='Input table workspace.')
        self.declareProperty(ITableWorkspaceProperty('OutputWorkspace', '', Direction.Output),
                             doc='Output workspace contatining column statitics.')


    def PyExec(self):
        in_ws = mtd[self.getPropertyValue('InputWorkspace')]
        out_ws_name = self.getPropertyValue('OutputWorkspace')

        out_ws = ms.CreateEmptyTableWorkspace(OutputWOrkspace=out_ws_name)

        out_ws.addColumn('str', 'statistic')

        stats = {
            'standard_deviation': dict(),
            'maximum': dict(),
            'minimum': dict(),
            'mean': dict(),
            'median': dict(),
        }

        for name in in_ws.getColumnNames():
            try:
Dan Nixon's avatar
Dan Nixon committed
                col_stats = _stats_to_dict(Stats.getStatistics(np.array([float(v) for v in in_ws.column(name)])))
                for statname in stats.keys():
Dan Nixon's avatar
Dan Nixon committed
                    stats[statname][name] = col_stats[statname]
                out_ws.addColumn('float', name)
Dan Nixon's avatar
Dan Nixon committed
            except ValueError:
                logger.notice('Column \'%s\' is not numerical, skipping' % name)

Dan Nixon's avatar
Dan Nixon committed
        for name, stat in stats.items():
            stat1 = dict(stat)
            stat1['statistic'] = name
            out_ws.addRow(stat1)

        self.setProperty('OutputWorkspace', out_ws_name)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(StatisticsOfTableWorkspace)