Exemplo n.º 1
0
    def _plot_output(self):
        """
        Plot the first spectrum of the input and output workspace together.
        """
        from IndirectImport import import_mantidplot
        mtd_plot = import_mantidplot()

        mtd_plot.plotSpectrum([self._sample, self._output_workspace], 0)
Exemplo n.º 2
0
    def _plot_output(self):
        """
        Plot the first spectrum of the input and output workspace together.
        """
        from IndirectImport import import_mantidplot
        mtd_plot = import_mantidplot()

        mtd_plot.plotSpectrum([self._sample, self._output_workspace], 0)
Exemplo n.º 3
0
    def _post_process(self):
        """
        Handles adding logs, saving and plotting.
        """

        use_scale_factor = self._scale_factor == 1.0
        AddSampleLog(Workspace=self._out_ws,
                     LogName='scale',
                     LogType='String',
                     LogText=str(use_scale_factor))
        if use_scale_factor:
            AddSampleLog(Workspace=self._out_ws,
                         LogName='scale_factor',
                         LogType='Number',
                         LogText=str(self._scale_factor))

        AddSampleLog(Workspace=self._out_ws,
                     LogName='res_smoothing_applied',
                     LogType='String',
                     LogText=str(self._smooth))

        AddSampleLog(Workspace=self._out_ws,
                     LogName='back_start',
                     LogType='Number',
                     LogText=str(self._background[0]))
        AddSampleLog(Workspace=self._out_ws,
                     LogName='back_end',
                     LogType='Number',
                     LogText=str(self._background[1]))

        rebin_params = self._rebin_string.split(',')
        if len(rebin_params) == 3:
            AddSampleLog(Workspace=self._out_ws,
                         LogName='rebin_low',
                         LogType='Number',
                         LogText=rebin_params[0])
            AddSampleLog(Workspace=self._out_ws,
                         LogName='rebin_width',
                         LogType='Number',
                         LogText=rebin_params[1])
            AddSampleLog(Workspace=self._out_ws,
                         LogName='rebin_high',
                         LogType='Number',
                         LogText=rebin_params[2])

        self.setProperty('OutputWorkspace', self._out_ws)

        if self._save:
            if self._verbose:
                logger.notice(
                    "Resolution file saved to default save directory.")
            SaveNexusProcessed(InputWorkspace=self._out_ws,
                               Filename=self._out_ws + '.nxs')

        if self._plot:
            from IndirectImport import import_mantidplot
            mtd_plot = import_mantidplot()
            mtd_plot.plotSpectrum(self._out_ws, 0)
Exemplo n.º 4
0
    def PyExec(self):
        self.log().information('IndirectILLreduction')

        run_path = self.getPropertyValue('Run')
        self._calibration_workspace = self.getPropertyValue('CalibrationWorkspace')
        self._raw_workspace = self.getPropertyValue('RawWorkspace')
        self._red_workspace = self.getPropertyValue('ReducedWorkspace')
        self._red_left_workspace = self.getPropertyValue('LeftWorkspace')
        self._red_right_workspace = self.getPropertyValue('RightWorkspace')
        self._map_file = self.getProperty('MapFile').value

        self._use_mirror_mode = self.getProperty('MirrorMode').value
        self._save = self.getProperty('Save').value
        self._plot = self.getProperty('Plot').value

        LoadILLIndirect(FileName=run_path, OutputWorkspace=self._raw_workspace)

        instrument = mtd[self._raw_workspace].getInstrument()
        self._instrument_name = instrument.getName()

        self._run_number = mtd[self._raw_workspace].getRunNumber()
        self._analyser = self.getPropertyValue('Analyser')
        self._reflection = self.getPropertyValue('Reflection')
        self._run_name = self._instrument_name + '_' + str(self._run_number)

        AddSampleLog(Workspace=self._raw_workspace, LogName="mirror_sense",
                     LogType="String", LogText=str(self._use_mirror_mode))

        logger.information('Nxs file : %s' % run_path)

        output_workspaces = self._reduction()

        if self._save:
            workdir = config['defaultsave.directory']
            for ws in output_workspaces:
                file_path = os.path.join(workdir, ws + '.nxs')
                SaveNexusProcessed(InputWorkspace=ws, Filename=file_path)
                logger.information('Output file : ' + file_path)

        if self._plot:
            from IndirectImport import import_mantidplot
            mtd_plot = import_mantidplot()
            graph = mtd_plot.newGraph()

            for ws in output_workspaces:
                mtd_plot.plotSpectrum(ws, 0, window=graph)

            layer = graph.activeLayer()
            layer.setAxisTitle(mtd_plot.Layer.Bottom, 'Energy Transfer (meV)')
            layer.setAxisTitle(mtd_plot.Layer.Left, '')
            layer.setTitle('')

        self.setPropertyValue('RawWorkspace', self._raw_workspace)
        self.setPropertyValue('ReducedWorkspace', self._red_workspace)

        if self._use_mirror_mode:
            self.setPropertyValue('LeftWorkspace', self._red_left_workspace)
            self.setPropertyValue('RightWorkspace', self._red_right_workspace)
Exemplo n.º 5
0
    def _plotResult(self, total, spectrum1D, residuals):
        plotResults = self.getProperty('PlotResult').value

        if plotResults:
            from IndirectImport import import_mantidplot

            plot = import_mantidplot()

            plotWindow = plot.plotSpectrum(total, 0, type=1)
            plotWindow = plot.plotSpectrum(spectrum1D, 0, type=0, window=plotWindow)
            plotWindow = plot.plotSpectrum(residuals, 0, type=0, window=plotWindow)
            plotWindow.activeLayer().setTitle('Fit result for ' + self.baseName)
            plotWindow.activeLayer().removeLegend()
Exemplo n.º 6
0
    def _plotResult(self, total, spectrum1D, residuals):
        plotResults = self.getProperty('PlotResult').value

        if plotResults:
            from IndirectImport import import_mantidplot

            plot = import_mantidplot()

            plotWindow = plot.plotSpectrum(total, 0, type=1)
            plotWindow = plot.plotSpectrum(spectrum1D, 0, type=0, window=plotWindow)
            plotWindow = plot.plotSpectrum(residuals, 0, type=0, window=plotWindow)
            plotWindow.activeLayer().setTitle('Fit result for ' + self.baseName)
            plotWindow.activeLayer().removeLegend()
Exemplo n.º 7
0
    def _plot_output(self):
        """
        Plot output.
        """
        from IndirectImport import import_mantidplot
        mtd_plot = import_mantidplot()

        spectra_range = range(0, mtd[self._output_workspace].getNumberHistograms())

        graph = mtd_plot.plotSpectrum(self._output_workspace, spectra_range)

        layer = graph.activeLayer()
        layer.setScale(mtd_plot.Layer.Left, 0, 1.0)
Exemplo n.º 8
0
    def _plot_output(self):
        """
        Plot output.
        """
        from IndirectImport import import_mantidplot
        mtd_plot = import_mantidplot()

        spectra_range = range(
            0, mtd[self._output_workspace].getNumberHistograms())

        graph = mtd_plot.plotSpectrum(self._output_workspace, spectra_range)

        layer = graph.activeLayer()
        layer.setScale(mtd_plot.Layer.Left, 0, 1.0)
    def PyExec(self):
        from IndirectCommon import StartTime, EndTime
        self._setup()

        StartTime('IndirectTransmissionMonitor')

        ws_basename = str(self._sample_ws_in)

        self._trans_mon(ws_basename, 'Sam', self._sample_ws_in)
        self._trans_mon(ws_basename, 'Can', self._can_ws_in)

        # Generate workspace names
        sam_ws = ws_basename + '_Sam'
        can_ws = ws_basename + '_Can'
        trans_ws = ws_basename + '_Trans'

        # Divide sample and can workspaces
        Divide(LHSWorkspace=sam_ws,
               RHSWorkspace=can_ws,
               OutputWorkspace=trans_ws)
        trans = numpy.average(mtd[trans_ws].readY(0))

        AddSampleLog(Workspace=trans_ws,
                     LogName='can_workspace',
                     LogType='String',
                     LogText=self._can_ws_in)

        # Group workspaces
        group = sam_ws + ',' + can_ws + ',' + trans_ws
        GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._out_ws)

        self.setProperty('OutputWorkspace', self._out_ws)

        if self._verbose:
            logger.notice('Transmission : ' + str(trans))

        # Save the tranmissin workspace group to a nexus file
        if self._save:
            workdir = config['defaultsave.directory']
            path = os.path.join(workdir, self._out_ws + '.nxs')
            SaveNexusProcessed(InputWorkspace=self._out_ws, Filename=path)
            if self._verbose:
                logger.notice('Output file created : ' + path)

        # Plot spectra from transmission workspace
        if self._plot:
            mtd_plot = import_mantidplot()
            mtd_plot.plotSpectrum(self._out_ws, 0)

        EndTime('IndirectTransmissionMonitor')
Exemplo n.º 10
0
    def _process_output(self, workspace):
        if self._save:
            from mantid.simpleapi import SaveNexusProcessed
            from IndirectCommon import getDefaultWorkingDirectory
            workdir = getDefaultWorkingDirectory()
            fit_path = os.path.join(workdir, workspace + '.nxs')
            SaveNexusProcessed(InputWorkspace=workspace, Filename=fit_path)

            logger.information('Fit file is ' + fit_path)

        if self._plot:
            from IndirectImport import import_mantidplot
            mtd_plot = import_mantidplot()
            mtd_plot.plotSpectrum(workspace, [0, 1, 2], True)
Exemplo n.º 11
0
    def PyExec(self):
        from IndirectCommon import StartTime, EndTime
        self._setup()

        StartTime('IndirectTransmissionMonitor')

        ws_basename = str(self._sample_ws_in)

        self._trans_mon(ws_basename, 'Sam', self._sample_ws_in)
        self._trans_mon(ws_basename, 'Can', self._can_ws_in)

        # Generate workspace names
        sam_ws = ws_basename + '_Sam'
        can_ws = ws_basename + '_Can'
        trans_ws = ws_basename + '_Trans'

        # Divide sample and can workspaces
        Divide(LHSWorkspace=sam_ws, RHSWorkspace=can_ws, OutputWorkspace=trans_ws)
        trans = numpy.average(mtd[trans_ws].readY(0))

        AddSampleLog(Workspace=trans_ws, LogName='can_workspace', LogType='String', LogText=self._can_ws_in)

        # Generate an output workspace name if none provided
        if self._out_ws == '':
            self._out_ws = ws_basename + '_Transmission'

        # Group workspaces
        group = sam_ws + ',' + can_ws + ',' + trans_ws
        GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._out_ws)

        self.setProperty('OutputWorkspace', self._out_ws)

        if self._verbose:
            logger.notice('Transmission : ' + str(trans))

        # Save the tranmissin workspace group to a nexus file
        if self._save:
            workdir = config['defaultsave.directory']
            path = os.path.join(workdir, self._out_ws + '.nxs')
            SaveNexusProcessed(InputWorkspace=self._out_ws, Filename=path)
            if self._verbose:
                logger.notice('Output file created : ' + path)

        # Plot spectra from transmission workspace
        if self._plot:
            mtd_plot = import_mantidplot()
            mtd_plot.plotSpectrum(self._out_ws, 0)

        EndTime('IndirectTransmissionMonitor')
Exemplo n.º 12
0
    def PyExec(self):
        from IndirectCommon import CheckXrange

        self._setup()

        # CheckXrange(xRange, 'Time')
        out_ws_list = []

        for index, filename in enumerate(self._raw_files):
            raw_file = self._read_raw_file(filename)

            # Only need to process the calib file once
            if index == 0 and self._calib_ws is not None:
                self._process_calib(raw_file)

            slice_file = self._process_raw_file(raw_file)
            Transpose(InputWorkspace=slice_file, OutputWorkspace=slice_file)
            unit = mtd[slice_file].getAxis(0).setUnit("Label")
            unit.setLabel("Spectrum Number", "")

            out_ws_list.append(slice_file)
            DeleteWorkspace(raw_file)

            if self._save:
                work_dir = config['defaultsave.directory']
                save_path = os.path.join(work_dir, slice_file + '.nxs')
                SaveNexusProcessed(InputWorkspace=slice_file,
                                   Filename=save_path)

                if self._verbose:
                    logger.notice('Output file :' + save_path)

        all_workspaces = ','.join(out_ws_list)
        GroupWorkspaces(InputWorkspaces=all_workspaces,
                        OutputWorkspace=self._out_ws_group)
        self.setProperty('OutputWorkspace', self._out_ws_group)

        if self._plot:
            try:
                from IndirectImport import import_mantidplot
                mp = import_mantidplot()
                mp.plotSpectrum(slice_file, 0)
            except RuntimeError, e:
                # User clicked cancel on plot so don't do anything
                pass
Exemplo n.º 13
0
    def PyExec(self):
        self._setup()
        logger.information('Nxs file : %s' % self._run_path)
        LoadILLIndirect(FileName=self._run_path,
                        OutputWorkspace=self._raw_workspace)
        self._setup_mirror()
        if self._calibration_workspace != '':
            LoadNexus(Filename=self._origin_workspace + '.nxs',
                      OutputWorkspace=self._origin_workspace)                  

        instrument = mtd[self._raw_workspace].getInstrument()
        self._instrument_name = instrument.getName()
        self._run_number = mtd[self._raw_workspace].getRunNumber()
        self._analyser = self.getPropertyValue('Analyser')
        self._reflection = self.getPropertyValue('Reflection')
        self._run_name = self._instrument_name + '_' + str(self._run_number)

        output_workspaces = self._reduction()

        self.setPropertyValue('RawWorkspace', self._raw_workspace)
        self.setPropertyValue('ReducedWorkspace', self._red_workspace)

        if self._use_mirror_mode:
            self.setPropertyValue('LeftWorkspace', self._red_left_workspace)
            self.setPropertyValue('RightWorkspace', self._red_right_workspace)

        if self._save:
            workdir = config['defaultsave.directory']
            for ws in output_workspaces:
                file_path = os.path.join(workdir, ws + '.nxs')
                SaveNexusProcessed(InputWorkspace=ws, Filename=file_path)
                logger.information('Output file : ' + file_path)

        if self._plot:
            from IndirectImport import import_mantidplot
            mtd_plot = import_mantidplot()
            graph = mtd_plot.newGraph()

            for ws in output_workspaces:
                mtd_plot.plotSpectrum(ws, 0, window=graph)

            layer = graph.activeLayer()
            layer.setAxisTitle(mtd_plot.Layer.Bottom, 'Energy Transfer (meV)')
            layer.setAxisTitle(mtd_plot.Layer.Left, '')
            layer.setTitle('')
Exemplo n.º 14
0
    def _plot_result(self):
        """
        Handles plotting result workspaces.
        """

        from IndirectImport import import_mantidplot
        mtd_plot = import_mantidplot()

        x_label = ''
        ws_run = mtd[self._input_ws].getRun()
        if 'vert_axis' in ws_run:
            x_label = ws_run.getLogData('vert_axis').value

        result_ws = mtd[self._output_msd_ws + '_A1']
        if len(result_ws.readX(0)) > 1:
            msd_plot = mtd_plot.plotSpectrum(result_ws, 0, True)
            msd_layer = msd_plot.activeLayer()
            msd_layer.setAxisTitle(mtd_plot.Layer.Bottom, x_label)
            msd_layer.setAxisTitle(mtd_plot.Layer.Left, '<u2>')
Exemplo n.º 15
0
    def _plot_result(self):
        """
        Handles plotting result workspaces.
        """

        from IndirectImport import import_mantidplot
        mtd_plot = import_mantidplot()

        x_label = ''
        ws_run = mtd[self._input_ws].getRun()
        if 'vert_axis' in ws_run:
            x_label = ws_run.getLogData('vert_axis').value

        result_ws = mtd[self._output_msd_ws + '_A1']
        if len(result_ws.readX(0)) > 1:
            msd_plot = mtd_plot.plotSpectrum(result_ws, 0, True)
            msd_layer = msd_plot.activeLayer()
            msd_layer.setAxisTitle(mtd_plot.Layer.Bottom, x_label)
            msd_layer.setAxisTitle(mtd_plot.Layer.Left, '<u2>')
Exemplo n.º 16
0
def plotSpectra(ws, y_axis_title, indicies=[]):
    """
    Plot a selection of spectra given a list of indicies

    @param ws - the workspace to plot
    @param y_axis_title - label for the y axis
    @param indicies - list of spectrum indicies to plot
    """
    if len(indicies) == 0:
        num_spectra = mtd[ws].getNumberHistograms()
        indicies = range(num_spectra)

    try:
        mp = import_mantidplot()
        plot = mp.plotSpectrum(ws, indicies, True)
        layer = plot.activeLayer()
        layer.setAxisTitle(mp.Layer.Left, y_axis_title)
    except RuntimeError:
        #User clicked cancel on plot so don't do anything
        return
Exemplo n.º 17
0
    def PyExec(self):
        from IndirectCommon import CheckXrange

        self._setup()

        # CheckXrange(xRange, 'Time')
        out_ws_list = []

        for index, filename in enumerate(self._raw_files):
            raw_file = self._read_raw_file(filename)

            # Only need to process the calib file once
            if index == 0 and self._calib_ws is not None:
                self._process_calib(raw_file)

            slice_file = self._process_raw_file(raw_file)
            Transpose(InputWorkspace=slice_file, OutputWorkspace=slice_file)
            unit = mtd[slice_file].getAxis(0).setUnit("Label")
            unit.setLabel("Spectrum Number", "")

            out_ws_list.append(slice_file)
            DeleteWorkspace(raw_file)

            if self._save:
                work_dir = config['defaultsave.directory']
                save_path = os.path.join(work_dir, slice_file + '.nxs')
                SaveNexusProcessed(InputWorkspace=slice_file, Filename=save_path)
                logger.information('Output file :' + save_path)

        all_workspaces = ','.join(out_ws_list)
        GroupWorkspaces(InputWorkspaces=all_workspaces, OutputWorkspace=self._out_ws_group)
        self.setProperty('OutputWorkspace', self._out_ws_group)

        if self._plot:
            try:
                from IndirectImport import import_mantidplot
                mp = import_mantidplot()
                mp.plotSpectrum(slice_file, 0)
            except RuntimeError, e:
                # User clicked cancel on plot so don't do anything
                pass
Exemplo n.º 18
0
def plotSpectra(ws, y_axis_title, indicies=None):
    """
    Plot a selection of spectra given a list of indicies

    @param ws - the workspace to plot
    @param y_axis_title - label for the y axis
    @param indicies - list of spectrum indicies to plot
    """
    if indicies is None:
        indicies = []

    if len(indicies) == 0:
        num_spectra = mtd[ws].getNumberHistograms()
        indicies = range(num_spectra)

    try:
        mtd_plot = import_mantidplot()
        plot = mtd_plot.plotSpectrum(ws, indicies, True)
        layer = plot.activeLayer()
        layer.setAxisTitle(mtd_plot.Layer.Left, y_axis_title)
    except RuntimeError:
        # User clicked cancel on plot so don't do anything
        return
Exemplo n.º 19
0
    def PyExec(self):
        from IndirectCommon import getEfixed

        self._setup()

        # Set up progress reporting
        n_prog_reports = 2
        if self._can_ws_name is not None:
            n_prog_reports += 1
        prog = Progress(self, 0.0, 1.0, n_prog_reports)

        efixed = getEfixed(self._sample_ws_name)

        sample_wave_ws = '__sam_wave'
        ConvertUnits(InputWorkspace=self._sample_ws_name, OutputWorkspace=sample_wave_ws,
                     Target='Wavelength', EMode='Indirect', EFixed=efixed)

        SetSampleMaterial(sample_wave_ws, ChemicalFormula=self._sample_chemical_formula, SampleNumberDensity=self._sample_number_density)

        prog.report('Calculating sample corrections')
        CylinderAbsorption(InputWorkspace=sample_wave_ws,
                           OutputWorkspace=self._ass_ws,
                           SampleNumberDensity=self._sample_number_density,
                           NumberOfWavelengthPoints=10,
                           CylinderSampleHeight=3.0,
                           CylinderSampleRadius=self._sample_radius,
                           NumberOfSlices=1,
                           NumberOfAnnuli=10)

        plot_data = [self._output_ws, self._sample_ws_name]
        plot_corr = [self._ass_ws]
        group = self._ass_ws

        if self._can_ws_name is not None:
            can_wave_ws = '__can_wave'
            ConvertUnits(InputWorkspace=self._can_ws_name, OutputWorkspace=can_wave_ws,
                         Target='Wavelength', EMode='Indirect', EFixed=efixed)
            if self._can_scale != 1.0:
                logger.information('Scaling can by: ' + str(self._can_scale))
                Scale(InputWorkspace=can_wave_ws, OutputWorkspace=can_wave_ws, Factor=self._can_scale, Operation='Multiply')

            can_thickness = self._can_radius - self._sample_radius
            logger.information('Container thickness: ' + str(can_thickness))

            if self._use_can_corrections:
                # Doing can corrections
                prog.report('Calculating container corrections')
                Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws)

                SetSampleMaterial(can_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_number_density)
                AnnularRingAbsorption(InputWorkspace=can_wave_ws,
                                      OutputWorkspace=self._acc_ws,
                                      SampleHeight=3.0,
                                      SampleThickness=can_thickness,
                                      CanInnerRadius=0.9*self._sample_radius,
                                      CanOuterRadius=1.1*self._can_radius,
                                      SampleChemicalFormula=self._can_chemical_formula,
                                      SampleNumberDensity=self._can_number_density,
                                      NumberOfWavelengthPoints=10,
                                      EventsPerPoint=self._events)

                Divide(LHSWorkspace=can_wave_ws, RHSWorkspace=self._acc_ws, OutputWorkspace=can_wave_ws)
                Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can_wave_ws, OutputWorkspace=sample_wave_ws)
                plot_corr.append(self._acc_ws)
                group += ',' + self._acc_ws

            else:
                # Doing simple can subtraction
                prog.report('Calculating container scaling')
                Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can_wave_ws, OutputWorkspace=sample_wave_ws)
                Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws)

            DeleteWorkspace(can_wave_ws)
            plot_data.append(self._can_ws_name)

        else:
            Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws)

        ConvertUnits(InputWorkspace=sample_wave_ws, OutputWorkspace=self._output_ws,
                     Target='DeltaE', EMode='Indirect', EFixed=efixed)
        DeleteWorkspace(sample_wave_ws)

        # Record sample logs
        prog.report('Recording sample logs')
        sample_log_workspaces = [self._output_ws, self._ass_ws]
        sample_logs = [('sample_shape', 'cylinder'),
                       ('sample_filename', self._sample_ws_name),
                       ('sample_radius', self._sample_radius)]

        if self._can_ws_name is not None:
            sample_logs.append(('container_filename', self._can_ws_name))
            sample_logs.append(('container_scale', self._can_scale))
            if self._use_can_corrections:
                sample_log_workspaces.append(self._acc_ws)
                sample_logs.append(('container_thickness', can_thickness))

        log_names = [item[0] for item in sample_logs]
        log_values = [item[1] for item in sample_logs]

        for ws_name in sample_log_workspaces:
            AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values)

        self.setProperty('OutputWorkspace', self._output_ws)

        # Output the Abs group workspace if it is wanted, delete if not
        if self._abs_ws == '':
            DeleteWorkspace(self._ass_ws)
            if self._can_ws_name is not None and self._use_can_corrections:
                DeleteWorkspace(self._acc_ws)

        else:
            GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws)
            self.setProperty('CorrectionsWorkspace', self._abs_ws)

        if self._plot:
            from IndirectImport import import_mantidplot
            mantid_plot = import_mantidplot()
            mantid_plot.plotSpectrum(plot_data, 0)
            if self._abs_ws != '':
                mantid_plot.plotSpectrum(plot_corr, 0)
Exemplo n.º 20
0
from mantid.simpleapi import *
from IndirectCommon import *
from IndirectImport import import_mantidplot
mp = import_mantidplot()
from mantid import config, logger
import inelastic_indirect_reducer
import sys, os.path, numpy as np

def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,
        Suffix=''):
    workspaces = []
    for file in rawfiles:
        ( dir, filename ) = os.path.split(file)
        ( name, ext ) = os.path.splitext(filename)
        try:
            if ( SpecMin == -1 ) and ( SpecMax == -1 ):
                Load(Filename=file, OutputWorkspace=name+Suffix, LoadLogFiles=False)
            else:
                Load(Filename=file, OutputWorkspace=name+Suffix, SpectrumMin=SpecMin,
                    SpectrumMax=SpecMax, LoadLogFiles=False)
            workspaces.append(name+Suffix)
        except ValueError, message:
            logger.notice(message)
            sys.exit(message)
    if Sum and ( len(workspaces) > 1 ):
        MergeRuns(InputWorkspaces=','.join(workspaces), OutputWorkspace=outWS+Suffix)
        factor = 1.0 / len(workspaces)
        Scale(InputWorkspace=outWS+Suffix, OutputWorkspace=outWS+Suffix, Factor=factor)
        for ws in workspaces:
            DeleteWorkspace(ws)
        return [outWS+Suffix]
Exemplo n.º 21
0
    def PyExec(self):
        from IndirectImport import import_mantidplot
        mp = import_mantidplot()
        workdir = config['defaultsave.directory']
        # self._setup()

        q2_workspaces = []
        scan_alg = self.createChildAlgorithm("EnergyWindowScan", 0.05, 0.95)
        for numb in range(self._number_samples):
            run_numbers = []
            run_names = []
            first_run = self._run_first + numb
            for idx in range(int(self._number_runs)):
                run = str(first_run + idx * self._number_samples)
                run_numbers.append(run)
                run_names.append(self._instrument + run)
            q0 = self._instrument.lower(
            ) + run_numbers[0] + '_to_' + run_numbers[-1] + '_s' + str(numb)
            output_ws = q0 + '_red'
            scan_ws = q0 + '_scan'
            scan_alg.setProperty('InputFiles', run_names)
            scan_alg.setProperty('LoadLogFiles', self._load_logs)
            scan_alg.setProperty('CalibrationWorkspace', self._calibration_ws)
            scan_alg.setProperty('Instrument', self._instrument_name)
            scan_alg.setProperty('Analyser', self._analyser)
            scan_alg.setProperty('Reflection', self._reflection)
            scan_alg.setProperty('SpectraRange', self._spectra_range)
            scan_alg.setProperty('ElasticRange', self._elastic_range)
            scan_alg.setProperty('InelasticRange', self._inelastic_range)
            scan_alg.setProperty('DetailedBalance', self._detailed_balance)
            scan_alg.setProperty('GroupingMethod', self._grouping_method)
            scan_alg.setProperty('SampleEnvironmentLogName',
                                 self._sample_log_name)
            scan_alg.setProperty('SampleEnvironmentLogValue',
                                 self._sample_log_value)
            scan_alg.setProperty('msdFit', self._msdfit)
            scan_alg.setProperty('ReducedWorkspace', output_ws)
            scan_alg.setProperty('ScanWorkspace', scan_ws)
            scan_alg.execute()

            logger.information('OutputWorkspace : %s' % output_ws)
            logger.information('ScanWorkspace : %s' % scan_ws)

            q1_ws = scan_ws + '_el_eq1'
            q2_ws = scan_ws + '_el_eq2'
            q2_workspaces.append(q2_ws)
            eisf_ws = scan_ws + '_eisf'
            el_elt_ws = scan_ws + '_el_elt'
            inel_elt_ws = scan_ws + '_inel_elt'
            output_workspaces = [q1_ws, q2_ws, eisf_ws, el_elt_ws, inel_elt_ws]

            if self._plot:
                mp.plotSpectrum(q1_ws, 0, error_bars=True)
                mp.plotSpectrum(q2_ws, 0, error_bars=True)
                mp.plotSpectrum(eisf_ws, 0, error_bars=True)
                if self._msdfit:
                    mp.plotSpectrum(scan_ws + '_msd', 1, error_bars=True)

            if self._save:
                save_alg = self.createChildAlgorithm("SaveNexusProcessed",
                                                     enableLogging=False)
                if self._msdfit:
                    output_workspaces.append(scan_ws + '_msd')
                    output_workspaces.append(scan_ws + '_msd_fit')
                for ws in output_workspaces:
                    file_path = os.path.join(workdir, ws + '.nxs')
                    save_alg.setProperty("InputWorkspace", ws)
                    save_alg.setProperty("Filename", file_path)
                    save_alg.execute()
                    logger.information('Output file : %s' % file_path)
                if self._msdfit:
                    for ws in [scan_ws + '_msd', scan_ws + '_msd_fit']:
                        file_path = os.path.join(workdir, ws + '.nxs')
                        save_alg.setProperty("InputWorkspace", ws)
                        save_alg.setProperty("Filename", file_path)
                        save_alg.execute()
                        logger.information('Output file : %s' % file_path)
Exemplo n.º 22
0
    def _plot_moments(self, inputWS):
    	from IndirectImport import import_mantidplot
    	mp = import_mantidplot()

    	mp.plotSpectrum(inputWS+'_M0',0)
    	mp.plotSpectrum([inputWS+'_M2',inputWS+'_M4'],0)
Exemplo n.º 23
0
    def PyExec(self):
        from IndirectImport import import_mantidplot
        from IndirectCommon import getInstrRun

        # Do setup
        self._setup()

        logger.debug('in_ws:'+str(type(self._input_workspaces)))

        # Get input workspaces
        input_workspace_names = self._input_workspaces.getNames()

        # Lists of input and output workspaces
        q_workspaces = list()
        q2_workspaces = list()
        run_numbers = list()
        temperatures = list()

        # Perform the ElasticWindow algorithms
        for input_ws in input_workspace_names:
            logger.information('Running ElasticWindow for workspace: %s' % input_ws)

            q_ws = '__' + input_ws + '_q'
            q2_ws = '__' + input_ws + '_q2'

            if self._background_range_start != Property.EMPTY_DBL and self._background_range_end != Property.EMPTY_DBL:
                ElasticWindow(InputWorkspace=input_ws,
                              OutputInQ=q_ws,
                              OutputInQSquared=q2_ws,
                              IntegrationRangeStart=self._integration_range_start,
                              IntegrationRangeEnd=self._integration_range_end,
                              BackgroundRangeStart=self._background_range_start,
                              BackgroundRangeEnd=self._background_range_end)
            else:
                ElasticWindow(InputWorkspace=input_ws,
                              OutputInQ=q_ws,
                              OutputInQSquared=q2_ws,
                              IntegrationRangeStart=self._integration_range_start,
                              IntegrationRangeEnd=self._integration_range_end)

            Logarithm(InputWorkspace=q2_ws,
                      OutputWorkspace=q2_ws)

            q_workspaces.append(q_ws)
            q2_workspaces.append(q2_ws)

            # Get the run number
            run_no = getInstrRun(input_ws)[1]
            run_numbers.append(run_no)

            # Get the sample temperature
            temp = self._get_temperature(input_ws)
            if temp is not None:
                temperatures.append(temp)
            else:
                # No need to output a tmperature workspace if there are no temperatures
                self._elt_workspace = ''

        logger.information('Creating Q and Q^2 workspaces')

        if len(input_workspace_names) == 1:
            # Just rename single workspaces
            RenameWorkspace(InputWorkspace=q_workspaces[0],
                            OutputWorkspace=self._q_workspace)
            RenameWorkspace(InputWorkspace=q2_workspaces[0],
                            OutputWorkspace=self._q2_workspace)
        else:
            # Append the spectra of the first two workspaces
            AppendSpectra(InputWorkspace1=q_workspaces[0],
                          InputWorkspace2=q_workspaces[1],
                          OutputWorkspace=self._q_workspace)
            AppendSpectra(InputWorkspace1=q2_workspaces[0],
                          InputWorkspace2=q2_workspaces[1],
                          OutputWorkspace=self._q2_workspace)

            # Append to the spectra of each remaining workspace
            for idx in range(2, len(input_workspace_names)):
                AppendSpectra(InputWorkspace1=self._q_workspace,
                              InputWorkspace2=q_workspaces[idx],
                              OutputWorkspace=self._q_workspace)
                AppendSpectra(InputWorkspace1=self._q2_workspace,
                              InputWorkspace2=q2_workspaces[idx],
                              OutputWorkspace=self._q2_workspace)

            # Delete the output workspaces from the ElasticWindow algorithms
            for q_ws in q_workspaces:
                DeleteWorkspace(q_ws)
            for q2_ws in q2_workspaces:
                DeleteWorkspace(q2_ws)

        logger.information('Setting vertical axis units and values')

        # Set the verical axis units
        v_axis_is_temp = len(input_workspace_names) == len(temperatures)

        if v_axis_is_temp:
            logger.notice('Vertical axis is in temperature')
            unit = ('Temperature', 'K')
        else:
            logger.notice('Vertical axis is in run number')
            unit = ('Run No', 'last 3 digits')

        # Create a new vertical axis for the Q and Q**2 workspaces
        q_ws_axis = NumericAxis.create(len(input_workspace_names))
        q_ws_axis.setUnit("Label").setLabel(unit[0], unit[1])

        q2_ws_axis = NumericAxis.create(len(input_workspace_names))
        q2_ws_axis.setUnit("Label").setLabel(unit[0], unit[1])

        # Set the vertical axis values
        for idx in range(0, len(input_workspace_names)):
            if v_axis_is_temp:
                q_ws_axis.setValue(idx, float(temperatures[idx]))
                q2_ws_axis.setValue(idx, float(temperatures[idx]))
            else:
                q_ws_axis.setValue(idx, float(run_numbers[idx][-3:]))
                q2_ws_axis.setValue(idx, float(run_numbers[idx][-3:]))

        # Add the new vertical axis to each workspace
        mtd[self._q_workspace].replaceAxis(1, q_ws_axis)
        mtd[self._q2_workspace].replaceAxis(1, q2_ws_axis)

        # Process the ELF workspace
        if self._elf_workspace != '':
            logger.information('Creating ELF workspace')

            Transpose(InputWorkspace=self._q_workspace,
                      OutputWorkspace=self._elf_workspace)
            SortXAxis(InputWorkspace=self._elf_workspace,
                      OutputWorkspace=self._elf_workspace)

            self.setProperty('OutputELF', self._elf_workspace)

        # Do temperature normalisation
        if self._elt_workspace != '':
            logger.information('Creating ELT workspace')

            # If the ELT workspace was not already created then create it here,
            # otherwise just clone it
            if self._elf_workspace == '':
                Transpose(InputWorkspace=self._q_workspace,
                          OutputWorkspace=self._elt_workspace)
                SortXAxis(InputWorkspace=self._elt_workspace,
                          OutputWorkspace=self._elt_workspace)
            else:
                CloneWorkspace(InputWorkspace=self._elf_workspace,
                               OutputWorkspace=self._elt_workspace)

            _normalize_to_lowest_temp(self._elt_workspace)

            self.setProperty('OutputELT', self._elt_workspace)

        # Set the output workspace
        self.setProperty('OutputInQ', self._q_workspace)
        self.setProperty('OutputInQSquared', self._q2_workspace)

        # Plot spectra plots
        if self._plot:
            self._mtd_plot = import_mantidplot()

            self._plot_spectra(self._q_workspace)
            self._plot_spectra(self._q2_workspace)

            if self._elf_workspace != '':
                self._plot_spectra(self._elf_workspace)

            if self._elt_workspace != '':
                self._plot_spectra(self._elt_workspace)
Exemplo n.º 24
0
from mantid.simpleapi import *
from IndirectCommon import *
from IndirectImport import import_mantidplot
mp = import_mantidplot()
from mantid import config, logger
import inelastic_indirect_reducer
import sys, os.path, numpy as np

def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,
        Suffix=''):
    workspaces = []
    for file in rawfiles:
        ( dir, filename ) = os.path.split(file)
        ( name, ext ) = os.path.splitext(filename)
        try:
            if ( SpecMin == -1 ) and ( SpecMax == -1 ):
                Load(Filename=file, OutputWorkspace=name+Suffix, LoadLogFiles=False)
            else:
                Load(Filename=file, OutputWorkspace=name+Suffix, SpectrumMin=SpecMin,
                    SpectrumMax=SpecMax, LoadLogFiles=False)
            workspaces.append(name+Suffix)
        except ValueError, message:
            logger.notice(message)
            sys.exit(message)
    if Sum and ( len(workspaces) > 1 ):
        MergeRuns(InputWorkspaces=','.join(workspaces), OutputWorkspace=outWS+Suffix)
        factor = 1.0 / len(workspaces)
        Scale(InputWorkspace=outWS+Suffix, OutputWorkspace=outWS+Suffix, Factor=factor)
        for ws in workspaces:
            DeleteWorkspace(ws)
        return [outWS+Suffix]
Exemplo n.º 25
0
    def PyExec(self):
        from IndirectImport import import_mantidplot
        self._mtd_plot = import_mantidplot()

        output_ws_name = self.getPropertyValue('OutputWorkspace')
        version, data_name, _ = self._get_version_and_data_path()

        logger.information('Detected data from nMoldyn version {0}'.format(version))

        # Run nMOLDYN import
        if version == 3:
            LoadNMoldyn3Ascii(Filename=data_name,
                              OutputWorkspace=output_ws_name,
                              Functions=self.getPropertyValue('Functions'))
        elif version == 4:
            LoadNMoldyn4Ascii(Directory=data_name,
                              OutputWorkspace=output_ws_name,
                              Functions=self.getPropertyValue('Functions'))
        else:
            raise RuntimeError('No loader for input data')

        symmetrise = self.getProperty('SymmetriseEnergy').value
        max_energy_param = self.getProperty('MaxEnergy').value

        # Do processing specific to workspaces in energy
        if isinstance(mtd[output_ws_name], WorkspaceGroup):
            for ws_name in mtd[output_ws_name].getNames():
                if mtd[ws_name].getAxis(0).getUnit().unitID() == 'Energy':
                    # Get an XMax value, default to max energy if not cropping
                    max_energy = mtd[ws_name].dataX(0).max()
                    logger.debug('Max energy in workspace %s: %f' % (ws_name, max_energy))

                    if max_energy_param != Property.EMPTY_DBL:
                        if max_energy_param > max_energy:
                            raise ValueError('MaxEnergy crop is out of energy range for function %s' % ws_name)
                        max_energy = max_energy_param

                    # If we are going to Symmetrise then there is no need to crop
                    # as the Symmetrise algorithm will do this
                    if symmetrise:
                        # Symmetrise the sample workspace in x=0
                        Symmetrise(InputWorkspace=ws_name,
                                   XMin=0,
                                   XMax=max_energy,
                                   OutputWorkspace=ws_name)

                    elif max_energy_param != Property.EMPTY_DBL:
                        CropWorkspace(InputWorkspace=ws_name,
                                      OutputWorkspace=ws_name,
                                      XMin=-max_energy,
                                      XMax=max_energy)

        # Do convolution if given a resolution workspace
        if self.getPropertyValue('Resolution') != '':
            # Create a workspace with enough spectra for convolution
            num_sample_hist = mtd[output_ws_name].getItem(0).getNumberHistograms()
            resolution_ws = self._create_res_ws(num_sample_hist)

            # Convolve all workspaces in output group
            for ws_name in mtd[output_ws_name].getNames():
                if 'Energy' in mtd[ws_name].getAxis(0).getUnit().unitID():
                    self._convolve_with_res(resolution_ws, ws_name)
                else:
                    logger.information('Ignoring workspace %s in convolution step' % ws_name)

            # Remove the generated resolution workspace
            DeleteWorkspace(resolution_ws)

        # Set the output workspace
        self.setProperty('OutputWorkspace', output_ws_name)
Exemplo n.º 26
0
    def PyExec(self):
        from IndirectImport import import_mantidplot
        mp = import_mantidplot()
        workdir = config['defaultsave.directory']
        # self._setup()

        q2_workspaces = []
        scan_alg = self.createChildAlgorithm("EnergyWindowScan", 0.05, 0.95)
        for numb in range(self._number_samples):
            run_numbers = []
            run_names = []
            first_run = self._run_first + numb
            for idx in range(int(self._number_runs)):
                run = str(first_run + idx * self._number_samples)
                run_numbers.append(run)
                run_names.append(self._instrument + run)
            q0 = self._instrument.lower() + run_numbers[0] + '_to_' + run_numbers[-1] + '_s' + str(numb)
            output_ws = q0 + '_red'
            scan_ws = q0 + '_scan'
            scan_alg.setProperty('InputFiles', run_names)
            scan_alg.setProperty('LoadLogFiles', self._load_logs)
            scan_alg.setProperty('CalibrationWorkspace', self._calibration_ws)
            scan_alg.setProperty('Instrument', self._instrument_name)
            scan_alg.setProperty('Analyser', self._analyser)
            scan_alg.setProperty('Reflection', self._reflection)
            scan_alg.setProperty('SpectraRange', self._spectra_range)
            scan_alg.setProperty('ElasticRange', self._elastic_range)
            scan_alg.setProperty('InelasticRange', self._inelastic_range)
            scan_alg.setProperty('DetailedBalance', self._detailed_balance)
            scan_alg.setProperty('GroupingMethod', self._grouping_method)
            scan_alg.setProperty('SampleEnvironmentLogName', self._sample_log_name)
            scan_alg.setProperty('SampleEnvironmentLogValue', self._sample_log_value)
            scan_alg.setProperty('msdFit', self._msdfit)
            scan_alg.setProperty('ReducedWorkspace', output_ws)
            scan_alg.setProperty('ScanWorkspace', scan_ws)
            scan_alg.execute()

            logger.information('OutputWorkspace : %s' % output_ws)
            logger.information('ScanWorkspace : %s' % scan_ws)

            q1_ws = scan_ws + '_el_eq1'
            q2_ws = scan_ws + '_el_eq2'
            q2_workspaces.append(q2_ws)
            eisf_ws = scan_ws + '_eisf'
            el_elt_ws = scan_ws + '_el_elt'
            inel_elt_ws = scan_ws + '_inel_elt'
            output_workspaces = [q1_ws, q2_ws, eisf_ws, el_elt_ws, inel_elt_ws]

            if self._plot:
                mp.plotSpectrum(q1_ws, 0, error_bars=True)
                mp.plotSpectrum(q2_ws, 0, error_bars=True)
                mp.plotSpectrum(eisf_ws, 0, error_bars=True)
                if self._msdfit:
                    mp.plotSpectrum(scan_ws + '_msd', 1, error_bars=True)

            if self._save:
                save_alg = self.createChildAlgorithm("SaveNexusProcessed", enableLogging=False)
                if self._msdfit:
                    output_workspaces.append(scan_ws + '_msd')
                    output_workspaces.append(scan_ws + '_msd_fit')
                for ws in output_workspaces:
                    file_path = os.path.join(workdir, ws + '.nxs')
                    save_alg.setProperty("InputWorkspace", ws)
                    save_alg.setProperty("Filename", file_path)
                    save_alg.execute()
                    logger.information('Output file : %s' % file_path)
                if self._msdfit:
                    for ws in [scan_ws + '_msd', scan_ws + '_msd_fit']:
                        file_path = os.path.join(workdir, ws + '.nxs')
                        save_alg.setProperty("InputWorkspace", ws)
                        save_alg.setProperty("Filename", file_path)
                        save_alg.execute()
                        logger.information('Output file : %s' % file_path)
Exemplo n.º 27
0
    def PyExec(self):
        from IndirectImport import import_mantidplot

        self._mtd_plot = import_mantidplot()

        # Do setup
        self._setup()

        try:
            # Load data file
            data, name, ext = self._load_file()

            # Run nMOLDYN import
            if ext == 'cdl':
                self._cdl_import(data, name)
            elif ext == 'dat':
                self._ascii_import(data, name)
            else:
                raise RuntimeError('Unrecognised file format: %s' % ext)

        except Exception as ex:
            logger.error('Error parsing file %s' % (self._sam_path))
            logger.debug('Error is: %s' % (str(ex)))

        # Do processing specific to workspaces in energy
        if isinstance(mtd[self._out_ws], WorkspaceGroup):
            for ws_name in mtd[self._out_ws].getNames():
                if mtd[ws_name].getAxis(0).getUnit().unitID() == 'Energy':
                    # Get an XMax value, default to max energy if not cropping
                    e_max = mtd[ws_name].dataX(0).max()
                    logger.debug('Max energy in workspace %s: %f' %
                                 (ws_name, e_max))

                    if self._emax is not None:
                        if self._emax > e_max:
                            raise ValueError(
                                'MaxEnergy crop is out of energy range for function %s'
                                % ws_name)
                        e_max = self._emax

                    # If we are going to Symmetrise then there is no need to crop
                    # as the Symmetrise algorithm will do this
                    if self._symmetrise:
                        # Symmetrise the sample workspace in x=0
                        Symmetrise(Sample=ws_name,
                                   XMin=0,
                                   XMax=e_max,
                                   Verbose=self._verbose,
                                   Plot=False,
                                   Save=False,
                                   OutputWorkspace=ws_name)

                    elif self._emax is not None:
                        CropWorkspace(InputWorkspace=ws_name,
                                      OutputWorkspace=ws_name,
                                      XMax=self._emax)

        # Do convolution if given a resolution workspace
        if self._res_ws is not '':
            # Create a workspace with enough spectra for convolution
            num_sample_hist = mtd[self._out_ws].getItem(
                0).getNumberHistograms()
            resolution_ws = self._create_res_ws(num_sample_hist)

            # Convolve all workspaces in output group
            for ws_name in mtd[self._out_ws].getNames():
                if ws_name.lower().find('sqw') != -1:
                    self._convolve_with_res(resolution_ws, ws_name)
                else:
                    if self._verbose:
                        logger.notice(
                            'Ignoring workspace %s in convolution step' %
                            ws_name)

            # Remove the generated resolution workspace
            DeleteWorkspace(resolution_ws)

        # Save result workspace group
        if self._save:
            workdir = config['defaultsave.directory']
            out_filename = os.path.join(workdir, self._out_ws + '.nxs')
            if self._verbose:
                logger.information('Creating file: %s' % out_filename)
                SaveNexus(InputWorkspace=self._out_ws, Filename=out_filename)

        # Set the output workspace
        self.setProperty('OutputWorkspace', self._out_ws)

        # Plot spectra plots
        if self._plot == 'Spectra' or self._plot == 'Both':
            if isinstance(mtd[self._out_ws], WorkspaceGroup):
                for ws_name in mtd[self._out_ws].getNames():
                    self._plot_spectra(ws_name)
            else:
                self._plot_spectra(self._out_ws)

        # Plot contour plot
        if self._plot == 'Contour' or self._plot == 'Both':
            self._mtd_plot.plot2D(self._out_ws)
Exemplo n.º 28
0
    def PyExec(self):
        from IndirectImport import import_mantidplot
        from IndirectCommon import getInstrRun

        # Do setup
        self._setup()

        logger.debug('in_ws:' + str(type(self._input_workspaces)))

        # Get input workspaces
        input_workspace_names = self._input_workspaces.getNames()

        # Lists of input and output workspaces
        q_workspaces = list()
        q2_workspaces = list()
        run_numbers = list()
        temperatures = list()

        # Perform the ElasticWindow algorithms
        for input_ws in input_workspace_names:
            logger.information('Running ElasticWindow for workspace: %s' %
                               input_ws)

            q_ws = '__' + input_ws + '_q'
            q2_ws = '__' + input_ws + '_q2'

            if self._range_2_start != '' and self._range_2_end != '':
                ElasticWindow(InputWorkspace=input_ws,
                              OutputInQ=q_ws,
                              OutputInQSquared=q2_ws,
                              Range1Start=self._range_1_start,
                              Range1End=self._range_1_end,
                              Range2Start=float(self._range_2_start),
                              Range2End=float(self._range_2_end))
            else:
                ElasticWindow(InputWorkspace=input_ws,
                              OutputInQ=q_ws,
                              OutputInQSquared=q2_ws,
                              Range1Start=self._range_1_start,
                              Range1End=self._range_1_end)

            Logarithm(InputWorkspace=q2_ws, OutputWorkspace=q2_ws)

            q_workspaces.append(q_ws)
            q2_workspaces.append(q2_ws)

            # Get the run number
            run_no = getInstrRun(input_ws)[1]
            run_numbers.append(run_no)

            # Get the sample temperature
            temp = self._get_temperature(input_ws)
            if temp is not None:
                temperatures.append(temp)

        logger.information('Creating Q and Q^2 workspaces')

        if len(input_workspace_names) == 1:
            # Just rename single workspaces
            RenameWorkspace(InputWorkspace=q_workspaces[0],
                            OutputWorkspace=self._q_workspace)
            RenameWorkspace(InputWorkspace=q2_workspaces[0],
                            OutputWorkspace=self._q2_workspace)
        else:
            # Append the spectra of the first two workspaces
            AppendSpectra(InputWorkspace1=q_workspaces[0],
                          InputWorkspace2=q_workspaces[1],
                          OutputWorkspace=self._q_workspace)
            AppendSpectra(InputWorkspace1=q2_workspaces[0],
                          InputWorkspace2=q2_workspaces[1],
                          OutputWorkspace=self._q2_workspace)

            # Append to the spectra of each remaining workspace
            for idx in range(2, len(input_workspace_names)):
                AppendSpectra(InputWorkspace1=self._q_workspace,
                              InputWorkspace2=q_workspaces[idx],
                              OutputWorkspace=self._q_workspace)
                AppendSpectra(InputWorkspace1=self._q2_workspace,
                              InputWorkspace2=q2_workspaces[idx],
                              OutputWorkspace=self._q2_workspace)

            # Delete the output workspaces from the ElasticWindow algorithms
            for q_ws in q_workspaces:
                DeleteWorkspace(q_ws)
            for q2_ws in q2_workspaces:
                DeleteWorkspace(q2_ws)

        logger.information('Setting vertical axis units and values')

        # Set the verical axis units
        v_axis_is_temp = len(input_workspace_names) == len(temperatures)

        if v_axis_is_temp:
            logger.notice('Vertical axis is in temperature')
            unit = ('Temperature', 'K')
        else:
            logger.notice('Vertical axis is in run number')
            unit = ('Run No', 'last 3 digits')

        q_ws_axis = mtd[self._q_workspace].getAxis(1)
        q_ws_axis.setUnit("Label").setLabel(unit[0], unit[1])

        q2_ws_axis = mtd[self._q2_workspace].getAxis(1)
        q2_ws_axis.setUnit("Label").setLabel(unit[0], unit[1])

        # Set the vertical axis values
        for idx in range(0, len(input_workspace_names)):
            if v_axis_is_temp:
                q_ws_axis.setValue(idx, float(temperatures[idx]))
                q2_ws_axis.setValue(idx, float(temperatures[idx]))
            else:
                q_ws_axis.setValue(idx, float(run_numbers[idx][-3:]))
                q2_ws_axis.setValue(idx, float(run_numbers[idx][-3:]))

        # Process the ELF workspace
        if self._elf_workspace != '':
            logger.information('Creating ELF workspace')

            Transpose(InputWorkspace=self._q_workspace,
                      OutputWorkspace=self._elf_workspace)
            SortXAxis(InputWorkspace=self._elf_workspace,
                      OutputWorkspace=self._elf_workspace)

            self.setProperty('OutputELF', self._elf_workspace)

        # Do temperature normalisation
        if self._elt_workspace != '':
            logger.information('Creating ELT workspace')

            # If the ELT workspace was not already created then create it here, otherwise just clone it
            if self._elf_workspace == '':
                Transpose(InputWorkspace=self._q_workspace,
                          OutputWorkspace=self._elt_workspace)
                SortXAxis(InputWorkspace=self._elt_workspace,
                          OutputWorkspace=self._elt_workspace)
            else:
                CloneWorkspace(InputWorkspace=self._elf_workspace,
                               OutputWorkspace=self._elt_workspace)

            _normalize_to_lowest_temp(self._elt_workspace)

            self.setProperty('OutputELT', self._elt_workspace)

        # Set the output workspace
        self.setProperty('OutputInQ', self._q_workspace)
        self.setProperty('OutputInQSquared', self._q2_workspace)

        # Plot spectra plots
        if self._plot:
            self._mtd_plot = import_mantidplot()

            self._plot_spectra(self._q_workspace)
            self._plot_spectra(self._q2_workspace)

            if self._elf_workspace != '':
                self._plot_spectra(self._elf_workspace)

            if self._elt_workspace != '':
                self._plot_spectra(self._elt_workspace)
Exemplo n.º 29
0
    def _plot_moments(self, inputWS):
        from IndirectImport import import_mantidplot
        mtd_plot = import_mantidplot()

        mtd_plot.plotSpectrum(inputWS+'_M0', 0)
        mtd_plot.plotSpectrum([inputWS+'_M2', inputWS+'_M4'], 0)
Exemplo n.º 30
0
    def PyExec(self):
        from IndirectImport import import_mantidplot

        self._mtd_plot = import_mantidplot()

        # Do setup
        self._setup()

        try:
            # Load data file
            data, name, ext = self._load_file()

            # Run nMOLDYN import
            if ext == 'cdl':
                self._cdl_import(data, name)
            elif ext == 'dat':
                self._ascii_import(data, name)
            else:
                raise RuntimeError('Unrecognised file format: %s' % ext)

        except Exception as ex:
            logger.error('Error parsing file %s' % (self._sam_path))
            logger.debug('Error is: %s' % (str(ex)))

        # Do processing specific to workspaces in energy
        if isinstance(mtd[self._out_ws], WorkspaceGroup):
            for ws_name in mtd[self._out_ws].getNames():
                if mtd[ws_name].getAxis(0).getUnit().unitID() == 'Energy':
                    # Get an XMax value, default to max energy if not cropping
                    e_max = mtd[ws_name].dataX(0).max()
                    logger.debug('Max energy in workspace %s: %f' % (ws_name, e_max))

                    if self._emax is not None:
                        if self._emax > e_max:
                            raise ValueError('MaxEnergy crop is out of energy range for function %s' % ws_name)
                        e_max = self._emax

                    # If we are going to Symmetrise then there is no need to crop
                    # as the Symmetrise algorithm will do this
                    if self._symmetrise:
                        # Symmetrise the sample workspace in x=0
                        Symmetrise(Sample=ws_name, XMin=0, XMax=e_max,
                                   Plot=False, Save=False,
                                   OutputWorkspace=ws_name)

                    elif self._emax is not None:
                        CropWorkspace(InputWorkspace=ws_name, OutputWorkspace=ws_name,
                                      XMax=self._emax)

        # Do convolution if given a resolution workspace
        if self._res_ws is not '':
            # Create a workspace with enough spectra for convolution
            num_sample_hist = mtd[self._out_ws].getItem(0).getNumberHistograms()
            resolution_ws = self._create_res_ws(num_sample_hist)

            # Convolve all workspaces in output group
            for ws_name in mtd[self._out_ws].getNames():
                if ws_name.lower().find('sqw') != -1:
                    self._convolve_with_res(resolution_ws, ws_name)
                else:
                    logger.information('Ignoring workspace %s in convolution step' % ws_name)

            # Remove the generated resolution workspace
            DeleteWorkspace(resolution_ws)

        # Save result workspace group
        if self._save:
            workdir = config['defaultsave.directory']
            out_filename = os.path.join(workdir, self._out_ws + '.nxs')
            logger.information('Creating file: %s' % out_filename)
            SaveNexus(InputWorkspace=self._out_ws, Filename=out_filename)

        # Set the output workspace
        self.setProperty('OutputWorkspace', self._out_ws)

        # Plot spectra plots
        if self._plot == 'Spectra' or self._plot == 'Both':
            if isinstance(mtd[self._out_ws], WorkspaceGroup):
                for ws_name in mtd[self._out_ws].getNames():
                    self._plot_spectra(ws_name)
            else:
                self._plot_spectra(self._out_ws)

        # Plot contour plot
        if self._plot == 'Contour' or self._plot == 'Both':
            self._mtd_plot.plot2D(self._out_ws)
Exemplo n.º 31
0
    def PyExec(self):
        self.log().information('IndirectILLreduction')

        run_path = self.getPropertyValue('Run')
        self._calibration_workspace = self.getPropertyValue(
            'CalibrationWorkspace')
        self._raw_workspace = self.getPropertyValue('RawWorkspace')
        self._red_workspace = self.getPropertyValue('ReducedWorkspace')
        self._red_left_workspace = self.getPropertyValue('LeftWorkspace')
        self._red_right_workspace = self.getPropertyValue('RightWorkspace')
        self._map_file = self.getProperty('MapFile').value

        self._use_mirror_mode = self.getProperty('MirrorMode').value
        self._save = self.getProperty('Save').value
        self._plot = self.getProperty('Plot').value

        LoadILLIndirect(FileName=run_path, OutputWorkspace=self._raw_workspace)

        instrument = mtd[self._raw_workspace].getInstrument()
        self._instrument_name = instrument.getName()

        self._run_number = mtd[self._raw_workspace].getRunNumber()
        self._analyser = self.getPropertyValue('Analyser')
        self._reflection = self.getPropertyValue('Reflection')
        self._run_name = self._instrument_name + '_' + str(self._run_number)

        AddSampleLog(Workspace=self._raw_workspace,
                     LogName="mirror_sense",
                     LogType="String",
                     LogText=str(self._use_mirror_mode))

        logger.information('Nxs file : %s' % run_path)

        output_workspaces = self._reduction()

        if self._save:
            workdir = config['defaultsave.directory']
            for ws in output_workspaces:
                file_path = os.path.join(workdir, ws + '.nxs')
                SaveNexusProcessed(InputWorkspace=ws, Filename=file_path)
                logger.information('Output file : ' + file_path)

        if self._plot:
            from IndirectImport import import_mantidplot
            mtd_plot = import_mantidplot()
            graph = mtd_plot.newGraph()

            for ws in output_workspaces:
                mtd_plot.plotSpectrum(ws, 0, window=graph)

            layer = graph.activeLayer()
            layer.setAxisTitle(mtd_plot.Layer.Bottom, 'Energy Transfer (meV)')
            layer.setAxisTitle(mtd_plot.Layer.Left, '')
            layer.setTitle('')

        self.setPropertyValue('RawWorkspace', self._raw_workspace)
        self.setPropertyValue('ReducedWorkspace', self._red_workspace)

        if self._use_mirror_mode:
            self.setPropertyValue('LeftWorkspace', self._red_left_workspace)
            self.setPropertyValue('RightWorkspace', self._red_right_workspace)
Exemplo n.º 32
0
    def PyExec(self):
        from IndirectCommon import getEfixed

        self._setup()

        # Set up progress reporting
        n_prog_reports = 2
        if self._can_ws_name is not None:
            n_prog_reports += 1
        prog = Progress(self, 0.0, 1.0, n_prog_reports)

        efixed = getEfixed(self._sample_ws)

        sample_wave_ws = '__sam_wave'
        ConvertUnits(InputWorkspace=self._sample_ws, OutputWorkspace=sample_wave_ws,
                     Target='Wavelength', EMode='Indirect', EFixed=efixed)

        SetSampleMaterial(sample_wave_ws, ChemicalFormula=self._sample_chemical_formula, SampleNumberDensity=self._sample_number_density)

        prog.report('Calculating sample corrections')
        FlatPlateAbsorption(InputWorkspace=sample_wave_ws,
                            OutputWorkspace=self._ass_ws,
                            SampleHeight=self._sample_height,
                            SampleWidth=self._sample_width,
                            SampleThickness=self._sample_thickness,
                            ElementSize=self._element_size,
                            EMode='Indirect',
                            EFixed=efixed,
                            NumberOfWavelengthPoints=10)

        plot_data = [self._output_ws, self._sample_ws]
        plot_corr = [self._ass_ws]
        group = self._ass_ws

        if self._can_ws_name is not None:
            can_wave_ws = '__can_wave'
            ConvertUnits(InputWorkspace=self._can_ws_name, OutputWorkspace=can_wave_ws,
                         Target='Wavelength', EMode='Indirect', EFixed=efixed)
            if self._can_scale != 1.0:
                logger.information('Scaling container by: ' + str(self._can_scale))
                Scale(InputWorkspace=can_wave_ws, OutputWorkspace=can_wave_ws, Factor=self._can_scale, Operation='Multiply')

            if self._use_can_corrections:
                prog.report('Calculating container corrections')
                Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws)

                SetSampleMaterial(can_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_number_density)
                FlatPlateAbsorption(InputWorkspace=can_wave_ws,
                                    OutputWorkspace=self._acc_ws,
                                    SampleHeight=self._sample_height,
                                    SampleWidth=self._sample_width,
                                    SampleThickness=self._can_front_thickness + self._can_back_thickness,
                                    ElementSize=self._element_size,
                                    EMode='Indirect',
                                    EFixed=efixed,
                                    NumberOfWavelengthPoints=10)

                Divide(LHSWorkspace=can_wave_ws, RHSWorkspace=self._acc_ws, OutputWorkspace=can_wave_ws)
                Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can_wave_ws, OutputWorkspace=sample_wave_ws)
                plot_corr.append(self._acc_ws)
                group += ',' + self._acc_ws

            else:
                prog.report('Calculating container scaling')
                Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can_wave_ws, OutputWorkspace=sample_wave_ws)
                Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws)

            DeleteWorkspace(can_wave_ws)
            plot_data.append(self._can_ws_name)

        else:
            Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws)

        ConvertUnits(InputWorkspace=sample_wave_ws, OutputWorkspace=self._output_ws,
                     Target='DeltaE', EMode='Indirect', EFixed=efixed)
        DeleteWorkspace(sample_wave_ws)

        prog.report('Recording samle logs')
        sample_log_workspaces = [self._output_ws, self._ass_ws]
        sample_logs = [('sample_shape', 'flatplate'),
                       ('sample_filename', self._sample_ws),
                       ('sample_height', self._sample_height),
                       ('sample_width', self._sample_width),
                       ('sample_thickness', self._sample_thickness),
                       ('element_size', self._element_size)]

        if self._can_ws_name is not None:
            sample_logs.append(('container_filename', self._can_ws_name))
            sample_logs.append(('container_scale', self._can_scale))
            if self._use_can_corrections:
                sample_log_workspaces.append(self._acc_ws)
                sample_logs.append(('container_front_thickness', self. _can_front_thickness))
                sample_logs.append(('container_back_thickness', self. _can_back_thickness))

        log_names = [item[0] for item in sample_logs]
        log_values = [item[1] for item in sample_logs]

        for ws_name in sample_log_workspaces:
            AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values)

        self.setProperty('OutputWorkspace', self._output_ws)

        # Output the Ass workspace if it is wanted, delete if not
        if self._abs_ws == '':
            DeleteWorkspace(self._ass_ws)
            if self._can_ws_name is not None and self._use_can_corrections:
                DeleteWorkspace(self._acc_ws)
        else:
            GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws)
            self.setProperty('CorrectionsWorkspace', self._abs_ws)

        if self._plot:
            from IndirectImport import import_mantidplot
            mantid_plot = import_mantidplot()
            mantid_plot.plotSpectrum(plot_data, 0)
            if self._abs_ws != '':
                mantid_plot.plotSpectrum(plot_corr, 0)
 def _plot_result(self, workspaces):
     from IndirectImport import import_mantidplot
     mp = import_mantidplot()
     mp.plotSpectrum(workspaces,0)
Exemplo n.º 34
0
#pylint: disable=invalid-name,too-many-locals,too-many-arguments

from IndirectImport import import_mantidplot
MTD_PLOT = import_mantidplot()
from IndirectCommon import *

import math, re, os.path, numpy as np
from mantid.simpleapi import *
from mantid.api import TextAxis
from mantid import *


def createFuryMultiDomainFunction(function, input_ws):
    multi = 'composite=MultiDomainFunction,NumDeriv=true;'
    comp = '(composite=CompositeFunction,NumDeriv=true,$domains=i;' + function + ');'

    ties = []
    kwargs = {}
    num_spectra = mtd[input_ws].getNumberHistograms()
    for i in range(0, num_spectra):
        multi += comp
        kwargs['WorkspaceIndex_' + str(i)] = i

        if i > 0:
            kwargs['InputWorkspace_' + str(i)] = input_ws

            #tie beta for every spectrum
            tie = 'f%d.f1.Beta=f0.f1.Beta' % i
            ties.append(tie)

    ties = ','.join(ties)
Exemplo n.º 35
0
    def PyExec(self):
        from IndirectImport import import_mantidplot
        self._mtd_plot = import_mantidplot()

        output_ws_name = self.getPropertyValue('OutputWorkspace')
        version, data_name, _ = self._get_version_and_data_path()

        logger.information('Detected data from nMoldyn version {0}'.format(version))

        # Run nMOLDYN import
        if version == 3:
            LoadNMoldyn3Ascii(Filename=data_name,
                              OutputWorkspace=output_ws_name,
                              Functions=self.getPropertyValue('Functions'))
        elif version == 4:
            LoadNMoldyn4Ascii(Directory=data_name,
                              OutputWorkspace=output_ws_name,
                              Functions=self.getPropertyValue('Functions'))
        else:
            raise RuntimeError('No loader for input data')

        symmetrise = self.getProperty('SymmetriseEnergy').value
        max_energy_param = self.getProperty('MaxEnergy').value

        # Do processing specific to workspaces in energy
        if isinstance(mtd[output_ws_name], WorkspaceGroup):
            for ws_name in mtd[output_ws_name].getNames():
                if mtd[ws_name].getAxis(0).getUnit().unitID() == 'Energy':
                    # Get an XMax value, default to max energy if not cropping
                    max_energy = mtd[ws_name].dataX(0).max()
                    logger.debug('Max energy in workspace %s: %f' % (ws_name, max_energy))

                    if max_energy_param != Property.EMPTY_DBL:
                        if max_energy_param > max_energy:
                            raise ValueError('MaxEnergy crop is out of energy range for function %s' % ws_name)
                        max_energy = max_energy_param

                    # If we are going to Symmetrise then there is no need to crop
                    # as the Symmetrise algorithm will do this
                    if symmetrise:
                        # Symmetrise the sample workspace in x=0
                        Symmetrise(InputWorkspace=ws_name,
                                   XMin=0,
                                   XMax=max_energy,
                                   OutputWorkspace=ws_name)

                    elif max_energy_param != Property.EMPTY_DBL:
                        CropWorkspace(InputWorkspace=ws_name,
                                      OutputWorkspace=ws_name,
                                      XMin=-max_energy,
                                      XMax=max_energy)

        # Do convolution if given a resolution workspace
        if self.getPropertyValue('Resolution') != '':
            # Create a workspace with enough spectra for convolution
            num_sample_hist = mtd[output_ws_name].getItem(0).getNumberHistograms()
            resolution_ws = self._create_res_ws(num_sample_hist)

            # Convolve all workspaces in output group
            for ws_name in mtd[output_ws_name].getNames():
                if 'Energy' in mtd[ws_name].getAxis(0).getUnit().unitID():
                    self._convolve_with_res(resolution_ws, ws_name)
                else:
                    logger.information('Ignoring workspace %s in convolution step' % ws_name)

            # Remove the generated resolution workspace
            DeleteWorkspace(resolution_ws)

        # Save result workspace group
        if self.getProperty('Save').value:
            workdir = config['defaultsave.directory']
            out_filename = os.path.join(workdir, output_ws_name + '.nxs')
            logger.information('Creating file: %s' % out_filename)
            SaveNexus(InputWorkspace=output_ws_name, Filename=out_filename)

        # Set the output workspace
        self.setProperty('OutputWorkspace', output_ws_name)

        plot = self.getProperty('Plot').value
        # Plot spectra plots
        if plot == 'Spectra' or plot == 'Both':
            if isinstance(mtd[output_ws_name], WorkspaceGroup):
                for ws_name in mtd[output_ws_name].getNames():
                    self._plot_spectra(ws_name)
            else:
                self._plot_spectra(output_ws_name)

        # Plot contour plot
        if plot == 'Contour' or plot == 'Both':
            self._mtd_plot.plot2D(output_ws_name)
Exemplo n.º 36
0
#pylint: disable=invalid-name,too-many-locals,too-many-arguments

from IndirectImport import import_mantidplot
MTD_PLOT = import_mantidplot()
from IndirectCommon import *

import math, re, os.path, numpy as np
from mantid.simpleapi import *
from mantid.api import TextAxis
from mantid import *


##############################################################################
# ConvFit
##############################################################################

def calculateEISF(params_table):
    #get height data from parameter table
    height = search_for_fit_params('Height', params_table)[0]
    height_error = search_for_fit_params('Height_Err', params_table)[0]
    height_y = np.asarray(mtd[params_table].column(height))
    height_e = np.asarray(mtd[params_table].column(height_error))

    #get amplitude column names
    amp_names = search_for_fit_params('Amplitude', params_table)
    amp_error_names = search_for_fit_params('Amplitude_Err', params_table)

    #for each lorentzian, calculate EISF
    for amp_name, amp_error_name in zip(amp_names, amp_error_names):
        #get amplitude from column in table workspace
        amp_y = np.asarray(mtd[params_table].column(amp_name))
    def PyExec(self):
        from IndirectImport import import_mantidplot
        mp = import_mantidplot()
        workdir = config['defaultsave.directory']
        # self._setup()

        q2_workspaces = []
        scan_alg = self.createChildAlgorithm("EnergyWindowScan", 0.05, 0.95)
        for numb in range(self._number_samples):
            run_numbers = []
            run_names = []
            first_run = self._run_first + numb
            for idx in range(int(self._number_runs)):
                run = str(first_run + idx * self._number_samples)
                run_numbers.append(run)
                run_names.append(self._instrument + run)
            q0 = self._instrument.lower() + run_numbers[0] + '_to_' + run_numbers[-1] + '_s' + str(numb)
            output_ws = q0 + '_red'
            scan_ws = q0 + '_scan'
            scan_alg.setProperty('InputFiles', run_names)
            scan_alg.setProperty('LoadLogFiles', True)
            scan_alg.setProperty('CalibrationWorkspace', '')
            scan_alg.setProperty('Instrument', self._instrument_name)
            scan_alg.setProperty('Analyser', self._analyser)
            scan_alg.setProperty('Reflection', self._reflection)
            scan_alg.setProperty('SpectraRange', self._spectra_range)
            scan_alg.setProperty('ElasticRange', self._elastic_range)
            scan_alg.setProperty('InelasticRange', self._inelastic_range)
            scan_alg.setProperty('TotalRange', self._total_range)
            scan_alg.setProperty('DetailedBalance', Property.EMPTY_DBL)
            scan_alg.setProperty('GroupingMethod', 'Individual')
            scan_alg.setProperty('SampleEnvironmentLogName', self._sample_log_name)
            scan_alg.setProperty('SampleEnvironmentLogValue', self._sample_log_value)
            scan_alg.setProperty('msdFit', self._msdfit)
            scan_alg.setProperty('ReducedWorkspace', output_ws)
            scan_alg.setProperty('ScanWorkspace', scan_ws)
            scan_alg.execute()

            logger.information('OutputWorkspace : %s' % output_ws)
            logger.information('ScanWorkspace : %s' % scan_ws)

            q1_ws = scan_ws + '_el_eq1'
            q2_ws = scan_ws + '_el_eq2'
            q2_workspaces.append(q2_ws)
            eisf_ws = scan_ws + '_eisf'
            el_elt_ws = scan_ws + '_el_elt'
            inel_elt_ws = scan_ws + '_inel_elt'
            tot_elt_ws = scan_ws + '_total_elt'
            msd_ws = scan_ws + '_msd'
#            output_workspaces = [q1_ws, q2_ws, eisf_ws, el_elt_ws, inel_elt_ws, tot_elt_ws]
            output_workspaces = [q1_ws, eisf_ws, el_elt_ws, inel_elt_ws, tot_elt_ws]
            if self._msdfit:
                output_workspaces.append(msd_ws)

            if self._plot:
                for ws in output_workspaces:
                    mp.plotSpectrum(ws, 0, error_bars=True)

            if self._save:
                self._save_output(output_workspaces)

        if self._widthfit:
            result_workspaces = list()
            chi_workspaces = list()
            temperatures = list()
        # Get input workspaces
            fit_progress = Progress(self, 0.0, 0.05, 3)
            input_workspace_names = mtd[output_ws].getNames()
            x = mtd[input_workspace_names[0]].readX(0)
            xmin = x[0]
            xmax = x[len(x) - 1]
            for input_ws in input_workspace_names:

                red_ws = input_ws[:-3] + 'red'
                # Get the sample temperature
                temp = self._get_temperature(red_ws)
                if temp is not None:
                    temperatures.append(temp)
                else:
                # Get the run number
                    run_no = self._get_InstrRun(input_ws)[1]
                    run_numbers.append(run_no)

                num_hist = mtd[input_ws].getNumberHistograms()
                logger.information('Reduced histograms : %i' % num_hist)
                result = input_ws[:-3] + 'fit'
                func = 'name=Lorentzian,Amplitude=1.0,PeakCentre=0.0,FWHM=0.01'
                func += ',constraint=(Amplitude>0.0,FWHM>0.0)'
                for idx in range(num_hist):
                    fit_progress.report('Fitting workspace: %s ; spectrum %i' % (input_ws, idx))
                    IndirectTwoPeakFit(SampleWorkspace=input_ws,
                                       EnergyMin=xmin,
                                       EnergyMax=xmax,
                                       Minimizer='Levenberg-Marquardt',
                                       MaxIterations=500,
                                       OutputName=result)
                result_workspaces.append(result + '_Result')
                chi_workspaces.append(result + '_ChiSq')

                if self._plot:
                    mp.plotSpectrum(result + '_ChiSq', [0, 1], error_bars=False)
                    mp.plotSpectrum(result + '_Result', 0, error_bars=True)