Beispiel #1
0
    def setUp(self):
        config['default.facility'] = 'ILL'
        config['default.instrument'] = 'D11'
        config['logging.loggers.root.level'] = 'Warning'
        config.appendDataSearchSubDir('ILL/D11/')
        # prepare mask for instrument edges first:
        MaskBTP(Instrument='D11', Tube='0-6,250-256')
        RenameWorkspace(InputWorkspace='D11MaskBTP',
                        OutputWorkspace='mask_vertical')
        MaskBTP(Instrument='D11', Pixel='0-6,250-256')
        Plus(LHSWorkspace='mask_vertical',
             RHSWorkspace='D11MaskBTP',
             OutputWorkspace='edge_masks')
        # the edges mask can be used as a default mask for all distances and wavelengths

        MaskBTP(Instrument='D11', Tube='114-142,', Pixel='114-142')
        RenameWorkspace(InputWorkspace='D11MaskBTP',
                        OutputWorkspace='mask_8m_4_6A_center')
        MaskBTP(Instrument='D11', Tube='3-14', Pixel='240-256')
        Plus(LHSWorkspace='D11MaskBTP',
             RHSWorkspace='mask_8m_4_6A_center',
             OutputWorkspace='mask_8m_4_6A')
        MaskBTP(Instrument='D11', Tube='103-147', Pixel='103-147')
        RenameWorkspace(InputWorkspace='D11MaskBTP',
                        OutputWorkspace='mask_1m_4_6A_center')
        MaskBTP(Instrument='D11', Tube='3-14', Pixel='240-256')
        Plus(LHSWorkspace='D11MaskBTP',
             RHSWorkspace='mask_1m_4_6A_center',
             OutputWorkspace='mask_1m_4_6A')
    def __accumulate(self, chunkname, sumname, chunkunfocusname, sumuunfocusname, firstrun, removelogs=False):
        """accumulate newdata `wkspname` into sum `sumwkspname` and delete `wkspname`"""
        # the first call to accumulate to a specific target should be a simple rename
        self.log().debug('__accumulate({}, {}, {}, {}, {})'.format(chunkname, sumname, chunkunfocusname,
                                                                   sumuunfocusname, firstrun))
        if chunkname == sumname:
            return  # there is nothing to be done

        if not firstrun:
            # if the sum workspace doesn't already exist, just rename
            if not mtd.doesExist(sumname):
                firstrun = True

        if firstrun:
            if chunkname != sumname:
                RenameWorkspace(InputWorkspace=chunkname, OutputWorkspace=sumname)
            if chunkunfocusname and chunkunfocusname != sumuunfocusname:
                RenameWorkspace(InputWorkspace=chunkunfocusname, OutputWorkspace=sumuunfocusname)
        else:
            if removelogs:
                RemoveLogs(Workspace=chunkname)  # accumulation has them already
            RebinToWorkspace(WorkspaceToRebin=chunkname, WorkspaceToMatch=sumname,
                             OutputWorkspace=chunkname)
            Plus(LHSWorkspace=sumname, RHSWorkspace=chunkname, OutputWorkspace=sumname,
                 ClearRHSWorkspace=self.kwargs['PreserveEvents'])
            DeleteWorkspace(Workspace=chunkname)
            self.__compressEvents(sumname)  # could be smarter about when to run

            if chunkunfocusname and chunkunfocusname != sumuunfocusname:
                if removelogs:
                    RemoveLogs(Workspace=chunkunfocusname)  # accumulation has them already
                Plus(LHSWorkspace=sumuunfocusname, RHSWorkspace=chunkunfocusname, OutputWorkspace=sumuunfocusname,
                     ClearRHSWorkspace=self.kwargs['PreserveEvents'])
                DeleteWorkspace(Workspace=chunkunfocusname)
                self.__compressEvents(sumuunfocusname)  # could be smarter about when to run
Beispiel #3
0
def norm(sample, blank, masks):
    """
    Normalise the neutron polarisation on a tube by tube basis

    Parameters
    ----------
    sample: string
      The name of the sample to be normalised.  The individual tubes are
      assumed to be in workspaces with names like sample_2
    blank: string
      The name of the blank to be normalised agains.  The individual tubes are
      assumed to be in workspaces with names like blank_2
    masks: list of string
      The file names for the masks used for the individual tubes.
    """
    for t, _ in enumerate(masks):
        wtemp = mtd[sample + "_{}".format(t)] / \
            mtd[blank + "_{}".format(t)]

        y = mtd[blank + "_{}".format(t)].extractY()
        e = wtemp.extractE()

        e[np.abs(y) < 0.2] *= 1e9
        wtemp.setE(0, e[0])

        RenameWorkspace("wtemp", sample + "_{}_norm".format(t))
    wtemp = WeightedMean(sample + "_0_norm", sample + "_1_norm")
    for tube in range(2, len(masks)):
        wtemp = WeightedMean(wtemp, sample + "_{}_norm".format(tube))
    RenameWorkspace(wtemp, OutputWorkspace=sample + "_Norm")
    DeleteWorkspaces(
        ["{}_{}_norm".format(sample, tube) for tube, _ in enumerate(masks)])
Beispiel #4
0
def sumToShim(rnum, output_dir=None):
    """
    Combine both spin states into a single workspace

    Parameters
    ----------
    rnum : int
      The run number to be shimmed
    output_dir : string
      If given, the folder where the workspace should be saved

    """
    try:
        wtemp = Load(BASE.format(rnum), LoadMonitors=True)
        RebinToWorkspace('wtemp_1',
                         'wtemp_monitors_1',
                         PreserveEvents=False,
                         OutputWorkspace='wtemp_1')
        RebinToWorkspace('wtemp_2',
                         'wtemp_monitors_1',
                         PreserveEvents=False,
                         OutputWorkspace='wtemp_2')
        wtemp_1 = ConjoinWorkspaces('wtemp_monitors_1', 'wtemp_1')
        wtemp_2 = ConjoinWorkspaces('wtemp_monitors_2', 'wtemp_2')
    except:
        wtemp_monitors = Load(BASE.format(rnum))
    wtempShim = mtd['wtemp_monitors_1'] + mtd['wtemp_monitors_2']
    RenameWorkspace(wtempShim, 'LARMOR{:08d}'.format(rnum))
    if output_dir:
        SaveNexusProcessed(
            'LARMOR{:08d}'.format(rnum),
            os.path.join(output_dir, "LARMOR{:08d}-add.nxs".format(rnum)))
    RenameWorkspace('LARMOR{:08d}'.format(rnum),
                    'LARMOR{:08d}-add'.format(rnum))
Beispiel #5
0
    def fit_multiple_peaks(self, peak_tags, x_mins, x_maxs):
        '''Fit multiple peaks across subruns. This will return a :py:obj:`FitResult`
        Concrete instances may instantiate this as needed'''
        x_mins, x_maxs = self._check_fit_range(x_mins, x_maxs)
        assert len(peak_tags) == len(x_mins) == len(x_maxs), 'All inputs must have same number of values'

        # fit each peak separately
        peakcollections = []
        fitted = None
        for peak_tag, x_min, x_max in zip(peak_tags, x_mins, x_maxs):
            # fit an individual peak
            individual = self.fit_peaks(peak_tag, x_min, x_max)

            # collect information
            peakcollections.extend(individual.peakcollections)
            if fitted:
                fitted += individual.fitted
                DeleteWorkspace(individual.fitted)
            else:
                fitted = individual.fitted
                fitted = RenameWorkspace(InputWorkspace=fitted,
                                         OutputWorkspace='{}_fitted'.format(peak_tags[0]))

            # original difference isn't needed
            DeleteWorkspace(individual.difference)

        # calculate the difference
        difference = self._mtd_wksp - fitted
        difference = RenameWorkspace(InputWorkspace=difference, OutputWorkspace=peak_tags[0]+'_diff')

        return FitResult(peakcollections=peakcollections, fitted=fitted, difference=difference)
Beispiel #6
0
def calibrate_tube(workspace: WorkspaceTypes,
                   tube_name: str,
                   output_peak_table: str = 'PeakTable',
                   output_parameters_table: str = 'ParametersTable',
                   output_peak_y_table: str = 'PeakYTable',
                   shadow_height: float = 1000,
                   shadow_width: float = 4,
                   fit_domain: float = 7) -> TableWorkspace:
    r"""
    Calibration table for one tube of CORELLI

    This function creates TableWorkspace 'CalibTable', TableWorkspace 'PeakTable',
    and WorkspaceGroup 'ParametersTable' containing TableWorkspace 'ParametersTableI'
    where 'I' is the tube number.

    :param workspace: string or handle to ~mantid.dataobjects.Workspace2D
    :param tube_name: string uniquely representing one tube e.g. 'bank88/sixteenpack/tube3'
    :param output_peak_table:
    :param output_parameters_table:
    :param output_peak_y_table:
    :param shadow_height: estimated dip in the background intensity. Dips typical of Cd-wire runs are around 1000
        neutron counts.
    :param shadow_width: estimated width of the shadow cast by the wire, in pixel units. The Cd-wire typically
        cast a shadow over four pixels.
    :param fit_domain: estimated range, in pixel units, over which to carry out the fit. An appropriate value
        is about twice the shadow width
    :return: table containing detector ID and position vector
    """
    message = f'Cannot process workspace {workspace}. Pass the name of an existing workspace or a workspace handle'
    assert isinstance(workspace, (str, Workspace2D)), message
    assert shadow_height > 0, 'shadow height must be positive'
    for marker in ('bank', 'sixteenpack', 'tube'):
        assert marker in tube_name, f'{tube_name} does not uniquely specify one tube'
    peak_height, peak_width = -shadow_height, shadow_width
    # Initial guess for the peak positions, assuming:
    # - the center of the the wire mesh coincides with the center ot the tube_calib_fit_params
    # - wires cast a shadow on a perfectly calibrated tube
    fit_extent = (fit_domain / PIXELS_PER_TUBE) * TUBE_LENGTH  # fit domain in meters
    assert fit_extent < WIRE_GAP, 'The fit domain cannot be larger than the distance between consecutive wires'
    wire_pixel_positions = wire_positions(units='pixels')[1: -1]
    fit_par = TubeCalibFitParams(wire_pixel_positions, height=peak_height, width=peak_width, margin=fit_domain)
    fit_par.setAutomatic(True)
    # Generate the calibration table, the peak table, and the parameters table
    peaks_form = [1] * len(wire_pixel_positions)  # signals we'll be fitting dips (peaks with negative heights)
    calibration_table, _ = tube.calibrate(workspace, tube_name, wire_positions(units='meters')[1: -1], peaks_form,
                                          fitPar=fit_par, outputPeak=True,
                                          parameters_table_group='ParametersTableGroup')
    calibration_table = trim_calibration_table(calibration_table)  # discard X and Z coordinates

    # Additional workspaces
    # Table with shadow positions along the tube, in pixel units
    if output_peak_table != 'PeakTable':  # 'PeakTable' is output by tube.calibrate
        RenameWorkspace(InputWorkspace='PeakTable', OutputWorkspace=output_peak_table)
    # Table with shadow positions along the vertical axis
    calculate_peak_y_table(output_peak_table, 'ParametersTableGroup', output_workspace=output_peak_y_table)
    # Table with optimized parameters for the polynomial coefficients A0, A1, A2, and chi-square
    RenameWorkspace(InputWorkspace=mtd['ParametersTableGroup'].getItem(0), OutputWorkspace=output_parameters_table)
    UnGroupWorkspace(InputWorkspace='ParametersTableGroup')
    return calibration_table
Beispiel #7
0
    def PyExec(self):
        # get parameter values
        wsString = self.getPropertyValue("InputWorkspace").strip()
        #internal values
        wsOutput = "__OutputWorkspace"
        wsTemp = "__Sort_temp"
        #get the workspace list
        wsNames = []
        for wsName in wsString.split(","):
            ws = mtd[wsName.strip()]
            if type(ws) == WorkspaceGroup:
                wsNames.extend(ws.getNames())
            else:
                wsNames.append(wsName)

        if wsOutput in mtd:
            DeleteWorkspace(Workspace=wsOutput)
        sortStat = []
        for wsName in wsNames:
            if "qvectors" in wsName:
                #extract the spectrum
                ws = mtd[wsName.strip()]
                for s in range(0, ws.getNumberHistograms()):
                    y_s = ws.readY(s)
                    tuple = (self.GetXValue(y_s), s)
                    sortStat.append(tuple)
                sortStat.sort()
        if len(sortStat) == 0:
            raise RuntimeError("Cannot find file with qvectors, aborting")
        #sort spectra using norm of q
        for wsName in wsNames:
            ws = mtd[wsName.strip()]
            yUnit = ws.getAxis(1).getUnit().unitID()
            transposed = False
            if ws.getNumberHistograms() < len(sortStat):
                Transpose(InputWorkspace=wsName, OutputWorkspace=wsName)
                transposed = True
            for norm, spec in sortStat:
                ExtractSingleSpectrum(InputWorkspace=wsName, OutputWorkspace=wsTemp, WorkspaceIndex=spec)
                if wsOutput in mtd:
                    ConjoinWorkspaces(InputWorkspace1=wsOutput,InputWorkspace2=wsTemp,CheckOverlapping=False)
                    if wsTemp in mtd:
                        DeleteWorkspace(Workspace=wsTemp)
                else:
                    RenameWorkspace(InputWorkspace=wsTemp, OutputWorkspace=wsOutput)

            #put norm as y value and copy units from input
            loopIndex = 0
            wsOut = mtd[wsOutput]
            for norm, spec in sortStat:
                wsOut.getSpectrum(loopIndex).setSpectrumNo(int(norm*1000))
                loopIndex = loopIndex + 1
            if len(yUnit) > 0:
                wsOut.getAxis(1).setUnit(yUnit)
            if transposed:
                Transpose(InputWorkspace=wsOutput, OutputWorkspace=wsOutput)
            RenameWorkspace(InputWorkspace=wsOutput, OutputWorkspace=wsName)
Beispiel #8
0
 def __init__(self, ws_name, ws_unit):
     if ws_unit == MHz:
         self._freq = ws_name+UNIT+MHz
         self._field = convert_to_field(ws_name, ws_name+UNIT+GAUSS)
         RenameWorkspace(InputWorkspace=ws_name, OutputWorkspace=self._freq)
     elif ws_unit == GAUSS:
         self._field = ws_name+UNIT+GAUSS
         self._freq = convert_to_freq(ws_name, ws_name+UNIT+MHz)
         RenameWorkspace(InputWorkspace=ws_name, OutputWorkspace=self._field)
Beispiel #9
0
 def _renameWorkspaceBasedOnRunNumber(self, workspace_name, isTrans):
     """Rename the given workspace based on its run number and a standard prefix"""
     new_name = self._prefixedName(_getRunNumberAsString(workspace_name), isTrans)
     if new_name != workspace_name:
         RenameWorkspace(InputWorkspace=workspace_name, OutputWorkspace=new_name)
         # Also rename the monitor workspace, if there is one
         if AnalysisDataService.doesExist(_monitorWorkspace(workspace_name)):
             RenameWorkspace(InputWorkspace=_monitorWorkspace(workspace_name),
                             OutputWorkspace=_monitorWorkspace(new_name))
     return new_name
Beispiel #10
0
    def setUp(self):
        self._input_name = 'iris26176_graphite002_conv_1L_s0_to_17_Result'
        self._single_fit_name = 'iris26176_graphite002_conv_1L_s1_Result'
        self._result_group_name = 'iris26176_graphite002_conv_1L_s0_to_17_Results'
        self._output_name = 'iris26176_graphite002_conv_1L_s0_to_17_Result_Edit'

        red_name = 'iris26176_graphite002_red'
        res_name = 'iris26173_graphite002_res'
        fit_function = 'composite=Convolution,FixResolution=true,NumDeriv=true;name=Resolution, ' \
                       'Workspace=__ConvFitResolution0,WorkspaceIndex=0,X=(),Y=();name=Lorentzian,'
        start_x = '-0.54761329492537092'
        end_x = '0.54325428563315703'
        convolve_members = True
        max_iterations = '5000'

        # Perform fits to produce the result workspaces to use for a data replacement
        LoadNexus(Filename=red_name + '.nxs', OutputWorkspace=red_name)
        LoadNexus(Filename=res_name + '.nxs', OutputWorkspace=res_name)
        LoadNexus(Filename='conv_fit_resolution.nxs',
                  OutputWorkspace='__ConvFitResolution0')
        ConvolutionFitSequential(
            Input=get_sequential_input_string(red_name, 18),
            Function=fit_function + 'Amplitude=1,PeakCentre=0,FWHM=0.0175',
            MaxIterations=max_iterations,
            ConvolveMembers=convolve_members,
            PassWSIndexToFunction='1',
            StartX=start_x,
            EndX=end_x,
            OutputWorkspace=self._result_group_name,
            OutputParameterWorkspace=
            'iris26176_graphite002_conv_1L_s0_to_17_Parameters',
            OutputWorkspaceGroup=
            'iris26176_graphite002_conv_1L_s0_to_17_Workspaces')
        ConvolutionFitSimultaneous(
            InputWorkspace=red_name,
            Function=fit_function +
            'Amplitude=4.96922,PeakCentre=-0.000735068,FWHM=0.0671319',
            MaxIterations=max_iterations,
            ConvolveMembers=convolve_members,
            WorkspaceIndex='1',
            StartX=start_x,
            EndX=end_x,
            OutputWorkspace=self._single_fit_name + 's',
            OutputParameterWorkspace=
            'iris26176_graphite002_conv_1L_s1_Parameters',
            OutputWorkspaceGroup='iris26176_graphite002_conv_1L_s1_Workspaces')
        RenameWorkspace(InputWorkspace=self._input_name + 's_1',
                        OutputWorkspace=self._input_name)
        RenameWorkspace(InputWorkspace=self._single_fit_name + 's_1',
                        OutputWorkspace=self._single_fit_name)

        self._input_workspace = get_ads_workspace(self._input_name)
        self._single_fit_workspace = get_ads_workspace(self._single_fit_name)
        self._result_group = get_ads_workspace(self._result_group_name)
Beispiel #11
0
    def _load_runs(self, runs, w_name):
        """
        Load all run event Nexus files into a single `EventWorkspace`

        Parameters
        ----------
        runs: str
            Run numbers to be reduced. Symbol `;` separates the runs into
            substrings. Each substring represents a set of runs to be
            reduced together
        w_name: str
            Name of output workspace

        Returns
        -------
        Mantid.EventsWorkspace
        """
        rl = self._run_list(runs)
        #
        # Load files together
        #
        _t_all_w = None
        _t_all_w_name = tws('aggregate_load_run')
        _t_w_name = tws('load_run')
        for run in rl:
            _t_w = self._load_single_run(run, _t_w_name)
            if _t_all_w is None:
                _t_all_w = CloneWorkspace(_t_w, OutputWorkspace=_t_all_w_name)
            else:
                _t_all_w = Plus(_t_all_w, _t_w, OutputWorkspace=_t_all_w_name)
        RenameWorkspace(_t_all_w, OutputWorkspace=w_name)
        return _t_all_w
Beispiel #12
0
    def _load_runs(self, runs, w_name):
        """
        Load all run event Nexus files into a single `EventWorkspace`

        Parameters
        ----------
        runs: str
            Run numbers to be reduced. Symbol `;` separates the runs into
            substrings. Each substring represents a set of runs to be
            reduced together
        w_name: str
            Name of output workspace

        Returns
        -------
        Mantid.EventsWorkspace
        """
        rl = self._run_lists(runs)
        #
        # Load files together
        #
        _t_all_w = None
        for run in rl:
            file_name = "{0}_{1}_event.nxs".format(self._short_inst, str(run))
            _t_w = LoadEventNexus(Filename=file_name,
                                  NXentryName='entry-diff',
                                  SingleBankPixelsOnly=False)
            if _t_all_w is None:
                _t_all_w = CloneWorkspace(_t_w)
            else:
                _t_all_w += _t_w
        RenameWorkspace(_t_all_w, OutputWorkspace=w_name)
        return _t_all_w
Beispiel #13
0
 def monitorTransfit(self, files, foilType, divE):
     isFirstFile = True
     isSingleFile = len(files) == 1
     firstFileName = ""
     for file in files:
         discard, fileName = path.split(file)
         fnNoExt = path.splitext(fileName)[0]
         if isFirstFile:
             firstFileName = fnNoExt
         fileName_Raw = fnNoExt + '_raw'
         fileName_3 = fnNoExt + '_3'
         LoadRaw(Filename=file, OutputWorkspace=fileName_Raw)
         CropWorkspace(InputWorkspace=fileName_Raw, OutputWorkspace=fileName_Raw, XMin=100, XMax=19990)
         NormaliseByCurrent(InputWorkspace=fileName_Raw, OutputWorkspace=fileName_Raw)
         ExtractSingleSpectrum(InputWorkspace=fileName_Raw, OutputWorkspace=fileName_3, WorkspaceIndex=3)
         DeleteWorkspace(fileName_Raw)
         ConvertUnits(InputWorkspace=fileName_3, Target='Energy', OutputWorkspace=fileName_3)
         self.TransfitRebin(fileName_3, fileName_3, foilType, divE)
         if not isFirstFile:
             Plus(LHSWorkspace=firstFileName + '_3', RHSWorkspace=fileName_3, OutputWorkspace=firstFileName + '_3')
             DeleteWorkspace(fileName_3)
         else:
             isFirstFile = False
     if isSingleFile:
         RenameWorkspace(InputWorkspace=firstFileName + '_3', OutputWorkspace=firstFileName + '_monitor')
     else:
         noFiles = len(files) ** (-1)
         CreateSingleValuedWorkspace(OutputWorkspace='scale', DataValue=noFiles)
         Multiply(LHSWorkspace=firstFileName + '_3', RHSWorkspace='scale',
                  OutputWorkspace=firstFileName + '_monitor')
         DeleteWorkspace('scale')
         DeleteWorkspace(firstFileName + '_3')
Beispiel #14
0
def sel(sample, const):
    """
    Convert workspace into normalised spin echo units

    Parameters
    ----------
    sample : str
      The name of the workspace to be converted
    const : float
      The spin echo length of a one angstrom neutron in nanometers

    Returns
    -------
    The name of a workspace with the x coordinate in proper spin echo
    units and the y coordinate in log(P/P₀)/λ²
    """
    wtemp = mtd[sample]
    x = wtemp.extractX()
    y = wtemp.extractY()
    e = wtemp.extractE()

    dx = (x[:, 1:] + x[:, :-1]) / 2

    wtemp = ConvertUnits(sample, "SpinEchoLength", EFixed=const)

    wenv = CreateWorkspace(wtemp.extractX(),
                           np.log(y) / dx**2,
                           e / y / dx**2,
                           UnitX="SpinEchoLength",
                           YUnitLabel="Counts")
    RenameWorkspace(wenv, OutputWorkspace=sample + "_sel")
Beispiel #15
0
    def test_renaming_in_ads_calls_any_change_handle(self):
        CreateSampleWorkspace(OutputWorkspace="ws1")

        self.project.anyChangeHandle = mock.MagicMock()
        RenameWorkspace(InputWorkspace="ws1", OutputWorkspace="ws2")

        # Called twice because first workspace is removed and second is added
        self.assertEqual(2, self.project.anyChangeHandle.call_count)
Beispiel #16
0
 def _rename_workspace(self, input_name: str, workspace_name: str) -> str:
     """Renames a resulting workspace from a simultaneous fit."""
     new_name, _ = create_fitted_workspace_name(
         input_name, self.fitting_context.function_name)
     new_name += '; Simultaneous'
     RenameWorkspace(InputWorkspace=workspace_name,
                     OutputWorkspace=new_name)
     return new_name
    def test_observeRename_calls_renameHandle_when_set_on_ads_and_a_workspace_is_renamed(self):
        CreateSampleWorkspace(OutputWorkspace="ws")

        self.fake_class.observeRename(True)
        self.fake_class.renameHandle = mock.MagicMock()
        RenameWorkspace(InputWorkspace="ws", OutputWorkspace="ws1")

        self.assertEqual(self.fake_class.renameHandle.call_count, 1)
Beispiel #18
0
    def fit_peaks(self, peak_tag, x_min, x_max):
        x_min, x_max = self._check_fit_range(x_min, x_max)

        # Create output workspace names
        r_positions_ws_name = 'fitted_peak_positions_{0}'.format(
            self._mtd_wksp)
        r_param_table_name = 'param_m_{0}'.format(self._mtd_wksp)
        r_error_table_name = 'param_e_{0}'.format(self._mtd_wksp)
        r_model_ws_name = 'model_full_{0}'.format(self._mtd_wksp)

        # estimate the peak center
        peak_center = self._guess_center(x_min, x_max)

        # add in extra parameters for starting values
        kwargs = {}
        if self._peak_function == PeakShape.PSEUDOVOIGT:
            kwargs[
                'PeakParameterNames'] = 'Mixing'  # FWHM and Intensity also available
            kwargs['PeakParameterValues'] = '0.6'  # mixing agreed upon default

        # Fit peak by Mantid.FitPeaks
        fit_return = FitPeaks(
            InputWorkspace=self._mtd_wksp,
            PeakFunction=str(self._peak_function),
            BackgroundType=str(self._background_function),
            FindBackgroundSigma=1,
            HighBackground=True,
            PeakCenters=peak_center,
            FitWindowBoundaryList=(x_min, x_max),
            # ConstrainPeakPositions=True,  TODO should this be turned on?
            RawPeakParameters=True,
            OutputWorkspace=r_positions_ws_name,  # peak centers
            OutputPeakParametersWorkspace=r_param_table_name,  # peak parameters
            OutputParameterFitErrorsWorkspace=
            r_error_table_name,  # peak parameter uncertainties
            FittedPeaksWorkspace=r_model_ws_name,  # peaks calculated from model
            MaxFitIterations=50,  # TODO increase to 500
            **kwargs)
        # r is a class containing multiple outputs (workspaces)
        if fit_return is None:
            raise RuntimeError('return from FitPeaks cannot be None')

        # convert the output tables into a pyrs.peaks.PeakCollection
        peak_collection = self.__tables_to_peak_collection(
            peak_tag, fit_return.OutputPeakParametersWorkspace,
            fit_return.OutputParameterFitErrorsWorkspace)
        DeleteWorkspace(fit_return.OutputPeakParametersWorkspace)
        DeleteWorkspace(fit_return.OutputParameterFitErrorsWorkspace)

        # create the difference workspace
        difference = self._mtd_wksp - fit_return.FittedPeaksWorkspace
        difference = RenameWorkspace(InputWorkspace=difference,
                                     OutputWorkspace=peak_tag + '_diff')

        # return the final results
        return FitResult(peakcollections=(peak_collection, ),
                         fitted=fit_return.FittedPeaksWorkspace,
                         difference=difference)
    def test_view_title_did_not_change_other_workspace_rename(self):
        ws = CreateSampleWorkspace()
        pres = SliceViewer(ws)
        title = pres.model.get_title()
        other_workspace = CreateSampleWorkspace()
        other_renamed = RenameWorkspace(other_workspace)  # noqa F841

        self.assertEqual(pres.model.get_title(), title)
        self.assertEqual(pres.view.windowTitle(), pres.model.get_title())
    def setUp(self):
        config['default.facility'] = 'ILL'
        config['default.instrument'] = 'D11'
        config['logging.loggers.root.level'] = 'Warning'
        config.appendDataSearchSubDir('ILL/D11/')

        # prepare mask for instrument edges first:
        MaskBTP(Instrument='D11', Tube='1-3,253-256')
        RenameWorkspace(InputWorkspace='D11MaskBTP', OutputWorkspace='mask_vertical')
        MaskBTP(Instrument='D11', Pixel='1-3,253-256')
        Plus(LHSWorkspace='mask_vertical', RHSWorkspace='D11MaskBTP', OutputWorkspace='edge_masks')
        # the edges mask can be used as a default mask for all distances and wavelengths
        MaskBTP(Instrument='D11', Tube='116-139', Pixel='90-116')
        RenameWorkspace(InputWorkspace='D11MaskBTP', OutputWorkspace='mask_39m_10A')
        MaskBTP(Instrument='D11', Tube='115-140', Pixel='115-140')
        RenameWorkspace(InputWorkspace='D11MaskBTP', OutputWorkspace='mask_8m_4_6A')
        MaskBTP(Instrument='D11', Tube='105-145', Pixel='105-145')
        RenameWorkspace(InputWorkspace='D11MaskBTP', OutputWorkspace='mask_1m_4_6A')
    def setUp(self):
        config['default.facility'] = 'ILL'
        config['default.instrument'] = 'D22'
        config['logging.loggers.root.level'] = 'Warning'
        config.appendDataSearchSubDir('ILL/D22/')

        MaskBTP(Instrument='D22', Pixel='0-12,245-255')
        MaskBTP(Workspace='D22MaskBTP', Tube='54-75', Pixel='108-150')
        RenameWorkspace(InputWorkspace='D22MaskBTP', OutputWorkspace='D22_mask_central')
Beispiel #22
0
 def update_log_group_name(self):
     run_info = ADS.retrieve('run_info')
     if run_info.rowCount() > 0:
         runs = run_info.column('Run')
         name = f"{run_info.row(0)['Instrument']}_{min(runs)}-{max(runs)}_logs"
         if not name == self._log_workspaces.name():
             RenameWorkspace(InputWorkspace=self._log_workspaces.name(), OutputWorkspace=name)
     else:
         self.clear_logs()
Beispiel #23
0
 def _regularize_output_names(output_ws):
     """Regularizes the workspace names in the output group, according to the group name
     and workspace index in the group. Only needed for workspace groups, otherwise the name
     is already correct."""
     if isinstance(mtd[output_ws], WorkspaceGroup):
         for entry_no, entry in enumerate(mtd[output_ws]):
             ordered_name = "{}_{}".format(output_ws, entry_no)
             RenameWorkspace(InputWorkspace=entry,
                             OutputWorkspace=ordered_name)
 def runTest(self):
     UseCompatibilityMode()
     SANS2D()
     MaskFile('MaskSANS2DReductionGUI.txt')
     AssignSample('22048')
     AssignCan('22023')
     TransmissionSample('22041', '22024')
     TransmissionCan('22024', '22024')
     reduced = WavRangeReduction()
     RenameWorkspace(reduced, OutputWorkspace='trans_test_rear')
Beispiel #25
0
    def runTest(self):
        HelperTestingClass.__init__(self)
        ws = CreateSampleWorkspace()
        pres = SliceViewer(ws)
        title = pres.model.get_title()
        other_workspace = CreateSampleWorkspace()
        other_renamed = RenameWorkspace(other_workspace)  # noqa F841

        self.assertEqual(pres.model.get_title(), title)
        self.assertEqual(pres.view.windowTitle(), pres.model.get_title())
Beispiel #26
0
def remove_unwanted_workspaces(workspace_name, temp_workspace_name, period):
    # Delete all entries except for the period which is requested
    workspaces_to_keep = temp_workspace_name + "_" + str(period)
    group_workspace = mtd[temp_workspace_name]
    workspace_names_to_remove = [element.name() for element in group_workspace if element.name() != workspaces_to_keep]
    for to_remove in workspace_names_to_remove:
        DeleteWorkspace(to_remove)
    # We need to ungroup the group workspace which only contains now a single workspace
    UnGroupWorkspace(group_workspace)
    RenameWorkspace(InputWorkspace=workspaces_to_keep, OutputWorkspace=workspace_name)
    def name(self, full_name):
        new_workspace_name = full_name.split("/")[-1]
        if not new_workspace_name:
            return

        if not self.is_hidden:
            if len(new_workspace_name) > 0 and self._workspace_name != str(new_workspace_name):
                RenameWorkspace(InputWorkspace=self._workspace_name, OutputWorkspace=new_workspace_name)

        self._directory_structure = "/".join(full_name.split("/")[0:-1])
        self._workspace_name = new_workspace_name
Beispiel #28
0
    def test_ensure_that_the_ads_observer_calls_rename_handle(self, _):
        presenter = PeaksViewerCollectionPresenter(MagicMock())
        presenter.rename_handle = MagicMock()
        self.assertTrue(isinstance(presenter._ads_observer, SliceViewerADSObserver))
        presenter._ads_observer = SliceViewerADSObserver(presenter.replace_handle, presenter.rename_handle,
                                                         presenter.clear_handle, presenter.delete_handle)

        CreateSampleWorkspace(OutputWorkspace="ws")
        RenameWorkspace(InputWorkspace="ws", OutputWorkspace="ws1")

        presenter.rename_handle.assert_called_once_with("ws", "ws1")
 def runTest(self):
     UseCompatibilityMode()
     SANS2D()
     MaskFile(MASKFILE)
     AssignSample('22048')
     AssignCan('22023')
     TransmissionSample('22041', '22024')
     TransmissionCan('22024', '22024')
     SetEventSlices("0.0-450, 5-10")
     reduced = WavRangeReduction()
     RenameWorkspace(reduced, OutputWorkspace='trans_test_rear')
Beispiel #30
0
    def TransfitRebin(self, inputWS, outputWSName, foilType, divE):
        ws2D = mtd[inputWS]
        # Expand the limits for rebinning to prevent potential issues at the boundaries
        startE = self.ResParamsDict[foilType + '_startE']
        endE = self.ResParamsDict[foilType + '_endE']
        startEp = 0.99 * startE
        endEp = 1.01 * endE
        CropWorkspace(InputWorkspace=ws2D,
                      OutputWorkspace=ws2D,
                      XMin=1000 * startEp,
                      XMax=1000 * endEp)
        numPts = np.int(((endEp - startEp) / divE) + 1)
        xData_out = []
        xData_in = ws2D.readX(0)
        yData_in = ws2D.readY(0)
        # Deals with issues in Mantid where Xdata mark start of bin, not true x position
        # calculates the bin width and then takes middle of bin as x value
        current_bin_widths = []
        xActual = []
        for x in range(0, len(xData_in) - 1):
            current_bin_widths.append(xData_in[x + 1] - xData_in[x])
            xActual.append(xData_in[x] + 0.5 * (xData_in[x + 1] - xData_in[x]))
        # Make xData with uniform binning defined by divE
        for j in range(numPts):
            xData_out.append(1000 * (startEp + j * divE))
        yData_out = [0] * (len(xData_out))
        # Normalise output ydata accordingly based on surrounding values
        yNorm = [0] * (len(xData_out))
        for j in range(0, len(yData_in)):
            currentBin = np.int((xActual[j] - startEp * 1000) / (divE * 1000))
            scale1 = 1 - ((xActual[j] - xData_out[currentBin]) / (divE * 1000))
            yData_out[currentBin] += yData_in[j] * scale1
            yNorm[currentBin] += scale1
            if currentBin < (len(xData_out) - 1):
                yData_out[currentBin + 1] += yData_in[j] * (1 - scale1)
                yNorm[currentBin + 1] += 1 - scale1
        # Apply the normalisation, with a catch for any potential divide by zero errors
        for i in range(len(yData_out)):
            if yNorm[i] != 0:
                yData_out[i] = yData_out[i] / yNorm[i]
            else:
                print('Empty bin')

        outputWS = CreateWorkspace(DataX=xData_out,
                                   DataY=yData_out,
                                   NSpec=1,
                                   UnitX='meV')
        CropWorkspace(InputWorkspace=outputWS,
                      OutputWorkspace=outputWS,
                      XMin=1000 * startE,
                      XMax=1000 * endE)
        RenameWorkspace(InputWorkspace=outputWS, OutputWorkspace=outputWSName)
    def test_renameWorkspace(self):
        RenameWorkspace(self._raw_ws,'name1',RenameMonitors=True)
        self.assertTrue('name1' in mtd)
        self.assertTrue('name1_monitors' in mtd)
        #
        #ws = mtd['name1']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name1_monitors')

        RenameWorkspace(InputWorkspace='name1',OutputWorkspace='name2',RenameMonitors=True)
        self.assertFalse('name1' in mtd)
        self.assertFalse('name1_monitors' in mtd)
        self.assertTrue('name2' in mtd)
        self.assertTrue('name2_monitors' in mtd)
        #
        #ws = mtd['name2']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name2_monitors')



        RenameWorkspace('name2','name3',True)
        self.assertFalse('name2' in mtd)
        self.assertFalse('name2_monitors' in mtd)
        self.assertTrue('name3' in mtd)
        self.assertTrue('name3_monitors' in mtd)
        #
        #ws = mtd['name3']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name3_monitors')


        RenameWorkspace('name3','name4')
        self.assertFalse('name3' in mtd)
        self.assertTrue('name3_monitors' in mtd)
        self.assertTrue('name4' in mtd)
        self.assertFalse('name4_monitors' in mtd)
        #
        #ws = mtd['name4']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name3_monitors')


        RenameWorkspace('name3_monitors','name4_monitors',True)
        self.assertFalse('name3_monitors' in mtd)
        self.assertTrue('name4_monitors' in mtd)
        #
        #ws = mtd['name4']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name4_monitors')


        name5=RenameWorkspace('name4')
        self.assertFalse('name4' in mtd)
        self.assertTrue('name4_monitors' in mtd)
        self.assertTrue('name5' in mtd)
        self.assertFalse('name5_monitors' in mtd)
        #
        #monWs1 = name5.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name4_monitors')


        name6=RenameWorkspace('name5',True)
        self.assertFalse('name5' in mtd)
        self.assertFalse('name4_monitors' in mtd)
        self.assertTrue('name6' in mtd)
        self.assertTrue('name6_monitors' in mtd)
        #
        #monWs1 = name6.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name6_monitors')


        name7=RenameWorkspace('name6',RenameMonitors=True)
        self.assertFalse('name6' in mtd)
        self.assertFalse('name6_monitors' in mtd)
        self.assertTrue('name7' in mtd)
        self.assertTrue('name7_monitors' in mtd)
        #
        #monWs1 = name7.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name7_monitors')


        ws = RenameWorkspace(name7,OutputWorkspace='name8',RenameMonitors=True)
        self.assertEqual(ws.name(),'name8')
        self.assertFalse('name7' in mtd)
        self.assertFalse('name7_monitors' in mtd)
        self.assertTrue('name8' in mtd)
        self.assertTrue('name8_monitors' in mtd)
        #
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name8_monitors')

        # test with the logging keyword
        try:
            name9 = RenameWorkspace('name8', EnableLogging=False)
            self.assertTrue('name9' in mtd)
            self.assertTrue(name9)
            self.assertFalse('name8' in mtd)
        except RuntimeError as e:
            self.fail('Magic keyword not recognised '+e.what())

        # test trying to disable ADS
        try:
            name10 = RenameWorkspace('name9', StoreInADS=False)
            self.fail('Disabling on ADS did not throw for RenameWorkspace')
        except KeyError:
            pass

        # test text value for disabling
        try:
            name10 = RenameWorkspace('name9', StoreInADS='disable')
            self.fail('Disabling on ADS did not throw for RenameWorkspace')
        except KeyError:
            pass
    def test_renameWorkspace(self):
        RenameWorkspace(self._raw_ws, "name1", RenameMonitors=True)
        self.assertTrue("name1" in mtd)
        self.assertTrue("name1_monitors" in mtd)
        #
        # ws = mtd['name1']
        # monWs1 = ws.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name1_monitors')

        RenameWorkspace(InputWorkspace="name1", OutputWorkspace="name2", RenameMonitors=True)
        self.assertFalse("name1" in mtd)
        self.assertFalse("name1_monitors" in mtd)
        self.assertTrue("name2" in mtd)
        self.assertTrue("name2_monitors" in mtd)
        #
        # ws = mtd['name2']
        # monWs1 = ws.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name2_monitors')

        RenameWorkspace("name2", "name3", True)
        self.assertFalse("name2" in mtd)
        self.assertFalse("name2_monitors" in mtd)
        self.assertTrue("name3" in mtd)
        self.assertTrue("name3_monitors" in mtd)
        #
        # ws = mtd['name3']
        # monWs1 = ws.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name3_monitors')

        RenameWorkspace("name3", "name4")
        self.assertFalse("name3" in mtd)
        self.assertTrue("name3_monitors" in mtd)
        self.assertTrue("name4" in mtd)
        self.assertFalse("name4_monitors" in mtd)
        #
        # ws = mtd['name4']
        # monWs1 = ws.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name3_monitors')

        RenameWorkspace("name3_monitors", "name4_monitors", True)
        self.assertFalse("name3_monitors" in mtd)
        self.assertTrue("name4_monitors" in mtd)
        #
        # ws = mtd['name4']
        # monWs1 = ws.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name4_monitors')

        name5 = RenameWorkspace("name4")
        self.assertFalse("name4" in mtd)
        self.assertTrue("name4_monitors" in mtd)
        self.assertTrue("name5" in mtd)
        self.assertFalse("name5_monitors" in mtd)
        #
        # monWs1 = name5.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name4_monitors')

        name6 = RenameWorkspace("name5", True)
        self.assertFalse("name5" in mtd)
        self.assertFalse("name4_monitors" in mtd)
        self.assertTrue("name6" in mtd)
        self.assertTrue("name6_monitors" in mtd)
        #
        # monWs1 = name6.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name6_monitors')

        name7 = RenameWorkspace("name6", RenameMonitors=True)
        self.assertFalse("name6" in mtd)
        self.assertFalse("name6_monitors" in mtd)
        self.assertTrue("name7" in mtd)
        self.assertTrue("name7_monitors" in mtd)
        #
        # monWs1 = name7.getMonitorWorkspace()
        # self.assertEqual(monWs1.name(),'name7_monitors')

        ws = RenameWorkspace(name7, OutputWorkspace="name8", RenameMonitors=True)
        self.assertEqual(ws.name(), "name8")
        self.assertFalse("name7" in mtd)
        self.assertFalse("name7_monitors" in mtd)
        self.assertTrue("name8" in mtd)
        self.assertTrue("name8_monitors" in mtd)
    def test_renameWorkspace(self):
        RenameWorkspace(self._raw_ws,'name1',RenameMonitors=True)
        self.assertTrue('name1' in mtd)
        self.assertTrue('name1_monitors' in mtd)
        #
        #ws = mtd['name1']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name1_monitors')

        RenameWorkspace(InputWorkspace='name1',OutputWorkspace='name2',RenameMonitors=True)
        self.assertFalse('name1' in mtd)
        self.assertFalse('name1_monitors' in mtd)
        self.assertTrue('name2' in mtd)
        self.assertTrue('name2_monitors' in mtd)
        #
        #ws = mtd['name2']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name2_monitors')



        RenameWorkspace('name2','name3',True)
        self.assertFalse('name2' in mtd)
        self.assertFalse('name2_monitors' in mtd)
        self.assertTrue('name3' in mtd)
        self.assertTrue('name3_monitors' in mtd)
        #
        #ws = mtd['name3']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name3_monitors')


        RenameWorkspace('name3','name4')
        self.assertFalse('name3' in mtd)
        self.assertTrue('name3_monitors' in mtd)
        self.assertTrue('name4' in mtd)
        self.assertFalse('name4_monitors' in mtd)
        #
        #ws = mtd['name4']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name3_monitors')


        RenameWorkspace('name3_monitors','name4_monitors',True)
        self.assertFalse('name3_monitors' in mtd)
        self.assertTrue('name4_monitors' in mtd)
        #
        #ws = mtd['name4']
        #monWs1 = ws.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name4_monitors')


        name5=RenameWorkspace('name4')
        self.assertFalse('name4' in mtd)
        self.assertTrue('name4_monitors' in mtd)
        self.assertTrue('name5' in mtd)
        self.assertFalse('name5_monitors' in mtd)
        #
        #monWs1 = name5.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name4_monitors')


        name6=RenameWorkspace('name5',True)
        self.assertFalse('name5' in mtd)
        self.assertFalse('name4_monitors' in mtd)
        self.assertTrue('name6' in mtd)
        self.assertTrue('name6_monitors' in mtd)
        #
        #monWs1 = name6.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name6_monitors')


        name7=RenameWorkspace('name6',RenameMonitors=True)
        self.assertFalse('name6' in mtd)
        self.assertFalse('name6_monitors' in mtd)
        self.assertTrue('name7' in mtd)
        self.assertTrue('name7_monitors' in mtd)
        #
        #monWs1 = name7.getMonitorWorkspace()
        #self.assertEqual(monWs1.name(),'name7_monitors')


        ws = RenameWorkspace(name7,OutputWorkspace='name8',RenameMonitors=True)
        self.assertEqual(ws.name(),'name8')
        self.assertFalse('name7' in mtd)
        self.assertFalse('name7_monitors' in mtd)
        self.assertTrue('name8' in mtd)
        self.assertTrue('name8_monitors' in mtd)