Пример #1
0
def normalise_ws_current(ws_to_correct, monitor_ws, spline_coeff, lambda_values, integration_range, ex_regions):
    processed_monitor_ws = mantid.ConvertUnits(InputWorkspace=monitor_ws, Target="Wavelength")
    processed_monitor_ws = mantid.CropWorkspace(InputWorkspace=processed_monitor_ws,
                                                XMin=lambda_values[0], XMax=lambda_values[-1])

    for reg in range(0, 4):
        processed_monitor_ws = mantid.MaskBins(InputWorkspace=processed_monitor_ws, XMin=ex_regions[0, reg],
                                               XMax=ex_regions[1, reg])

    splined_monitor_ws = mantid.SplineBackground(InputWorkspace=processed_monitor_ws,
                                                 WorkspaceIndex=0, NCoeff=spline_coeff)

    normalised_ws = mantid.ConvertUnits(InputWorkspace=ws_to_correct, Target="Wavelength",
                                        OutputWorkspace=ws_to_correct)
    normalised_ws = mantid.NormaliseToMonitor(InputWorkspace=normalised_ws, MonitorWorkspace=splined_monitor_ws,
                                              IntegrationRangeMin=integration_range[0],
                                              IntegrationRangeMax=integration_range[-1],
                                              OutputWorkspace=normalised_ws)

    normalised_ws = mantid.ConvertUnits(InputWorkspace=normalised_ws, Target="TOF", OutputWorkspace=normalised_ws)

    common.remove_intermediate_workspace(processed_monitor_ws)
    common.remove_intermediate_workspace(splined_monitor_ws)

    return normalised_ws
Пример #2
0
def _sum_groups_of_three_ws(calibrated_spectra, output_file_names):
    workspace_list = []
    output_list = []
    for outer_loop_count in range(0, 3):
        # First clone workspaces 1/4/7
        pass_multiplier = (outer_loop_count * 3)
        workspace_names = "focus_mode_groups-" + str(pass_multiplier + 1)
        workspace_list.append(
            mantid.CloneWorkspace(
                InputWorkspace=calibrated_spectra[pass_multiplier],
                OutputWorkspace=workspace_names))
        # Then add workspaces 1+2+3 / 4+5+6 / 7+8+9
        for i in range(1, 3):
            input_ws_index = i + pass_multiplier  # Workspaces 2/3 * n
            inner_workspace_names = "focus_mode_groups-" + str(input_ws_index)
            workspace_list[outer_loop_count] = mantid.Plus(
                LHSWorkspace=workspace_list[outer_loop_count],
                RHSWorkspace=calibrated_spectra[input_ws_index],
                OutputWorkspace=inner_workspace_names)

        # Finally scale the output workspaces
        mod_first_number = str((outer_loop_count * 3) + 1)  # Generates 1/4/7
        mod_last_number = str((outer_loop_count + 1) * 3)  # Generates 3/6/9
        workspace_names = output_file_names[
            "output_name"] + "_mod" + mod_first_number + '-' + mod_last_number
        output_list.append(
            mantid.Scale(InputWorkspace=workspace_list[outer_loop_count],
                         OutputWorkspace=workspace_names,
                         Factor=0.333333333333))

    common.remove_intermediate_workspace(workspace_list)
    return output_list
Пример #3
0
def _spline_old_instrument_background(in_workspace):
    van_stripped = mantid.ConvertUnits(InputWorkspace=in_workspace, Target="dSpacing")

    # remove bragg peaks before spline
    van_stripped = mantid.StripPeaks(InputWorkspace=van_stripped, FWHM=15, Tolerance=6, WorkspaceIndex=0)
    van_stripped = mantid.StripPeaks(InputWorkspace=van_stripped, FWHM=15, Tolerance=6, WorkspaceIndex=2)
    van_stripped = mantid.StripPeaks(InputWorkspace=van_stripped, FWHM=15, Tolerance=6, WorkspaceIndex=3)
    van_stripped = mantid.StripPeaks(InputWorkspace=van_stripped, FWHM=40, Tolerance=12, WorkspaceIndex=1)
    van_stripped = mantid.StripPeaks(InputWorkspace=van_stripped, FWHM=60, Tolerance=12, WorkspaceIndex=1)

    # Mask low d region that is zero before spline
    for reg in range(0, 4):
        if reg == 1:
            van_stripped = mantid.MaskBins(InputWorkspace=van_stripped, XMin=0, XMax=0.14, SpectraList=reg)
        else:
            van_stripped = mantid.MaskBins(InputWorkspace=van_stripped, XMin=0, XMax=0.06, SpectraList=reg)

    van_stripped = mantid.ConvertUnits(InputWorkspace=van_stripped, Target="TOF")

    splined_ws_list = []
    for i in range(0, 4):
        out_ws_name = "spline" + str(i+1)
        if i == 1:
            coeff = 80
        else:
            coeff = 100
        splined_ws_list.append(mantid.SplineBackground(InputWorkspace=van_stripped, OutputWorkspace=out_ws_name,
                                                       WorkspaceIndex=i, NCoeff=coeff))
    common.remove_intermediate_workspace(van_stripped)
    return splined_ws_list
Пример #4
0
def apply_vanadium_absorb_corrections(van_ws, run_details, absorb_ws=None):
    if absorb_ws is None:
        absorb_ws = mantid.Load(Filename=run_details.vanadium_absorption_path)

    van_original_units = van_ws.getAxis(0).getUnit().unitID()
    absorb_units = absorb_ws.getAxis(0).getUnit().unitID()
    if van_original_units != absorb_units:
        van_ws = mantid.ConvertUnits(InputWorkspace=van_ws,
                                     Target=absorb_units,
                                     OutputWorkspace=van_ws)

    absorb_ws = mantid.RebinToWorkspace(WorkspaceToRebin=absorb_ws,
                                        WorkspaceToMatch=van_ws,
                                        OutputWorkspace=absorb_ws)
    van_ws = mantid.Divide(LHSWorkspace=van_ws,
                           RHSWorkspace=absorb_ws,
                           OutputWorkspace=van_ws)

    if van_original_units != absorb_units:
        van_ws = mantid.ConvertUnits(InputWorkspace=van_ws,
                                     Target=van_original_units,
                                     OutputWorkspace=van_ws)

    common.remove_intermediate_workspace(absorb_ws)
    return van_ws
Пример #5
0
def _calibration_processing(calibration_dir, calibration_runs, cross_correlate_params, get_det_offset_params,
                            grouping_file_name, input_ws, instrument, offset_file, rebin_1_params, rebin_2_params):
    calibration_ws = input_ws
    if calibration_ws.getAxis(0).getUnit().unitID() != WORKSPACE_UNITS.d_spacing:
        calibration_ws = mantid.Rebin(InputWorkspace=input_ws, Params=rebin_1_params)
        calibration_ws = mantid.ConvertUnits(InputWorkspace=calibration_ws, Target="dSpacing")
    spectrum_list = []
    for i in range(0, calibration_ws.getNumberHistograms()):
        try:
            calibration_ws.getDetector(i)

        except RuntimeError:
            pass
        else:
            spectrum_list.append(i)
    calibration_ws = mantid.ExtractSpectra(InputWorkspace=calibration_ws, WorkspaceIndexList=spectrum_list)
    rebinned = mantid.Rebin(InputWorkspace=calibration_ws, Params=rebin_2_params)
    cross_correlated = mantid.CrossCorrelate(InputWorkspace=rebinned, **cross_correlate_params)

    # Offsets workspace must be referenced as string so it can be deleted, as simpleapi doesn't recognise it as a ws
    offsets_ws_name = "offsets"
    mantid.GetDetectorOffsets(InputWorkspace=cross_correlated, GroupingFileName=offset_file,
                              OutputWorkspace=offsets_ws_name, **get_det_offset_params)
    rebinned_tof = mantid.ConvertUnits(InputWorkspace=rebinned, Target="TOF")
    aligned = mantid.AlignDetectors(InputWorkspace=rebinned_tof, CalibrationFile=offset_file)
    grouping_file = os.path.join(calibration_dir, grouping_file_name)
    focused = mantid.DiffractionFocussing(InputWorkspace=aligned, GroupingFileName=grouping_file,
                                          OutputWorkspace=instrument._generate_output_file_name(calibration_runs)
                                          + "_grouped")
    print("Saved cal file to " + offset_file)
    common.remove_intermediate_workspace([calibration_ws, rebinned, cross_correlated, rebinned_tof,
                                          offsets_ws_name])
    return focused
Пример #6
0
def process_vanadium_for_focusing(bank_spectra, mask_path, spline_number):
    bragg_masking_list = _read_masking_file(mask_path)
    masked_workspace_list = _apply_bragg_peaks_masking(bank_spectra, mask_list=bragg_masking_list)
    output = common.spline_workspaces(focused_vanadium_spectra=masked_workspace_list,
                                      num_splines=spline_number)
    common.remove_intermediate_workspace(masked_workspace_list)
    return output
Пример #7
0
    def test_remove_intermediate_workspace(self):
        ws_list = []
        ws_names_list = []

        ws_single_name = "remove_intermediate_ws-single"
        ws_single = mantid.CreateSampleWorkspace(OutputWorkspace=ws_single_name, NumBanks=1, BankPixelWidth=1,
                                                 XMax=10, BinWidth=1)

        for i in range(0, 3):
            out_name = "remove_intermediate_ws_" + str(i)
            ws_names_list.append(out_name)
            ws_list.append(mantid.CreateSampleWorkspace(OutputWorkspace=out_name, NumBanks=1, BankPixelWidth=1,
                                                        XMax=10, BinWidth=1))

        # Check single workspaces are removed
        self.assertEqual(True, mantid.mtd.doesExist(ws_single_name))
        common.remove_intermediate_workspace(ws_single)
        self.assertEqual(False, mantid.mtd.doesExist(ws_single_name))

        # Next check lists are handled
        for ws_name in ws_names_list:
            self.assertEqual(True, mantid.mtd.doesExist(ws_name))

        common.remove_intermediate_workspace(ws_list)

        for ws_name in ws_names_list:
            self.assertEqual(False, mantid.mtd.doesExist(ws_name))
Пример #8
0
def process_vanadium_for_focusing(bank_spectra, mask_path, spline_number):
    bragg_masking_list = _read_masking_file(mask_path)
    masked_workspace_list = _apply_bragg_peaks_masking(bank_spectra, mask_list=bragg_masking_list)
    output = common.spline_workspaces(focused_vanadium_spectra=masked_workspace_list,
                                      num_splines=spline_number)
    common.remove_intermediate_workspace(masked_workspace_list)
    return output
Пример #9
0
def _adjust_cal_file(original_cal, generated_cal):
    origin_ws = "origin{}"
    gen_ws = "newCal{}"
    out_ws = "adjusted_cal"
    mantid.LoadCalFile(InstrumentName="Gem",
                       MakeGroupingWorkspace=False,
                       MakeMaskWorkspace=False,
                       MakeOffsetsWorkspace=True,
                       WorkspaceName=origin_ws.format(''),
                       CalFilename=original_cal)
    mantid.LoadCalFile(InstrumentName="Gem",
                       MakeGroupingWorkspace=False,
                       MakeMaskWorkspace=False,
                       MakeOffsetsWorkspace=True,
                       WorkspaceName=gen_ws.format(''),
                       CalFilename=generated_cal)
    mantid.Plus(LHSWorkspace=origin_ws.format("_offsets"),
                RHSWorkspace=gen_ws.format("_offsets"),
                OutputWorkspace=out_ws)
    mantid.SaveCalFile(OffsetsWorkspace=out_ws, Filename=generated_cal)
    common.remove_intermediate_workspace([
        origin_ws.format("_offsets"),
        gen_ws.format("_offsets"),
        origin_ws.format("_cal"),
        gen_ws.format("_cal")
    ])
Пример #10
0
def _divide_by_vanadium_splines(spectra_list, vanadium_splines):

    if hasattr(vanadium_splines,
               "OutputWorkspace"):  # vanadium_splines is a group
        vanadium_splines = vanadium_splines.OutputWorkspace

        num_splines = len(vanadium_splines)
        num_spectra = len(spectra_list)

        if num_splines != num_spectra:
            raise RuntimeError(
                "Mismatch between number of banks in vanadium and number of banks in workspace to focus"
                "\nThere are {} banks for vanadium but {} for the run".format(
                    num_splines, num_spectra))

        output_list = [
            _divide_one_spectrum_by_spline(data_ws, van_ws)
            for data_ws, van_ws in zip(spectra_list, vanadium_splines)
        ]
        return output_list

    output_list = [
        _divide_one_spectrum_by_spline(spectra_list[0], vanadium_splines)
    ]
    common.remove_intermediate_workspace(vanadium_splines)
    return output_list
Пример #11
0
    def create_solid_angle_corrections(self, vanadium, run_details):
        """
        Creates the solid angle corrections from a vanadium run, only applicable on HRPD otherwise return None
        :param vanadium: The vanadium used to create this
        :param run_details: the run details of to use
        """
        settings = self._inst_settings
        if not settings.do_solid_angle:
            return
        solid_angle = mantid.SolidAngle(InputWorkspace=vanadium)
        solid_angle = mantid.Scale(InputWorkspace=solid_angle, Factor=100, Operation='Multiply')

        eff = mantid.Divide(LHSWorkspace=vanadium, RHSWorkspace=solid_angle)
        eff = mantid.ConvertUnits(InputWorkspace=eff, Target='Wavelength')
        integration_range = settings.eff_integration_range
        # use full range if no range is supplied
        integration_range = integration_range if integration_range is not None else (None, None)
        eff = mantid.Integration(InputWorkspace=eff,
                                 RangeLower=integration_range[0],
                                 RangeUpper=integration_range[1])

        correction = mantid.Multiply(LHSWorkspace=solid_angle, RHSWorkspace=eff)
        correction = mantid.Scale(InputWorkspace=correction, Factor=1e-5,
                                  Operation='Multiply')
        name = "sac" + common.generate_splined_name(run_details.run_number, [])
        path = run_details.van_paths

        mantid.SaveNexus(InputWorkspace=correction, Filename=os.path.join(path, name))
        common.remove_intermediate_workspace(eff)
        common.remove_intermediate_workspace(correction)
Пример #12
0
    def test_remove_intermediate_workspace(self):
        ws_list = []
        ws_names_list = []

        ws_single_name = "remove_intermediate_ws-single"
        ws_single = mantid.CreateSampleWorkspace(
            OutputWorkspace=ws_single_name,
            NumBanks=1,
            BankPixelWidth=1,
            XMax=10,
            BinWidth=1)

        for i in range(0, 3):
            out_name = "remove_intermediate_ws_" + str(i)
            ws_names_list.append(out_name)
            ws_list.append(
                mantid.CreateSampleWorkspace(OutputWorkspace=out_name,
                                             NumBanks=1,
                                             BankPixelWidth=1,
                                             XMax=10,
                                             BinWidth=1))

        # Check single workspaces are removed
        self.assertEqual(True, mantid.mtd.doesExist(ws_single_name))
        common.remove_intermediate_workspace(ws_single)
        self.assertEqual(False, mantid.mtd.doesExist(ws_single_name))

        # Next check lists are handled
        for ws_name in ws_names_list:
            self.assertEqual(True, mantid.mtd.doesExist(ws_name))

        common.remove_intermediate_workspace(ws_list)

        for ws_name in ws_names_list:
            self.assertEqual(False, mantid.mtd.doesExist(ws_name))
Пример #13
0
def _sum_groups_of_three_ws(calibrated_spectra, output_file_names):
    workspace_list = []
    output_list = []
    for outer_loop_count in range(0, 3):
        # First clone workspaces 1/4/7
        pass_multiplier = (outer_loop_count * 3)
        workspace_names = "focus_mode_groups-" + str(pass_multiplier + 1)
        workspace_list.append(mantid.CloneWorkspace(InputWorkspace=calibrated_spectra[pass_multiplier],
                                                    OutputWorkspace=workspace_names))
        # Then add workspaces 1+2+3 / 4+5+6 / 7+8+9
        for i in range(1, 3):
            input_ws_index = i + pass_multiplier  # Workspaces 2/3 * n
            inner_workspace_names = "focus_mode_groups-" + str(input_ws_index)
            workspace_list[outer_loop_count] = mantid.Plus(LHSWorkspace=workspace_list[outer_loop_count],
                                                           RHSWorkspace=calibrated_spectra[input_ws_index],
                                                           OutputWorkspace=inner_workspace_names)

        # Finally scale the output workspaces
        mod_first_number = str((outer_loop_count * 3) + 1)  # Generates 1/4/7
        mod_last_number = str((outer_loop_count + 1) * 3)  # Generates 3/6/9
        workspace_names = output_file_names["output_name"] + "_mod" + mod_first_number + '-' + mod_last_number
        output_list.append(mantid.Scale(InputWorkspace=workspace_list[outer_loop_count],
                                        OutputWorkspace=workspace_names, Factor=0.333333333333))
    for ws in workspace_list:
        common.remove_intermediate_workspace(ws)
    return output_list
Пример #14
0
def normalise_ws_current(ws_to_correct, monitor_ws, spline_coeff, lambda_values, integration_range, ex_regions):
    processed_monitor_ws = mantid.ConvertUnits(InputWorkspace=monitor_ws, Target="Wavelength")
    processed_monitor_ws = mantid.CropWorkspace(InputWorkspace=processed_monitor_ws,
                                                XMin=lambda_values[0], XMax=lambda_values[-1])

    for reg in range(0, 4):
        processed_monitor_ws = mantid.MaskBins(InputWorkspace=processed_monitor_ws, XMin=ex_regions[0, reg],
                                               XMax=ex_regions[1, reg])

    splined_monitor_ws = mantid.SplineBackground(InputWorkspace=processed_monitor_ws,
                                                 WorkspaceIndex=0, NCoeff=spline_coeff)

    normalised_ws = mantid.ConvertUnits(InputWorkspace=ws_to_correct, Target="Wavelength",
                                        OutputWorkspace=ws_to_correct)
    normalised_ws = mantid.NormaliseToMonitor(InputWorkspace=normalised_ws, MonitorWorkspace=splined_monitor_ws,
                                              IntegrationRangeMin=integration_range[0],
                                              IntegrationRangeMax=integration_range[-1],
                                              OutputWorkspace=normalised_ws)

    normalised_ws = mantid.ConvertUnits(InputWorkspace=normalised_ws, Target="TOF", OutputWorkspace=normalised_ws)

    common.remove_intermediate_workspace(processed_monitor_ws)
    common.remove_intermediate_workspace(splined_monitor_ws)

    return normalised_ws
Пример #15
0
def generate_ts_pdf(run_number, focus_file_path, merge_banks=False, q_lims=None, cal_file_name=None,
                    sample_details=None, delta_r=None, delta_q=None, pdf_type="G(r)", lorch_filter=None,
                    freq_params=None, debug=False):
    focused_ws = _obtain_focused_run(run_number, focus_file_path)
    focused_ws = mantid.ConvertUnits(InputWorkspace=focused_ws, Target="MomentumTransfer", EMode='Elastic')

    raw_ws = mantid.Load(Filename='POLARIS'+str(run_number)+'.nxs')
    sample_geometry = common.generate_sample_geometry(sample_details)
    sample_material = common.generate_sample_material(sample_details)
    self_scattering_correction = mantid.TotScatCalculateSelfScattering(
        InputWorkspace=raw_ws,
        CalFileName=cal_file_name,
        SampleGeometry=sample_geometry,
        SampleMaterial=sample_material,
        CrystalDensity=sample_details.material_object.crystal_density)

    ws_group_list = []
    for i in range(self_scattering_correction.getNumberHistograms()):
        ws_name = 'correction_' + str(i)
        mantid.ExtractSpectra(InputWorkspace=self_scattering_correction, OutputWorkspace=ws_name,
                              WorkspaceIndexList=[i])
        ws_group_list.append(ws_name)
    self_scattering_correction = mantid.GroupWorkspaces(InputWorkspaces=ws_group_list)
    self_scattering_correction = mantid.RebinToWorkspace(WorkspaceToRebin=self_scattering_correction,
                                                         WorkspaceToMatch=focused_ws)

    focused_ws = mantid.Subtract(LHSWorkspace=focused_ws, RHSWorkspace=self_scattering_correction)
    if delta_q:
        focused_ws = mantid.Rebin(InputWorkspace=focused_ws, Params=delta_q)
    if merge_banks:
        q_min, q_max = _load_qlims(q_lims)
        merged_ws = mantid.MatchAndMergeWorkspaces(InputWorkspaces=focused_ws, XMin=q_min, XMax=q_max,
                                                   CalculateScale=False)
        fast_fourier_filter(merged_ws, freq_params=freq_params)
        pdf_output = mantid.PDFFourierTransform(Inputworkspace="merged_ws", InputSofQType="S(Q)-1", PDFType=pdf_type,
                                                Filter=lorch_filter, DeltaR=delta_r,
                                                rho0=sample_details.material_object.crystal_density)
    else:
        for ws in focused_ws:
            fast_fourier_filter(ws, freq_params=freq_params)
        pdf_output = mantid.PDFFourierTransform(Inputworkspace='focused_ws', InputSofQType="S(Q)-1", PDFType=pdf_type,
                                                Filter=lorch_filter, DeltaR=delta_r,
                                                rho0=sample_details.material_object.crystal_density)
        pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output, WorkspaceToMatch=pdf_output[4],
                                             PreserveEvents=True)
    if not debug:
        common.remove_intermediate_workspace('self_scattering_correction')
    # Rename output ws
    if 'merged_ws' in locals():
        mantid.RenameWorkspace(InputWorkspace='merged_ws', OutputWorkspace=run_number + '_merged_Q')
    mantid.RenameWorkspace(InputWorkspace='focused_ws', OutputWorkspace=run_number+'_focused_Q')
    if isinstance(focused_ws, WorkspaceGroup):
        for i in range(len(focused_ws)):
            mantid.RenameWorkspace(InputWorkspace=focused_ws[i], OutputWorkspace=run_number+'_focused_Q_'+str(i+1))
    mantid.RenameWorkspace(InputWorkspace='pdf_output', OutputWorkspace=run_number+'_pdf_R')
    if isinstance(pdf_output, WorkspaceGroup):
        for i in range(len(pdf_output)):
            mantid.RenameWorkspace(InputWorkspace=pdf_output[i], OutputWorkspace=run_number+'_pdf_R_'+str(i+1))
    return pdf_output
Пример #16
0
def create_calibration(calibration_runs, instrument, offset_file_name,
                       grouping_file_name, calibration_dir, rebin_1_params,
                       rebin_2_params, cross_correlate_params,
                       get_det_offset_params):
    """
    Create a calibration file from (usually) a ceria run
    :param calibration_runs: Run number(s) for this run
    :param instrument: The PEARL instrument object
    :param offset_file_name: Name of the file to write detector offset information to
    :param grouping_file_name: Name of grouping calibration file
    :param calibration_dir: Path to directory containing calibration information
    :param rebin_1_params: Parameters for the first rebin step (as a string in the usual format)
    :param rebin_2_params: Parameters for the second rebin step (as a string in the usual format)
    :param cross_correlate_params: Parameters for CrossCorrelate (as a dictionary PropertyName: PropertyValue)
    :param get_det_offset_params: Parameters for GetDetectorOffsets (as a dictionary PropertyName: PropertyValue)
    """
    input_ws_list = common.load_current_normalised_ws_list(
        run_number_string=calibration_runs,
        instrument=instrument,
        input_batching=INPUT_BATCHING.Summed)

    input_ws = input_ws_list[0]
    calibration_ws = mantid.Rebin(InputWorkspace=input_ws,
                                  Params=rebin_1_params)

    if calibration_ws.getAxis(
            0).getUnit().unitID() != WORKSPACE_UNITS.d_spacing:
        calibration_ws = mantid.ConvertUnits(InputWorkspace=calibration_ws,
                                             Target="dSpacing")

    rebinned = mantid.Rebin(InputWorkspace=calibration_ws,
                            Params=rebin_2_params)
    cross_correlated = mantid.CrossCorrelate(InputWorkspace=rebinned,
                                             **cross_correlate_params)

    offset_file = os.path.join(calibration_dir, offset_file_name)
    # Offsets workspace must be referenced as string so it can be deleted, as simpleapi doesn't recognise it as a ws
    offsets_ws_name = "offsets"
    mantid.GetDetectorOffsets(InputWorkspace=cross_correlated,
                              GroupingFileName=offset_file,
                              OutputWorkspace=offsets_ws_name,
                              **get_det_offset_params)

    rebinned_tof = mantid.ConvertUnits(InputWorkspace=rebinned, Target="TOF")
    aligned = mantid.AlignDetectors(InputWorkspace=rebinned_tof,
                                    CalibrationFile=offset_file)

    grouping_file = os.path.join(calibration_dir, grouping_file_name)
    focused = mantid.DiffractionFocussing(
        InputWorkspace=aligned,
        GroupingFileName=grouping_file,
        OutputWorkspace=instrument._generate_output_file_name(calibration_runs)
        + "_grouped")

    common.remove_intermediate_workspace([
        calibration_ws, rebinned, cross_correlated, rebinned_tof, aligned,
        offsets_ws_name
    ])
    return focused
Пример #17
0
    def generate_solid_angle_corrections(self, run_details):
        solid_angle_vanadium_ws = common.load_current_normalised_ws(run_number_string=run_details.vanadium,
                                                                    instrument=self)

        corrections = _calculate_solid_angle_efficiency_corrections(solid_angle_vanadium_ws)
        mantid.SaveNexusProcessed(InputWorkspace=corrections, Filename=run_details.solid_angle_corr)

        common.remove_intermediate_workspace(solid_angle_vanadium_ws)
        return corrections
Пример #18
0
def _spline_new_background(in_workspace, num_splines, instrument_version):
    # Remove bragg peaks before spline
    alg_range, unused = _get_instrument_ranges(instrument_version)
    van_stripped = _strip_peaks_new_inst(in_workspace, alg_range)

    van_stripped = mantid.ConvertUnits(InputWorkspace=van_stripped, Target="TOF")

    splined_ws_list = _perform_spline_range(instrument_version, num_splines, van_stripped)
    common.remove_intermediate_workspace(van_stripped)
    return splined_ws_list
Пример #19
0
    def correct_sample_vanadium(self, focused_ws, index, vanadium_ws=None):
        spectra_name = "sample_ws-" + str(index + 1)
        mantid.CropWorkspace(InputWorkspace=focused_ws, OutputWorkspace=spectra_name,
                             StartWorkspaceIndex=index, EndWorkspaceIndex=index)

        if vanadium_ws:
            van_rebinned = mantid.RebinToWorkspace(WorkspaceToRebin=vanadium_ws, WorkspaceToMatch=spectra_name)
            mantid.Divide(LHSWorkspace=spectra_name, RHSWorkspace=van_rebinned, OutputWorkspace=spectra_name)
            common.remove_intermediate_workspace(van_rebinned)

        return spectra_name
Пример #20
0
    def _apply_van_calibration_tof_rebinning(self, vanadium_ws, tof_rebin_pass, return_units):
        tof_rebin_param_dict = self._get_create_van_tof_binning()
        tof_rebin_param = tof_rebin_param_dict[str(tof_rebin_pass)]

        rebinned_ws = mantid.ConvertUnits(InputWorkspace=vanadium_ws, Target="TOF")
        rebinned_ws = mantid.Rebin(InputWorkspace=rebinned_ws, Params=tof_rebin_param)

        rebinned_ws = mantid.ConvertUnits(InputWorkspace=rebinned_ws, Target=return_units)

        common.remove_intermediate_workspace(vanadium_ws)
        vanadium_ws = rebinned_ws
        return vanadium_ws
Пример #21
0
def _divide_by_vanadium_splines(spectra_list, spline_file_path):
    vanadium_ws_list = mantid.LoadNexus(Filename=spline_file_path)
    output_list = []
    for data_ws, van_ws in zip(spectra_list, vanadium_ws_list[1:]):
        vanadium_ws = mantid.RebinToWorkspace(WorkspaceToRebin=van_ws,
                                              WorkspaceToMatch=data_ws)
        output_ws = mantid.Divide(LHSWorkspace=data_ws,
                                  RHSWorkspace=vanadium_ws,
                                  OutputWorkspace=data_ws)
        output_list.append(output_ws)
        common.remove_intermediate_workspace(vanadium_ws)
    return output_list
Пример #22
0
    def _normalise_ws_current(self, ws_to_correct):
        monitor_spectra = self._inst_settings.monitor_spec_no

        monitor_ws = common.extract_single_spectrum(ws_to_process=ws_to_correct,
                                                    spectrum_number_to_extract=monitor_spectra)

        normalised_ws = pearl_algs.normalise_ws_current(ws_to_correct=ws_to_correct, monitor_ws=monitor_ws,
                                                        spline_coeff=self._inst_settings.monitor_spline,
                                                        integration_range=self._inst_settings.monitor_integration_range,
                                                        lambda_values=self._inst_settings.monitor_lambda,
                                                        ex_regions=self._inst_settings.monitor_mask_regions)
        common.remove_intermediate_workspace(monitor_ws)
        return normalised_ws
Пример #23
0
def attenuate_workspace(attenuation_file_path, ws_to_correct):
    original_units = ws_to_correct.getAxis(0).getUnit().unitID()
    wc_attenuated = mantid.PearlMCAbsorption(attenuation_file_path)
    wc_attenuated = mantid.ConvertToHistogram(InputWorkspace=wc_attenuated, OutputWorkspace=wc_attenuated)
    ws_to_correct = mantid.ConvertUnits(InputWorkspace=ws_to_correct, OutputWorkspace=ws_to_correct,
                                        Target=wc_attenuated.getAxis(0).getUnit().unitID())
    wc_attenuated = mantid.RebinToWorkspace(WorkspaceToRebin=wc_attenuated, WorkspaceToMatch=ws_to_correct,
                                            OutputWorkspace=wc_attenuated)
    pearl_attenuated_ws = mantid.Divide(LHSWorkspace=ws_to_correct, RHSWorkspace=wc_attenuated)
    common.remove_intermediate_workspace(workspaces=wc_attenuated)
    pearl_attenuated_ws = mantid.ConvertUnits(InputWorkspace=pearl_attenuated_ws, OutputWorkspace=pearl_attenuated_ws,
                                              Target=original_units)
    return pearl_attenuated_ws
Пример #24
0
    def _normalise_ws_current(self, ws_to_correct):
        monitor_spectra = self._inst_settings.monitor_spec_no

        monitor_ws = common.extract_single_spectrum(ws_to_process=ws_to_correct,
                                                    spectrum_number_to_extract=monitor_spectra)

        normalised_ws = pearl_algs.normalise_ws_current(ws_to_correct=ws_to_correct, monitor_ws=monitor_ws,
                                                        spline_coeff=self._inst_settings.monitor_spline,
                                                        integration_range=self._inst_settings.monitor_integration_range,
                                                        lambda_values=self._inst_settings.monitor_lambda,
                                                        ex_regions=self._inst_settings.monitor_mask_regions)
        common.remove_intermediate_workspace(monitor_ws)
        return normalised_ws
Пример #25
0
    def _run_attenuate_workspace(self, input_workspace):
        if self._old_atten_file is None:  # For old API support
            attenuation_path = self._attenuation_full_path
        else:
            attenuation_path = self._old_atten_file

        wc_attenuated = mantid.PearlMCAbsorption(attenuation_path)
        wc_attenuated = mantid.ConvertToHistogram(InputWorkspace=wc_attenuated, OutputWorkspace=wc_attenuated)
        wc_attenuated = mantid.RebinToWorkspace(WorkspaceToRebin=wc_attenuated, WorkspaceToMatch=input_workspace,
                                                OutputWorkspace=wc_attenuated)
        pearl_attenuated_ws = mantid.Divide(LHSWorkspace=input_workspace, RHSWorkspace=wc_attenuated)
        common.remove_intermediate_workspace(workspace_name=wc_attenuated)
        return pearl_attenuated_ws
Пример #26
0
def attenuate_workspace(attenuation_file_path, ws_to_correct):
    original_units = ws_to_correct.getAxis(0).getUnit().unitID()
    wc_attenuated = mantid.PearlMCAbsorption(attenuation_file_path)
    wc_attenuated = mantid.ConvertToHistogram(InputWorkspace=wc_attenuated, OutputWorkspace=wc_attenuated)
    ws_to_correct = mantid.ConvertUnits(InputWorkspace=ws_to_correct, OutputWorkspace=ws_to_correct,
                                        Target=wc_attenuated.getAxis(0).getUnit().unitID())
    wc_attenuated = mantid.RebinToWorkspace(WorkspaceToRebin=wc_attenuated, WorkspaceToMatch=ws_to_correct,
                                            OutputWorkspace=wc_attenuated)
    pearl_attenuated_ws = mantid.Divide(LHSWorkspace=ws_to_correct, RHSWorkspace=wc_attenuated)
    common.remove_intermediate_workspace(workspaces=wc_attenuated)
    pearl_attenuated_ws = mantid.ConvertUnits(InputWorkspace=pearl_attenuated_ws, OutputWorkspace=pearl_attenuated_ws,
                                              Target=original_units)
    return pearl_attenuated_ws
Пример #27
0
def generate_vanadium_absorb_corrections(van_ws, output_filename):
    shape_ws = mantid.CloneWorkspace(InputWorkspace=van_ws)
    shape_ws = mantid.ConvertUnits(InputWorkspace=shape_ws, OutputWorkspace=shape_ws, Target="Wavelength")
    mantid.CreateSampleShape(InputWorkspace=shape_ws, ShapeXML='<sphere id="sphere_1"> <centre x="0" y="0" z= "0" />\
                                                      <radius val="0.005" /> </sphere>')

    absorb_ws = \
        mantid.AbsorptionCorrection(InputWorkspace=shape_ws, AttenuationXSection="5.08",
                                    ScatteringXSection="5.1", SampleNumberDensity="0.072",
                                    NumberOfWavelengthPoints="25", ElementSize="0.05")
    mantid.SaveNexus(Filename=output_filename,
                     InputWorkspace=absorb_ws, Append=False)
    common.remove_intermediate_workspace(shape_ws)
    return absorb_ws
Пример #28
0
    def create_solid_angle_corrections(self, vanadium, run_details):
        """
        Creates the solid angle corrections from a vanadium run, only applicable on HRPD otherwise return None
        :param vanadium: The vanadium used to create this
        :param run_details: the run details of to use
        """
        if not self._inst_settings.do_solid_angle:
            return
        solid_angle = mantid.SolidAngle(InputWorkspace=vanadium)

        scale = mantid.CreateSingleValuedWorkspace(DataValue='100')
        correction = mantid.Multiply(LHSWorkspace=solid_angle,
                                     RHSWorkspace=scale)

        eff = mantid.Divide(LHSWorkspace=vanadium, RHSWorkspace=correction)
        eff = mantid.ConvertUnits(InputWorkspace=eff, Target='Wavelength')
        eff = mantid.Integration(InputWorkspace=eff,
                                 RangeLower='1.3999999999999999',
                                 RangeUpper='3')

        correction = mantid.Multiply(LHSWorkspace=correction, RHSWorkspace=eff)
        scale = mantid.CreateSingleValuedWorkspace(DataValue='100000')
        correction = mantid.Divide(LHSWorkspace=correction, RHSWorkspace=scale)

        name = "sac" + common.generate_splined_name(run_details.run_number, [])
        path = run_details.van_paths

        mantid.SaveNexus(InputWorkspace=correction,
                         Filename=os.path.join(path, name))

        common.remove_intermediate_workspace(solid_angle)
        common.remove_intermediate_workspace(scale)
        common.remove_intermediate_workspace(eff)
        common.remove_intermediate_workspace(correction)
Пример #29
0
    def apply_solid_angle_efficiency_corr(self, ws_to_correct, run_details):
        if not self._apply_solid_angle:
            return ws_to_correct

        if not run_details or not os.path.isfile(run_details.solid_angle_corr):
            corrections = self.generate_solid_angle_corrections(run_details)
        else:
            corrections = mantid.Load(Filename=run_details.solid_angle_corr)

        corrected_ws = mantid.Divide(LHSWorkspace=ws_to_correct, RHSWorkspace=corrections)
        common.remove_intermediate_workspace(corrections)
        common.remove_intermediate_workspace(ws_to_correct)
        ws_to_correct = corrected_ws
        return ws_to_correct
Пример #30
0
def _apply_absorb_corrections(instrument, run_details, corrected_van_ws, gen_absorb):
    corrected_van_ws = mantid.ConvertUnits(InputWorkspace=corrected_van_ws, Target="Wavelength")

    if gen_absorb or not run_details.vanadium_absorption:
        absorb_ws = instrument._generate_vanadium_absorb_corrections(run_details, corrected_van_ws)
    else:
        absorb_ws = mantid.LoadNexus(Filename=run_details.vanadium_absorption)

    # PEARL rebins whilst POLARIS does not as some of the older absorption files have different number of bins
    corrected_van_ws = instrument._calibration_rebin_to_workspace(ws_to_rebin=corrected_van_ws, ws_to_match=absorb_ws)
    corrected_van_ws = mantid.Divide(LHSWorkspace=corrected_van_ws, RHSWorkspace=absorb_ws)
    corrected_van_ws = mantid.ConvertUnits(InputWorkspace=corrected_van_ws, Target="dSpacing")
    common.remove_intermediate_workspace(absorb_ws)
    return corrected_van_ws
Пример #31
0
def generate_vanadium_absorb_corrections(van_ws, output_filename):
    shape_ws = mantid.CloneWorkspace(InputWorkspace=van_ws)
    shape_ws = mantid.ConvertUnits(InputWorkspace=shape_ws, OutputWorkspace=shape_ws, Target="Wavelength")
    mantid.CreateSampleShape(InputWorkspace=shape_ws, ShapeXML='<sphere id="sphere_1"> <centre x="0" y="0" z= "0" />\
                                                      <radius val="0.005" /> </sphere>')

    absorb_ws = \
        mantid.AbsorptionCorrection(InputWorkspace=shape_ws, AttenuationXSection="5.08",
                                    ScatteringXSection="5.1", SampleNumberDensity="0.072",
                                    NumberOfWavelengthPoints="25", ElementSize="0.05")
    mantid.SaveNexus(Filename=output_filename,
                     InputWorkspace=absorb_ws, Append=False)
    common.remove_intermediate_workspace(shape_ws)
    return absorb_ws
Пример #32
0
def create_van(instrument, run_details, absorb):
    """
    Creates a splined vanadium run for the following instrument. Requires the run_details for the
    vanadium workspace we will process and whether to apply absorption corrections.
    :param instrument: The instrument object that will be used to supply various instrument specific methods
    :param run_details: The run details associated with this vanadium run
    :param absorb: Boolean flag whether to apply absorption corrections
    :return: Processed workspace group in dSpacing (but not splined)
    """
    van = run_details.vanadium_run_numbers
    # Always sum a range of inputs as its a vanadium run over multiple captures
    input_van_ws_list = common.load_current_normalised_ws_list(
        run_number_string=van,
        instrument=instrument,
        input_batching=INPUT_BATCHING.Summed)
    input_van_ws = input_van_ws_list[
        0]  # As we asked for a summed ws there should only be one returned

    corrected_van_ws = common.subtract_summed_runs(
        ws_to_correct=input_van_ws,
        empty_sample_ws_string=run_details.empty_runs,
        instrument=instrument)

    # Crop the tail end of the data on PEARL if they are not capturing slow neutrons
    corrected_van_ws = instrument._crop_raw_to_expected_tof_range(
        ws_to_crop=corrected_van_ws)

    if absorb:
        corrected_van_ws = instrument._apply_absorb_corrections(
            run_details=run_details, ws_to_correct=corrected_van_ws)

    aligned_ws = mantid.AlignDetectors(
        InputWorkspace=corrected_van_ws,
        CalibrationFile=run_details.offset_file_path)
    focused_vanadium = mantid.DiffractionFocussing(
        InputWorkspace=aligned_ws,
        GroupingFileName=run_details.grouping_file_path)

    focused_spectra = common.extract_ws_spectra(focused_vanadium)
    focused_spectra = instrument._crop_van_to_expected_tof_range(
        focused_spectra)

    d_spacing_group, tof_group = instrument._output_focused_ws(
        processed_spectra=focused_spectra,
        run_details=run_details,
        output_mode="mods")

    _create_vanadium_splines(focused_spectra, instrument, run_details)

    common.keep_single_ws_unit(d_spacing_group=d_spacing_group,
                               tof_group=tof_group,
                               unit_to_keep=instrument._get_unit_to_keep())

    common.remove_intermediate_workspace(corrected_van_ws)
    common.remove_intermediate_workspace(aligned_ws)
    common.remove_intermediate_workspace(focused_vanadium)
    common.remove_intermediate_workspace(focused_spectra)

    return d_spacing_group
Пример #33
0
def _divide_by_vanadium_splines(spectra_list, vanadium_splines, instrument):
    if hasattr(vanadium_splines, "OutputWorkspace"):
        vanadium_splines = vanadium_splines.OutputWorkspace
    if type(vanadium_splines) is WorkspaceGroup:  # vanadium splines is a workspacegroup
        num_splines = len(vanadium_splines)
        num_spectra = len(spectra_list)
        if num_splines != num_spectra:
            raise RuntimeError("Mismatch between number of banks in vanadium and number of banks in workspace to focus"
                               "\nThere are {} banks for vanadium but {} for the run".format(num_splines, num_spectra))
        output_list = [_divide_one_spectrum_by_spline(data_ws, van_ws, instrument)
                       for data_ws, van_ws in zip(spectra_list, vanadium_splines)]
        return output_list
    output_list = [_divide_one_spectrum_by_spline(spectra_list[0], vanadium_splines, instrument)]
    common.remove_intermediate_workspace(vanadium_splines)
    return output_list
Пример #34
0
def apply_vanadium_absorb_corrections(van_ws, run_details, absorb_ws=None):

    def generate_det_id_list(ws):
        det_id_list = []
        for i in range(0, ws.getNumberHistograms()):
            try:
                det_ids = ws.getSpectrum(i).getDetectorIDs()

            except RuntimeError:
                pass
            else:
                for det_id in det_ids:
                    det_id_list.append(det_id)
        return det_id_list

    if absorb_ws is None:
        absorb_ws = mantid.Load(Filename=run_details.vanadium_absorption_path)

    van_original_units = van_ws.getAxis(0).getUnit().unitID()
    absorb_units = absorb_ws.getAxis(0).getUnit().unitID()
    if van_original_units != absorb_units:
        van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=absorb_units, OutputWorkspace=van_ws)

    # PEARL sometimes do special runs with different detector cards so extract common spectra before doing
    # RebinToWorkspace to ensure histogram by histogram by rebin
    abs_det_id_list = generate_det_id_list(absorb_ws)
    van_det_id_list = generate_det_id_list(van_ws)

    common_det_ids = [det_id for det_id in abs_det_id_list if det_id in van_det_id_list]
    if not common_det_ids:
        raise RuntimeError("No common detectors in Vanadium and sample workspaces")

    MSG_STEM = "Vanadium workspace and absorption workspaces have different spectra. "
    if common_det_ids != van_det_id_list:
        logger.warning(MSG_STEM + "Removing unmatched spectra from the Vanadium workspace")
        van_ws = mantid.ExtractSpectra(InputWorkspace=van_ws, DetectorList=common_det_ids)
    if common_det_ids != abs_det_id_list:
        logger.warning(MSG_STEM + "Removing unmatched spectra from the absorption workspace")
        absorb_ws = mantid.ExtractSpectra(InputWorkspace=absorb_ws, DetectorList=common_det_ids)

    absorb_ws = mantid.RebinToWorkspace(WorkspaceToRebin=absorb_ws, WorkspaceToMatch=van_ws, OutputWorkspace=absorb_ws)
    van_ws = mantid.Divide(LHSWorkspace=van_ws, RHSWorkspace=absorb_ws, OutputWorkspace=van_ws, AllowDifferentNumberSpectra=True)

    if van_original_units != absorb_units:
        van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=van_original_units, OutputWorkspace=van_ws)

    common.remove_intermediate_workspace(absorb_ws)
    return van_ws
Пример #35
0
    def _generate_vanadium_absorb_corrections(self, calibration_full_paths, ws_to_match):
        raise NotImplementedError("Generating absorption corrections needs to be implemented correctly")

        # TODO are these values applicable to all instruments
        shape_ws = mantid.CloneWorkspace(InputWorkspace=ws_to_match)
        mantid.CreateSampleShape(InputWorkspace=shape_ws, ShapeXML='<sphere id="sphere_1"> <centre x="0" y="0" z= "0" />\
                                                          <radius val="0.005" /> </sphere>')

        absorb_ws = \
            mantid.AbsorptionCorrection(InputWorkspace=shape_ws, AttenuationXSection="5.08",
                                        ScatteringXSection="5.1", SampleNumberDensity="0.072",
                                        NumberOfWavelengthPoints="25", ElementSize="0.05")
        mantid.SaveNexus(Filename=calibration_full_paths["vanadium_absorption"],
                         InputWorkspace=absorb_ws, Append=False)
        common.remove_intermediate_workspace(shape_ws)
        return absorb_ws
Пример #36
0
def generate_vanadium_absorb_corrections(van_ws):
    raise NotImplementedError("Generating absorption corrections needs to be implemented correctly")

    # TODO are these values applicable to all instruments
    shape_ws = mantid.CloneWorkspace(InputWorkspace=van_ws)
    mantid.CreateSampleShape(InputWorkspace=shape_ws, ShapeXML='<sphere id="sphere_1"> <centre x="0" y="0" z= "0" />\
                                                      <radius val="0.005" /> </sphere>')

    calibration_full_paths = None
    absorb_ws = \
        mantid.AbsorptionCorrection(InputWorkspace=shape_ws, AttenuationXSection="5.08",
                                    ScatteringXSection="5.1", SampleNumberDensity="0.072",
                                    NumberOfWavelengthPoints="25", ElementSize="0.05")
    mantid.SaveNexus(Filename=calibration_full_paths["vanadium_absorption"],
                     InputWorkspace=absorb_ws, Append=False)
    common.remove_intermediate_workspace(shape_ws)
    return absorb_ws
Пример #37
0
def apply_vanadium_absorb_corrections(van_ws, run_details, absorb_ws=None):
    if absorb_ws is None:
        absorb_ws = mantid.Load(Filename=run_details.vanadium_absorption_path)

    van_original_units = van_ws.getAxis(0).getUnit().unitID()
    absorb_units = absorb_ws.getAxis(0).getUnit().unitID()
    if van_original_units != absorb_units:
        van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=absorb_units, OutputWorkspace=van_ws)

    absorb_ws = mantid.RebinToWorkspace(WorkspaceToRebin=absorb_ws, WorkspaceToMatch=van_ws, OutputWorkspace=absorb_ws)
    van_ws = mantid.Divide(LHSWorkspace=van_ws, RHSWorkspace=absorb_ws, OutputWorkspace=van_ws)

    if van_original_units != absorb_units:
        van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=van_original_units, OutputWorkspace=van_ws)

    common.remove_intermediate_workspace(absorb_ws)
    return van_ws
Пример #38
0
def _spline_new2_background(in_workspace, num_splines, instrument_version):
    # remove bragg peaks before spline
    alg_range, unused = _get_instrument_ranges(instrument_version)
    van_stripped_ws = _strip_peaks_new_inst(in_workspace, alg_range)

    # run twice on low angle as peaks are very broad
    for i in range(0, 2):
        van_stripped_ws = mantid.StripPeaks(InputWorkspace=van_stripped_ws, FWHM=100, Tolerance=10,
                                            WorkspaceIndex=12)
        van_stripped_ws = mantid.StripPeaks(InputWorkspace=van_stripped_ws, FWHM=60, Tolerance=10,
                                            WorkspaceIndex=13)

    van_stripped_ws = mantid.ConvertUnits(InputWorkspace=van_stripped_ws, Target="TOF")

    splined_ws_list = _perform_spline_range(instrument_version, num_splines, van_stripped_ws)
    common.remove_intermediate_workspace(van_stripped_ws)
    return splined_ws_list
Пример #39
0
def generate_ts_pdf(run_number, focus_file_path, merge_banks=False, q_lims=None, cal_file_name=None,
                    sample_details=None, output_binning=None, pdf_type="G(r)", freq_params=None):
    focused_ws = _obtain_focused_run(run_number, focus_file_path)
    focused_ws = mantid.ConvertUnits(InputWorkspace=focused_ws, Target="MomentumTransfer", EMode='Elastic')

    raw_ws = mantid.Load(Filename='POLARIS'+str(run_number)+'.nxs')
    sample_geometry = common.generate_sample_geometry(sample_details)
    sample_material = common.generate_sample_material(sample_details)
    self_scattering_correction = mantid.TotScatCalculateSelfScattering(InputWorkspace=raw_ws,
                                                                       CalFileName=cal_file_name,
                                                                       SampleGeometry=sample_geometry,
                                                                       SampleMaterial=sample_material)

    ws_group_list = []
    for i in range(self_scattering_correction.getNumberHistograms()):
        ws_name = 'correction_' + str(i)
        mantid.ExtractSpectra(InputWorkspace=self_scattering_correction, OutputWorkspace=ws_name,
                              WorkspaceIndexList=[i])
        ws_group_list.append(ws_name)
    self_scattering_correction = mantid.GroupWorkspaces(InputWorkspaces=ws_group_list)
    self_scattering_correction = mantid.RebinToWorkspace(WorkspaceToRebin=self_scattering_correction,
                                                         WorkspaceToMatch=focused_ws)
    focused_ws = mantid.Subtract(LHSWorkspace=focused_ws, RHSWorkspace=self_scattering_correction)

    if merge_banks:
        q_min, q_max = _load_qlims(q_lims)
        merged_ws = mantid.MatchAndMergeWorkspaces(InputWorkspaces=focused_ws, XMin=q_min, XMax=q_max,
                                                   CalculateScale=False)
        fast_fourier_filter(merged_ws, freq_params)
        pdf_output = mantid.PDFFourierTransform(Inputworkspace="merged_ws", InputSofQType="S(Q)-1", PDFType=pdf_type,
                                                Filter=True)
    else:
        for ws in focused_ws:
            fast_fourier_filter(ws, freq_params)
        pdf_output = mantid.PDFFourierTransform(Inputworkspace='focused_ws', InputSofQType="S(Q)-1",
                                                PDFType=pdf_type, Filter=True)
        pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output, WorkspaceToMatch=pdf_output[4],
                                             PreserveEvents=True)
    common.remove_intermediate_workspace('self_scattering_correction')
    if output_binning is not None:
        try:
            pdf_output = mantid.Rebin(InputWorkspace=pdf_output, Params=output_binning)
        except RuntimeError:
            return pdf_output
    return pdf_output
Пример #40
0
    def _spline_background(self, focused_vanadium_ws, spline_number, instrument_version=''):

        if spline_number is None:
            spline_number = 100

        mode = "spline"  # TODO support spline modes for all instruments
        extracted_spectra = _extract_bank_spectra(focused_vanadium_ws, self._number_of_banks)

        if mode == "spline":
            output = self._mask_spline_vanadium_ws(vanadium_spectra_list=extracted_spectra,
                                                   spline_coefficient=spline_number)
        else:
            raise NotImplementedError("Other vanadium processing methods not yet implemented")

        for ws in extracted_spectra:
            common.remove_intermediate_workspace(ws)

        return output
Пример #41
0
def normalise_ws_current(ws_to_correct, monitor_ws, spline_coeff,
                         lambda_values, integration_range):
    processed_monitor_ws = mantid.ConvertUnits(InputWorkspace=monitor_ws,
                                               Target="Wavelength")
    processed_monitor_ws = mantid.CropWorkspace(
        InputWorkspace=processed_monitor_ws,
        XMin=lambda_values[0],
        XMax=lambda_values[-1])
    # TODO move these masks to the adv. config file
    ex_regions = numpy.zeros((2, 4))
    ex_regions[:, 0] = [3.45, 3.7]
    ex_regions[:, 1] = [2.96, 3.2]
    ex_regions[:, 2] = [2.1, 2.26]
    ex_regions[:, 3] = [1.73, 1.98]

    for reg in range(0, 4):
        processed_monitor_ws = mantid.MaskBins(
            InputWorkspace=processed_monitor_ws,
            XMin=ex_regions[0, reg],
            XMax=ex_regions[1, reg])

    splined_monitor_ws = mantid.SplineBackground(
        InputWorkspace=processed_monitor_ws,
        WorkspaceIndex=0,
        NCoeff=spline_coeff)

    normalised_ws = mantid.ConvertUnits(InputWorkspace=ws_to_correct,
                                        Target="Wavelength",
                                        OutputWorkspace=ws_to_correct)
    normalised_ws = mantid.NormaliseToMonitor(
        InputWorkspace=normalised_ws,
        MonitorWorkspace=splined_monitor_ws,
        IntegrationRangeMin=integration_range[0],
        IntegrationRangeMax=integration_range[-1],
        OutputWorkspace=normalised_ws)

    normalised_ws = mantid.ConvertUnits(InputWorkspace=normalised_ws,
                                        Target="TOF",
                                        OutputWorkspace=normalised_ws)

    common.remove_intermediate_workspace(processed_monitor_ws)
    common.remove_intermediate_workspace(splined_monitor_ws)

    return normalised_ws
Пример #42
0
def create_calibration(calibration_runs, instrument, offset_file_name, grouping_file_name, calibration_dir,
                       rebin_1_params, rebin_2_params, cross_correlate_params, get_det_offset_params):
    """
    Create a calibration file from (usually) a ceria run
    :param calibration_runs: Run number(s) for this run
    :param instrument: The PEARL instrument object
    :param offset_file_name: Name of the file to write detector offset information to
    :param grouping_file_name: Name of grouping calibration file
    :param calibration_dir: Path to directory containing calibration information
    :param rebin_1_params: Parameters for the first rebin step (as a string in the usual format)
    :param rebin_2_params: Parameters for the second rebin step (as a string in the usual format)
    :param cross_correlate_params: Parameters for CrossCorrelate (as a dictionary PropertyName: PropertyValue)
    :param get_det_offset_params: Parameters for GetDetectorOffsets (as a dictionary PropertyName: PropertyValue)
    """
    input_ws_list = common.load_current_normalised_ws_list(run_number_string=calibration_runs, instrument=instrument,
                                                           input_batching=INPUT_BATCHING.Summed)

    input_ws = input_ws_list[0]
    calibration_ws = mantid.Rebin(InputWorkspace=input_ws, Params=rebin_1_params)

    if calibration_ws.getAxis(0).getUnit().unitID() != WORKSPACE_UNITS.d_spacing:
        calibration_ws = mantid.ConvertUnits(InputWorkspace=calibration_ws, Target="dSpacing")

    rebinned = mantid.Rebin(InputWorkspace=calibration_ws, Params=rebin_2_params)
    cross_correlated = mantid.CrossCorrelate(InputWorkspace=rebinned, **cross_correlate_params)

    offset_file = os.path.join(calibration_dir, offset_file_name)
    # Offsets workspace must be referenced as string so it can be deleted, as simpleapi doesn't recognise it as a ws
    offsets_ws_name = "offsets"
    mantid.GetDetectorOffsets(InputWorkspace=cross_correlated, GroupingFileName=offset_file,
                              OutputWorkspace=offsets_ws_name, **get_det_offset_params)

    rebinned_tof = mantid.ConvertUnits(InputWorkspace=rebinned, Target="TOF")
    aligned = mantid.AlignDetectors(InputWorkspace=rebinned_tof, CalibrationFile=offset_file)

    grouping_file = os.path.join(calibration_dir, grouping_file_name)
    focused = mantid.DiffractionFocussing(InputWorkspace=aligned, GroupingFileName=grouping_file,
                                          OutputWorkspace=instrument._generate_output_file_name(calibration_runs)
                                          + "_grouped")

    common.remove_intermediate_workspace([calibration_ws, rebinned, cross_correlated, rebinned_tof, aligned,
                                          offsets_ws_name])
    return focused
Пример #43
0
    def _do_silicon_calibration(self, runs_to_process, cal_file_name, grouping_file_name):
        # TODO fix all of this as the script is too limited to be useful
        create_si_ws = common.load_current_normalised_ws(run_number_string=runs_to_process, instrument=self)
        cycle_details = self._get_label_information(runs_to_process)
        instrument_version = cycle_details["instrument_version"]

        if instrument_version == "new" or instrument_version == "new2":
            create_si_ws = mantid.Rebin(InputWorkspace=create_si_ws, Params="100,-0.0006,19950")

        create_si_d_spacing_ws = mantid.ConvertUnits(InputWorkspace=create_si_ws, Target="dSpacing")

        if instrument_version == "new2":
            create_si_d_spacing_rebin_ws = mantid.Rebin(InputWorkspace=create_si_d_spacing_ws, Params="1.71,0.002,2.1")
            create_si_cross_corr_ws = mantid.CrossCorrelate(InputWorkspace=create_si_d_spacing_rebin_ws,
                                                            ReferenceSpectra=20, WorkspaceIndexMin=9,
                                                            WorkspaceIndexMax=1063, XMin=1.71, XMax=2.1)
        elif instrument_version == "new":
            create_si_d_spacing_rebin_ws = mantid.Rebin(InputWorkspace=create_si_d_spacing_ws, Params="1.85,0.002,2.05")
            create_si_cross_corr_ws = mantid.CrossCorrelate(InputWorkspace=create_si_d_spacing_rebin_ws,
                                                            ReferenceSpectra=20, WorkspaceIndexMin=9,
                                                            WorkspaceIndexMax=943, XMin=1.85, XMax=2.05)
        elif instrument_version == "old":
            create_si_d_spacing_rebin_ws = mantid.Rebin(InputWorkspace=create_si_d_spacing_ws, Params="3,0.002,3.2")
            create_si_cross_corr_ws = mantid.CrossCorrelate(InputWorkspace=create_si_d_spacing_rebin_ws,
                                                            ReferenceSpectra=500, WorkspaceIndexMin=1,
                                                            WorkspaceIndexMax=1440, XMin=3, XMax=3.2)
        else:
            raise NotImplementedError("The instrument version is not supported for creating a silicon calibration")

        common.remove_intermediate_workspace(create_si_d_spacing_ws)
        common.remove_intermediate_workspace(create_si_d_spacing_rebin_ws)

        calibration_output_path = self.calibration_dir + cal_file_name
        create_si_offsets_ws = mantid.GetDetectorOffsets(InputWorkspace=create_si_cross_corr_ws,
                                                         Step=0.002, DReference=1.920127251, XMin=-200, XMax=200,
                                                         GroupingFileName=calibration_output_path)
        create_si_aligned_ws = mantid.AlignDetectors(InputWorkspace=create_si_ws,
                                                     CalibrationFile=calibration_output_path)
        grouping_output_path = self.calibration_dir + grouping_file_name
        create_si_grouped_ws = mantid.DiffractionFocussing(InputWorkspace=create_si_aligned_ws,
                                                           GroupingFileName=grouping_output_path)
        del create_si_offsets_ws, create_si_grouped_ws
Пример #44
0
def generate_ts_pdf(run_number,
                    focus_file_path,
                    merge_banks=False,
                    q_lims=None):
    focused_ws = _obtain_focused_run(run_number, focus_file_path)

    if merge_banks:
        pdf_output = _generate_grouped_ts_pdf(focused_ws, q_lims)
    else:
        focused_ws = mantid.ConvertUnits(InputWorkspace=focused_ws.name(),
                                         Target="MomentumTransfer")
        pdf_output = mantid.PDFFourierTransform(Inputworkspace=focused_ws,
                                                InputSofQType="S(Q)",
                                                PDFType="G(r)",
                                                Filter=True)
        pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output,
                                             WorkspaceToMatch=pdf_output[4],
                                             PreserveEvents=True)
    common.remove_intermediate_workspace('focused_ws')
    return pdf_output
Пример #45
0
    def correct_sample_vanadium(self, focused_ws, index, vanadium_ws=None):
        data_ws = mantid.ExtractSingleSpectrum(InputWorkspace=focused_ws, WorkspaceIndex=index)
        data_ws = mantid.ConvertUnits(InputWorkspace=data_ws, Target="TOF")
        data_ws = mantid.Rebin(InputWorkspace=data_ws, Params=self._focus_tof_binning)

        if vanadium_ws:
            data_processed = "van_processed" + str(index)  # Workaround for Mantid overwriting the WS in a loop
            vanadium_ws = mantid.Rebin(InputWorkspace=vanadium_ws, Params=self._focus_tof_binning)
            data_ws = mantid.Divide(LHSWorkspace=data_ws, RHSWorkspace=vanadium_ws, OutputWorkspace=data_processed)
        else:
            data_processed = "processed-" + str(index)

        mantid.CropWorkspace(InputWorkspace=data_ws, XMin=0.1, OutputWorkspace=data_processed)

        if vanadium_ws:
            mantid.Scale(InputWorkspace=data_processed, Factor=10, OutputWorkspace=data_processed)

        common.remove_intermediate_workspace(data_ws)

        return data_processed
Пример #46
0
def _divide_by_vanadium_splines(spectra_list, spline_file_path):
    vanadium_splines = mantid.LoadNexus(Filename=spline_file_path)

    if hasattr(vanadium_splines, "OutputWorkspace"):  # vanadium_splines is a group
        vanadium_splines = vanadium_splines.OutputWorkspace

        num_splines = len(vanadium_splines)
        num_spectra = len(spectra_list)

        if num_splines != num_spectra:
            raise RuntimeError("Mismatch between number of banks in vanadium and number of banks in workspace to focus"
                               "\nThere are {} banks for vanadium but {} for the run".format(num_splines, num_spectra))

        output_list = [_divide_one_spectrum_by_spline(data_ws, van_ws)
                       for data_ws, van_ws in zip(spectra_list, vanadium_splines)]
        return output_list

    output_list = [_divide_one_spectrum_by_spline(spectra_list[0], vanadium_splines)]
    common.remove_intermediate_workspace(vanadium_splines)
    return output_list
Пример #47
0
def _divide_sample_by_vanadium(instrument, run_number, input_workspace, perform_vanadium_norm):
    processed_spectra = []

    run_details = instrument._get_run_details(run_number=run_number)

    alg_range, save_range = instrument._get_instrument_alg_save_ranges(run_details.instrument_version)

    for index in range(0, alg_range):
        if perform_vanadium_norm:
            vanadium_ws = mantid.LoadNexus(Filename=run_details.splined_vanadium, EntryNumber=index + 1)

            processed_spectra.append(
                instrument.correct_sample_vanadium(focused_ws=input_workspace, index=index, vanadium_ws=vanadium_ws))

            common.remove_intermediate_workspace(vanadium_ws)
        else:
            processed_spectra.append(
                instrument.correct_sample_vanadium(focused_ws=input_workspace, index=index))

    return processed_spectra
Пример #48
0
def create_van(instrument, run_details, absorb):
    """
    Creates a splined vanadium run for the following instrument. Requires the run_details for the
    vanadium workspace we will process and whether to apply absorption corrections.
    :param instrument: The instrument object that will be used to supply various instrument specific methods
    :param run_details: The run details associated with this vanadium run
    :param absorb: Boolean flag whether to apply absorption corrections
    :return: Processed workspace group in dSpacing (but not splined)
    """
    van = run_details.vanadium_run_numbers
    # Always sum a range of inputs as its a vanadium run over multiple captures
    input_van_ws_list = common.load_current_normalised_ws_list(run_number_string=van, instrument=instrument,
                                                               input_batching=INPUT_BATCHING.Summed)
    input_van_ws = input_van_ws_list[0]  # As we asked for a summed ws there should only be one returned

    corrected_van_ws = common.subtract_summed_runs(ws_to_correct=input_van_ws,
                                                   empty_sample_ws_string=run_details.empty_runs,
                                                   instrument=instrument)

    # Crop the tail end of the data on PEARL if they are not capturing slow neutrons
    corrected_van_ws = instrument._crop_raw_to_expected_tof_range(ws_to_crop=corrected_van_ws)

    if absorb:
        corrected_van_ws = instrument._apply_absorb_corrections(run_details=run_details,
                                                                ws_to_correct=corrected_van_ws)
    else:
        # Assume that create_van only uses Vanadium runs
        mantid.SetSampleMaterial(InputWorkspace=corrected_van_ws, ChemicalFormula='V')

    aligned_ws = mantid.AlignDetectors(InputWorkspace=corrected_van_ws,
                                       CalibrationFile=run_details.offset_file_path)
    focused_vanadium = mantid.DiffractionFocussing(InputWorkspace=aligned_ws,
                                                   GroupingFileName=run_details.grouping_file_path)

    focused_spectra = common.extract_ws_spectra(focused_vanadium)
    focused_spectra = instrument._crop_van_to_expected_tof_range(focused_spectra)

    d_spacing_group, tof_group = instrument._output_focused_ws(processed_spectra=focused_spectra,
                                                               run_details=run_details)

    _create_vanadium_splines(focused_spectra, instrument, run_details)

    common.keep_single_ws_unit(d_spacing_group=d_spacing_group, tof_group=tof_group,
                               unit_to_keep=instrument._get_unit_to_keep())

    common.remove_intermediate_workspace(corrected_van_ws)
    common.remove_intermediate_workspace(aligned_ws)
    common.remove_intermediate_workspace(focused_vanadium)
    common.remove_intermediate_workspace(focused_spectra)

    return d_spacing_group
Пример #49
0
    def _normalise_current_ws(self, ws_to_correct, load_monitor_ws, spline_terms):
        get_monitor_ws = mantid.ConvertUnits(InputWorkspace=load_monitor_ws, Target="Wavelength")
        common.remove_intermediate_workspace(load_monitor_ws)
        lmin, lmax = self._get_lambda_range()
        get_monitor_ws = mantid.CropWorkspace(InputWorkspace=get_monitor_ws, XMin=lmin, XMax=lmax)
        ex_regions = numpy.zeros((2, 4))
        ex_regions[:, 0] = [3.45, 3.7]
        ex_regions[:, 1] = [2.96, 3.2]
        ex_regions[:, 2] = [2.1, 2.26]
        ex_regions[:, 3] = [1.73, 1.98]

        for reg in range(0, 4):
            get_monitor_ws = mantid.MaskBins(InputWorkspace=get_monitor_ws, XMin=ex_regions[0, reg],
                                             XMax=ex_regions[1, reg])

        monitor_ws = mantid.SplineBackground(InputWorkspace=get_monitor_ws, WorkspaceIndex=0, NCoeff=spline_terms)

        normalised_ws = mantid.ConvertUnits(InputWorkspace=ws_to_correct, Target="Wavelength")
        normalised_ws = mantid.NormaliseToMonitor(InputWorkspace=normalised_ws, MonitorWorkspace=monitor_ws,
                                                  IntegrationRangeMin=0.6, IntegrationRangeMax=5.0)
        normalised_ws = mantid.ConvertUnits(InputWorkspace=normalised_ws, Target="TOF")

        common.remove_intermediate_workspace(get_monitor_ws)
        common.remove_intermediate_workspace(monitor_ws)

        return normalised_ws
Пример #50
0
def _focus_mode_groups(cycle_information, output_file_paths, save_range, calibrated_spectra):
    output_list = []
    to_save = _sum_groups_of_three_ws(calibrated_spectra, output_file_paths)

    workspaces_4_to_9_name = output_file_paths["output_name"] + "_mods4-9"
    workspaces_4_to_9 = mantid.Plus(LHSWorkspace=to_save[1], RHSWorkspace=to_save[2])
    workspaces_4_to_9 = mantid.Scale(InputWorkspace=workspaces_4_to_9, Factor=0.5,
                                     OutputWorkspace=workspaces_4_to_9_name)
    to_save.append(workspaces_4_to_9)
    append = False
    index = 1
    for ws in to_save:
        if cycle_information["instrument_version"] == "new":
            mantid.SaveGSS(InputWorkspace=ws, Filename=output_file_paths["gss_filename"], Append=append,
                           Bank=index)
        elif cycle_information["instrument_version"] == "new2":
            mantid.SaveGSS(InputWorkspace=ws, Filename=output_file_paths["gss_filename"], Append=False,
                           Bank=index)

        workspace_names = ws.name()
        dspacing_ws = mantid.ConvertUnits(InputWorkspace=ws, OutputWorkspace=workspace_names, Target="dSpacing")
        common.remove_intermediate_workspace(ws)
        output_list.append(dspacing_ws)
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"], InputWorkspace=dspacing_ws, Append=append)
        append = True
        index += 1

    for i in range(0, save_range):
        monitor_ws_name = output_file_paths["output_name"] + "_mod" + str(i + 10)

        monitor_ws = calibrated_spectra[i + 9]
        to_save = mantid.CloneWorkspace(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws_name)

        mantid.SaveGSS(InputWorkspace=to_save, Filename=output_file_paths["gss_filename"], Append=True, Bank=i + 5)
        to_save = mantid.ConvertUnits(InputWorkspace=to_save, OutputWorkspace=monitor_ws_name, Target="dSpacing")
        mantid.SaveNexus(Filename=output_file_paths["nxs_filename"], InputWorkspace=to_save, Append=True)

        output_list.append(to_save)

    return output_list
Пример #51
0
def _run_focus(instrument, run_number, perform_attenuation, perform_vanadium_norm):
    # Read
    read_ws = common.load_current_normalised_ws(run_number_string=run_number, instrument=instrument)
    input_workspace = instrument._do_tof_rebinning_focus(read_ws)  # Rebins for PEARL

    run_details = instrument._get_run_details(run_number=run_number)

    # Check the necessary splined vanadium file has been created
    if not os.path.isfile(run_details.splined_vanadium):
        raise ValueError("Processed vanadium runs not found at this path: "
                         + str(run_details.splined_vanadium) +
                         " \n\nHave you created a vanadium calibration with these settings yet?")

    # Compensate for empty sample if specified
    input_workspace = common.subtract_sample_empty(ws_to_correct=input_workspace, instrument=instrument,
                                                   empty_sample_ws_string=run_details.sample_empty)

    # Align / Focus
    input_workspace = mantid.AlignDetectors(InputWorkspace=input_workspace,
                                            CalibrationFile=run_details.calibration)

    input_workspace = instrument.apply_solid_angle_efficiency_corr(ws_to_correct=input_workspace,
                                                                   run_details=run_details)

    focused_ws = mantid.DiffractionFocussing(InputWorkspace=input_workspace,
                                             GroupingFileName=run_details.grouping)

    # Process
    rebinning_params = instrument.calculate_focus_binning_params(sample=focused_ws)

    calibrated_spectra = _divide_sample_by_vanadium(instrument=instrument, run_number=run_number,
                                                    input_workspace=focused_ws,
                                                    perform_vanadium_norm=perform_vanadium_norm)

    _apply_binning_to_spectra(spectra_list=calibrated_spectra, binning_list=rebinning_params)

    # Output
    processed_nexus_files = instrument._process_focus_output(calibrated_spectra, run_details=run_details,
                                                             attenuate=perform_attenuation)

    # Tidy
    common.remove_intermediate_workspace(read_ws)
    common.remove_intermediate_workspace(input_workspace)
    common.remove_intermediate_workspace(focused_ws)
    for ws in calibrated_spectra:
        common.remove_intermediate_workspace(ws)
        pass

    return processed_nexus_files
Пример #52
0
def create_van(instrument, van, empty, output_van_file_name, num_of_splines, absorb, gen_absorb):

    input_van_ws = common.load_current_normalised_ws(run_number_string=van, instrument=instrument)
    corrected_van_ws = common.subtract_sample_empty(ws_to_correct=input_van_ws, empty_sample_ws_string=empty,
                                                    instrument=instrument)

    common.remove_intermediate_workspace(input_van_ws)

    run_details = instrument._get_run_details(run_number=van)

    corrected_van_ws = instrument. _apply_van_calibration_tof_rebinning(vanadium_ws=corrected_van_ws,
                                                                        tof_rebin_pass=1, return_units="TOF")

    corrected_van_ws = mantid.AlignDetectors(InputWorkspace=corrected_van_ws,
                                             CalibrationFile=run_details.calibration)

    corrected_van_ws = instrument.apply_solid_angle_efficiency_corr(ws_to_correct=corrected_van_ws,
                                                                    run_details=run_details)
    if absorb:
        corrected_van_ws = _apply_absorb_corrections(instrument=instrument,
                                                     run_details=run_details,
                                                     corrected_van_ws=corrected_van_ws, gen_absorb=gen_absorb)

    focused_van_file = mantid.DiffractionFocussing(InputWorkspace=corrected_van_ws,
                                                   GroupingFileName=run_details.grouping)

    # Optional
    focused_van_file = instrument. _apply_van_calibration_tof_rebinning(vanadium_ws=focused_van_file,
                                                                        tof_rebin_pass=2, return_units="dSpacing")

    common.remove_intermediate_workspace(corrected_van_ws)

    cycle_information = instrument._get_run_details(run_number=van)
    splined_ws_list = instrument._spline_background(focused_van_file, num_of_splines,
                                                    cycle_information.instrument_version)
    # Figure out who will provide the path name
    if instrument._PEARL_filename_is_full_path():
        out_van_file_path = output_van_file_name
    elif output_van_file_name:
        # The user has manually specified the output file
        out_van_file_path = os.path.join(instrument.calibration_dir, output_van_file_name)
    elif run_details.splined_vanadium:
        out_van_file_path = run_details.splined_vanadium
    else:
        raise ValueError("The output name must be manually specified for this instrument/run")

    append = False
    for ws in splined_ws_list:
        mantid.SaveNexus(Filename=out_van_file_path, InputWorkspace=ws, Append=append)
        common.remove_intermediate_workspace(ws)
        append = True

    output_ws = mantid.LoadNexus(Filename=out_van_file_path, OutputWorkspace="Van_data")
    return output_ws
Пример #53
0
def _focus_one_ws(input_workspace,
                  run_number,
                  instrument,
                  perform_vanadium_norm,
                  absorb,
                  sample_details,
                  vanadium_path,
                  empty_can_subtraction_method,
                  paalman_pings_events_per_point=None):
    run_details = instrument._get_run_details(run_number_string=run_number)
    if perform_vanadium_norm:
        _test_splined_vanadium_exists(instrument, run_details)

    # Subtract empty instrument runs, as long as this run isn't an empty, user hasn't turned empty subtraction off, or
    # The user has not supplied a sample empty
    is_run_empty = common.runs_overlap(run_number, run_details.empty_inst_runs)
    summed_empty = None
    if not is_run_empty and instrument.should_subtract_empty_inst(
    ) and not run_details.sample_empty:
        if os.path.isfile(run_details.summed_empty_inst_file_path):
            logger.warning('Pre-summed empty instrument workspace found at ' +
                           run_details.summed_empty_inst_file_path)
            summed_empty = mantid.LoadNexus(
                Filename=run_details.summed_empty_inst_file_path)
        else:
            summed_empty = common.generate_summed_runs(
                empty_sample_ws_string=run_details.empty_inst_runs,
                instrument=instrument)
    elif run_details.sample_empty:
        scale_factor = 1.0
        if empty_can_subtraction_method != 'PaalmanPings':
            scale_factor = instrument._inst_settings.sample_empty_scale
        # Subtract a sample empty if specified ie empty can
        summed_empty = common.generate_summed_runs(
            empty_sample_ws_string=run_details.sample_empty,
            instrument=instrument,
            scale_factor=scale_factor)

    if absorb and empty_can_subtraction_method == 'PaalmanPings':
        if run_details.sample_empty:  # need summed_empty including container
            input_workspace = instrument._apply_paalmanpings_absorb_and_subtract_empty(
                workspace=input_workspace,
                summed_empty=summed_empty,
                sample_details=sample_details,
                paalman_pings_events_per_point=paalman_pings_events_per_point)
            # Crop to largest acceptable TOF range
            input_workspace = instrument._crop_raw_to_expected_tof_range(
                ws_to_crop=input_workspace)
        else:
            raise TypeError(
                "The PaalmanPings absorption method requires 'sample_empty' to be supplied."
            )
    else:
        if summed_empty:
            input_workspace = common.subtract_summed_runs(
                ws_to_correct=input_workspace, empty_sample=summed_empty)
        # Crop to largest acceptable TOF range
        input_workspace = instrument._crop_raw_to_expected_tof_range(
            ws_to_crop=input_workspace)

        if absorb:
            input_workspace = instrument._apply_absorb_corrections(
                run_details=run_details, ws_to_correct=input_workspace)
        else:
            # Set sample material if specified by the user
            if sample_details is not None:
                mantid.SetSample(
                    InputWorkspace=input_workspace,
                    Geometry=sample_details.generate_sample_geometry(),
                    Material=sample_details.generate_sample_material())

    # Align
    mantid.ApplyDiffCal(InstrumentWorkspace=input_workspace,
                        CalibrationFile=run_details.offset_file_path)
    aligned_ws = mantid.ConvertUnits(InputWorkspace=input_workspace,
                                     Target="dSpacing")

    solid_angle = instrument.get_solid_angle_corrections(
        run_details.vanadium_run_numbers, run_details)
    if solid_angle:
        aligned_ws = mantid.Divide(LHSWorkspace=aligned_ws,
                                   RHSWorkspace=solid_angle)
        mantid.DeleteWorkspace(solid_angle)

    # Focus the spectra into banks
    focused_ws = mantid.DiffractionFocussing(
        InputWorkspace=aligned_ws,
        GroupingFileName=run_details.grouping_file_path)

    instrument.apply_calibration_to_focused_data(focused_ws)

    calibrated_spectra = _apply_vanadium_corrections(
        instrument=instrument,
        input_workspace=focused_ws,
        perform_vanadium_norm=perform_vanadium_norm,
        vanadium_splines=vanadium_path)

    output_spectra = instrument._crop_banks_to_user_tof(calibrated_spectra)

    bin_widths = instrument._get_instrument_bin_widths()
    if bin_widths:
        # Reduce the bin width if required on this instrument
        output_spectra = common.rebin_workspace_list(
            workspace_list=output_spectra, bin_width_list=bin_widths)

    # Output
    d_spacing_group, tof_group = instrument._output_focused_ws(
        output_spectra, run_details=run_details)

    common.keep_single_ws_unit(d_spacing_group=d_spacing_group,
                               tof_group=tof_group,
                               unit_to_keep=instrument._get_unit_to_keep())

    # Tidy workspaces from Mantid
    common.remove_intermediate_workspace(input_workspace)
    common.remove_intermediate_workspace(aligned_ws)
    common.remove_intermediate_workspace(focused_ws)
    common.remove_intermediate_workspace(output_spectra)

    return d_spacing_group
Пример #54
0
def create_calibration(self, calibration_runs, offset_file_name,
                       grouping_file_name):
    input_ws_list = common.load_current_normalised_ws_list(
        run_number_string=calibration_runs,
        instrument=self,
        input_batching=INPUT_BATCHING.Summed)
    input_ws = input_ws_list[0]
    run_details = self._get_run_details(calibration_runs)

    if run_details.instrument_version == "new" or run_details.instrument_version == "new2":
        input_ws = mantid.Rebin(InputWorkspace=input_ws,
                                Params="100,-0.0006,19950")

    d_spacing_cal = mantid.ConvertUnits(InputWorkspace=input_ws,
                                        Target="dSpacing")
    d_spacing_cal = mantid.Rebin(InputWorkspace=d_spacing_cal,
                                 Params="1.8,0.002,2.1")

    if run_details.instrument_version == "new2":
        cross_cor_ws = mantid.CrossCorrelate(InputWorkspace=d_spacing_cal,
                                             ReferenceSpectra=20,
                                             WorkspaceIndexMin=9,
                                             WorkspaceIndexMax=1063,
                                             XMin=1.8,
                                             XMax=2.1)

    elif run_details.instrument_version == "new":
        cross_cor_ws = mantid.CrossCorrelate(InputWorkspace=d_spacing_cal,
                                             ReferenceSpectra=20,
                                             WorkspaceIndexMin=9,
                                             WorkspaceIndexMax=943,
                                             XMin=1.8,
                                             XMax=2.1)
    else:
        cross_cor_ws = mantid.CrossCorrelate(InputWorkspace=d_spacing_cal,
                                             ReferenceSpectra=500,
                                             WorkspaceIndexMin=1,
                                             WorkspaceIndexMax=1440,
                                             XMin=1.8,
                                             XMax=2.1)
    if self._old_api_uses_full_paths:  # Workaround for old API setting full paths
        grouping_file_path = grouping_file_name
        offset_file_path = offset_file_name
    else:
        offset_file_path = os.path.join(self.calibration_dir, offset_file_name)
        grouping_file_path = os.path.join(self.calibration_dir,
                                          grouping_file_name)

    # Ceo Cell refined to 5.4102(3) so 220 is 1.912795
    offset_output_path = mantid.GetDetectorOffsets(
        InputWorkspace=cross_cor_ws,
        Step=0.002,
        DReference=1.912795,
        XMin=-200,
        XMax=200,
        GroupingFileName=offset_file_path)
    del offset_output_path  # This isn't used so delete it to keep linters happy
    aligned_ws = mantid.AlignDetectors(InputWorkspace=input_ws,
                                       CalibrationFile=offset_file_path)
    cal_grouped_ws = mantid.DiffractionFocussing(
        InputWorkspace=aligned_ws, GroupingFileName=grouping_file_path)

    common.remove_intermediate_workspace(d_spacing_cal)
    common.remove_intermediate_workspace(cross_cor_ws)
    common.remove_intermediate_workspace(aligned_ws)
    common.remove_intermediate_workspace(cal_grouped_ws)
Пример #55
0
def do_silicon_calibration(self, runs_to_process, cal_file_name,
                           grouping_file_name):
    # TODO fix all of this as the script is too limited to be useful
    create_si_ws = common.load_current_normalised_ws_list(
        run_number_string=runs_to_process, instrument=self)
    cycle_details = self._get_label_information(runs_to_process)
    instrument_version = cycle_details["instrument_version"]

    if instrument_version == "new" or instrument_version == "new2":
        create_si_ws = mantid.Rebin(InputWorkspace=create_si_ws,
                                    Params="100,-0.0006,19950")

    create_si_d_spacing_ws = mantid.ConvertUnits(InputWorkspace=create_si_ws,
                                                 Target="dSpacing")

    if instrument_version == "new2":
        create_si_d_spacing_rebin_ws = mantid.Rebin(
            InputWorkspace=create_si_d_spacing_ws, Params="1.71,0.002,2.1")
        create_si_cross_corr_ws = mantid.CrossCorrelate(
            InputWorkspace=create_si_d_spacing_rebin_ws,
            ReferenceSpectra=20,
            WorkspaceIndexMin=9,
            WorkspaceIndexMax=1063,
            XMin=1.71,
            XMax=2.1)
    elif instrument_version == "new":
        create_si_d_spacing_rebin_ws = mantid.Rebin(
            InputWorkspace=create_si_d_spacing_ws, Params="1.85,0.002,2.05")
        create_si_cross_corr_ws = mantid.CrossCorrelate(
            InputWorkspace=create_si_d_spacing_rebin_ws,
            ReferenceSpectra=20,
            WorkspaceIndexMin=9,
            WorkspaceIndexMax=943,
            XMin=1.85,
            XMax=2.05)
    elif instrument_version == "old":
        create_si_d_spacing_rebin_ws = mantid.Rebin(
            InputWorkspace=create_si_d_spacing_ws, Params="3,0.002,3.2")
        create_si_cross_corr_ws = mantid.CrossCorrelate(
            InputWorkspace=create_si_d_spacing_rebin_ws,
            ReferenceSpectra=500,
            WorkspaceIndexMin=1,
            WorkspaceIndexMax=1440,
            XMin=3,
            XMax=3.2)
    else:
        raise NotImplementedError(
            "The instrument version is not supported for creating a silicon calibration"
        )

    common.remove_intermediate_workspace(create_si_d_spacing_ws)
    common.remove_intermediate_workspace(create_si_d_spacing_rebin_ws)

    calibration_output_path = self.calibration_dir + cal_file_name
    create_si_offsets_ws = mantid.GetDetectorOffsets(
        InputWorkspace=create_si_cross_corr_ws,
        Step=0.002,
        DReference=1.920127251,
        XMin=-200,
        XMax=200,
        GroupingFileName=calibration_output_path)
    create_si_aligned_ws = mantid.AlignDetectors(
        InputWorkspace=create_si_ws, CalibrationFile=calibration_output_path)
    grouping_output_path = self.calibration_dir + grouping_file_name
    create_si_grouped_ws = mantid.DiffractionFocussing(
        InputWorkspace=create_si_aligned_ws,
        GroupingFileName=grouping_output_path)
    del create_si_offsets_ws, create_si_grouped_ws
Пример #56
0
def _focus_one_ws(ws, run_number, instrument, perform_vanadium_norm, absorb):
    run_details = instrument._get_run_details(run_number_string=run_number)
    if perform_vanadium_norm:
        _test_splined_vanadium_exists(instrument, run_details)

    # Subtract empty instrument runs
    input_workspace = common.subtract_summed_runs(
        ws_to_correct=ws,
        instrument=instrument,
        empty_sample_ws_string=run_details.empty_runs)
    # Subtract a sample empty if specified
    if run_details.sample_empty:
        input_workspace = common.subtract_summed_runs(
            ws_to_correct=input_workspace,
            instrument=instrument,
            empty_sample_ws_string=run_details.sample_empty,
            scale_factor=instrument._inst_settings.sample_empty_scale)

    # Crop to largest acceptable TOF range
    input_workspace = instrument._crop_raw_to_expected_tof_range(
        ws_to_crop=input_workspace)

    # Correct for absorption / multiple scattering if required
    if absorb:
        input_workspace = instrument._apply_absorb_corrections(
            run_details=run_details, ws_to_correct=input_workspace)

    # Align
    aligned_ws = mantid.AlignDetectors(
        InputWorkspace=input_workspace,
        CalibrationFile=run_details.offset_file_path)

    # Focus the spectra into banks
    focused_ws = mantid.DiffractionFocussing(
        InputWorkspace=aligned_ws,
        GroupingFileName=run_details.grouping_file_path)

    calibrated_spectra = _apply_vanadium_corrections(
        instrument=instrument,
        run_number=run_number,
        input_workspace=focused_ws,
        perform_vanadium_norm=perform_vanadium_norm)

    output_spectra = instrument._crop_banks_to_user_tof(calibrated_spectra)

    bin_widths = instrument._get_instrument_bin_widths()
    if bin_widths:
        # Reduce the bin width if required on this instrument
        output_spectra = common.rebin_workspace_list(
            workspace_list=output_spectra, bin_width_list=bin_widths)

    # Output
    d_spacing_group, tof_group = instrument._output_focused_ws(
        output_spectra, run_details=run_details)

    common.keep_single_ws_unit(d_spacing_group=d_spacing_group,
                               tof_group=tof_group,
                               unit_to_keep=instrument._get_unit_to_keep())

    # Tidy workspaces from Mantid
    common.remove_intermediate_workspace(input_workspace)
    common.remove_intermediate_workspace(aligned_ws)
    common.remove_intermediate_workspace(focused_ws)
    common.remove_intermediate_workspace(output_spectra)

    return d_spacing_group
Пример #57
0
def create_van(instrument, run_details, absorb):
    """
    Creates a splined vanadium run for the following instrument. Requires the run_details for the
    vanadium workspace we will process and whether to apply absorption corrections.
    :param instrument: The instrument object that will be used to supply various instrument specific methods
    :param run_details: The run details associated with this vanadium run
    :param absorb: Boolean flag whether to apply absorption corrections
    :return: Processed workspace group in dSpacing (but not splined)
    """
    van = run_details.vanadium_run_numbers
    # Always sum a range of inputs as its a vanadium run over multiple captures
    input_van_ws_list = common.load_current_normalised_ws_list(
        run_number_string=van,
        instrument=instrument,
        input_batching=INPUT_BATCHING.Summed)
    input_van_ws = input_van_ws_list[
        0]  # As we asked for a summed ws there should only be one returned

    instrument.create_solid_angle_corrections(input_van_ws, run_details)

    if not (run_details.empty_runs is None):
        summed_empty = common.generate_summed_runs(
            empty_sample_ws_string=run_details.empty_runs,
            instrument=instrument)
        mantid.SaveNexus(Filename=run_details.summed_empty_file_path,
                         InputWorkspace=summed_empty)
        corrected_van_ws = common.subtract_summed_runs(
            ws_to_correct=input_van_ws, empty_sample=summed_empty)

    # Crop the tail end of the data on PEARL if they are not capturing slow neutrons
    corrected_van_ws = instrument._crop_raw_to_expected_tof_range(
        ws_to_crop=corrected_van_ws)

    if absorb:
        corrected_van_ws = instrument._apply_absorb_corrections(
            run_details=run_details, ws_to_correct=corrected_van_ws)
    else:
        # Assume that create_van only uses Vanadium runs
        mantid.SetSampleMaterial(InputWorkspace=corrected_van_ws,
                                 ChemicalFormula='V')

    mantid.ApplyDiffCal(InstrumentWorkspace=corrected_van_ws,
                        CalibrationFile=run_details.offset_file_path)
    aligned_ws = mantid.ConvertUnits(InputWorkspace=corrected_van_ws,
                                     Target="dSpacing")
    solid_angle = instrument.get_solid_angle_corrections(
        run_details.run_number, run_details)
    if solid_angle:
        aligned_ws = mantid.Divide(LHSWorkspace=aligned_ws,
                                   RHSWorkspace=solid_angle)
        mantid.DeleteWorkspace(solid_angle)
    focused_vanadium = mantid.DiffractionFocussing(
        InputWorkspace=aligned_ws,
        GroupingFileName=run_details.grouping_file_path)
    # convert back to TOF based on engineered detector positions
    mantid.ApplyDiffCal(InstrumentWorkspace=focused_vanadium,
                        ClearCalibration=True)
    focused_spectra = common.extract_ws_spectra(focused_vanadium)
    focused_spectra = instrument._crop_van_to_expected_tof_range(
        focused_spectra)

    d_spacing_group, tof_group = instrument._output_focused_ws(
        processed_spectra=focused_spectra, run_details=run_details)
    _create_vanadium_splines(focused_spectra, instrument, run_details)

    common.keep_single_ws_unit(d_spacing_group=d_spacing_group,
                               tof_group=tof_group,
                               unit_to_keep=instrument._get_unit_to_keep())

    common.remove_intermediate_workspace(corrected_van_ws)
    common.remove_intermediate_workspace(aligned_ws)
    common.remove_intermediate_workspace(focused_vanadium)
    common.remove_intermediate_workspace(focused_spectra)

    return d_spacing_group
Пример #58
0
def _focus_one_ws(input_workspace, run_number, instrument,
                  perform_vanadium_norm, absorb, sample_details,
                  vanadium_path):
    run_details = instrument._get_run_details(run_number_string=run_number)
    if perform_vanadium_norm:
        _test_splined_vanadium_exists(instrument, run_details)

    # Subtract empty instrument runs, as long as this run isn't an empty and user hasn't turned empty subtraction off
    if not common.runs_overlap(run_number, run_details.empty_runs
                               ) and instrument.should_subtract_empty_inst():
        input_workspace = common.subtract_summed_runs(
            ws_to_correct=input_workspace,
            instrument=instrument,
            empty_sample_ws_string=run_details.empty_runs)

    # Subtract a sample empty if specified
    if run_details.sample_empty:
        input_workspace = common.subtract_summed_runs(
            ws_to_correct=input_workspace,
            instrument=instrument,
            empty_sample_ws_string=run_details.sample_empty,
            scale_factor=instrument._inst_settings.sample_empty_scale)

    # Crop to largest acceptable TOF range
    input_workspace = instrument._crop_raw_to_expected_tof_range(
        ws_to_crop=input_workspace)

    # Correct for absorption / multiple scattering if required
    if absorb:
        input_workspace = instrument._apply_absorb_corrections(
            run_details=run_details, ws_to_correct=input_workspace)
    else:
        # Set sample material if specified by the user
        if sample_details is not None:
            mantid.SetSample(
                InputWorkspace=input_workspace,
                Geometry=common.generate_sample_geometry(sample_details),
                Material=common.generate_sample_material(sample_details))
    # Align
    aligned_ws = mantid.AlignDetectors(
        InputWorkspace=input_workspace,
        CalibrationFile=run_details.offset_file_path)

    # Focus the spectra into banks
    focused_ws = mantid.DiffractionFocussing(
        InputWorkspace=aligned_ws,
        GroupingFileName=run_details.grouping_file_path)

    calibrated_spectra = _apply_vanadium_corrections(
        instrument=instrument,
        input_workspace=focused_ws,
        perform_vanadium_norm=perform_vanadium_norm,
        vanadium_splines=vanadium_path)

    output_spectra = instrument._crop_banks_to_user_tof(calibrated_spectra)

    bin_widths = instrument._get_instrument_bin_widths()
    if bin_widths:
        # Reduce the bin width if required on this instrument
        output_spectra = common.rebin_workspace_list(
            workspace_list=output_spectra, bin_width_list=bin_widths)

    # Output
    d_spacing_group, tof_group = instrument._output_focused_ws(
        output_spectra, run_details=run_details)

    common.keep_single_ws_unit(d_spacing_group=d_spacing_group,
                               tof_group=tof_group,
                               unit_to_keep=instrument._get_unit_to_keep())

    # Tidy workspaces from Mantid
    common.remove_intermediate_workspace(input_workspace)
    common.remove_intermediate_workspace(aligned_ws)
    common.remove_intermediate_workspace(focused_ws)
    common.remove_intermediate_workspace(output_spectra)

    return d_spacing_group
Пример #59
0
def generate_ts_pdf(run_number,
                    focus_file_path,
                    sample_details,
                    merge_banks=False,
                    q_lims=None,
                    cal_file_name=None,
                    delta_r=None,
                    delta_q=None,
                    pdf_type="G(r)",
                    lorch_filter=None,
                    freq_params=None,
                    debug=False):
    if sample_details is None:
        raise RuntimeError(
            "A SampleDetails object was not set. Please create a SampleDetails object and set the "
            "relevant properties it. Then set the new sample by calling set_sample_details()"
        )
    focused_ws = _obtain_focused_run(run_number, focus_file_path)
    focused_ws = mantid.ConvertUnits(InputWorkspace=focused_ws,
                                     Target="MomentumTransfer",
                                     EMode='Elastic')

    raw_ws = mantid.Load(Filename='POLARIS' + str(run_number))
    sample_geometry_json = sample_details.generate_sample_geometry()
    sample_material_json = sample_details.generate_sample_material()

    self_scattering_correction = mantid.TotScatCalculateSelfScattering(
        InputWorkspace=raw_ws,
        CalFileName=cal_file_name,
        SampleGeometry=sample_geometry_json,
        SampleMaterial=sample_material_json)

    ws_group_list = []
    for i in range(self_scattering_correction.getNumberHistograms()):
        ws_name = 'correction_' + str(i)
        mantid.ExtractSpectra(InputWorkspace=self_scattering_correction,
                              OutputWorkspace=ws_name,
                              WorkspaceIndexList=[i])
        ws_group_list.append(ws_name)
    self_scattering_correction = mantid.GroupWorkspaces(
        InputWorkspaces=ws_group_list)
    self_scattering_correction = mantid.RebinToWorkspace(
        WorkspaceToRebin=self_scattering_correction,
        WorkspaceToMatch=focused_ws)
    if not compare_ws_compatibility(focused_ws, self_scattering_correction):
        raise RuntimeError(
            "To use create_total_scattering_pdf you need to run focus with "
            "do_van_normalisation=true first.")
    focused_ws = mantid.Subtract(LHSWorkspace=focused_ws,
                                 RHSWorkspace=self_scattering_correction)
    if debug:
        dcs_corrected = mantid.CloneWorkspace(InputWorkspace=focused_ws)

    # convert diff cross section to S(Q) - 1
    material_builder = MaterialBuilder()
    sample = material_builder.setFormula(
        sample_details.material_object.chemical_formula).build()
    sample_total_scatter_cross_section = sample.totalScatterXSection()
    sample_coh_scatter_cross_section = sample.cohScatterXSection()
    focused_ws = focused_ws - sample_total_scatter_cross_section / (4 *
                                                                    math.pi)
    focused_ws = focused_ws * 4 * math.pi / sample_coh_scatter_cross_section
    if debug:
        s_of_q_minus_one = mantid.CloneWorkspace(InputWorkspace=focused_ws)

    if delta_q:
        focused_ws = mantid.Rebin(InputWorkspace=focused_ws, Params=delta_q)
    if merge_banks:
        q_min, q_max = _load_qlims(q_lims)
        merged_ws = mantid.MatchAndMergeWorkspaces(InputWorkspaces=focused_ws,
                                                   XMin=q_min,
                                                   XMax=q_max,
                                                   CalculateScale=False)
        fast_fourier_filter(merged_ws,
                            rho0=sample_details.material_object.number_density,
                            freq_params=freq_params)
        pdf_output = mantid.PDFFourierTransform(
            Inputworkspace="merged_ws",
            InputSofQType="S(Q)-1",
            PDFType=pdf_type,
            Filter=lorch_filter,
            DeltaR=delta_r,
            rho0=sample_details.material_object.number_density)
    else:
        for ws in focused_ws:
            fast_fourier_filter(
                ws,
                rho0=sample_details.material_object.number_density,
                freq_params=freq_params)
        pdf_output = mantid.PDFFourierTransform(
            Inputworkspace='focused_ws',
            InputSofQType="S(Q)-1",
            PDFType=pdf_type,
            Filter=lorch_filter,
            DeltaR=delta_r,
            rho0=sample_details.material_object.number_density)
        pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output,
                                             WorkspaceToMatch=pdf_output[4],
                                             PreserveEvents=True)
    if not debug:
        common.remove_intermediate_workspace('self_scattering_correction')
    # Rename output ws
    if 'merged_ws' in locals():
        mantid.RenameWorkspace(InputWorkspace='merged_ws',
                               OutputWorkspace=run_number + '_merged_Q')
    mantid.RenameWorkspace(InputWorkspace='focused_ws',
                           OutputWorkspace=run_number + '_focused_Q')
    target_focus_ws_name = run_number + '_focused_Q_'
    target_pdf_ws_name = run_number + '_pdf_R_'
    if isinstance(focused_ws, WorkspaceGroup):
        for i in range(len(focused_ws)):
            if str(focused_ws[i]) != (target_focus_ws_name + str(i + 1)):
                mantid.RenameWorkspace(InputWorkspace=focused_ws[i],
                                       OutputWorkspace=target_focus_ws_name +
                                       str(i + 1))
    mantid.RenameWorkspace(InputWorkspace='pdf_output',
                           OutputWorkspace=run_number + '_pdf_R')
    if isinstance(pdf_output, WorkspaceGroup):
        for i in range(len(pdf_output)):
            if str(pdf_output[i]) != (target_pdf_ws_name + str(i + 1)):
                mantid.RenameWorkspace(InputWorkspace=pdf_output[i],
                                       OutputWorkspace=target_pdf_ws_name +
                                       str(i + 1))
    return pdf_output