Beispiel #1
0
    def calculate_scaled_hab_output(self, shift, scale, sample_count_secondary,
                                    sample_norm_secondary, can_count_secondary,
                                    can_norm_secondary):
        scaled_norm_front = mantid_api.Scale(
            InputWorkspace=sample_norm_secondary,
            Factor=1.0 / scale,
            Operation='Multiply',
            StoreInADS=False)
        shifted_norm_front = mantid_api.Scale(
            InputWorkspace=sample_norm_secondary,
            Factor=shift,
            Operation='Multiply',
            StoreInADS=False)
        numerator = mantid_api.Plus(LHSWorkspace=sample_count_secondary,
                                    RHSWorkspace=shifted_norm_front,
                                    StoreInADS=False)
        hab_sample = mantid_api.Divide(LHSWorkspace=numerator,
                                       RHSWorkspace=scaled_norm_front,
                                       StoreInADS=False)

        if can_count_secondary is not None and can_norm_secondary is not None:
            scaled_norm_front_can = mantid_api.Scale(
                InputWorkspace=can_norm_secondary,
                Factor=1.0 / scale,
                Operation='Multiply',
                StoreInADS=False)
            hab_can = mantid_api.Divide(LHSWorkspace=can_count_secondary,
                                        RHSWorkspace=scaled_norm_front_can,
                                        StoreInADS=False)
            hab_sample = mantid_api.Minus(LHSWorkspace=hab_sample,
                                          RHSWorkspace=hab_can,
                                          StoreInADS=False)
            return hab_sample
        else:
            return hab_sample
Beispiel #2
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)
Beispiel #3
0
    def PyExec(self):
        # Input
        vana_input = self.getProperty("VanadiumWorkspaces").value
        bg_input = self.getProperty("BackgroundWorkspaces").value
        vana_workspaces = self._expand_groups(vana_input)
        bg_workspaces = self._expand_groups(bg_input)
        self.log().notice("Input Vanadium workspaces: " + str(vana_workspaces))
        self.log().notice("Input Background workspaces: " + str(bg_workspaces))

        # number of vanadium and background workspaces must match
        if len(vana_workspaces) != len(bg_workspaces):
            raise RuntimeError("Number of Vanadium and background workspaces doe not match!")

        # compare optional sample logs, throw warnings
        result = api.CompareSampleLogs(vana_workspaces+bg_workspaces, self.properties_to_compare, 5e-3)
        if result:
            self.log().warning("Following properties do not match: " + result)

        # split input workspaces to groups SF/NSF and detector angles
        deterota = self._get_detector_positions(vana_workspaces)
        sfvana, nsfvana = self._sort_workspaces(vana_workspaces, deterota)
        sfbg, nsfbg = self._sort_workspaces(bg_workspaces, deterota)

        # subract background
        sfv = self._subtract_background(sfvana, sfbg, deterota)
        nsfv = self._subtract_background(nsfvana, nsfbg, deterota)
        total = self._sum_signal(sfv, nsfv, deterota)

        # compute vmean
        _mean_ws_ = api.Mean(",".join(list(total.values())))     # Mean takes string
        self.toremove.append(_mean_ws_.name())
        num =  self._get_notmasked_detectors_number(_mean_ws_)
        if num == 0:
            self.cleanup(self.toremove)
            raise RuntimeError("All detectors are masked! Cannot compute coefficients.")
        _vana_mean_ = api.SumSpectra(_mean_ws_)/num
        self.toremove.append(_vana_mean_.name())

        # compute coefficients k_i = (VSF_i + VNSF_i)/Vmean
        outws_name = self.getPropertyValue("OutputWorkspace")
        # for only one detector position only one workspace will be created
        if len(deterota) == 1:
            api.Divide(list(total.values())[0], _vana_mean_, OutputWorkspace=outws_name)
        else:
            # for many detector positions group of workspaces will be created
            results = []
            for angle in deterota:
                wsname = outws_name + '_2theta' + str(angle)
                api.Divide(total[angle], _vana_mean_, OutputWorkspace=wsname)
                results.append(wsname)

            api.GroupWorkspaces(results, OutputWorkspace=outws_name)

        self.cleanup(self.toremove)
        outws = api.AnalysisDataService.retrieve(outws_name)
        self.setProperty("OutputWorkspace", outws)

        return
Beispiel #4
0
def _divide_one_spectrum_by_spline(spectrum, spline, instrument):
    rebinned_spline = mantid.RebinToWorkspace(WorkspaceToRebin=spline, WorkspaceToMatch=spectrum, StoreInADS=False)
    if instrument.get_instrument_prefix() == "GEM":
        divided = mantid.Divide(LHSWorkspace=spectrum, RHSWorkspace=rebinned_spline, OutputWorkspace=spectrum,
                                StoreInADS=False)
        complete = mantid.ReplaceSpecialValues(InputWorkspace=divided, NaNValue=0, StoreInADS=False)
        # crop based off max between 1000 and 2000 tof as the vanadium peak on Gem will always occur here
        return _crop_spline_to_percent_of_max(rebinned_spline, complete, spectrum, 1000, 2000)

    divided = mantid.Divide(LHSWorkspace=spectrum, RHSWorkspace=rebinned_spline,
                            StoreInADS=False)
    complete = mantid.ReplaceSpecialValues(InputWorkspace=divided, NaNValue=0, OutputWorkspace=spectrum)

    return complete
    def _correct_sample_can(self):
        """
        Correct for sample and container.
        """

        logger.information('Correcting sample and container')
        corrected_can_ws = '__corrected_can'

        factor_types = ['_ass']
        if self._use_can:
            factor_types.extend(['_acc', '_acsc', '_assc'])
        corr_unit = s_api.mtd[self._corrections +
                              '_ass'].getAxis(0).getUnit().unitID()
        for f_type in factor_types:
            self._convert_units_wavelength(corr_unit,
                                           self._corrections + f_type,
                                           self._corrections + f_type,
                                           "Wavelength")

        if self._rebin_container_ws:
            s_api.RebinToWorkspace(
                WorkspaceToRebin=self._scaled_container_wavelength,
                WorkspaceToMatch=self._corrections + '_acc',
                OutputWorkspace=self._scaled_container_wavelength)

        # Acc
        s_api.Divide(LHSWorkspace=self._scaled_container_wavelength,
                     RHSWorkspace=self._corrections + '_acc',
                     OutputWorkspace=corrected_can_ws)

        # Acsc
        s_api.Multiply(LHSWorkspace=corrected_can_ws,
                       RHSWorkspace=self._corrections + '_acsc',
                       OutputWorkspace=corrected_can_ws)
        s_api.Minus(LHSWorkspace=self._sample_ws_wavelength,
                    RHSWorkspace=corrected_can_ws,
                    OutputWorkspace=self._output_ws_name)

        # Assc
        s_api.Divide(LHSWorkspace=self._output_ws_name,
                     RHSWorkspace=self._corrections + '_assc',
                     OutputWorkspace=self._output_ws_name)

        for f_type in factor_types:
            self._convert_units_wavelength(corr_unit,
                                           self._corrections + f_type,
                                           self._corrections + f_type,
                                           corr_unit)

        s_api.DeleteWorkspace(corrected_can_ws)
    def _fr_correction(self):
        """
        applies flipping ratio correction
        according to J Appl. Cryst. 42, 69-84, 2009
        creates the corrected workspaces
        """
        wslist = []
        # 1. retrieve NiCr and Background
        sf_nicr = api.AnalysisDataService.retrieve(self.input_workspaces['SF_NiCr'])
        nsf_nicr = api.AnalysisDataService.retrieve(self.input_workspaces['NSF_NiCr'])
        sf_bkgr = api.AnalysisDataService.retrieve(self.input_workspaces['SF_Background'])
        nsf_bkgr = api.AnalysisDataService.retrieve(self.input_workspaces['NSF_Background'])

        # 2. subtract background from NiCr
        _sf_nicr_bg_ = sf_nicr - sf_bkgr
        wslist.append(_sf_nicr_bg_.name())
        _nsf_nicr_bg_ = nsf_nicr - nsf_bkgr
        wslist.append(_nsf_nicr_bg_.name())
        # check negative values, throw exception
        sf_arr = np.array(_sf_nicr_bg_.extractY()).flatten()
        nsf_arr = np.array(_nsf_nicr_bg_.extractY()).flatten()
        sf_neg_values = np.where(sf_arr < 0)[0]
        nsf_neg_values = np.where(nsf_arr < 0)[0]
        if len(sf_neg_values) or len(nsf_neg_values):
            self.cleanup(wslist)
            message = "Background is higher than NiCr signal!"
            self.log().error(message)
            raise RuntimeError(message)

        # 3. calculate flipping ratio F - 1 = (NiCr - Bkg)NSF/(NiCr - Bkg)SF - 1
        _coef_ws_ = api.Divide(LHSWorkspace=_nsf_nicr_bg_, RHSWorkspace=_sf_nicr_bg_, WarnOnZeroDivide=True) - 1.0
        wslist.append(_coef_ws_.name())
        # 4. apply correction raw data
        sf_data_ws = api.AnalysisDataService.retrieve(self.input_workspaces['SF_Data'])
        nsf_data_ws = api.AnalysisDataService.retrieve(self.input_workspaces['NSF_Data'])
        # NSF_corr[i] = NSF[i] + (NSF[i] - SF[i])/(F[i] - 1)
        _diff_ws_ = nsf_data_ws - sf_data_ws
        wslist.append(_diff_ws_.name())
        _tmp_ws_ = api.Divide(LHSWorkspace=_diff_ws_, RHSWorkspace=_coef_ws_, WarnOnZeroDivide=True)
        _tmp_ws_.setYUnit(nsf_data_ws.YUnit())
        api.Plus(LHSWorkspace=nsf_data_ws, RHSWorkspace=_tmp_ws_, OutputWorkspace=self.nsf_outws_name)
        # SF_corr[i] = SF[i] - (NSF[i] - SF[i])/(F[i] - 1)
        api.Minus(LHSWorkspace=sf_data_ws, RHSWorkspace=_tmp_ws_, OutputWorkspace=self.sf_outws_name)
        api.DeleteWorkspace(_tmp_ws_)

        # cleanup
        self.cleanup(wslist)
        return
def ProcessVana(rnum, cycle):
    # Preparation of the V/Nd sphere run for SX normalization
    mantid.LoadRaw(Filename='/archive/NDXWISH/Instrument/data/cycle_' + cycle + '/WISH000' + str(rnum) + '.raw',
                   OutputWorkspace='Vana', LoadMonitors='Separate')
    mantid.CropWorkspace(InputWorkspace='Vana', OutputWorkspace='Vana', XMin=6000, XMax=99000)
    mantid.NormaliseByCurrent(InputWorkspace='Vana', OutputWorkspace='Vana')
    mantid.ConvertUnits(InputWorkspace='Vana', OutputWorkspace='Vana', Target='Wavelength')
    # create Abs Correction for V
    shape = '''<sphere id="V-sphere">
    <centre x="0.0"  y="0.0" z="0.0" />
    <radius val="0.0025"/>
    </sphere>'''
    mantid.CreateSampleShape('Vana', shape)
    mantid.SetSampleMaterial('Vana', SampleNumberDensity=0.0719, ScatteringXSection=5.197, AttenuationXSection=4.739,
                             ChemicalFormula='V0.95 Nb0.05')
    mantid.AbsorptionCorrection(InputWorkspace='Vana', OutputWorkspace='Abs_corr', ElementSize=0.5)
    # SphericalAbsorption(InputWorkspace='WISH00038428', OutputWorkspace='Abs_corr_sphere', SphericalSampleRadius=0.25)
    # correct Vanadium run for absorption
    mantid.Divide(LHSWorkspace='Vana', RHSWorkspace='Abs_corr', OutputWorkspace='Vana_Abs')
    mantid.DeleteWorkspace('Vana')
    mantid.DeleteWorkspace('Abs_corr')
    # Smoot data with redius 3
    mantid.SmoothNeighbours(InputWorkspace='Vana_Abs', OutputWorkspace='Vana_smoot', Radius=3)
    mantid.DeleteWorkspace('Vana_Abs')
    # SmoothData38428
    mantid.SmoothData(InputWorkspace='Vana_smoot', OutputWorkspace='Vana_smoot1', NPoints=300)
    mantid.DeleteWorkspace('Vana_smoot')
Beispiel #8
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)
Beispiel #9
0
def _divide_one_spectrum_by_spline(spectrum, spline, instrument):
    rebinned_spline = mantid.RebinToWorkspace(WorkspaceToRebin=spline,
                                              WorkspaceToMatch=spectrum,
                                              StoreInADS=False)
    if instrument.get_instrument_prefix() == "GEM":
        divided = mantid.Divide(LHSWorkspace=spectrum,
                                RHSWorkspace=rebinned_spline,
                                OutputWorkspace=spectrum,
                                StoreInADS=False)
        return _crop_spline_to_percent_of_max(rebinned_spline, divided,
                                              spectrum)

    divided = mantid.Divide(LHSWorkspace=spectrum,
                            RHSWorkspace=rebinned_spline,
                            OutputWorkspace=spectrum)
    return divided
Beispiel #10
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)
Beispiel #11
0
    def _calibData(self, sam_ws, mon_ws):
        sapi.MaskDetectors(Workspace=sam_ws,
                           DetectorList=self._dMask)
        sapi.ModeratorTzeroLinear(InputWorkspace=sam_ws,
                                  OutputWorkspace=sam_ws)
        sapi.LoadParameterFile(Workspace=sam_ws,
                               Filename=pjoin(DEFAULT_CONFIG_DIR,
                                              self._reflection["parameter_file"]))
        sapi.ConvertUnits(InputWorkspace=sam_ws,
                          OutputWorkspace=sam_ws,
                          Target='Wavelength',
                          EMode='Indirect')

        if self._MonNorm:
            sapi.ModeratorTzeroLinear(InputWorkspace=mon_ws,
                                      OutputWorkspace=mon_ws)
            sapi.Rebin(InputWorkspace=mon_ws,
                       OutputWorkspace=mon_ws,
                       Params='10')
            sapi.ConvertUnits(InputWorkspace=mon_ws,
                              OutputWorkspace=mon_ws,
                              Target='Wavelength')
            sapi.OneMinusExponentialCor(InputWorkspace=mon_ws,
                                        OutputWorkspace=mon_ws,
                                        C='0.20749999999999999',
                                        C1='0.001276')
            sapi.Scale(InputWorkspace=mon_ws,
                       OutputWorkspace=mon_ws,
                       Factor='1e-06')
            sapi.RebinToWorkspace(WorkspaceToRebin=sam_ws,
                                  WorkspaceToMatch=mon_ws,
                                  OutputWorkspace=sam_ws)
            sapi.Divide(LHSWorkspace=sam_ws,
                        RHSWorkspace=mon_ws,
                        OutputWorkspace=sam_ws)
Beispiel #12
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
Beispiel #13
0
def convert_to_y_space_and_symmetrise(ws_name,mass):
    # phenomenological roule-of-thumb to define the y-range for a given mass
    max_Y = np.ceil(2.5*mass+27)
    rebin_parameters = str(-max_Y)+","+str(2.*max_Y/120)+","+str(max_Y)
    # converting to y-space, rebinning, and defining a normalisation matrix to take into account the kinetic cut-off
    sapi.ConvertToYSpace(InputWorkspace=ws_name,Mass=mass,OutputWorkspace=ws_name+"_JoY",QWorkspace=ws_name+"_Q")
    ws = sapi.Rebin(InputWorkspace=ws_name+"_JoY", Params = rebin_parameters,FullBinsOnly=True, OutputWorkspace= ws_name+"_JoY")
    tmp=sapi.CloneWorkspace(InputWorkspace=ws_name+"_JoY")
    for j in range(tmp.getNumberHistograms()):
        for k in range(tmp.blocksize()):
            tmp.dataE(j)[k] =0.
            if np.isnan( tmp.dataY(j)[k] ) :
                ws.dataY(j)[k] =0.
                tmp.dataY(j)[k] =0.
            if (tmp.dataY(j)[k]!=0):
                tmp.dataY(j)[k] =1.
    tmp=sapi.SumSpectra('tmp')
    sapi.SumSpectra(InputWorkspace=ws_name+"_JoY",OutputWorkspace=ws_name+"_JoY_sum")
    sapi.Divide(LHSWorkspace=ws_name+"_JoY_sum", RHSWorkspace="tmp", OutputWorkspace =ws_name+"_JoY_sum")
    #rewriting the temporary workspaces ws and tmp
    ws=sapi.mtd[ws_name+"_JoY_sum"]
    tmp=sapi.CloneWorkspace(InputWorkspace=ws_name+"_JoY_sum")
    for k in range(tmp.blocksize()):
        tmp.dataE(0)[k] =(ws.dataE(0)[k]+ws.dataE(0)[ws.blocksize()-1-k])/2.
        tmp.dataY(0)[k] =(ws.dataY(0)[k]+ws.dataY(0)[ws.blocksize()-1-k])/2.
    sapi.RenameWorkspace(InputWorkspace="tmp",OutputWorkspace=ws_name+"_JoY_sym")
    normalise_workspace(ws_name+"_JoY_sym")
    return max_Y
Beispiel #14
0
def absorption_corrections(attenuation, height, number_density, radius,
                           scattering, input_ws):
    simple.ConvertUnits(InputWorkspace=input_ws,
                        OutputWorkspace=input_ws,
                        Target="Wavelength",
                        EMode="Elastic")
    simple.CylinderAbsorption(InputWorkspace=input_ws,
                              OutputWorkspace="absorptionWS",
                              CylinderSampleHeight=height,
                              CylinderSampleRadius=radius,
                              AttenuationXSection=attenuation,
                              ScatteringXSection=scattering,
                              SampleNumberDensity=number_density,
                              NumberOfSlices="10",
                              NumberOfAnnuli="10",
                              NumberOfWavelengthPoints="25",
                              ExpMethod="Normal")
    simple.Divide(LHSWorkspace=input_ws,
                  RHSWorkspace="absorptionWS",
                  OutputWorkspace=input_ws)
    simple.DeleteWorkspace("absorptionWS")
    simple.ConvertUnits(InputWorkspace=input_ws,
                        OutputWorkspace=input_ws,
                        Target="TOF",
                        EMode="Elastic")
Beispiel #15
0
def correct_for_multiple_scattering(ws_name,first_spectrum,last_spectrum, sample_properties, transmission_guess,
                                    multiple_scattering_order, number_of_events, g_log, masses, mean_intensity_ratios):
    g_log.debug( "Evaluating the Multiple Scattering Correction.")
    dens, trans = sapi.VesuvioThickness(Masses=masses, Amplitudes=mean_intensity_ratios, TransmissionGuess=transmission_guess,Thickness=0.1)
    _TotScattering, _MulScattering = sapi.VesuvioCalculateMS(ws_name, NoOfMasses=len(masses), SampleDensity=dens.cell(9,1),
                                                             AtomicProperties=sample_properties, BeamRadius=2.5,
                                                             NumScatters=multiple_scattering_order,
                                                             NumEventsPerRun=int(number_of_events))
    data_normalisation = sapi.Integration(ws_name)
    simulation_normalisation = sapi.Integration("_TotScattering")
    for workspace in ("_MulScattering","_TotScattering"):
        ws = sapi.mtd[workspace]
        for j in range(ws.getNumberHistograms()):
            for k in range(ws.blocksize()):
                ws.dataE(j)[
                         k] =0. # set the errors from the MonteCarlo simulation to zero - no propagation of such uncertainties
                #- Use high number of events for final corrections!!!
        sapi.Divide(LHSWorkspace = workspace, RHSWorkspace = simulation_normalisation, OutputWorkspace = workspace)
        sapi.Multiply(LHSWorkspace = workspace, RHSWorkspace = data_normalisation, OutputWorkspace = workspace)
        sapi.RenameWorkspace(InputWorkspace = workspace, OutputWorkspace = str(ws_name)+workspace)
    safe_delete_ws(data_normalisation)
    safe_delete_ws(simulation_normalisation)
    safe_delete_ws(trans)
    safe_delete_ws(dens)
    return
Beispiel #16
0
    def _calibData(self, sam_ws, mon_ws):
        api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask)
        #MaskedWorkspace='BASIS_MASK')
        api.ModeratorTzeroLinear(InputWorkspace=sam_ws,\
                           OutputWorkspace=sam_ws)
        api.LoadParameterFile(Workspace=sam_ws,
                              Filename=config.getInstrumentDirectory() +
                              'BASIS_silicon_111_Parameters.xml')
        api.ConvertUnits(InputWorkspace=sam_ws,
                         OutputWorkspace=sam_ws,
                         Target='Wavelength',
                         EMode='Indirect')

        if not self._noMonNorm:
            api.ModeratorTzeroLinear(InputWorkspace=mon_ws,\
                               OutputWorkspace=mon_ws)
            api.Rebin(InputWorkspace=mon_ws,
                      OutputWorkspace=mon_ws,
                      Params='10')
            api.ConvertUnits(InputWorkspace=mon_ws,
                             OutputWorkspace=mon_ws,
                             Target='Wavelength')
            api.OneMinusExponentialCor(InputWorkspace=mon_ws,
                                       OutputWorkspace=mon_ws,
                                       C='0.20749999999999999',
                                       C1='0.001276')
            api.Scale(InputWorkspace=mon_ws,
                      OutputWorkspace=mon_ws,
                      Factor='9.9999999999999995e-07')
            api.RebinToWorkspace(WorkspaceToRebin=sam_ws,
                                 WorkspaceToMatch=mon_ws,
                                 OutputWorkspace=sam_ws)
            api.Divide(LHSWorkspace=sam_ws,
                       RHSWorkspace=mon_ws,
                       OutputWorkspace=sam_ws)
Beispiel #17
0
def _divide_one_spectrum_by_spline(spectrum, spline):
    rebinned_spline = mantid.RebinToWorkspace(WorkspaceToRebin=spline,
                                              WorkspaceToMatch=spectrum,
                                              StoreInADS=False)
    divided = mantid.Divide(LHSWorkspace=spectrum,
                            RHSWorkspace=rebinned_spline,
                            OutputWorkspace=spectrum)
    return divided
Beispiel #18
0
    def _correct_sample(self):
        """
        Correct for sample only (when no container is given).
        """

        logger.information('Correcting sample')

        # Ass
        s_api.Divide(LHSWorkspace=self._sample_ws_wavelength,
                     RHSWorkspace=self._corrections + '_ass',
                     OutputWorkspace=self._output_ws_name)
Beispiel #19
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
Beispiel #20
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
Beispiel #21
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
Beispiel #22
0
def calculate_slab_absorb_corrections(ws_to_correct, sample_details_obj):
    """
    Sets a slab sample from the user specified dictionary and performs HRPDSlabCanAbsorption on the workspace.
    The SampleDetails object defines the sample, material and associated properties.
    :param ws_to_correct: The workspace to do corrections on
    :param sample_details_obj: The object containing the sample details
    :return: The corrected workspace
    """

    if not isinstance(sample_details_obj, sample_details.SampleDetails):
        raise RuntimeError("A SampleDetails object was not set or a different object type was found when sample"
                           " absorption corrections were requested. If you want sample absorption corrections please "
                           "create a SampleDetails object and set the relevant properties it. "
                           "Then set the new sample by calling set_sample_details().")
    if not sample_details_obj.is_material_set():
        raise RuntimeError("The material for this sample has not been set yet. Please call"
                           " set_material on the SampleDetails object to set the material")

    geometry_json = {"Shape": "FlatPlate", "Thick": sample_details_obj.thickness(), "Width": sample_details_obj.width(),
                     "Height": sample_details_obj.height(), "Center": sample_details_obj.center(),
                     "Angle": sample_details_obj.angle()}
    material = sample_details_obj.material_object
    # See SetSampleMaterial for documentation on this dictionary
    material_json = {"ChemicalFormula": material.chemical_formula}
    if material.number_density:
        material_json["SampleNumberDensity"] = material.number_density
    if material.absorption_cross_section:
        material_json["AttenuationXSection"] = material.absorption_cross_section
    if material.scattering_cross_section:
        material_json["ScatteringXSection"] = material.scattering_cross_section

    mantid.SetSample(InputWorkspace=ws_to_correct, Geometry=geometry_json, Material=material_json)

    previous_units = ws_to_correct.getAxis(0).getUnit().unitID()
    ws_units = common_enums.WORKSPACE_UNITS

    # HRPDSlabCanAbsorption must be completed in units of wavelength - convert if needed, than convert back afterwards
    if previous_units != ws_units.wavelength:
        ws_to_correct = mantid.ConvertUnits(InputWorkspace=ws_to_correct, OutputWorkspace=ws_to_correct,
                                            Target=ws_units.wavelength)

    absorb_factors = mantid.HRPDSlabCanAbsorption(InputWorkspace=ws_to_correct)
    ws_to_correct = mantid.Divide(LHSWorkspace=ws_to_correct, RHSWorkspace=absorb_factors,
                                  OutputWorkspace=ws_to_correct)
    mantid.DeleteWorkspace(Workspace=absorb_factors)

    if previous_units != ws_units.wavelength:
        ws_to_correct = mantid.ConvertUnits(InputWorkspace=ws_to_correct, OutputWorkspace=ws_to_correct,
                                            Target=previous_units)

    return ws_to_correct
Beispiel #23
0
def _normalize_one_spectrum(single_spectrum_ws, spline, instrument):
    rebinned_spline = mantid.RebinToWorkspace(
        WorkspaceToRebin=spline,
        WorkspaceToMatch=single_spectrum_ws,
        StoreInADS=False)
    divided = mantid.Divide(LHSWorkspace=single_spectrum_ws,
                            RHSWorkspace=rebinned_spline,
                            StoreInADS=False)
    if instrument.get_instrument_prefix() == "GEM":
        values_replaced = mantid.ReplaceSpecialValues(InputWorkspace=divided,
                                                      NaNValue=0,
                                                      StoreInADS=False)
        # crop based off max between 1000 and 2000 tof as the vanadium peak on Gem will always occur here
        complete = _crop_spline_to_percent_of_max(rebinned_spline,
                                                  values_replaced,
                                                  single_spectrum_ws, 1000,
                                                  2000)
    else:
        complete = mantid.ReplaceSpecialValues(
            InputWorkspace=divided,
            NaNValue=0,
            OutputWorkspace=single_spectrum_ws)

    if instrument.perform_abs_vanadium_norm():
        vanadium_material = spline.sample().getMaterial()
        v_number_density = vanadium_material.numberDensityEffective
        v_cross_section = vanadium_material.totalScatterXSection()
        vanadium_shape = spline.sample().getShape()
        # number density in Angstroms-3, volume in m3. Don't bother with 1E30 factor because will cancel
        num_v_atoms = vanadium_shape.volume() * v_number_density

        sample_material = single_spectrum_ws.sample().getMaterial()
        sample_number_density = sample_material.numberDensityEffective
        sample_shape = spline.sample().getShape()
        num_sample_atoms = sample_shape.volume() * sample_number_density

        abs_norm_factor = v_cross_section * num_v_atoms / \
                          (num_sample_atoms * 4 * math.pi)
        logger.notice(
            "Performing absolute normalisation, multiplying by factor=" +
            str(abs_norm_factor))
        # avoid "Variable invalidated, data has been deleted" error when debugging
        output_ws_name = single_spectrum_ws.name()
        abs_norm_factor_ws = mantid.CreateSingleValuedWorkspace(
            DataValue=abs_norm_factor, OutputWorkspace="__abs_norm_factor_ws")
        complete = mantid.Multiply(LHSWorkspace=complete,
                                   RHSWorkspace=abs_norm_factor_ws,
                                   OutputWorkspace=output_ws_name)

    return complete
Beispiel #24
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
Beispiel #25
0
 def _calibrate_data(self, run_set, sam_ws):
     sapi.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask)
     rpf = self._elucidate_reflection_parameter_file(sam_ws)
     sapi.LoadParameterFile(Workspace=sam_ws, Filename=rpf)
     sapi.ModeratorTzeroLinear(InputWorkspace=sam_ws,
                               OutputWorkspace=sam_ws)
     sapi.ConvertUnits(InputWorkspace=sam_ws,
                       OutputWorkspace=sam_ws,
                       Target='Wavelength', EMode='Indirect')
     if self._flux_normalization_type is not None:
         flux_ws = self._generate_flux_spectrum(run_set, sam_ws)
         sapi.RebinToWorkspace(WorkspaceToRebin=sam_ws,
                               WorkspaceToMatch=flux_ws,
                               OutputWorkspace=sam_ws)
         sapi.Divide(LHSWorkspace=sam_ws, RHSWorkspace=flux_ws,
                     OutputWorkspace=sam_ws)
Beispiel #26
0
 def apply_vanadium_corrections(self, cyclevana, i, focused_ws):
     simple.LoadNexusProcessed(Filename=self.get_vanadium(i, cyclevana),
                               OutputWorkspace="vana")
     simple.RebinToWorkspace(WorkspaceToRebin="vana",
                             WorkspaceToMatch=focused_ws,
                             OutputWorkspace="vana")
     simple.Divide(LHSWorkspace=focused_ws,
                   RHSWorkspace="vana",
                   OutputWorkspace=focused_ws)
     simple.DeleteWorkspace("vana")
     simple.ConvertUnits(InputWorkspace=focused_ws,
                         OutputWorkspace=focused_ws,
                         Target="TOF",
                         EMode="Elastic")
     simple.ReplaceSpecialValues(InputWorkspace=focused_ws,
                                 OutputWorkspace=focused_ws,
                                 NaNValue=0.0,
                                 NaNError=0.0,
                                 InfinityValue=0.0,
                                 InfinityError=0.0)
Beispiel #27
0
def _apply_vanadium_norm(sample_ws_foc, van_ws_foc):
    # divide by curves - automatically corrects for solid angle, det efficiency and lambda dep. flux
    sample_ws_foc = mantid.CropWorkspace(InputWorkspace=sample_ws_foc,
                                         OutputWorkspace=sample_ws_foc.name(),
                                         XMin=0.45)
    van_ws_foc_rb = mantid.RebinToWorkspace(
        WorkspaceToRebin=van_ws_foc,
        WorkspaceToMatch=sample_ws_foc,
        OutputWorkspace=VAN_CURVE_REBINNED_NAME)  # copy so as not to lose data
    sample_ws_foc = mantid.Divide(LHSWorkspace=sample_ws_foc,
                                  RHSWorkspace=van_ws_foc_rb,
                                  OutputWorkspace=sample_ws_foc.name(),
                                  AllowDifferentNumberSpectra=False)
    sample_ws_foc = mantid.ReplaceSpecialValues(
        InputWorkspace=sample_ws_foc,
        OutputWorkspace=sample_ws_foc.name(),
        NaNValue=0,
        NaNError=0.0,
        InfinityValue=0,
        InfinityError=0.0)
    return sample_ws_foc
Beispiel #28
0
def Norm_data(rnum, cycle):
    # Load and normalize SX data
    mantid.LoadRaw(
        Filename='/archive/Instruments$/NDXWISH/Instrument/data/cycle_' +
        cycle + '/WISH000' + str(rnum) + '.raw',
        OutputWorkspace='WISH000' + str(rnum),
        LoadMonitors='Separate')
    # ConvertToEventWorkspace(InputWorkspace='WISH000'+str(rnum), OutputWorkspace='WISH000'+str(rnum))
    mantid.CropWorkspace(InputWorkspace='WISH000' + str(rnum),
                         OutputWorkspace='WISH000' + str(i),
                         XMin=6000,
                         XMax=99000)
    mantid.ConvertUnits(InputWorkspace='WISH000' + str(rnum),
                        OutputWorkspace='WISH000' + str(rnum),
                        Target='Wavelength')
    mantid.NormaliseByCurrent(InputWorkspace='WISH000' + str(rnum),
                              OutputWorkspace='WISH000' + str(rnum))
    # normalize By vanadium PredictPeaks
    mantid.CropWorkspace(InputWorkspace='WISH000' + str(rnum),
                         OutputWorkspace='WISH000' + str(rnum),
                         XMin=0.75,
                         XMax=9.3)
    mantid.RebinToWorkspace(WorkspaceToRebin='Vana_smoot1',
                            WorkspaceToMatch='WISH000' + str(rnum),
                            OutputWorkspace='Vana_smoot1')
    mantid.Divide(LHSWorkspace='WISH000' + str(rnum),
                  RHSWorkspace='Vana_smoot1',
                  OutputWorkspace='WISH000' + str(rnum))
    # remove spike in the data above 1e15 and -1e15
    mantid.ReplaceSpecialValues(InputWorkspace='WISH000' + str(rnum),
                                OutputWorkspace='WISH000' + str(rnum),
                                NaNValue=0,
                                InfinityValue=0,
                                BigNumberThreshold=1e15,
                                SmallNumberThreshold=-1e15)
    # Convert to Diffraction MD and Lorentz Correction
    mantid.ConvertToDiffractionMDWorkspace(
        InputWorkspace='WISH000' + str(rnum),
        OutputWorkspace='WISH000' + str(rnum) + '_MD',
        LorentzCorrection=True)
Beispiel #29
0
def _apply_absorb_corrections(calibration_full_paths, corrected_van_ws,
                              gen_absorb):
    corrected_van_ws = mantid.ConvertUnits(InputWorkspace=corrected_van_ws,
                                           Target="Wavelength")

    if gen_absorb:
        raise NotImplementedError(
            "Generating absorption corrections is not currently working correctly"
        )
        # TODO look into this and see what is missing from the original script based on the current
        # TODO generated NXS file history
        absorb_ws = _generate_vanadium_absorb_corrections(
            calibration_full_paths, corrected_van_ws)
    else:
        absorb_ws = _load_van_absorb_corr(calibration_full_paths)

    corrected_van_ws = mantid.RebinToWorkspace(
        WorkspaceToRebin=corrected_van_ws, WorkspaceToMatch=absorb_ws)
    corrected_van_ws = mantid.Divide(LHSWorkspace=corrected_van_ws,
                                     RHSWorkspace=absorb_ws)
    remove_intermediate_workspace(absorb_ws)
    return corrected_van_ws
Beispiel #30
0
def calc_calibration_with_vanadium(focused_ws, index, vanadium_ws, instrument):
    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=instrument._get_focus_tof_binning())

    data_processed = "van_processed" + str(
        index)  # Workaround for Mantid overwriting the WS in a loop

    mantid.Divide(LHSWorkspace=data_ws,
                  RHSWorkspace=vanadium_ws,
                  OutputWorkspace=data_processed)
    mantid.CropWorkspace(InputWorkspace=data_processed,
                         XMin=0.1,
                         OutputWorkspace=data_processed)
    mantid.Scale(InputWorkspace=data_processed,
                 Factor=10,
                 OutputWorkspace=data_processed)

    remove_intermediate_workspace(data_ws)

    return data_processed