示例#1
0
    def PyExec(self):
        """ Main execution body
        """
        inputws = self.getProperty("InputWorkspace").value
        epptable = self.getProperty("EPPTable").value
        outws_name = self.getPropertyValue("OutputWorkspace")

        run = inputws.getRun()
        tof1 = float(run.getLogData('TOF1').value)
        wavelength = float(run.getLogData('wavelength').value)
        velocity = sp.constants.h/(sp.constants.m_n*wavelength*1e-10)   # m/s
        instrument = inputws.getInstrument()
        sample = instrument.getSample()
        t_fit = np.array(epptable.column('PeakCentre') ) - tof1
        outws = CloneWorkspace(inputws, OutputWorkspace=outws_name)
        # mask detectors with EPP=0
        bad_data = np.where(t_fit <= 0)[0]
        if len(bad_data) > 0:
            self.log().warning("Detectors " + str(bad_data) + " have EPP=0 and will be masked.")
            MaskDetectors(outws, DetectorList=bad_data)

        for idx in range(outws.getNumberHistograms()):
            # correct TOF only if fit of EPP was succesful
            if t_fit[idx] > 0:
                det = instrument.getDetector(outws.getSpectrum(idx).getDetectorIDs()[0])
                sdd = det.getDistance(sample)
                t2_el = sdd*1.0e+6/velocity         # microseconds
                newX = inputws.readX(idx) + t2_el - t_fit[idx]
                outws.setX(idx, newX)

        self.setProperty("OutputWorkspace", outws)
    def PyExec(self):
        ws_list = self.getProperty('InputWorkspaces').value
        x_min = self.getProperty('XMin').value
        x_max = self.getProperty('XMax').value
        scale_bool = self.getProperty('CalculateScale').value
        offset_bool = self.getProperty('CalculateOffset').value
        flattened_list = self.unwrap_groups(ws_list)
        largest_range_spectrum, rebin_param = self.get_common_bin_range_and_largest_spectra(flattened_list)
        CloneWorkspace(InputWorkspace=flattened_list[0], OutputWorkspace='ws_conjoined')
        Rebin(InputWorkspace='ws_conjoined', OutputWorkspace='ws_conjoined', Params=rebin_param)
        for ws in flattened_list[1:]:
            temp = CloneWorkspace(InputWorkspace=ws)
            temp = Rebin(InputWorkspace=temp, Params=rebin_param)
            ConjoinWorkspaces(InputWorkspace1='ws_conjoined',
                              InputWorkspace2=temp,
                              CheckOverlapping=False)
        ws_conjoined = AnalysisDataService.retrieve('ws_conjoined')
        ref_spec = ws_conjoined.getSpectrum(largest_range_spectrum).getSpectrumNo()
        ws_conjoined, offset, scale, chisq = MatchSpectra(InputWorkspace=ws_conjoined,
                                                          ReferenceSpectrum=ref_spec,
                                                          CalculateScale=scale_bool,
                                                          CalculateOffset=offset_bool)
        x_min, x_max, bin_width = self.fit_x_lims_to_match_histogram_bins(ws_conjoined, x_min, x_max)

        ws_conjoined = CropWorkspaceRagged(InputWorkspace=ws_conjoined, XMin=x_min, XMax=x_max)
        ws_conjoined = Rebin(InputWorkspace=ws_conjoined, Params=[min(x_min), bin_width, max(x_max)])
        merged_ws = SumSpectra(InputWorkspace=ws_conjoined, WeightedSum=True, MultiplyBySpectra=False, StoreInADS=False)
        DeleteWorkspace(ws_conjoined)
        self.setProperty('OutputWorkspace', merged_ws)
    def test_that_can_get_transmission_for_region_of_interest_radius(self):
        # This test picks the monitor detector ids based on a radius around the centre of the detector. This is much
        # more tricky to test here and in principle the main tests should be happening in the actual
        # CalculateTransmission algorithm.
        state = CalculateSansTransmissionTest._get_state(
            rebin_type=RebinType.REBIN,
            wavelength_low=2.,
            wavelength_high=8.,
            wavelength_step=2.,
            wavelength_step_type=RangeStepType.LIN,
            background_TOF_general_start=5000.,
            background_TOF_general_stop=10000.,
            incident_monitor=1,
            transmission_radius_on_detector=0.01,
            sample_fit_type=FitType.LINEAR,
            sample_polynomial_order=0,
            sample_wavelength_low=2.,
            sample_wavelength_high=8.)
        # Gets the full workspace
        transmission_workspace = CloneWorkspace(self.loq_ws)
        direct_workspace = CloneWorkspace(self.loq_ws)

        fitted_workspace, unfitted_workspace = CalculateSansTransmissionTest._run_test(
            transmission_workspace, direct_workspace, state, is_sample=True)
        self.assertEqual(fitted_workspace.getNumberHistograms(), 1)
    def test_that_calculates_transmission_for_general_background_and_no_prompt_peak(self):
        # Arrange
        state = CalculateSansTransmissionTest._get_state(rebin_type=RebinType.REBIN, wavelength_low=2.,
                                                         wavelength_high=8., wavelength_step=2.,
                                                         wavelength_step_type=RangeStepType.LIN,
                                                         background_TOF_general_start=5000.,
                                                         background_TOF_general_stop=10000., incident_monitor=1,
                                                         transmission_monitor=3, sample_fit_type=FitType.LINEAR,
                                                         sample_polynomial_order=0, sample_wavelength_low=2.,
                                                         sample_wavelength_high=8.)
        # Get a test monitor workspace with 4 bins where the first bin is the back ground
        trans_incident = [20., 220., 210., 230.]
        trans_trans = [10., 70., 50., 80.]
        direct_incident = [40., 401., 430., 420.]
        direct_trans = [30., 320., 350., 335.]
        data_transmission = {0: trans_incident, 2: trans_trans}

        transmission_workspace = CloneWorkspace(self.sans_ws)
        transmission_workspace = self._prepare_workspace(workspace=transmission_workspace, data=data_transmission)

        data_direct = {0: direct_incident, 2: direct_trans}
        direct_workspace = CloneWorkspace(self.sans_ws)
        direct_workspace = self._prepare_workspace(workspace=direct_workspace, data=data_direct)

        fitted_workspace, unfitted_workspace = CalculateSansTransmissionTest._run_test(transmission_workspace,
                                                                                       direct_workspace, state,
                                                                                       is_sample=True)
        # Assert
        self._do_assert(transmission_workspace, direct_workspace, unfitted_workspace, fitted_workspace,
                        trans_incident, trans_trans, direct_incident, direct_trans)
示例#5
0
 def set_transmission_workspaces_on_output(self, transmission_bundles,
                                           fit_state):
     for transmission_bundle in transmission_bundles:
         fit_performed = fit_state[DataType.to_string(
             transmission_bundle.data_type)].fit_type != FitType.NoFit
         calculated_transmission_workspace = transmission_bundle.calculated_transmission_workspace
         unfitted_transmission_workspace = transmission_bundle.unfitted_transmission_workspace
         if transmission_bundle.data_type is DataType.Can:
             if does_can_workspace_exist_on_ads(
                     calculated_transmission_workspace):
                 # The workspace is cloned here because the transmission runs are diagnostic output so even though
                 # the values already exist they need to be labelled seperately for each reduction.
                 calculated_transmission_workspace = CloneWorkspace(
                     calculated_transmission_workspace, StoreInADS=False)
             if does_can_workspace_exist_on_ads(
                     unfitted_transmission_workspace):
                 unfitted_transmission_workspace = CloneWorkspace(
                     unfitted_transmission_workspace, StoreInADS=False)
             if fit_performed:
                 self.setProperty(
                     "OutputWorkspaceCalculatedTransmissionCan",
                     calculated_transmission_workspace)
             self.setProperty("OutputWorkspaceUnfittedTransmissionCan",
                              unfitted_transmission_workspace)
         elif transmission_bundle.data_type is DataType.Sample:
             if fit_performed:
                 self.setProperty("OutputWorkspaceCalculatedTransmission",
                                  calculated_transmission_workspace)
             self.setProperty("OutputWorkspaceUnfittedTransmission",
                              unfitted_transmission_workspace)
         else:
             raise RuntimeError(
                 "SANSSingleReduction: The data type {0} should be"
                 " sample or can.".format(transmission_bundle.data_type))
示例#6
0
    def test_that_transmission_runs_are_output(self):
        state = CreateSANSAdjustmentWorkspacesTest._get_state()
        state.adjustment.wide_angle_correction = True

        sample_data = self._get_sample_data()

        sample_monitor_data = self._get_sample_monitor_data(3.)

        transmission_ws = CloneWorkspace(self.sans_data, StoreInADS=False)
        transmission_ws = self._prepare_trans_data(ws=transmission_ws,
                                                   value=1.)

        direct_ws = CloneWorkspace(self.sans_data, StoreInADS=False)
        direct_ws = self._prepare_trans_data(ws=direct_ws, value=2.)

        wavelength_adjustment, pixel_adjustment, wavelength_and_pixel_adjustment, \
            calculated_transmission, unfitted_transmisison = \
            CreateSANSAdjustmentWorkspacesTest._run_test(state, sample_data, sample_monitor_data,
                                                         transmission_ws, direct_ws)

        # We expect a wavelength adjustment workspace
        self.assertTrue(wavelength_adjustment)
        # We don't expect a pixel adjustment workspace since no files where specified
        self.assertFalse(pixel_adjustment)
        # We expect a wavelength and pixel adjustment workspace since we set the flag to true and provided a
        # sample data set
        self.assertTrue(wavelength_and_pixel_adjustment)
        # We expect transmission workspaces
        self.assertTrue(calculated_transmission)
        self.assertTrue(unfitted_transmisison)
示例#7
0
 def test_1d_bin_numeric_axis(self):
     fig, ax = plt.subplots()
     x_axis = mantid.api.NumericAxis.create(2)
     x_axis.setValue(0, 3.)
     x_axis.setValue(1, 5.)
     ws_local = CloneWorkspace(self.ws2d_histo, StoreInADS=False)
     ws_local.replaceAxis(1, x_axis)
     funcs.plot(ax, ws_local, 'rs', specNum=1, axis=MantidAxType.BIN)
示例#8
0
    def test_save_jana_with_no_lattice_information(self):
        peaks = CloneWorkspace(self._workspace)
        peaks.sample().clearOrientedLattice()
        file_name = os.path.join(self._test_dir, "test_jana_no_lattice.hkl")

        # Act
        SaveReflections(InputWorkspace=peaks, Filename=file_name,
                        Format="Jana", SplitFiles=False)
示例#9
0
 def test_1d_x_axes_label_numeric_axis_bin_plot(self):
     fig, ax = plt.subplots()
     x_axis = mantid.api.NumericAxis.create(2)
     x_axis.setValue(0, 3.)
     x_axis.setValue(1, 5.)
     ws_local = CloneWorkspace(self.ws2d_histo_non_dist, StoreInADS=False)
     ws_local.replaceAxis(1, x_axis)
     funcs.plot(ax, ws_local, 'rs', specNum=1, axis=MantidAxType.BIN)
     self.assertEqual(ax.get_xlabel(), "")
    def test_that_calculates_transmission_for_monitor_specific_background_and_prompt_peak_for_can(
            self):
        # Arrange
        incident_spectrum = 1
        transmission_spectrum = 3
        fix_for_remove_bins = 1e-6
        background_TOF_monitor_start = {
            str(incident_spectrum): 5000.,
            str(transmission_spectrum): 5000.
        }
        background_TOF_monitor_stop = {
            str(incident_spectrum): 10000.,
            str(transmission_spectrum): 10000.
        }
        state = CalculateSansTransmissionTest._get_state(
            rebin_type=RebinType.REBIN,
            wavelength_low=2.,
            wavelength_high=8.,
            wavelength_step=2.,
            wavelength_step_type=RangeStepType.LIN,
            prompt_peak_correction_min=15000. + fix_for_remove_bins,
            prompt_peak_correction_max=20000.,
            background_TOF_monitor_start=background_TOF_monitor_start,
            background_TOF_monitor_stop=background_TOF_monitor_stop,
            incident_monitor=incident_spectrum,
            transmission_monitor=transmission_spectrum,
            can_fit_type=FitType.LINEAR,
            can_polynomial_order=0,
            can_wavelength_low=2.,
            can_wavelength_high=8.)
        # Get a test monitor workspace with 4 bins where the first bin is the back ground
        trans_incident = [20., 220., 210000000., 220.]
        trans_trans = [10., 80., 210000000., 80.]
        direct_incident = [40., 401., 210000000., 401.]
        direct_trans = [30., 320., 210000000., 320.]
        data_transmission = {0: trans_incident, 2: trans_trans}
        transmission_workspace = CloneWorkspace(self.sans_ws)
        transmission_workspace = self._prepare_workspace(
            workspace=transmission_workspace, data=data_transmission)

        data_direct = {0: direct_incident, 2: direct_trans}
        direct_workspace = CloneWorkspace(self.sans_ws)
        direct_workspace = self._prepare_workspace(workspace=direct_workspace,
                                                   data=data_direct)

        # Act
        fitted_workspace, unfitted_workspace = CalculateSansTransmissionTest._run_test(
            transmission_workspace, direct_workspace, state, is_sample=False)
        # Assert
        trans_incident[2] = trans_incident[3]
        trans_trans[2] = trans_trans[3]
        direct_incident[2] = direct_incident[3]
        direct_trans[2] = direct_trans[3]

        self._do_assert(transmission_workspace, direct_workspace,
                        unfitted_workspace, fitted_workspace, trans_incident,
                        trans_trans, direct_incident, direct_trans)
示例#11
0
    def _create_workspaces(self):
        cal=CreateSampleWorkspace(NumBanks=1,BinWidth=20000,PixelSpacing=0.1,BankPixelWidth=100)
        RotateInstrumentComponent(cal, ComponentName='bank1', X=1, Y=0.5, Z=2, Angle=35)
        MoveInstrumentComponent(cal, ComponentName='bank1', X=1, Y=1, Z=5)
        bkg=CloneWorkspace(cal)
        data=CloneWorkspace(cal)
        AddSampleLog(cal, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='200')
        AddSampleLog(bkg, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='50')
        AddSampleLog(data, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='100')
        AddSampleLog(cal, LogName="duration", LogType='Number', NumberType='Double', LogText='20')
        AddSampleLog(bkg, LogName="duration", LogType='Number', NumberType='Double', LogText='5')
        AddSampleLog(data, LogName="duration", LogType='Number', NumberType='Double', LogText='10')

        def get_cal_counts(n):
            if n < 5000:
                return 0.9
            else:
                return 1.0

        def get_bkg_counts(n):
            return 1.5*get_cal_counts(n)

        def get_data_counts(n,twoTheta):
            tt1=30
            tt2=45
            return get_bkg_counts(n)+10*np.exp(-(twoTheta-tt1)**2/1)+20*np.exp(-(twoTheta-tt2)**2/0.2)

        for i in range(cal.getNumberHistograms()):
            cal.setY(i, [get_cal_counts(i)*2.0])
            bkg.setY(i, [get_bkg_counts(i)/2.0])
            twoTheta=data.getInstrument().getDetector(i+10000).getTwoTheta(V3D(0,0,0),V3D(0,0,1))*180/np.pi
            data.setY(i, [get_data_counts(i,twoTheta)])

        return data, cal, bkg
示例#12
0
    def _create_indexed_workspace(self, fractional_peaks, m1m2):
        # Create table with the number of columns we need
        modulated = CloneWorkspace(fractional_peaks)
        lattice = modulated.sample().getOrientedLattice()
        lattice.setModVec1(V3D(0.5, 0.0, 0.5))
        lattice.setModVec2(V3D(0.333, 0.333, 0.))
        for row, peak in enumerate(modulated):
            row_indices = m1m2[row]
            peak.setIntMNP(V3D(row_indices[0], row_indices[1], 0))

        return modulated
示例#13
0
def combine_loaded_runs(model, run_list, delete_added=False):
    period_list = [model._data_context.num_periods([run]) for run in run_list]
    if max(period_list) != min(period_list):
        raise RuntimeError(
            'Inconsistent periods across co-added runs. This is not supported.'
        )
    return_ws = model._loaded_data_store.get_data(
        run=[run_list[0]])["workspace"]
    running_total = []

    for index in range(min(period_list)):
        workspace = return_ws["OutputWorkspace"][index]
        running_total_item = workspace.workspace.name() + 'CoAdd'
        CloneWorkspace(InputWorkspace=workspace.workspace.name(),
                       OutputWorkspace=running_total_item)
        for run in run_list[1:]:
            ws = model._loaded_data_store.get_data(
                run=[run])["workspace"]["OutputWorkspace"][index].workspace
            Plus(LHSWorkspace=running_total_item,
                 RHSWorkspace=ws,
                 AllowDifferentNumberSpectra=False,
                 OutputWorkspace=running_total_item)

        running_total.append(running_total_item)

    return_ws_actual = {
        key: return_ws[key]
        for key in ['MainFieldDirection', 'TimeZero', 'FirstGoodData']
    }
    try:
        return_ws_actual['DetectorGroupingTable'] = return_ws[
            'DetectorGroupingTable']
    except KeyError:
        pass  # PSI Data does not include Detector Grouping table as it's read from sample logs instead
    try:
        return_ws_actual['DeadTimeTable'] = return_ws['DeadTimeTable']
    except KeyError:
        pass  # Again, PSI data does not always include DeadTimeTable either
    return_ws_actual["OutputWorkspace"] = [
        MuonWorkspaceWrapper(running_total_period)
        for running_total_period in running_total
    ]
    return_ws_actual['DataDeadTimeTable'] = CloneWorkspace(
        InputWorkspace=return_ws['DataDeadTimeTable'],
        OutputWorkspace=return_ws['DataDeadTimeTable'] + 'CoAdd').name()
    model._loaded_data_store.remove_data(
        run=flatten_run_list(run_list),
        instrument=model._data_context.instrument)
    model._loaded_data_store.add_data(
        run=flatten_run_list(run_list),
        workspace=return_ws_actual,
        filename="Co-added",
        instrument=model._data_context.instrument)
示例#14
0
 def test_translation(self):
     CloneWorkspace(InputWorkspace='test_workspace_TOF',
                    OutputWorkspace='perturbed')
     CloneWorkspace(InputWorkspace='test_workspace_TOF',
                    OutputWorkspace='perturbed')
     MoveInstrumentComponent(Workspace='perturbed',
                             ComponentName='bank1',
                             X=0.02,
                             y=0.005,
                             z=0.005,
                             RelativePosition=True)
     assert self.spacings_recovered('perturbed', calibrate=False) is False
     assert self.spacings_recovered('perturbed', calibrate=True)
     DeleteWorkspaces(['perturbed'])
示例#15
0
    def _binary_op_array(self, operator, other):
        """
        Perform binary operation (+,-,*,/) using a 1D numpy array.

        :param operator: binary operator to apply (add/sub/mul/div)
        :param other: 1D numpy array to use with operator.
        :return: new HistogramWorkspace
        """
        signal = self.get_signal()
        new_ws = CloneWorkspace(InputWorkspace=self._raw_ws, StoreInADS=False)
        error = RuntimeError("List or array must have same number of elements as an axis of the workspace")
        new_signal = apply_with_corrected_shape(operator, signal, other, error)
        new_ws.setSignalArray(new_signal)
        return new_ws
    def test_handles_inaccurate_goniometer(self):
        peaks1 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws,
                                      NumberOfPeaks=0,
                                      OutputWorkspace="SXD_peaks3")
        peaks2 = CloneWorkspace(InputWorkspace=peaks1,
                                OutputWorkspace="SXD_peaks4")
        # set different gonio on each run
        rot = 5
        SetGoniometer(Workspace=peaks1, Axis0=f'{-rot},0,1,0,1')
        SetGoniometer(Workspace=peaks2, Axis0=f'{rot},0,1,0,1')
        # Add peaks at QLab corresponding to slightly different gonio rotations
        UB = np.diag([0.25, 0.25, 0.1])  # alatt = [4,4,10]
        for h in range(0, 3):
            for k in range(0, 3):
                hkl = np.array([h, k, 4])
                qlab = 2 * np.pi * np.matmul(
                    np.matmul(getR(-(rot + 1), [0, 1, 0]), UB), hkl)
                pk = peaks1.createPeak(qlab)
                peaks1.addPeak(pk)
                qlab = 2 * np.pi * np.matmul(
                    np.matmul(getR(rot + 1, [0, 1, 0]), UB), hkl)
                pk = peaks2.createPeak(qlab)
                peaks2.addPeak(pk)

        FindGlobalBMatrix(PeakWorkspaces=[peaks1, peaks2],
                          a=4.15,
                          b=3.95,
                          c=10,
                          alpha=88,
                          beta=88,
                          gamma=89,
                          Tolerance=0.15)

        # check lattice - shouldn't be effected by error in goniometer
        self.assert_lattice([peaks1, peaks2],
                            4.0,
                            4.0,
                            10.0,
                            90.0,
                            90.0,
                            90.0,
                            delta_latt=2e-2,
                            delta_angle=2.5e-1)
        self.assert_matrix([peaks1],
                           getBMatrix(peaks2),
                           getBMatrix,
                           delta=1e-10)  # should have same B matrix
        self.assert_matrix([peaks1, peaks2], np.eye(3), getUMatrix, delta=5e-2)
示例#17
0
    def _load_monitors(self, target):
        """
        Load monitor data for all target runs into a single workspace

        Parameters
        ----------
        target: str
            Specify the entity the workspace refers to. Valid options are
            'sample', 'background', and 'vanadium'

        Returns
        -------
        Mantid.EventWorkspace
        """
        valid_targets = ('sample', 'background', 'vanadium')
        if target not in valid_targets:
            raise KeyError('Target must be one of ' + ', '.join(valid_targets))
        target_to_runs = dict(sample='RunNumbers',
                              background='BackgroundRuns',
                              vanadium='VanadiumRuns')
        #
        # Load monitors files together
        #
        rl = self._run_lists(self.getProperty(target_to_runs[target]).value)
        _t_all_w = None
        for run in rl:
            file_name = "{0}_{1}_event.nxs".format(self._short_inst, str(run))
            _t_w = LoadNexusMonitors(file_name)
            if _t_all_w is None:
                _t_all_w = CloneWorkspace(_t_w)
            else:
                _t_all_w += _t_w
        return _t_all_w
示例#18
0
    def _create_indexed_workspace(self, fractional_peaks, m1m2):
        # Create table with the number of columns we need
        modulated = CloneWorkspace(fractional_peaks)
        lattice = modulated.sample().getOrientedLattice()
        lattice.setModVec1(V3D(0.5, 0.0, 0.5))
        lattice.setModVec2(V3D(0.333, 0.333, 0.))
        for row, peak in enumerate(modulated):
            row_indices = m1m2[row]
            mnp = V3D(row_indices[0], row_indices[1], 0)
            peak.setIntMNP(mnp)
            # update hkl
            modvec = lattice.getModVec(0) * mnp[0] + lattice.getModVec(1) * mnp[1]
            hkl = peak.getHKL() + modvec
            peak.setHKL(hkl[0], hkl[1], hkl[2])

        return modulated
示例#19
0
文件: Abins.py 项目: liquidmet/mantid
    def _create_total_workspace(self, partial_workspaces=None):

        """
        Sets workspace with total S.
        :param partial_workspaces: list of workspaces which should be summed up to obtain total workspace
        :returns: workspace with total S from partial_workspaces
                """
        total_workspace = self._out_ws_name + "_total"

        if isinstance(mtd[partial_workspaces[0]], WorkspaceGroup):
            local_partial_workspaces = mtd[partial_workspaces[0]].names()
        else:
            local_partial_workspaces = partial_workspaces

        if len(local_partial_workspaces) > 1:

            # get frequencies
            ws = mtd[local_partial_workspaces[0]]

            # initialize S
            s_atoms = np.zeros_like(ws.dataY(0))

            # collect all S
            for partial_ws in local_partial_workspaces:
                if self._instrument.get_name() in AbinsModules.AbinsConstants.ONE_DIMENSIONAL_INSTRUMENTS:
                    s_atoms += mtd[partial_ws].dataY(0)

            # create workspace with S
            self._fill_s_workspace(s_atoms, total_workspace)

        # # Otherwise just repackage the workspace we have as the total
        else:
            CloneWorkspace(InputWorkspace=local_partial_workspaces[0], OutputWorkspace=total_workspace)

        return total_workspace
示例#20
0
 def test_fix_yaw(self) -> None:
     CloneWorkspace(InputWorkspace='test_workspace_TOF',
                    OutputWorkspace='perturbed')
     RotateInstrumentComponent(Workspace='perturbed',
                               ComponentName='bank1',
                               X=0,
                               Y=0,
                               z=1,
                               Angle=5,
                               RelativeRotation=True)
     r"""Pass option FixYaw=True"""
     CorelliPowderCalibrationCreate(InputWorkspace='perturbed',
                                    OutputWorkspacesPrefix='cal_',
                                    TofBinning=[300, 1.0, 16666.7],
                                    PeakPositions=self.spacings_reference,
                                    SourceToSampleDistance=10.0,
                                    ComponentList='bank1',
                                    ComponentMaxTranslation=0.2,
                                    FixYaw=True,
                                    ComponentMaxRotation=10,
                                    Minimizer='L-BFGS-B')
     # Check no change in the rotations around Z-axis of first bank
     row = mtd['cal_displacements'].row(0)
     self.assertAlmostEquals(row['DeltaGamma'], 0.0, places=5)
     DeleteWorkspaces(['perturbed'])
示例#21
0
    def testCalculateEfficiencyCorrectionAlphaForEventWkspInputWkspNotInADS(
            self):
        self.cleanup()

        # Create an exponentially decaying function in wavelength to simulate
        # measured sample
        tmp_wksp = CreateSampleWorkspace(
            WorkspaceType="Event",
            Function="User Defined",
            UserDefinedFunction="name=ExpDecay, Height=100, Lifetime=4",
            Xmin=0.2,
            Xmax=4.0,
            BinWidth=0.01,
            XUnit="Wavelength",
            NumEvents=10000,
            NumBanks=1,
            BankPixelWidth=1,
            OutputWorkspace=self._input_wksp,
            StoreInADS=False)

        # Calculate the efficiency correction
        alg_test = run_algorithm("CalculateEfficiencyCorrection",
                                 InputWorkspace=tmp_wksp,
                                 Alpha=self._alpha,
                                 OutputWorkspace=self._correction_wksp)
        self.assertTrue(alg_test.isExecuted())
        CloneWorkspace(InputWorkspace=tmp_wksp,
                       OutputWorkspace=self._input_wksp)
        ConvertToPointData(InputWorkspace=self._input_wksp,
                           OutputWorkspace=self._input_wksp)
        self.checkResults(eventCheck=True)
    def prepare_background(input_md, reference_sample_mde, background_md: str):
        """Prepare background MDEventWorkspace from reduced sample Matrix
        This is the previous solution to merge all the ExperimentInfo
        """
        dgs_data = CloneWorkspace(input_md)
        data_MDE = mtd[reference_sample_mde]
        if mtd.doesExist('background_MDE'):
            DeleteWorkspace('background_MDE')

        for i in range(data_MDE.getNumExperimentInfo()):
            phi, chi, omega = data_MDE.getExperimentInfo(
                i).run().getGoniometer().getEulerAngles('YZY')
            AddSampleLogMultiple(Workspace=dgs_data,
                                 LogNames='phi, chi, omega',
                                 LogValues='{},{},{}'.format(phi, chi, omega))
            SetGoniometer(Workspace=dgs_data, Goniometers='Universal')
            ConvertToMD(InputWorkspace=dgs_data,
                        QDimensions='Q3D',
                        dEAnalysisMode='Direct',
                        Q3DFrames="Q_sample",
                        MinValues='-11,-11,-11,-25',
                        MaxValues='11,11,11,49',
                        PreprocDetectorsWS='-',
                        OverwriteExisting=False,
                        OutputWorkspace=background_md)
示例#23
0
    def _plot_vanadium_curves():
        van_curve_twin_ws = "__engggui_vanadium_curves_twin_ws"

        if Ads.doesExist(van_curve_twin_ws):
            DeleteWorkspace(van_curve_twin_ws)
        CloneWorkspace(InputWorkspace="engggui_vanadium_curves", OutputWorkspace=van_curve_twin_ws)
        van_curves_ws = Ads.retrieve(van_curve_twin_ws)

        fig = plt.figure()
        gs = gridspec.GridSpec(1, 2)
        curve_plot_bank_1 = fig.add_subplot(gs[0], projection="mantid")
        curve_plot_bank_2 = fig.add_subplot(gs[1], projection="mantid")

        curve_plot_bank_1.plot(van_curves_ws, wkspIndex=0)
        curve_plot_bank_1.plot(van_curves_ws, wkspIndex=1)
        curve_plot_bank_1.plot(van_curves_ws, wkspIndex=2)
        curve_plot_bank_1.set_title("Engg GUI Vanadium Curves Bank 1")
        curve_plot_bank_1.legend(["Data", "Calc", "Diff"])

        curve_plot_bank_2.plot(van_curves_ws, wkspIndex=3)
        curve_plot_bank_2.plot(van_curves_ws, wkspIndex=4)
        curve_plot_bank_2.plot(van_curves_ws, wkspIndex=5)
        curve_plot_bank_2.set_title("Engg GUI Vanadium Curves Bank 2")
        curve_plot_bank_2.legend(["Data", "Calc", "Diff"])

        fig.show()
示例#24
0
    def _run_rebin(self, name, rebin_type, params):
        rebined_run_name = None
        if rebin_type == "Fixed":
            rebin_index = 1
            rebin_option = "Steps: " + str(params) + " KeV"
            rebined_run_name = str(name) + REBINNED_FIXED_WS_SUFFIX
        if rebin_type == "Variable":
            rebin_index = 2
            rebin_option = "Bin Boundaries: " + str(params)
            rebined_run_name = str(name) + REBINNED_VARIABLE_WS_SUFFIX

        remove_ws_if_present(rebined_run_name)
        raw_workspace = self.group_context[name].get_counts_workspace_for_run()

        CloneWorkspace(InputWorkspace=raw_workspace,
                       OutputWorkspace=rebined_run_name)
        rebin_ws(rebined_run_name, params)

        workspace = retrieve_ws(rebined_run_name)
        group_workspace = retrieve_ws(self.group_context[name].run_number)
        group_workspace.addWorkspace(workspace)
        group = self.group_context[name]
        group.update_workspaces(str(workspace),
                                rebin=True,
                                rebin_index=rebin_index,
                                rebin_option=rebin_option)
        self.update_plots_notifier.notify_subscribers(workspace)
示例#25
0
def _applyIncidentEnergyCalibration(ws, wsType, eiWS, wsNames, report,
                                    algorithmLogging):
    """Update incident energy and wavelength in the sample logs."""
    originalEnergy = ws.getRun().getLogData('Ei').value
    originalWavelength = ws.getRun().getLogData('wavelength').value
    energy = eiWS.readY(0)[0]
    wavelength = UnitConversion.run('Energy', 'Wavelength', energy, 0, 0, 0, Direct, 5)
    if wsType == common.WS_CONTENT_DETS:
        calibratedWSName = wsNames.withSuffix('incident_energy_calibrated_detectors')
    elif wsType == common.WS_CONTENT_MONS:
        calibratedWSName = wsNames.withSuffix('incident_energy_calibrated_monitors')
    else:
        raise RuntimeError('Unknown workspace content type')
    calibratedWS = CloneWorkspace(InputWorkspace=ws,
                                  OutputWorkspace=calibratedWSName,
                                  EnableLogging=algorithmLogging)
    AddSampleLog(Workspace=calibratedWS,
                 LogName='Ei',
                 LogText=str(energy),
                 LogType='Number',
                 NumberType='Double',
                 LogUnit='meV',
                 EnableLogging=algorithmLogging)
    AddSampleLog(Workspace=calibratedWS,
                 Logname='wavelength',
                 LogText=str(wavelength),
                 LogType='Number',
                 NumberType='Double',
                 LogUnit='Angstrom',
                 EnableLogging=algorithmLogging)
    report.notice("Applied Ei calibration to '" + str(ws) + "'.")
    report.notice('Original Ei: {} new Ei: {}.'.format(originalEnergy, energy))
    report.notice('Original wavelength: {} new wavelength {}.'.format(originalWavelength, wavelength))
    return calibratedWS
示例#26
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
示例#27
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
示例#28
0
    def setUpClass(cls):
        x = np.linspace(0, 99, 100)
        y = x * 1
        e = y * 0 + 2
        cls.m_workspace = wrap_workspace(
            CreateWorkspace(x, y, e, OutputWorkspace="m_ws"), 'm_ws')

        sim_workspace = CreateSimulationWorkspace(Instrument='MAR',
                                                  BinParams=[-10, 1, 10],
                                                  UnitX='DeltaE',
                                                  OutputWorkspace='ws1')
        AddSampleLog(sim_workspace,
                     LogName='Ei',
                     LogText='3.',
                     LogType='Number')
        cls.px_workspace = ConvertToMD(InputWorkspace=sim_workspace,
                                       OutputWorkspace="ws1",
                                       QDimensions='|Q|',
                                       dEAnalysisMode='Direct',
                                       MinValues='-10,0,0',
                                       MaxValues='10,6,500',
                                       SplitInto='50,50')
        cls.px_workspace_clone = CloneWorkspace(
            InputWorkspace=cls.px_workspace,
            OutputWorkspace='ws2',
            StoreInADS=False)
        cls.px_workspace = wrap_workspace(cls.px_workspace, 'ws1')
        cls.px_workspace_clone = wrap_workspace(cls.px_workspace_clone, 'ws2')
示例#29
0
 def test_fix_y(self) -> None:
     CloneWorkspace(InputWorkspace='test_workspace_TOF',
                    OutputWorkspace='perturbed')
     y = -0.0042  # desired fixed position
     MoveInstrumentComponent(Workspace='perturbed',
                             ComponentName='bank1',
                             X=0,
                             y=y,
                             z=0,
                             RelativePosition=False)
     r"""Pass option FixY=True"""
     CorelliPowderCalibrationCreate(InputWorkspace='perturbed',
                                    OutputWorkspacesPrefix='cal_',
                                    TofBinning=[300, 1.0, 16666.7],
                                    PeakPositions=self.spacings_reference,
                                    SourceToSampleDistance=10.0,
                                    ComponentList='bank1',
                                    FixY=True,
                                    ComponentMaxTranslation=0.2,
                                    ComponentMaxRotation=10,
                                    Minimizer='L-BFGS-B')
     # Check Y-position of first bank hasn't changed
     row = mtd['cal_adjustments'].row(1)
     self.assertAlmostEquals(row['Yposition'], y, places=5)
     DeleteWorkspaces(['perturbed'])
示例#30
0
def apply_calibration(workspace: WorkspaceTypes, calibration_table: InputTable,
                      output_workspace: Optional[str] = None, show_instrument: bool = False) -> Workspace2D:
    r"""
    Calibrate the detector positions with an input table, and open the instrument view if so requested.

    :param workspace: input Workspace2D containing total neutron counts per pixel
    :param calibration_table: a TableWorskpace containing one column for detector ID and one column
    for its calibrated XYZ coordinates, in meters
    :param output_workspace: name of the output workspace containing calibrated detectors. If `None`, then
        the output workspace name will be the input workspace plus the suffix `_calibrated`
    :param show_instrument: open the instrument view for `output_workspace`

    :raises AssertionError: either `workspace` or `calibration_table` are not found
    """
    assert AnalysisDataService.doesExist(str(workspace)), f'No worksapce {str(workspace)} found'
    assert AnalysisDataService.doesExist(str(calibration_table)), f'No table {str(calibration_table)} found'
    if output_workspace is None:
        output_workspace = str(workspace) + '_calibrated'

    CloneWorkspace(InputWorkspace=workspace, OutputWorkspace=output_workspace)
    ApplyCalibration(Workspace=output_workspace, CalibrationTable=calibration_table)

    if show_instrument is True and None not in (InstrumentViewPresenter, InstrumentViewPresenter):
        instrument_presenter = QAppThreadCall(InstrumentViewPresenter)(mtd[output_workspace])
        QAppThreadCall(instrument_presenter.show_view)()

    return mtd[output_workspace]
示例#31
0
    def set_transmission_workspaces_on_output(self, completed_event_slices,
                                              fit_state):
        calc_can, calc_sample = WorkspaceGroup(), WorkspaceGroup()
        unfit_can, unfit_sample = WorkspaceGroup(), WorkspaceGroup()

        output_hab_or_lab = None
        for bundle in completed_event_slices:
            if output_hab_or_lab is not None and output_hab_or_lab != bundle.output_bundle.reduction_mode:
                continue  # The transmission workspace for HAB/LAB is the same, so only output one
            output_hab_or_lab = bundle.output_bundle.reduction_mode
            calculated_transmission_workspace = bundle.transmission_bundle.calculated_transmission_workspace
            unfitted_transmission_workspace = bundle.transmission_bundle.unfitted_transmission_workspace
            if bundle.transmission_bundle.data_type is DataType.CAN:
                if does_can_workspace_exist_on_ads(
                        calculated_transmission_workspace):
                    # The workspace is cloned here because the transmission runs are diagnostic output so even though
                    # the values already exist they need to be labelled separately for each reduction.
                    calculated_transmission_workspace = CloneWorkspace(
                        calculated_transmission_workspace, StoreInADS=False)
                if does_can_workspace_exist_on_ads(
                        unfitted_transmission_workspace):
                    unfitted_transmission_workspace = CloneWorkspace(
                        unfitted_transmission_workspace, StoreInADS=False)
                if calculated_transmission_workspace:
                    calc_can.addWorkspace(calculated_transmission_workspace)
                if unfitted_transmission_workspace:
                    unfit_can.addWorkspace(unfitted_transmission_workspace)

            elif bundle.transmission_bundle.data_type is DataType.SAMPLE:
                if calculated_transmission_workspace:
                    calc_sample.addWorkspace(calculated_transmission_workspace)
                if unfitted_transmission_workspace:
                    unfit_sample.addWorkspace(unfitted_transmission_workspace)
            else:
                raise RuntimeError(
                    "SANSSingleReduction: The data type {0} should be"
                    " sample or can.".format(
                        bundle.transmission_bundle.data_type))

        self._set_prop_if_group_has_data(
            "OutputWorkspaceCalculatedTransmission", calc_sample)
        self._set_prop_if_group_has_data("OutputWorkspaceUnfittedTransmission",
                                         unfit_sample)
        self._set_prop_if_group_has_data(
            "OutputWorkspaceCalculatedTransmissionCan", calc_can)
        self._set_prop_if_group_has_data(
            "OutputWorkspaceUnfittedTransmissionCan", unfit_can)
示例#32
0
 def _rename_and_group_workspaces(index, output_workspaces):
     to_group = []
     for workspace in output_workspaces:
         CloneWorkspace(InputWorkspace=workspace,
                        OutputWorkspace='{}_{}'.format(workspace, index))
         to_group.append('{}_{}'.format(workspace, index))
     GroupWorkspaces(InputWorkspaces=to_group,
                     OutputWorkspace='Iteration_{}'.format(index))
    def _create_workspaces(self):
        cal=CreateSampleWorkspace(NumBanks=1,BinWidth=20000,PixelSpacing=0.1,BankPixelWidth=100)
        RotateInstrumentComponent(cal, ComponentName='bank1', X=1, Y=0.5, Z=2, Angle=35)
        MoveInstrumentComponent(cal, ComponentName='bank1', X=1, Y=1, Z=5)
        bkg=CloneWorkspace(cal)
        data=CloneWorkspace(cal)
        AddSampleLog(cal, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='200')
        AddSampleLog(bkg, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='50')
        AddSampleLog(data, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='100')
        AddSampleLog(cal, LogName="duration", LogType='Number', NumberType='Double', LogText='20')
        AddSampleLog(bkg, LogName="duration", LogType='Number', NumberType='Double', LogText='5')
        AddSampleLog(data, LogName="duration", LogType='Number', NumberType='Double', LogText='10')

        def get_cal_counts(n):
            if n < 5000:
                return 0.9
            else:
                return 1.0

        def get_bkg_counts(n):
            return 1.5*get_cal_counts(n)

        def get_data_counts(n,twoTheta):
            tt1=30
            tt2=45
            return get_bkg_counts(n)+10*np.exp(-(twoTheta-tt1)**2/1)+20*np.exp(-(twoTheta-tt2)**2/0.2)

        for i in range(cal.getNumberHistograms()):
            cal.setY(i, [get_cal_counts(i)*2.0])
            bkg.setY(i, [get_bkg_counts(i)/2.0])
            twoTheta=data.getInstrument().getDetector(i+10000).getTwoTheta(V3D(0,0,0),V3D(0,0,1))*180/np.pi
            data.setY(i, [get_data_counts(i,twoTheta)])

        return data, cal, bkg
示例#34
0
    def _generateNormalization(self, WS, normType, normWS):
        if normType == 'None':
            return None
        elif normType == "Extracted from Data":
            window = self.getProperty("PeakClippingWindowSize").value

            smooth_range = self.getProperty("SmoothingRange").value

            peak_clip_WS = str(WS).replace('_red', '_normalizer')
            peak_clip_WS = CloneWorkspace(InputWorkspace=WS, OutputWorkspace=peak_clip_WS)
            n_histo = peak_clip_WS.getNumberHistograms()

            for h in range(n_histo):
                peak_clip_WS.setY(h, self.peak_clip(peak_clip_WS.readY(h), win=window, decrese=True,
                                                    LLS=True, smooth_window=smooth_range))
            return str(peak_clip_WS)
        else:  # other values are already held in normWS
            return normWS
示例#35
0
 def computemodel(p,wse,wsc):
   """Assemble the model
   Arguments
     p: dictionary with parameter values
     wse: Mantid workspace holding the elastic line
     wsc: Mantid workspace holding the convolution of the resolution and the simulation
   Returns:
     wsm: Mantid workspace holding the resulting model
   """
   from mantid.simpleapi import CloneWorkspace
   wsm=CloneWorkspace(wsc)
   E=wse.readX(0) # energy values, bins boundary values
   Eshifted=(E[1:]+E[:-1])/2 # energy values, center bin values
   for i in range(wsc.getNumberHistograms()):
     elastic=wse.readY(i)   # elastic spectrum at a given Q
     convolved=wsc.readY(i) # convolved spectrum at a given Q
     wsm.setY(i, p['b0']+p['b1']*Eshifted + p['e0.'+str(i)]*elastic + p['c0']*convolved) # overwrite spectrum
   return wsm
示例#36
0
    def _generateNormalization(self, WS, normType, normWS):
        if normType == 'None':
            return None
        elif normType == "Extracted from Data":
            window = self.getProperty("PeakClippingWindowSize").value

            smooth_range = self.getProperty("SmoothingRange").value

            peak_clip_WS = CloneWorkspace(WS)
            n_histo = peak_clip_WS.getNumberHistograms()

            x = peak_clip_WS.extractX()
            y = peak_clip_WS.extractY()
            e = peak_clip_WS.extractE()

            for h in range(n_histo):
                peak_clip_WS.setX(h, x[h])
                peak_clip_WS.setY(h, self.peak_clip(y[h], win=window, decrese=True,
                                                    LLS=True, smooth_window=smooth_range))
                peak_clip_WS.setE(h, e[h])
            return peak_clip_WS
        else: # other values are already held in normWS
            return normWS