Esempio n. 1
0
def reduceToPowder(ws,
                   OutputWorkspace,
                   norm=None,
                   taget='Theta',
                   XMin=10,
                   XMax=135,
                   NumberBins=2500):
    # Add scale by monitor
    ConvertSpectrumAxis(InputWorkspace=ws,
                        Target=taget,
                        OutputWorkspace=OutputWorkspace)
    Transpose(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace)
    ResampleX(InputWorkspace=OutputWorkspace,
              OutputWorkspace=OutputWorkspace,
              XMin=XMin,
              XMax=XMax,
              NumberBins=NumberBins)
    if norm is not None:
        ConvertSpectrumAxis(InputWorkspace=norm,
                            Target=taget,
                            OutputWorkspace='__norm')
        Transpose(InputWorkspace='__norm', OutputWorkspace='__norm')
        ResampleX(InputWorkspace='__norm',
                  OutputWorkspace='__norm',
                  XMin=XMin,
                  XMax=XMax,
                  NumberBins=NumberBins)
        Divide(LHSWorkspace=OutputWorkspace,
               RHSWorkspace='__norm',
               OutputWorkspace=OutputWorkspace)
        DeleteWorkspace('__norm')
    return OutputWorkspace
Esempio n. 2
0
def reduceToPowder(ws,
                   OutputWorkspace,
                   cal=None,
                   target='Theta',
                   XMin=10,
                   XMax=135,
                   NumberBins=2500,
                   normaliseBy='Monitor'):
    ConvertSpectrumAxis(InputWorkspace=ws,
                        Target=target,
                        OutputWorkspace=OutputWorkspace)
    Transpose(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace)
    ResampleX(InputWorkspace=OutputWorkspace,
              OutputWorkspace=OutputWorkspace,
              XMin=XMin,
              XMax=XMax,
              NumberBins=NumberBins)

    if cal is not None:
        CopyInstrumentParameters(ws, cal)
        ConvertSpectrumAxis(InputWorkspace=cal,
                            Target=target,
                            OutputWorkspace='__cal')
        Transpose(InputWorkspace='__cal', OutputWorkspace='__cal')
        ResampleX(InputWorkspace='__cal',
                  OutputWorkspace='__cal',
                  XMin=XMin,
                  XMax=XMax,
                  NumberBins=NumberBins)
        Divide(LHSWorkspace=OutputWorkspace,
               RHSWorkspace='__cal',
               OutputWorkspace=OutputWorkspace)
        DeleteWorkspace('__cal')

    if normaliseBy == "Monitor":
        ws_monitor = mtd[ws].run().getProtonCharge()
        cal_monitor = mtd[cal].run().getProtonCharge()
        Scale(InputWorkspace=OutputWorkspace,
              OutputWorkspace=OutputWorkspace,
              Factor=cal_monitor / ws_monitor)
    elif normaliseBy == "Time":
        ws_duration = mtd[ws].run().getLogData('duration').value
        cal_duration = mtd[cal].run().getLogData('duration').value
        Scale(InputWorkspace=OutputWorkspace,
              OutputWorkspace=OutputWorkspace,
              Factor=cal_duration / ws_duration)

    return OutputWorkspace
Esempio n. 3
0
 def test_plotDOS_PlotMultiple(self):
     ws = CreateSampleWorkspace(NumBanks=1,
                                XUnit='DeltaE',
                                XMin=-12.,
                                XMax=12.,
                                BinWidth=0.2,
                                StoreInADS=False)
     MoveInstrumentComponent(ws, 'bank1', X=-0.5, StoreInADS=False)
     ws = ConvertSpectrumAxis(ws, 'Theta', 'Direct', 14., StoreInADS=False)
     SetInstrumentParameter(ws,
                            ParameterName='deltaE-mode',
                            Value='direct',
                            StoreInADS=False)
     AddSampleLog(ws,
                  LogName='Ei',
                  LogText=str(14.),
                  LogType='Number',
                  LogUnit='meV',
                  StoreInADS=False)
     stw = ComputeIncoherentDOS(ws)
     kwargs = {'workspaces': [stw, 'stw']}
     figure, axes = testhelpers.assertRaisesNothing(self,
                                                    directtools.plotDOS,
                                                    **kwargs)
     self.assertEqual(axes.get_xlabel(), 'Energy transfer ($meV$)')
     self.assertEqual(axes.get_ylabel(), '$g(E)$')
    def _resample_calibration(
        self, current_workspace, mask_name, x_min, x_max,
    ):
        """Perform resample on calibration"""
        cal = self.getProperty("CalibrationWorkspace").value
        target = self.getProperty("Target").value
        e_fixed = self.getProperty("EFixed").value
        number_bins = self.getProperty("NumberBins").value

        _ws_cal = ExtractUnmaskedSpectra(
            InputWorkspace=cal, MaskWorkspace=mask_name, EnableLogging=False
        )
        if isinstance(mtd["_ws_cal"], IEventWorkspace):
            _ws_cal = Integration(InputWorkspace=_ws_cal, EnableLogging=False)
        CopyInstrumentParameters(
            InputWorkspace=current_workspace,
            OutputWorkspace=_ws_cal,
            EnableLogging=False,
        )
        _ws_cal = ConvertSpectrumAxis(
            InputWorkspace=_ws_cal, Target=target, EFixed=e_fixed, EnableLogging=False,
        )
        _ws_cal = Transpose(InputWorkspace=_ws_cal, EnableLogging=False)
        return ResampleX(
            InputWorkspace=_ws_cal,
            XMin=x_min,
            XMax=x_max,
            NumberBins=number_bins,
            EnableLogging=False,
        )
Esempio n. 5
0
 def _compute_slice_nonPSD(self, workspace, x_axis, y_axis, e_mode,
                           norm_to_one):
     axes = [x_axis, y_axis]
     if x_axis.units == 'DeltaE':
         e_axis = 0
     elif y_axis.units == 'DeltaE':
         e_axis = 1
     else:
         raise RuntimeError(
             'Cannot calculate slices without an energy axis')
     q_axis = (e_axis + 1) % 2
     ebin = '%f, %f, %f' % (axes[e_axis].start, axes[e_axis].step,
                            axes[e_axis].end)
     qbin = '%f, %f, %f' % (axes[q_axis].start, axes[q_axis].step,
                            axes[q_axis].end)
     if axes[q_axis].units == '|Q|':
         thisslice = SofQW3(InputWorkspace=workspace,
                            QAxisBinning=qbin,
                            EAxisBinning=ebin,
                            EMode=e_mode,
                            StoreInADS=False)
     elif axes[q_axis].units == '2Theta':
         thisslice = ConvertSpectrumAxis(InputWorkspace=workspace,
                                         Target='Theta',
                                         StoreInADS=False)
         thisslice = Rebin2D(InputWorkspace=thisslice,
                             Axis1Binning=ebin,
                             Axis2Binning=qbin,
                             StoreInADS=False)
     else:
         raise RuntimeError(
             "axis %s not recognised, must be '|Q|' or '2Theta'" %
             axes[q_axis].units)
     return thisslice
Esempio n. 6
0
def save_reduction(worksspace_names, formats, x_units='DeltaE'):
    """
    Saves the workspaces to the default save directory.

    @param worksspace_names List of workspace names to save
    @param formats List of formats to save in
    @param Output X units
    """
    from mantid.simpleapi import (SaveSPE, SaveNexusProcessed, SaveNXSPE,
                                  SaveAscii, Rebin, DeleteWorkspace,
                                  ConvertSpectrumAxis, SaveDaveGrp)

    for workspace_name in worksspace_names:
        if 'spe' in formats:
            SaveSPE(InputWorkspace=workspace_name,
                    Filename=workspace_name + '.spe')

        if 'nxs' in formats:
            SaveNexusProcessed(InputWorkspace=workspace_name,
                               Filename=workspace_name + '.nxs')

        if 'nxspe' in formats:
            SaveNXSPE(InputWorkspace=workspace_name,
                      Filename=workspace_name + '.nxspe')

        if 'ascii' in formats:
            # Version 1 of SaveAscii produces output that works better with excel/origin
            # For some reason this has to be done with an algorithm object, using the function
            # wrapper with Version did not change the version that was run
            saveAsciiAlg = AlgorithmManager.createUnmanaged('SaveAscii', 1)
            saveAsciiAlg.initialize()
            saveAsciiAlg.setProperty('InputWorkspace', workspace_name)
            saveAsciiAlg.setProperty('Filename', workspace_name + '.dat')
            saveAsciiAlg.execute()

        if 'aclimax' in formats:
            if x_units == 'DeltaE_inWavenumber':
                bins = '24, -0.005, 4000' #cm-1
            else:
                bins = '3, -0.005, 500' #meV

            Rebin(InputWorkspace=workspace_name,
                  OutputWorkspace=workspace_name + '_aclimax_save_temp',
                  Params=bins)
            SaveAscii(InputWorkspace=workspace_name + '_aclimax_save_temp',
                      Filename=workspace_name + '_aclimax.dat',
                      Separator='Tab')
            DeleteWorkspace(Workspace=workspace_name + '_aclimax_save_temp')

        if 'davegrp' in formats:
            ConvertSpectrumAxis(InputWorkspace=workspace_name,
                                OutputWorkspace=workspace_name + '_davegrp_save_temp',
                                Target='ElasticQ',
                                EMode='Indirect')
            SaveDaveGrp(InputWorkspace=workspace_name + '_davegrp_save_temp',
                        Filename=workspace_name + '.grp')
            DeleteWorkspace(Workspace=workspace_name + '_davegrp_save_temp')
def save_reduction(workspace_names, formats, x_units='DeltaE'):
    """
    Saves the workspaces to the default save directory.

    @param workspace_names List of workspace names to save
    @param formats List of formats to save in
    @param x_units X units
    """
    from mantid.simpleapi import (SaveSPE, SaveNexusProcessed, SaveNXSPE,
                                  SaveAscii, Rebin, DeleteWorkspace,
                                  ConvertSpectrumAxis, SaveDaveGrp)

    for workspace_name in workspace_names:
        if 'spe' in formats:
            SaveSPE(InputWorkspace=workspace_name,
                    Filename=workspace_name + '.spe')

        if 'nxs' in formats:
            SaveNexusProcessed(InputWorkspace=workspace_name,
                               Filename=workspace_name + '.nxs')

        if 'nxspe' in formats:
            SaveNXSPE(InputWorkspace=workspace_name,
                      Filename=workspace_name + '.nxspe')

        if 'ascii' in formats:

            # Changed to version 2 to enable re-loading of files into mantid
            saveAsciiAlg = AlgorithmManager.createUnmanaged('SaveAscii', 2)
            saveAsciiAlg.initialize()
            saveAsciiAlg.setProperty('InputWorkspace', workspace_name)
            saveAsciiAlg.setProperty('Filename', workspace_name + '.dat')
            saveAsciiAlg.execute()

        if 'aclimax' in formats:
            if x_units == 'DeltaE_inWavenumber':
                bins = '24, -0.005, 4000'  #cm-1
            else:
                bins = '3, -0.005, 500'  #meV

            Rebin(InputWorkspace=workspace_name,
                  OutputWorkspace=workspace_name + '_aclimax_save_temp',
                  Params=bins)
            SaveAscii(InputWorkspace=workspace_name + '_aclimax_save_temp',
                      Filename=workspace_name + '_aclimax.dat',
                      Separator='Tab')
            DeleteWorkspace(Workspace=workspace_name + '_aclimax_save_temp')

        if 'davegrp' in formats:
            ConvertSpectrumAxis(InputWorkspace=workspace_name,
                                OutputWorkspace=workspace_name +
                                '_davegrp_save_temp',
                                Target='ElasticQ',
                                EMode='Indirect')
            SaveDaveGrp(InputWorkspace=workspace_name + '_davegrp_save_temp',
                        Filename=workspace_name + '.grp')
            DeleteWorkspace(Workspace=workspace_name + '_davegrp_save_temp')
    def _locate_global_xlimit(self):
        """Find the global bin from all spectrum"""
        input_workspaces = self.getProperty("InputWorkspace").value
        mask = self.getProperty("MaskWorkspace").value
        maks_angle = self.getProperty("MaskAngle").value
        target = self.getProperty("Target").value
        e_fixed = self.getProperty("EFixed").value

        # NOTE:
        # Due to range difference among incoming spectra, a common bin para is needed
        # such that all data can be binned exactly the same way.
        _xMin, _xMax = 1e16, -1e16

        # BEGIN_FOR: located_global_xMin&xMax
        for n, _wsn in enumerate(input_workspaces):
            _ws = AnalysisDataService.retrieve(_wsn)
            _mskn = f"__mask_{n}"
            self.temp_workspace_list.append(_mskn)

            ExtractMask(_ws, OutputWorkspace=_mskn, EnableLogging=False)
            if maks_angle != Property.EMPTY_DBL:
                MaskAngle(
                    Workspace=_mskn,
                    MinAngle=maks_angle,
                    Angle="Phi",
                    EnableLogging=False,
                )
            if mask is not None:
                BinaryOperateMasks(
                    InputWorkspace1=_mskn,
                    InputWorkspace2=mask,
                    OperationType="OR",
                    OutputWorkspace=_mskn,
                    EnableLogging=False,
                )

            _ws_tmp = ExtractUnmaskedSpectra(
                InputWorkspace=_ws, MaskWorkspace=_mskn, EnableLogging=False
            )
            if isinstance(mtd["_ws_tmp"], IEventWorkspace):
                _ws_tmp = Integration(InputWorkspace=_ws_tmp, EnableLogging=False)
            _ws_tmp = ConvertSpectrumAxis(
                InputWorkspace=_ws_tmp,
                Target=target,
                EFixed=e_fixed,
                EnableLogging=False,
            )
            _ws_tmp = Transpose(
                InputWorkspace=_ws_tmp, OutputWorkspace=f"__ws_{n}", EnableLogging=False
            )

            _xMin = min(_xMin, _ws_tmp.readX(0).min())
            _xMax = max(_xMax, _ws_tmp.readX(0).max())
        # END_FOR: located_global_xMin&xMax

        return _xMin, _xMax
Esempio n. 9
0
def _cut_nonPSD_theta(cut_binning, int_binning, selected_workspace):

    converted_nonpsd = ConvertSpectrumAxis(OutputWorkspace='__convToTheta',
                                           InputWorkspace=selected_workspace,
                                           Target='theta',
                                           StoreInADS=False)

    ws_out = Rebin2D(InputWorkspace=converted_nonpsd,
                     Axis1Binning=int_binning,
                     Axis2Binning=cut_binning,
                     StoreInADS=False)
    return ws_out
Esempio n. 10
0
 def _calcThetaEproj(self, input_workspace, emode, axis1, axis2):
     """ Carries out either the 2Theta-E or E-2Theta projections """
     retval = ConvertSpectrumAxis(InputWorkspace=input_workspace, Target='Theta')
     # Work-around for a bug in ConvertToMD.
     wsdet = self._getDetWS(input_workspace) if emode == 'Indirect' else '-'
     retval = ConvertToMD(InputWorkspace=retval, QDimensions='CopyToMD', PreprocDetectorsWS=wsdet,
                          dEAnalysisMode=emode, StoreInADS=False)
     if emode == 'Indirect':
         DeleteWorkspace(wsdet)
     if axis1 == THETA_LABEL:
         retval = self._flip_axes(retval)
     return retval
Esempio n. 11
0
def convert_to_2theta(ws_name, num_bins=1000):
    """
    """
    # duplicate for vanadium
    vanadium = CloneWorkspace(InputWorkspace=ws_name,
                              OutputWorkspace='vanadium')

    # transfer to 2theta for data
    ConvertSpectrumAxis(InputWorkspace=ws_name,
                        OutputWorkspace=ws_name,
                        Target='Theta')
    Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name)
    ResampleX(InputWorkspace=ws_name,
              OutputWorkspace=ws_name,
              NumberBins=num_bins,
              PreserveEvents=False)

    # vanadium: set to 1 for now
    time_van_start = time.time()
    for iws in range(vanadium.getNumberHistograms()):
        vanadium.dataY(iws)[0] = 1.
    time_van_stop = time.time()
    ConvertSpectrumAxis(InputWorkspace='vanadium',
                        OutputWorkspace='vanadium',
                        Target='Theta')
    Transpose(InputWorkspace='vanadium', OutputWorkspace='vanadium')
    ResampleX(InputWorkspace='vanadium',
              OutputWorkspace='vanadium',
              NumberBins=num_bins,
              PreserveEvents=False)

    norm_ws_name = ws_name + '_normalized'
    Divide(LHSWorkspace=ws_name,
           RHSWorkspace='vanadium',
           OutputWorkspace=norm_ws_name)

    print('Create vanadium workspace : {} seconds'.format(time_van_stop -
                                                          time_van_start))

    return norm_ws_name
Esempio n. 12
0
def save_reduction(workspace_names, formats, x_units='DeltaE'):
    """
    Saves the workspaces to the default save directory.

    @param workspace_names List of workspace names to save
    @param formats List of formats to save in
    @param x_units X units
    """
    from mantid.simpleapi import (SaveSPE, SaveNexusProcessed, SaveNXSPE,
                                  SaveAscii, Rebin, DeleteWorkspace,
                                  ConvertSpectrumAxis, SaveDaveGrp)

    for workspace_name in workspace_names:
        if 'spe' in formats:
            SaveSPE(InputWorkspace=workspace_name,
                    Filename=workspace_name + '.spe')

        if 'nxs' in formats:
            SaveNexusProcessed(InputWorkspace=workspace_name,
                               Filename=workspace_name + '.nxs')

        if 'nxspe' in formats:
            SaveNXSPE(InputWorkspace=workspace_name,
                      Filename=workspace_name + '.nxspe')

        if 'ascii' in formats:
            _save_ascii(workspace_name, workspace_name + ".dat")

        if 'aclimax' in formats:
            if x_units == 'DeltaE_inWavenumber':
                bins = '24, -0.005, 4000'  # cm-1
            else:
                bins = '3, -0.005, 500'  # meV

            Rebin(InputWorkspace=workspace_name,
                  OutputWorkspace=workspace_name + '_aclimax_save_temp',
                  Params=bins)
            SaveAscii(InputWorkspace=workspace_name + '_aclimax_save_temp',
                      Filename=workspace_name + '_aclimax.dat',
                      Separator='Tab')
            DeleteWorkspace(Workspace=workspace_name + '_aclimax_save_temp')

        if 'davegrp' in formats:
            ConvertSpectrumAxis(InputWorkspace=workspace_name,
                                OutputWorkspace=workspace_name +
                                '_davegrp_save_temp',
                                Target='ElasticQ',
                                EMode='Indirect')
            SaveDaveGrp(InputWorkspace=workspace_name + '_davegrp_save_temp',
                        Filename=workspace_name + '.grp')
            DeleteWorkspace(Workspace=workspace_name + '_davegrp_save_temp')
Esempio n. 13
0
 def _outputWSConvertedToTheta(self, mainWS):
     """
     If requested, convert the spectrum axis to theta and save the result
     into the proper output property.
     """
     if not self.getProperty(common.PROP_OUTPUT_THETA_W_WS).isDefault:
         thetaWSName = self._names.withSuffix('in_theta_energy_for_output')
         thetaWS = ConvertSpectrumAxis(InputWorkspace=mainWS,
                                       OutputWorkspace=thetaWSName,
                                       Target='Theta',
                                       EMode='Direct',
                                       EnableLogging=self._subalgLogging)
         self.setProperty(common.PROP_OUTPUT_THETA_W_WS, thetaWS)
         self._cleanup.cleanup(thetaWS)
Esempio n. 14
0
 def _outputWSConvertedToTheta(self, mainWS, wsNames, wsCleanup,
                               subalgLogging):
     """If requested, convert the spectrum axis to theta and save the result
     into the proper output property.
     """
     thetaWSName = self.getProperty(common.PROP_OUTPUT_THETA_W_WS).valueAsStr
     if thetaWSName:
         thetaWSName = self.getProperty(common.PROP_OUTPUT_THETA_W_WS).value
         thetaWS = ConvertSpectrumAxis(InputWorkspace=mainWS,
                                       OutputWorkspace=thetaWSName,
                                       Target='Theta',
                                       EMode='Direct',
                                       EnableLogging=subalgLogging)
         self.setProperty(common.PROP_OUTPUT_THETA_W_WS, thetaWS)
Esempio n. 15
0
    def _to_spectrum_axis(self,
                          workspace_in,
                          workspace_out,
                          mask,
                          instrument_donor=None):
        target = self.getProperty("Target").value
        wavelength = self.getProperty("Wavelength").value
        e_fixed = UnitConversion.run('Wavelength', 'Energy', wavelength, 0, 0,
                                     0, Elastic, 0)

        ExtractUnmaskedSpectra(
            InputWorkspace=workspace_in,
            OutputWorkspace=workspace_out,
            MaskWorkspace=mask,
            EnableLogging=False,
        )

        if isinstance(mtd[workspace_out], IEventWorkspace):
            Integration(
                InputWorkspace=workspace_out,
                OutputWorkspace=workspace_out,
                EnableLogging=False,
            )

        if instrument_donor:
            CopyInstrumentParameters(
                InputWorkspace=instrument_donor,
                OutputWorkspace=workspace_out,
                EnableLogging=False,
            )

        ConvertSpectrumAxis(
            InputWorkspace=workspace_out,
            OutputWorkspace=workspace_out,
            Target=target,
            EFixed=e_fixed,
            EnableLogging=False,
        )

        Transpose(
            InputWorkspace=workspace_out,
            OutputWorkspace=workspace_out,
            EnableLogging=False,
        )

        return workspace_out
Esempio n. 16
0
    def _resample_background(
        self,
        current_background,
        current_workspace,
        make_name,
        x_min,
        x_max,
        resmapled_calibration,
    ):
        """Perform resample on given background"""
        cal = self.getProperty("CalibrationWorkspace").value
        target = self.getProperty("Target").value
        e_fixed = self.getProperty("EFixed").value
        number_bins = self.getProperty("NumberBins").value

        _ws_bkg = ExtractUnmaskedSpectra(
            InputWorkspace=current_background,
            MaskWorkspace=make_name,
            EnableLogging=False,
        )

        if isinstance(mtd["_ws_bkg"], IEventWorkspace):
            _ws_bkg = Integration(InputWorkspace=_ws_bkg, EnableLogging=False)

        CopyInstrumentParameters(
            InputWorkspace=current_workspace,
            OutputWorkspace=_ws_bkg,
            EnableLogging=False,
        )

        _ws_bkg = ConvertSpectrumAxis(
            InputWorkspace=_ws_bkg, Target=target, EFixed=e_fixed, EnableLogging=False,
        )

        _ws_bkg = Transpose(InputWorkspace=_ws_bkg, EnableLogging=False)

        _ws_bkg_resampled = ResampleX(
            InputWorkspace=_ws_bkg,
            XMin=x_min,
            XMax=x_max,
            NumberBins=number_bins,
            EnableLogging=False,
        )

        if cal is not None:
            _ws_bkg_resampled = Divide(
                LHSWorkspace=_ws_bkg_resampled,
                RHSWorkspace=resmapled_calibration,
                EnableLogging=False,
            )

        _ws_bkg_resampled = Scale(
            InputWorkspace=_ws_bkg_resampled,
            Factor=self._get_scale(cal) / self._get_scale(current_background),
            EnableLogging=False,
        )

        _ws_bkg_resampled = Scale(
            InputWorkspace=_ws_bkg_resampled,
            Factor=self.getProperty("BackgroundScale").value,
            EnableLogging=False,
        )

        return _ws_bkg_resampled
Esempio n. 17
0
def reduce_to_2theta(hb2b_builder,
                     pixel_matrix,
                     hb2b_data_ws_name,
                     counts_array,
                     mask_vec,
                     mask_ws_name,
                     num_bins=1000):
    """
    Reduce to 2theta with Masks
    :param hb2b_builder:
    :param pixel_matrix:
    :param hb2b_data_ws_name:
    :param counts_array:
    :param mask_vec:
    :param num_bins:
    :return:
    """
    # reduce by PyRS
    if False:
        pyrs_raw_ws = mtd[pyrs_raw_name]
        vec_counts = pyrs_raw_ws.readY(0)
    else:
        vec_counts = counts_array.astype('float64')

    # mask
    if mask_vec is not None:
        print(mask_vec.dtype)
        vec_counts.astype('float64')
        mask_vec.astype('float64')
        vec_counts *= mask_vec
    # reduce
    bin_edgets, histogram = hb2b_builder.reduce_to_2theta_histogram(
        pixel_matrix, vec_counts, num_bins)

    # create workspace
    pyrs_reduced_name = '{}_pyrs_reduced'.format(hb2b_data_ws_name)
    CreateWorkspace(DataX=bin_edgets,
                    DataY=histogram,
                    NSpec=1,
                    OutputWorkspace=pyrs_reduced_name)
    SaveNexusProcessed(InputWorkspace=pyrs_reduced_name,
                       Filename='{}.nxs'.format(pyrs_reduced_name),
                       Title='PyRS reduced: {}'.format(hb2b_data_ws_name))

    if True:
        # Mantid
        # transfer to 2theta for data
        two_theta_ws_name = '{}_2theta'.format(hb2b_data_ws_name)

        # Mask
        if mask_ws_name:
            # Multiply by masking workspace
            masked_ws_name = '{}_masked'.format(hb2b_data_ws_name)
            Multiply(LHSWorkspace=hb2b_data_ws_name,
                     RHSWorkspace=mask_ws_name,
                     OutputWorkspace=masked_ws_name,
                     ClearRHSWorkspace=False)
            hb2b_data_ws_name = masked_ws_name
            SaveNexusProcessed(InputWorkspace=hb2b_data_ws_name,
                               Filename='{}_raw.nxs'.format(hb2b_data_ws_name))
        # END-IF

        # # this is for test only!
        # ConvertSpectrumAxis(InputWorkspace=hb2b_data_ws_name, OutputWorkspace=two_theta_ws_name, Target='Theta',
        #                     OrderAxis=False)
        # Transpose(InputWorkspace=two_theta_ws_name, OutputWorkspace=two_theta_ws_name)
        # two_theta_ws = mtd[two_theta_ws_name]
        # for i in range(10):
        #     print ('{}: x = {}, y = {}'.format(i, two_theta_ws.readX(0)[i], two_theta_ws.readY(0)[i]))
        # for i in range(10010, 10020):
        #     print ('{}: x = {}, y = {}'.format(i, two_theta_ws.readX(0)[i], two_theta_ws.readY(0)[i]))

        ConvertSpectrumAxis(InputWorkspace=hb2b_data_ws_name,
                            OutputWorkspace=two_theta_ws_name,
                            Target='Theta')
        Transpose(InputWorkspace=two_theta_ws_name,
                  OutputWorkspace=two_theta_ws_name)
        # final:
        mantid_reduced_name = '{}_mtd_reduced'.format(hb2b_data_ws_name)
        ResampleX(InputWorkspace=two_theta_ws_name,
                  OutputWorkspace=mantid_reduced_name,
                  NumberBins=num_bins,
                  PreserveEvents=False)
        mantid_ws = mtd[mantid_reduced_name]

        SaveNexusProcessed(
            InputWorkspace=mantid_reduced_name,
            Filename='{}.nxs'.format(mantid_reduced_name),
            Title='Mantid reduced: {}'.format(hb2b_data_ws_name))

        plt.plot(mantid_ws.readX(0),
                 mantid_ws.readY(0),
                 color='blue',
                 mark='o')

    # END-IF

    plt.plot(bin_edgets[:-1], histogram, color='red')

    plt.show()

    return
Esempio n. 18
0
 def _create_workspace(self,
                       ws_2D=True,
                       sample=True,
                       xAx=True,
                       yAxSpec=True,
                       yAxMt=True,
                       instrument=True):
     """ create Workspace
     :param ws_2D: should workspace be 2D?
     :param sample: should workspace have sample logs?
     :param xAx: should x axis be DeltaE?
     :param yAxMt: should y axis be MomentumTransfer?
     :param yAxSpec: should y axis be SpectrumAxis?
     :param instrument: should workspace have a instrument?
     """
     # Event Workspace
     if not ws_2D:
         ws = CreateSampleWorkspace("Event", "One Peak", XUnit="DeltaE")
         return ws
     if not xAx:
         ws = CreateWorkspace(DataX=self.data_x,
                              DataY=self.data_y,
                              DataE=np.sqrt(self.data_y),
                              NSpec=1,
                              UnitX="TOF")
         return ws
     if not instrument:
         ws = CreateWorkspace(DataX=self.data_x,
                              DataY=self.data_y,
                              DataE=np.sqrt(self.data_y),
                              NSpec=1,
                              UnitX="DeltaE")
         return ws
     if not yAxMt and not yAxSpec:
         ws = CreateWorkspace(DataX=self.data_x,
                              DataY=self.data_y,
                              DataE=np.sqrt(self.data_y),
                              NSpec=1,
                              UnitX="DeltaE")
         LoadInstrument(ws, True, InstrumentName="TOFTOF")
         ConvertSpectrumAxis(InputWorkspace=ws,
                             OutputWorkspace=ws,
                             Target="theta",
                             EMode="Direct")
         return ws
     if not yAxSpec and yAxMt:
         ws = CreateWorkspace(DataX=self.data_x,
                              DataY=self.data_y,
                              DataE=np.sqrt(self.data_y),
                              NSpec=1,
                              UnitX="DeltaE")
         LoadInstrument(ws, True, InstrumentName="TOFTOF")
         self._add_all_sample_logs(ws)
         ConvertSpectrumAxis(InputWorkspace=ws,
                             OutputWorkspace="ws2",
                             Target="ElasticQ",
                             EMode="Direct")
         ws2 = mtd["ws2"]
         return ws2
     if not sample:
         ws = CreateWorkspace(DataX=self.data_x,
                              DataY=self.data_y,
                              DataE=np.sqrt(self.data_y),
                              NSpec=1,
                              UnitX="DeltaE")
         LoadInstrument(ws, False, InstrumentName="TOFTOF")
         for i in range(ws.getNumberHistograms()):
             ws.getSpectrum(i).setDetectorID(i + 1)
         return ws
     else:
         ws = CreateWorkspace(DataX=self.data_x,
                              DataY=self.data_y,
                              DataE=np.sqrt(self.data_y),
                              NSpec=1,
                              UnitX="DeltaE")
         LoadInstrument(ws, True, InstrumentName="TOFTOF")
         self._add_all_sample_logs(ws)
         return ws
Esempio n. 19
0
    def PyExec(self):
        data = self.getProperty("InputWorkspace").value
        cal = self.getProperty("CalibrationWorkspace").value
        bkg = self.getProperty("BackgroundWorkspace").value
        mask = self.getProperty("MaskWorkspace").value
        target = self.getProperty("Target").value
        eFixed = self.getProperty("EFixed").value
        xMin = self.getProperty("XMin").value
        xMax = self.getProperty("XMax").value
        numberBins = self.getProperty("NumberBins").value
        normaliseBy = self.getProperty("NormaliseBy").value
        maskAngle = self.getProperty("MaskAngle").value
        outWS = self.getPropertyValue("OutputWorkspace")

        data_scale = 1
        cal_scale = 1
        bkg_scale = 1

        if normaliseBy == "Monitor":
            data_scale = data.run().getProtonCharge()
        elif normaliseBy == "Time":
            data_scale = data.run().getLogData('duration').value

        ExtractMask(data, OutputWorkspace='__mask_tmp', EnableLogging=False)

        if maskAngle != Property.EMPTY_DBL:
            MaskAngle(Workspace='__mask_tmp',
                      MinAngle=maskAngle,
                      Angle='Phi',
                      EnableLogging=False)

        if mask is not None:
            BinaryOperateMasks(InputWorkspace1='__mask_tmp',
                               InputWorkspace2=mask,
                               OperationType='OR',
                               OutputWorkspace='__mask_tmp',
                               EnableLogging=False)

        ExtractUnmaskedSpectra(InputWorkspace=data,
                               MaskWorkspace='__mask_tmp',
                               OutputWorkspace='__data_tmp',
                               EnableLogging=False)
        if isinstance(mtd['__data_tmp'], IEventWorkspace):
            Integration(InputWorkspace='__data_tmp',
                        OutputWorkspace='__data_tmp',
                        EnableLogging=False)
        ConvertSpectrumAxis(InputWorkspace='__data_tmp',
                            Target=target,
                            EFixed=eFixed,
                            OutputWorkspace=outWS,
                            EnableLogging=False)
        Transpose(InputWorkspace=outWS,
                  OutputWorkspace=outWS,
                  EnableLogging=False)
        ResampleX(InputWorkspace=outWS,
                  OutputWorkspace=outWS,
                  XMin=xMin,
                  XMax=xMax,
                  NumberBins=numberBins,
                  EnableLogging=False)

        if cal is not None:
            ExtractUnmaskedSpectra(InputWorkspace=cal,
                                   MaskWorkspace='__mask_tmp',
                                   OutputWorkspace='__cal_tmp',
                                   EnableLogging=False)
            if isinstance(mtd['__cal_tmp'], IEventWorkspace):
                Integration(InputWorkspace='__cal_tmp',
                            OutputWorkspace='__cal_tmp',
                            EnableLogging=False)
            CopyInstrumentParameters(data, '__cal_tmp', EnableLogging=False)
            ConvertSpectrumAxis(InputWorkspace='__cal_tmp',
                                Target=target,
                                EFixed=eFixed,
                                OutputWorkspace='__cal_tmp',
                                EnableLogging=False)
            Transpose(InputWorkspace='__cal_tmp',
                      OutputWorkspace='__cal_tmp',
                      EnableLogging=False)
            ResampleX(InputWorkspace='__cal_tmp',
                      OutputWorkspace='__cal_tmp',
                      XMin=xMin,
                      XMax=xMax,
                      NumberBins=numberBins,
                      EnableLogging=False)
            Divide(LHSWorkspace=outWS,
                   RHSWorkspace='__cal_tmp',
                   OutputWorkspace=outWS,
                   EnableLogging=False)
            if normaliseBy == "Monitor":
                cal_scale = cal.run().getProtonCharge()
            elif normaliseBy == "Time":
                cal_scale = cal.run().getLogData('duration').value

        Scale(InputWorkspace=outWS,
              OutputWorkspace=outWS,
              Factor=cal_scale / data_scale,
              EnableLogging=False)

        if bkg is not None:
            ExtractUnmaskedSpectra(InputWorkspace=bkg,
                                   MaskWorkspace='__mask_tmp',
                                   OutputWorkspace='__bkg_tmp',
                                   EnableLogging=False)
            if isinstance(mtd['__bkg_tmp'], IEventWorkspace):
                Integration(InputWorkspace='__bkg_tmp',
                            OutputWorkspace='__bkg_tmp',
                            EnableLogging=False)
            CopyInstrumentParameters(data, '__bkg_tmp', EnableLogging=False)
            ConvertSpectrumAxis(InputWorkspace='__bkg_tmp',
                                Target=target,
                                EFixed=eFixed,
                                OutputWorkspace='__bkg_tmp',
                                EnableLogging=False)
            Transpose(InputWorkspace='__bkg_tmp',
                      OutputWorkspace='__bkg_tmp',
                      EnableLogging=False)
            ResampleX(InputWorkspace='__bkg_tmp',
                      OutputWorkspace='__bkg_tmp',
                      XMin=xMin,
                      XMax=xMax,
                      NumberBins=numberBins,
                      EnableLogging=False)
            if cal is not None:
                Divide(LHSWorkspace='__bkg_tmp',
                       RHSWorkspace='__cal_tmp',
                       OutputWorkspace='__bkg_tmp',
                       EnableLogging=False)
            if normaliseBy == "Monitor":
                bkg_scale = bkg.run().getProtonCharge()
            elif normaliseBy == "Time":
                bkg_scale = bkg.run().getLogData('duration').value
            Scale(InputWorkspace='__bkg_tmp',
                  OutputWorkspace='__bkg_tmp',
                  Factor=cal_scale / bkg_scale,
                  EnableLogging=False)
            Scale(InputWorkspace='__bkg_tmp',
                  OutputWorkspace='__bkg_tmp',
                  Factor=self.getProperty('BackgroundScale').value,
                  EnableLogging=False)
            Minus(LHSWorkspace=outWS,
                  RHSWorkspace='__bkg_tmp',
                  OutputWorkspace=outWS,
                  EnableLogging=False)

        self.setProperty("OutputWorkspace", outWS)

        # remove temp workspaces
        [
            DeleteWorkspace(ws, EnableLogging=False)
            for ws in self.temp_workspace_list if mtd.doesExist(ws)
        ]