Esempio n. 1
0
def _run_focus(input_workspace,
               tof_output_name,
               vanadium_integration_ws,
               vanadium_curves_ws,
               df_kwarg,
               full_calib,
               region_calib):
    simple.NormaliseByCurrent(InputWorkspace=input_workspace, OutputWorkspace=input_workspace)
    input_workspace /= vanadium_integration_ws
    simple.ReplaceSpecialValues(InputWorkspace=input_workspace, OutputWorkspace=input_workspace, NaNValue=0,
                                InfinityValue=0)
    simple.ApplyDiffCal(InstrumentWorkspace=input_workspace, CalibrationWorkspace=full_calib)
    ws_d = simple.ConvertUnits(InputWorkspace=input_workspace, Target='dSpacing')
    focused_sample = simple.DiffractionFocussing(InputWorkspace=ws_d, **df_kwarg)
    curves_rebinned = simple.RebinToWorkspace(WorkspaceToRebin=vanadium_curves_ws, WorkspaceToMatch=focused_sample)
    normalised = simple.Divide(LHSWorkspace=focused_sample, RHSWorkspace=curves_rebinned,
                               AllowDifferentNumberSpectra=True)
    simple.ApplyDiffCal(InstrumentWorkspace=normalised, CalibrationWorkspace=region_calib)
    dspacing_output_name = tof_output_name + "_dSpacing"
    simple.CloneWorkspace(InputWorkspace=normalised, OutputWorkspace=dspacing_output_name)
    simple.ConvertUnits(InputWorkspace=normalised, OutputWorkspace=tof_output_name, Target='TOF')
    simple.DeleteWorkspace(curves_rebinned)
    simple.DeleteWorkspace(focused_sample)
    simple.DeleteWorkspace(normalised)
    simple.DeleteWorkspace(ws_d)
Esempio n. 2
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
Esempio n. 3
0
    def focus_and_make_van_curves(ceria_d, vanadium_d, grouping_kwarg):
        # focus ceria
        focused_ceria = simple.DiffractionFocussing(InputWorkspace=ceria_d, **grouping_kwarg)
        simple.ApplyDiffCal(InstrumentWorkspace=focused_ceria, ClearCalibration=True)
        tof_focused = simple.ConvertUnits(InputWorkspace=focused_ceria, Target='TOF')

        # focus van data
        focused_van = simple.DiffractionFocussing(InputWorkspace=vanadium_d, **grouping_kwarg)

        background_van = simple.EnggEstimateFocussedBackground(InputWorkspace=focused_van, NIterations='15',
                                                               XWindow=0.03)

        simple.DeleteWorkspace(focused_ceria)
        simple.DeleteWorkspace(focused_van)

        return tof_focused, background_van
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
0
 def focus_onepanel(self, work, focus, panel):
     cal = "WISH_diff{}"
     if cal.format("_cal") not in simple.mtd:
         simple.LoadDiffCal(filename=self.get_cal(),
                            InstrumentName="WISH",
                            WorkspaceName=cal.format(""))
     simple.AlignDetectors(InputWorkspace=work,
                           OutputWorkspace=work,
                           CalibrationWorkspace=cal.format("_cal"))
     simple.DiffractionFocussing(InputWorkspace=work,
                                 OutputWorkspace=focus,
                                 GroupingWorkspace=cal.format("_group"))
     if self.deleteWorkspace:
         simple.DeleteWorkspace(work)
     if panel == 5 or panel == 6:
         simple.CropWorkspace(InputWorkspace=focus,
                              OutputWorkspace=focus,
                              XMin=0.3)
     return focus
Esempio n. 7
0
def _focus_run_and_apply_roi_calibration(ws, calibration, ws_foc_name=None):
    if not ws_foc_name:
        ws_foc_name = ws.name(
        ) + "_" + FOCUSED_OUTPUT_WORKSPACE_NAME + calibration.get_foc_ws_suffix(
        )
    ws_foc = mantid.DiffractionFocussing(
        InputWorkspace=ws,
        OutputWorkspace=ws_foc_name,
        GroupingWorkspace=calibration.get_group_ws())
    mantid.ApplyDiffCal(InstrumentWorkspace=ws_foc, ClearCalibration=True)
    ws_foc = mantid.ConvertUnits(InputWorkspace=ws_foc,
                                 OutputWorkspace=ws_foc.name(),
                                 Target='TOF')
    mantid.ApplyDiffCal(
        InstrumentWorkspace=ws_foc,
        CalibrationWorkspace=calibration.get_calibration_table())
    ws_foc = mantid.ConvertUnits(InputWorkspace=ws_foc,
                                 OutputWorkspace=ws_foc.name(),
                                 Target='dSpacing')
    return ws_foc
Esempio n. 8
0
    def _do_silicon_calibration(self, runs_to_process, cal_file_name, grouping_file_name):
        create_si_ws = common._read_ws(number=runs_to_process, instrument=self)
        cycle_details = self._get_cycle_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
Esempio n. 9
0
    def _create_calibration(self, calibration_runs, offset_file_name, grouping_file_name):
        input_ws = common._read_ws(number=calibration_runs, instrument=self)
        cycle_information = self._get_cycle_information(calibration_runs)

        # TODO move these hard coded params to instrument specific
        if cycle_information["instrument_version"] == "new" or cycle_information["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 cycle_information["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 cycle_information["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 = self.calibration_dir + offset_file_name
            grouping_file_path = 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)
Esempio n. 10
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
Esempio n. 11
0
def run_calibration(ceria_ws, calibration, full_instrument_cal_ws):
    """
    Creates Engineering calibration files with PDCalibration
    :param ceria_ws: The workspace with the ceria data.
    :param bank: The bank to crop to, both if none.
    :param calfile: The custom calibration file to crop to, not used if none.
    :param spectrum_numbers: The spectrum numbers to crop to, no crop if none.
    :return: dict containing calibrated diffractometer constants, and copy of the raw ceria workspace
    """

    # initial process of ceria ws
    mantid.NormaliseByCurrent(InputWorkspace=ceria_ws,
                              OutputWorkspace=ceria_ws)
    mantid.ApplyDiffCal(InstrumentWorkspace=ceria_ws,
                        CalibrationWorkspace=full_instrument_cal_ws)
    mantid.ConvertUnits(InputWorkspace=ceria_ws,
                        OutputWorkspace=ceria_ws,
                        Target='dSpacing')

    # get grouping workspace and focus
    grp_ws = calibration.get_group_ws()  # (creates if doesn't exist)
    focused_ceria = mantid.DiffractionFocussing(InputWorkspace=ceria_ws,
                                                GroupingWorkspace=grp_ws)
    mantid.ApplyDiffCal(
        InstrumentWorkspace=focused_ceria,
        ClearCalibration=True)  # DIFC of detector in middle of bank
    focused_ceria = mantid.ConvertUnits(InputWorkspace=focused_ceria,
                                        Target='TOF')

    # Run mantid.PDCalibration to fit peaks in TOF
    foc_name = focused_ceria.name(
    )  # PDCal invalidates ptr during rebin so keep track of ws name
    cal_table_name = "engggui_calibration_" + calibration.get_group_suffix()
    diag_ws_name = "diag_" + calibration.get_group_suffix()
    cal_table, diag_ws, mask = mantid.PDCalibration(
        InputWorkspace=foc_name,
        OutputCalibrationTable=cal_table_name,
        DiagnosticWorkspaces=diag_ws_name,
        PeakPositions=default_ceria_expected_peaks(final=True),
        TofBinning=[12000, -0.0003, 52000],
        PeakWindow=default_ceria_expected_peak_windows(final=True),
        MinimumPeakHeight=0.5,
        PeakFunction='BackToBackExponential',
        CalibrationParameters='DIFC+TZERO+DIFA',
        UseChiSq=True)
    mantid.ApplyDiffCal(InstrumentWorkspace=foc_name,
                        CalibrationWorkspace=cal_table)

    # warn user which spectra were unsuccessfully calibrated
    focused_ceria = ADS.retrieve(foc_name)
    masked_detIDs = mask.getMaskedDetectors()
    for ispec in range(focused_ceria.getNumberHistograms()):
        if focused_ceria.getSpectrum(
                ispec).getDetectorIDs()[0] in masked_detIDs:
            logger.warning(
                f'mantid.PDCalibration failed for spectrum index {ispec} - proceeding with uncalibrated DIFC.'
            )

    # store cal_table in calibration
    calibration.set_calibration_table(cal_table_name)

    return focused_ceria, cal_table, diag_ws
Esempio n. 12
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
Esempio n. 13
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
Esempio n. 14
0
def _run_pearl_focus(instrument, run_number, perform_attenuation,
                     perform_vanadium_norm):

    cycle_information = instrument._get_cycle_information(
        run_number=run_number)

    alg_range, save_range = instrument._get_instrument_alg_save_ranges(
        cycle_information["instrument_version"])

    input_file_paths = instrument._get_calibration_full_paths(
        cycle=cycle_information["cycle"])

    output_file_paths = instrument._generate_out_file_paths(
        run_number, instrument.output_dir)
    read_ws = _read_ws(number=run_number, instrument=instrument)
    input_workspace = mantid.Rebin(InputWorkspace=read_ws,
                                   Params=instrument._get_focus_tof_binning())
    input_workspace = mantid.AlignDetectors(
        InputWorkspace=input_workspace,
        CalibrationFile=input_file_paths["calibration"])
    input_workspace = mantid.DiffractionFocussing(
        InputWorkspace=input_workspace,
        GroupingFileName=input_file_paths["grouping"])

    calibrated_spectra = _focus_load(alg_range, input_workspace,
                                     input_file_paths, instrument,
                                     perform_vanadium_norm)

    remove_intermediate_workspace(read_ws)
    remove_intermediate_workspace(input_workspace)

    focus_mode = instrument.focus_mode
    if focus_mode == "all":
        processed_nexus_files = _focus_mode_all(output_file_paths,
                                                calibrated_spectra)

    elif focus_mode == "groups":
        processed_nexus_files = _focus_mode_groups(cycle_information,
                                                   output_file_paths,
                                                   save_range,
                                                   calibrated_spectra)

    elif focus_mode == "trans":

        processed_nexus_files = _focus_mode_trans(output_file_paths,
                                                  perform_attenuation,
                                                  instrument,
                                                  calibrated_spectra)

    elif focus_mode == "mods":

        processed_nexus_files = _focus_mode_mods(output_file_paths,
                                                 calibrated_spectra)

    else:
        raise ValueError("Focus mode unknown")

    for ws in calibrated_spectra:
        remove_intermediate_workspace(ws)

    return processed_nexus_files
Esempio n. 15
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
Esempio n. 16
0
def align_and_focus_event_ws(event_ws_name, output_ws_name, binning_params,
                             diff_cal_ws_name, grouping_ws_name,
                             reduction_params_dict, convert_to_matrix):
    """ Align and focus event workspace.  The procedure to reduce from the EventNexus includes
    1. compress event
    2. mask workspace
    3. align detectors
    4. sort events
    5. diffraction focus
    6. sort events
    7. edit instruments
    8. rebin (uniform binning)
    Output: still event workspace
    :exception RuntimeError: intolerable error
    :param event_ws_name:
    :param output_ws_name:
    :param binning_params:
    :param diff_cal_ws_name:
    :param grouping_ws_name:
    :param reduction_params_dict:
    :param convert_to_matrix:
    :return: string as ERROR message
    """
    # check inputs
    if not mantid_helper.is_event_workspace(event_ws_name):
        raise RuntimeError('Input {0} is not an EventWorkspace'.format(event_ws_name))
    if not mantid_helper.is_calibration_workspace(diff_cal_ws_name):
        diff_ws = mantid_helper.retrieve_workspace(diff_cal_ws_name)
        raise RuntimeError('Input {0} is not a Calibration workspace but a {1}'.format(diff_cal_ws_name,
                                                                                       diff_ws.__class__.__name__))
    # if not mantid_helper.is_masking_workspace(mask_ws_name):
    #     raise RuntimeError('Input {0} is not a Masking workspace'.format(mask_ws_name))
    if not mantid_helper.is_grouping_workspace(grouping_ws_name):
        raise RuntimeError('Input {0} is not a grouping workspace'.format(grouping_ws_name))

    datatypeutility.check_dict('Reduction parameter dictionary', reduction_params_dict)

    # Align detector
    mantidapi.AlignDetectors(InputWorkspace=event_ws_name,
                             OutputWorkspace=output_ws_name,
                             CalibrationWorkspace=diff_cal_ws_name)

    # # Mask detectors
    # mantid_helper.mask_workspace(to_mask_workspace_name=output_ws_name,
    #                              mask_workspace_name=mask_ws_name)

    # Sort events
    mantidapi.SortEvents(InputWorkspace=output_ws_name,
                         SortBy='X Value')

    # Diffraction focus
    event_ws = mantid_helper.retrieve_workspace(output_ws_name)
    if event_ws.getNumberEvents() == 0:
        print('[DB...BAT] {}: # events = {}'.format(event_ws, event_ws.getNumberEvents()))
        error_message = 'Unable to reduced {} as number of events = 0'.format(event_ws_name)
        raise RuntimeError(error_message)

    mantidapi.DiffractionFocussing(InputWorkspace=output_ws_name,
                                   OutputWorkspace=output_ws_name,
                                   GroupingWorkspace=grouping_ws_name,
                                   PreserveEvents=True)
    # Sort again!
    mantidapi.SortEvents(InputWorkspace=output_ws_name,
                         SortBy='X Value')

    # Compress events as an option
    if 'CompressEvents' in reduction_params_dict:
        compress_events_tolerance = reduction_params_dict['CompressEvents']['Tolerance']
        print('[DB...BAT] User-specified compress tolerance = {}'.format(compress_events_tolerance))
        mantidapi.CompressEvents(InputWorkspace=output_ws_name,
                                 OutputWorkspace=output_ws_name,
                                 Tolerance=1.E-5)

    # rebin
    if binning_params is not None:
        mantid_helper.rebin(workspace_name=output_ws_name,
                            params=binning_params, preserve=not convert_to_matrix)

    # Edit instrument as an option
    if 'EditInstrumentGeometry' in reduction_params_dict:
        try:
            # TODO - NIGHT - In case the number of histograms of output workspace does not match (masked a lot) ...
            # TODO - FIXME - 27 bank Polar and Azimuthal are all None
            print(reduction_params_dict['EditInstrumentGeometry'].keys())
            print(output_ws_name)
            print(mantid_helper.VULCAN_L1)
            print(reduction_params_dict['EditInstrumentGeometry']['SpectrumIDs'])
            print(reduction_params_dict['EditInstrumentGeometry']['L2'])
            print(reduction_params_dict['EditInstrumentGeometry']['Polar'])
            print(reduction_params_dict['EditInstrumentGeometry']['Azimuthal'])

            mantidapi.EditInstrumentGeometry(Workspace=output_ws_name,
                                             PrimaryFlightPath=mantid_helper.VULCAN_L1,
                                             SpectrumIDs=reduction_params_dict['EditInstrumentGeometry']['SpectrumIDs'],
                                             L2=reduction_params_dict['EditInstrumentGeometry']['L2'],
                                             Polar=reduction_params_dict['EditInstrumentGeometry']['Polar'],
                                             Azimuthal=reduction_params_dict['EditInstrumentGeometry']['Azimuthal'])
            """
            Workspace
            PrimaryFlightPath
            SpectrumIDs
            L2
            Polar
            Azimuthal
            DetectorIDs
            InstrumentName
            """
        except RuntimeError as run_err:
            error_message = 'Non-critical failure on EditInstrumentGeometry: {}\n'.format(run_err)
            return error_message

    return ''
Esempio n. 17
0
def _create_van(instrument,
                van,
                empty,
                output_van_file_name,
                num_of_splines=60,
                absorb=True,
                gen_absorb=False):
    cycle_information = instrument._get_cycle_information(van)

    input_van_ws = _read_ws(number=van, instrument=instrument)
    input_empty_ws = _read_ws(number=empty, instrument=instrument)

    corrected_van_ws = mantid.Minus(LHSWorkspace=input_van_ws,
                                    RHSWorkspace=input_empty_ws)

    remove_intermediate_workspace(input_empty_ws)
    remove_intermediate_workspace(input_van_ws)

    calibration_full_paths = instrument._get_calibration_full_paths(
        cycle=cycle_information["cycle"])
    tof_binning = instrument._get_create_van_tof_binning()

    if absorb:
        corrected_van_ws = _apply_absorb_corrections(calibration_full_paths,
                                                     corrected_van_ws,
                                                     gen_absorb)

    corrected_van_ws = mantid.ConvertUnits(InputWorkspace=corrected_van_ws,
                                           Target="TOF")
    corrected_van_ws = mantid.Rebin(InputWorkspace=corrected_van_ws,
                                    Params=tof_binning["1"])

    corrected_van_ws = mantid.AlignDetectors(
        InputWorkspace=corrected_van_ws,
        CalibrationFile=calibration_full_paths["calibration"])

    focused_van_file = mantid.DiffractionFocussing(
        InputWorkspace=corrected_van_ws,
        GroupingFileName=calibration_full_paths["grouping"])

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

    focused_van_file = mantid.Rebin(InputWorkspace=focused_van_file,
                                    Params=tof_binning["2"])
    focused_van_file = mantid.ConvertUnits(InputWorkspace=focused_van_file,
                                           Target="dSpacing")

    remove_intermediate_workspace(corrected_van_ws)

    splined_ws_list = instrument._spline_background(
        focused_van_file, num_of_splines,
        cycle_information["instrument_version"])

    if instrument._PEARL_use_full_path():
        out_van_file_path = output_van_file_name
    else:
        out_van_file_path = instrument.calibration_dir + output_van_file_name

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

    mantid.LoadNexus(Filename=out_van_file_path, OutputWorkspace="Van_data")
Esempio n. 18
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)