Example #1
0
def _load_monitor_sum_range(files, input_dir, instrument):
    loop = 0
    num = files.split("_")
    frange = list(range(int(num[0]), int(num[1]) + 1))
    mspectra = instrument._get_monitor_spectra(int(num[0]))
    for i in frange:
        file_path = instrument._generate_input_full_path(i, input_dir)
        outwork = "mon" + str(i)
        mantid.LoadRaw(Filename=file_path,
                       OutputWorkspace=outwork,
                       SpectrumMin=mspectra,
                       SpectrumMax=mspectra,
                       LoadLogFiles="0")
        loop += 1
        if loop == 2:
            firstwk = "mon" + str(i - 1)
            secondwk = "mon" + str(i)
            load_monitor_summed = mantid.Plus(LHSWorkspace=firstwk,
                                              RHSWorkspace=secondwk)
            mantid.mtd.remove(firstwk)
            mantid.mtd.remove(secondwk)
        elif loop > 2:
            secondwk = "mon" + str(i)
            load_monitor_summed = mantid.Plus(LHSWorkspace=load_monitor_summed,
                                              RHSWorkspace=secondwk)
            mantid.mtd.remove(secondwk)

    return load_monitor_summed
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')
Example #3
0
def _load_raw_files(run_number, instrument, input_dir):
    if isinstance(run_number, int):
        infile = instrument._generate_input_full_path(run_number=run_number,
                                                      input_dir=input_dir)
        load_raw_ws = mantid.LoadRaw(Filename=infile, LoadLogFiles="0")
    else:
        load_raw_ws = _load_raw_file_range(run_number, input_dir, instrument)
    return load_raw_ws
Example #4
0
 def load_multi_run_part(self, extension, run, panel):
     filename = self.get_file_name(run, extension)
     logger.notice("reading filename... {}".format(filename))
     spectra_min, spectra_max = self.return_panel.get(panel)
     output1 = "w{0}-{1}".format(run, panel)
     simple.LoadRaw(Filename=filename,
                    OutputWorkspace=output1,
                    SpectrumMin=str(spectra_min),
                    SpectrumMax=str(spectra_max),
                    LoadLogFiles="0")
     return output1
Example #5
0
def _load_monitor(number, input_dir, instrument):
    if isinstance(number, int):
        full_file_path = instrument._generate_input_full_path(
            run_number=number, input_dir=input_dir)
        mspectra = instrument._get_monitor_spectra(number)
        load_monitor_ws = mantid.LoadRaw(Filename=full_file_path,
                                         SpectrumMin=mspectra,
                                         SpectrumMax=mspectra,
                                         LoadLogFiles="0")
    else:
        load_monitor_ws = _load_monitor_sum_range(files=number,
                                                  input_dir=input_dir,
                                                  instrument=instrument)

    return load_monitor_ws
Example #6
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)
Example #7
0
def _load_raw_file_range(files, input_dir, instrument):
    loop = 0
    num = files.split("_")
    frange = list(range(int(num[0]), int(num[1]) + 1))
    out_ws = None
    for i in frange:
        file_path = instrument._generate_input_full_path(i, input_dir)
        outwork = "run" + str(i)
        mantid.LoadRaw(Filename=file_path,
                       OutputWorkspace=outwork,
                       LoadLogFiles="0")
        loop += 1
        if loop == 2:
            firstwk = "run" + str(i - 1)
            secondwk = "run" + str(i)
            out_ws = mantid.Plus(LHSWorkspace=firstwk, RHSWorkspace=secondwk)
            mantid.mtd.remove(firstwk)
            mantid.mtd.remove(secondwk)
        elif loop > 2:
            secondwk = "run" + str(i)
            out_ws = mantid.Plus(LHSWorkspace=out_ws, RHSWorkspace=secondwk)
            mantid.mtd.remove(secondwk)
    return out_ws
Example #8
0
def shared_load_files(extension, filename, ws, spectrum_max, spectrum_min,
                      is_monitor):
    if not (extension == "nxs" or extension == "raw" or extension[0] == "s"):
        return False
    if extension == "nxs":
        simple.Load(Filename=filename,
                    OutputWorkspace=ws,
                    SpectrumMin=spectrum_min,
                    SpectrumMax=spectrum_min)
    else:
        simple.LoadRaw(Filename=filename,
                       OutputWorkspace=ws,
                       SpectrumMin=spectrum_min,
                       SpectrumMax=spectrum_max,
                       LoadLogFiles="0")
    simple.Rebin(InputWorkspace=ws,
                 OutputWorkspace=ws,
                 Params='6000,-0.00063,110000')
    if not is_monitor:
        simple.MaskBins(InputWorkspace=ws,
                        OutputWorkspace=ws,
                        XMin=99900,
                        XMax=106000)
    return True
def calibrateMerlin(filename):
    # == Set parameters for calibration ==

    rangeLower = 3000  # Integrate counts in each spectra from rangeLower to rangeUpper
    rangeUpper = 20000  #

    # Get calibration raw file and integrate it
    rawCalibInstWS = mantid.LoadRaw(
        filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
    print("Integrating Workspace")
    CalibInstWS = mantid.Integration(rawCalibInstWS,
                                     RangeLower=rangeLower,
                                     RangeUpper=rangeUpper)
    mantid.DeleteWorkspace(rawCalibInstWS)
    print(
        "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate"
    )

    # the known positions are given in pixels inside the tubes and transformed to provide the positions
    # with the center of the tube as the origin
    knownPositions = 2.92713867188 * (numpy.array([
        27.30074322, 92.5, 294.65178585, 362.37861919, 512.77103043,
        663.41425323, 798.3223896, 930.9, 997.08480835
    ]) / 1024 - 0.5)
    funcForm = numpy.array([2, 2, 1, 1, 1, 1, 1, 2, 2], numpy.int8)
    # The calibration will follow different steps for sets of tubes

    # For the door9, the best points to define the known positions are the 1st edge, 5 peaks, last edge.
    points7 = knownPositions[[0, 2, 3, 4, 5, 6, 8]]
    points7func = funcForm[[0, 2, 3, 4, 5, 6, 8]]

    door9pos = points7
    door9func = points7func
    CalibratedComponent = 'MERLIN/door9'  # door9
    # == Get the calibration and put results into calibration table ==
    # also put peaks into PeakFile
    calibrationTable, peakTable = tube.calibrate(
        CalibInstWS,
        CalibratedComponent,
        door9pos,
        door9func,
        outputPeak=True,
        margin=30,
        rangeList=list(range(20))
        # because 20, 21, 22, 23 are defective detectors
    )
    print(
        "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt"
    )
    analisePeakTable(peakTable, 'door9_tube1_peaks')

    # For the door8, the best points to define the known positions are the 1st edge, 5 peaks, last_edge
    door8pos = points7
    door8func = points7func
    CalibratedComponent = 'MERLIN/door8'
    calibrationTable, peakTable = tube.calibrate(
        CalibInstWS,
        CalibratedComponent,
        door8pos,
        door8func,
        outputPeak=True,  # change to peakTable to append to peakTable
        calibTable=calibrationTable,
        margin=30)
    analisePeakTable(peakTable, 'door8_peaks')

    # For the doors 7,6,5,4, 2, 1 we may use the 9 points
    doorpos = knownPositions
    doorfunc = funcForm
    CalibratedComponent = ['MERLIN/door%d' % (i) for i in [7, 6, 5, 4, 2, 1]]
    calibrationTable, peakTable = tube.calibrate(CalibInstWS,
                                                 CalibratedComponent,
                                                 doorpos,
                                                 doorfunc,
                                                 outputPeak=True,
                                                 calibTable=calibrationTable,
                                                 margin=30)
    analisePeakTable(peakTable, 'door1to7_peaks')

    # The door 3 is a special case, because it is composed by diffent kind of tubes.
    # door 3 tubes: 5_8, 5_7, 5_6, 5_5, 5_4, 5_3, 5_2, 5_1, 4_8, 4_7, 4_6, 4_5, 4_4, 4_3, 4_2, 4_1, 3_8, 3_7, 3_6, 3_5, 3_4
    # obeys the same rules as the doors 7, 6, 5, 4, 2, 1
    # For the tubes 3_3, 3_2, 3_1 -> it is better to skip the central peak
    # For the tubes 1_x (smaller tube below), it is better to take the final part of known positions: peak4,peak5,edge6,edge7
    # For the tubes 2_x (smaller tube above, it is better to take the first part of known positions: edge1, edge2, peak1,peak2

    # NOTE: the smaller tubes they have length = 1.22879882813, but 1024 detectors
    # so we have to correct the known positiosn by multiplying by its lenght and dividing by the longer dimension

    from tube_calib_fit_params import TubeCalibFitParams

    # calibrating tubes 1_x
    CalibratedComponent = ['MERLIN/door3/tube_1_%d' % (i) for i in range(1, 9)]

    half_diff_center = (
        2.92713867188 -
        1.22879882813) / 2  # difference among the expected center position for
    # both tubes here a little bit of attempts is necessary.
    # The effective center position and lengh is different for the calibrated tube, that is the reason,
    # the calibrated values of the smaller tube does not seems aligned with the others. By, finding the
    # 'best' half_diff_center value, the alignment occurs nicely.
    half_diff_center = 0.835  #

    # the knownpositions were given with the center of the bigger tube as origin, to convert
    # to the center of the upper tube as origin is necessary to subtract them with  the half_diff_center
    doorpos = knownPositions[[5, 6, 7, 8]] - half_diff_center
    doorfunc = [1, 1, 2, 2]
    # for the smal tubes, automatically searching for the peak position in pixel was not working quite well,
    # so we will give the aproximate position for these tubes through fitPar argument
    fitPar = TubeCalibFitParams([216, 527, 826, 989])
    fitPar.setAutomatic(True)

    calibrationTable, peakTable = tube.calibrate(CalibInstWS,
                                                 CalibratedComponent,
                                                 doorpos,
                                                 doorfunc,
                                                 outputPeak=True,
                                                 fitPar=fitPar,
                                                 calibTable=calibrationTable,
                                                 margin=30)
    analisePeakTable(peakTable, 'door3_tube1_peaks')

    # calibrating tubes 2_x
    CalibratedComponent = ['MERLIN/door3/tube_2_%d' % (i) for i in range(1, 9)]
    # the knownpositions were given with the center of the bigger tube as origin, to convert
    # to the center of the lower tube as origin is necessary to sum them with  (len_big - len_small)/2
    doorpos = knownPositions[[0, 1, 2, 3]] + half_diff_center
    # print doorpos
    doorfunc = [2, 2, 1, 1]

    # for the smal tubes, automatically searching for the peak position in pixel was not working quite well,
    # so we will give the aproximate position for these tubes through fitPar argument
    fitPar = TubeCalibFitParams([50, 202, 664, 815])
    fitPar.setAutomatic(True)

    calibrationTable, peakTable = tube.calibrate(CalibInstWS,
                                                 CalibratedComponent,
                                                 doorpos,
                                                 doorfunc,
                                                 outputPeak=True,
                                                 calibTable=calibrationTable,
                                                 fitPar=fitPar,
                                                 margin=30)

    analisePeakTable(peakTable, 'door3_tube2_peaks')

    # calibrating tubes 3_3,3_2,3_1
    CalibratedComponent = ['MERLIN/door3/tube_3_%d' % (i) for i in [1, 2, 3]]
    doorpos = knownPositions[[0, 1, 2, 3, 5, 6, 7, 8]]
    doorfunc = funcForm[[0, 1, 2, 3, 5, 6, 7, 8]]
    calibrationTable, peakTable = tube.calibrate(CalibInstWS,
                                                 CalibratedComponent,
                                                 doorpos,
                                                 doorfunc,
                                                 outputPeak=True,
                                                 calibTable=calibrationTable,
                                                 margin=30)
    analisePeakTable(peakTable, 'door3_123_peaks')

    # calibrating others inside door3
    # 5_8, 5_7, 5_6, 5_5, 5_4, 5_3, 5_2, 5_1, 4_8, 4_7, 4_6, 4_5, 4_4, 4_3, 4_2, 4_1, 3_8, 3_7, 3_6, 3_5, 3_4
    part_3 = ['MERLIN/door3/tube_3_%d' % (i) for i in [4, 5, 6, 7, 8]]
    part_4 = ['MERLIN/door3/tube_4_%d' % (i) for i in range(1, 9)]
    part_5 = ['MERLIN/door3/tube_5_%d' % (i) for i in range(1, 9)]
    CalibratedComponent = part_3 + part_4 + part_5
    doorpos = knownPositions
    doorfunc = funcForm
    calibrationTable, peakTable = tube.calibrate(CalibInstWS,
                                                 CalibratedComponent,
                                                 doorpos,
                                                 doorfunc,
                                                 outputPeak=True,
                                                 calibTable=calibrationTable,
                                                 margin=30)
    analisePeakTable(peakTable, 'door3_peaks')

    # == Apply the Calibation ==
    mantid.ApplyCalibration(Workspace=CalibInstWS,
                            PositionTable=calibrationTable)
    print("Applied calibration")
Example #10
0
    def _load_and_sum_runs(self, spectra):
        """Load the input set of runs & sum them if there
        is more than one.
            @param spectra :: The list of spectra to load
            @returns a tuple of length 2 containing (main_detector_ws, monitor_ws)
        """
        isis = config.getFacility("ISIS")
        inst_prefix = isis.instrument("VESUVIO").shortName()

        runs = self._get_runs()

        self.summed_ws, self.summed_mon = "__loadraw_evs", "__loadraw_evs_monitors"
        for index, run in enumerate(runs):
            run = inst_prefix + str(run)
            self._raise_error_period_scatter(run, self._back_scattering)
            if index == 0:
                out_name, out_mon = SUMMED_WS, SUMMED_MON
            else:
                out_name, out_mon = SUMMED_WS + 'tmp', SUMMED_MON + 'tmp'

            # Load data
            raw_filepath = FileFinder.findRuns(run)[0]
            ms.LoadRaw(Filename=raw_filepath,
                       SpectrumList=spectra,
                       OutputWorkspace=out_name,
                       LoadMonitors='Exclude',
                       EnableLogging=_LOGGING_)
            ms.LoadRaw(Filename=raw_filepath,
                       SpectrumList=self._mon_spectra,
                       OutputWorkspace=out_mon,
                       EnableLogging=_LOGGING_)

            # Sum
            if index > 0:
                ms.Plus(LHSWorkspace=SUMMED_WS,
                        RHSWorkspace=out_name,
                        OutputWorkspace=SUMMED_WS,
                        EnableLogging=_LOGGING_)
                ms.Plus(LHSWorkspace=SUMMED_MON,
                        RHSWorkspace=out_mon,
                        OutputWorkspace=SUMMED_MON,
                        EnableLogging=_LOGGING_)

                ms.DeleteWorkspace(out_name, EnableLogging=_LOGGING_)
                ms.DeleteWorkspace(out_mon, EnableLogging=_LOGGING_)

        # Check to see if extra data needs to be loaded to normalise in data
        x_max = self._tof_max
        if self._foil_out_norm_end > self._tof_max:
            x_max = self._foil_out_norm_end
            self._crop_required = True

        ms.CropWorkspace(Inputworkspace= SUMMED_WS,
                         OutputWorkspace=SUMMED_WS,
                         XMax=x_max,
                         EnableLogging=_LOGGING_)
        ms.CropWorkspace(Inputworkspace= SUMMED_MON,
                         OutputWorkspace=SUMMED_MON,
                         XMax=self._mon_tof_max,
                         EnableLogging=_LOGGING_)

        summed_data, summed_mon = mtd[SUMMED_WS], mtd[SUMMED_MON]
        self._load_diff_mode_parameters(summed_data)
        return summed_data, summed_mon
Example #11
0
    def _exec_single_foil_state_mode(self):
        """
        Execution path when a single foil state is requested
        """
        runs = self._get_runs()
        if len(runs) > 1:
            raise RuntimeError("Single foil state mode does not currently support summing "
                               "multiple files")

        isis = config.getFacility("ISIS")
        inst_prefix = isis.instrument("VESUVIO").shortName()

        try:
            run_str = inst_prefix + runs[0]
        except ValueError:
            run_str = runs[0]

        self._raise_error_period_scatter(run_str, self._back_scattering)
        all_spectra = [item for sublist in self._spectra for item in sublist]
        ms.LoadRaw(Filename=run_str, OutputWorkspace=SUMMED_WS, SpectrumList=all_spectra,
                   EnableLogging=_LOGGING_)
        raw_group = mtd[SUMMED_WS]
        self._nperiods = raw_group.size()
        first_ws = raw_group[0]
        foil_out = WorkspaceFactory.create(first_ws)
        x_values = first_ws.readX(0)
        self.foil_out = foil_out

        foil_map = SpectraToFoilPeriodMap(self._nperiods)
        for ws_index, spectrum_no in enumerate(all_spectra):
            self._set_spectra_type(spectrum_no)
            foil_out_periods, foil_thin_periods, _ = self._get_foil_periods()

            if self._diff_opt == "FoilOut":
                raw_grp_indices = foil_map.get_indices(spectrum_no, foil_out_periods)
            elif self._diff_opt == "FoilIn":
                indices_thin = foil_map.get_indices(spectrum_no, foil_thin_periods)
                indices_thick = foil_map.get_indices(spectrum_no, foil_thin_periods)
                raw_grp_indices = indices_thin + indices_thick
            elif self._diff_opt == "FoilInOut":
                raw_grp_indices = range(0, self._nperiods)
            else:
                raise RuntimeError("Unknown single foil mode: %s." % (self._diff_opt))

            dataY = foil_out.dataY(ws_index)
            dataE = foil_out.dataE(ws_index)
            for group_index in raw_grp_indices:
                dataY += raw_group[group_index].readY(ws_index)
                dataE += np.square(raw_group[group_index].readE(ws_index))
            np.sqrt(dataE, dataE)
            foil_out.setX(ws_index, x_values)

        ip_file = self.getPropertyValue(INST_PAR_PROP)
        if len(ip_file) > 0:
            self.foil_out = self._load_ip_file(self.foil_out, ip_file)

        if self._sumspectra:
            self._sum_all_spectra()

        ms.DeleteWorkspace(Workspace=SUMMED_WS)
        self._store_results()
Example #12
0
    def process_incidentmon(self, number, extension, spline_terms=20):
        if type(number) is int:
            filename = self.get_file_name(number, extension)
            works = "monitor{}".format(number)
            shared_load_files(extension, filename, works, 4, 4, True)
            if extension[:9] == "nxs_event":
                temp = "w{}_monitors".format(number)
                works = "w{}_monitor4".format(number)
                simple.Rebin(InputWorkspace=temp,
                             OutputWorkspace=temp,
                             Params='6000,-0.00063,110000',
                             PreserveEvents=False)
                simple.ExtractSingleSpectrum(InputWorkspace=temp,
                                             OutputWorkspace=works,
                                             WorkspaceIndex=3)
        else:
            num_1, num_2 = split_run_string(number)
            works = "monitor{0}_{1}".format(num_1, num_2)
            filename = self.get_file_name(num_1, extension)
            works1 = "monitor{}".format(num_1)
            simple.LoadRaw(Filename=filename,
                           OutputWorkspace=works1,
                           SpectrumMin=4,
                           SpectrumMax=4,
                           LoadLogFiles="0")
            filename = self.get_file_name(num_2, extension)
            works2 = "monitor{}".format(num_2)
            simple.LoadRaw(Filename=filename,
                           OutputWorkspace=works2,
                           SpectrumMin=4,
                           SpectrumMax=4,
                           LoadLogFiles="0")
            simple.MergeRuns(InputWorkspaces=works1 + "," + works2,
                             OutputWorkspace=works)
            simple.DeleteWorkspace(works1)
            simple.DeleteWorkspace(works2)
        simple.ConvertUnits(InputWorkspace=works,
                            OutputWorkspace=works,
                            Target="Wavelength",
                            Emode="Elastic")
        lambda_min, lambda_max = Wish.LAMBDA_RANGE
        simple.CropWorkspace(InputWorkspace=works,
                             OutputWorkspace=works,
                             XMin=lambda_min,
                             XMax=lambda_max)
        ex_regions = np.array([[4.57, 4.76], [3.87, 4.12], [2.75, 2.91],
                               [2.24, 2.50]])
        simple.ConvertToDistribution(works)

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

        simple.SplineBackground(InputWorkspace=works,
                                OutputWorkspace=works,
                                WorkspaceIndex=0,
                                NCoeff=spline_terms)

        simple.SmoothData(InputWorkspace=works,
                          OutputWorkspace=works,
                          NPoints=40)
        simple.ConvertFromDistribution(works)
        return works
Example #13
0
def CalibrateWish(run_per_panel_list):
    '''
    :param run_per_panel_list: is a list of tuples with the run number and the associated panel

    run_per_panel_list =  [ (17706, 'panel01'), (17705, 'panel02'),  (17701, 'panel03'), (17702, 'panel04'), (17695, 'panel05')]
    '''
    # == Set parameters for calibration ==
    previousDefaultInstrument = mantid.config['default.instrument']
    mantid.config['default.instrument'] = "WISH"

    # definition of the parameters static for the calibration
    lower_tube = numpy.array(
        [-0.41, -0.31, -0.21, -0.11, -0.02, 0.09, 0.18, 0.28, 0.39])
    upper_tube = numpy.array(lower_tube + 0.003)
    funcForm = 9 * [1]  # 9 gaussian peaks
    margin = 15
    low_range = list(range(0, 76))
    high_range = list(range(76, 152))
    kwargs = {'margin': margin}

    # it will copy all the data from the runs to have a single instrument with the calibrated data.
    whole_instrument = mantid.LoadRaw(str(run_per_panel_list[0][0]))
    whole_instrument = mantid.Integration(whole_instrument)

    for (run_number, panel_name) in run_per_panel_list:
        panel_name = str(panel_name)
        run_number = str(run_number)
        # load your data and integrate it
        ws = mantid.LoadRaw(run_number, OutputWorkspace=panel_name)
        ws = mantid.Integration(ws, 1, 20000, OutputWorkspace=panel_name)

        # use the TubeSpec object to be able to copy the data to the whole_instrument
        tube_set = TubeSpec(ws)
        tube_set.setTubeSpecByString(panel_name)

        # update kwargs argument before calling calibrate
        kwargs['rangeList'] = low_range  # calibrate only the lower tubes
        calibrationTable = tube.calibrate(ws, tube_set, lower_tube, funcForm,
                                          **kwargs)

        # update kwargs
        kwargs[
            'calibTable'] = calibrationTable  # append calib to calibrationtable
        kwargs['rangeList'] = high_range  # calibrate only the upper tubes

        calibrationTable = tube.calibrate(ws, tube_set, upper_tube, funcForm,
                                          **kwargs)
        kwargs['calibTable'] = calibrationTable

        mantid.ApplyCalibration(ws, calibrationTable)

        # copy data from the current panel to the whole_instrument
        for i in range(tube_set.getNumTubes()):
            for spec_num in tube_set.getTube(i):
                whole_instrument.setY(spec_num, ws.dataY(spec_num))

    # calibrate the whole_instrument with the last calibrated panel which has the calibration accumulation
    # of all the others
    mantid.CopyInstrumentParameters(run_per_panel_list[-1][1],
                                    whole_instrument)

    mantid.config['default.instrument'] = previousDefaultInstrument
Example #14
0
def CalibrateMerlin(RunNumber):
    # == Set parameters for calibration ==
    previousDefaultInstrument = mantid.config['default.instrument']
    mantid.config['default.instrument'] = "MERLIN"
    filename = str(RunNumber)  # Name of calibration run.
    rangeLower = 3000  # Integrate counts in each spectra from rangeLower to rangeUpper
    rangeUpper = 20000  #

    # Set parameters for ideal tube.
    Left = 2.0  # Where the left end of tube should be in pixels (target for AP)
    Centre = 512.5  # Where the centre of the tube should be in pixels (target for CP)
    Right = 1023.0  # Where the right of the tube should be in pixels (target for BP)
    ActiveLength = 2.9  # Active length of tube in Metres

    # Set initial parameters for peak finding
    ExpectedHeight = 1000.0  # Expected Height of Gaussian Peaks (initial value of fit parameter)
    ExpectedWidth = 32.0  # Expected width of centre peak in Pixels (initial value of fit parameter)
    ExpectedPositions = [
        35.0, 512.0, 989.0
    ]  # Expected positions of the edges and peak in pixels (initial values of fit parameters)

    # Set what we want to calibrate (e.g whole instrument or one door )
    CalibratedComponent = 'MERLIN'  # Calibrate door 2

    # Get calibration raw file and integrate it
    print(filename)
    rawCalibInstWS = mantid.LoadRaw(filename)
    # 'raw' in 'rawCalibInstWS' means unintegrated.
    print("Integrating Workspace")
    CalibInstWS = mantid.Integration(rawCalibInstWS,
                                     RangeLower=rangeLower,
                                     RangeUpper=rangeUpper)
    mantid.DeleteWorkspace(rawCalibInstWS)
    print(
        "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate"
    )

    # == Create Objects needed for calibration ==

    ## In the merlin case, the positions are usually given in pixels, instead of being given in
    ## meters, to convert to meter and put the origin in the center, we have to apply the following
    ## transformation:
    ##
    ## pos = pixel * length/npixels - length/2 = length (pixel/npixels - 1/2)
    ##
    ## for merlin: npixels = 1024

    knownPos = ActiveLength * (numpy.array([Left, Centre, Right]) / 1024.0 -
                               0.5)
    funcForm = 3 * [1]

    # Get fitting parameters
    fitPar = TubeCalibFitParams(ExpectedPositions,
                                ExpectedHeight,
                                ExpectedWidth,
                                margin=40)

    print("Created objects needed for calibration.")

    # == Get the calibration and put results into calibration table ==
    # also put peaks into PeakFile
    calibrationTable, peakTable = tube.calibrate(CalibInstWS,
                                                 CalibratedComponent,
                                                 knownPos,
                                                 funcForm,
                                                 outputPeak=True,
                                                 fitPar=fitPar,
                                                 plotTube=list(
                                                     range(0, 280, 20)))
    print(
        "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt"
    )

    # == Apply the Calibation ==
    mantid.ApplyCalibration(Workspace=CalibInstWS,
                            CalibrationTable=calibrationTable)
    print("Applied calibration")

    # == Save workspace ==
    # mantid.SaveNexusProcessed(CalibInstWS, 'TubeCalibDemoMerlinResult.nxs', "Result of Running TubeCalibDemoMerlin_Simple.py")
    # print("saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMerlinResult.nxs")

    # == Reset default instrument ==
    mantid.config['default.instrument'] = previousDefaultInstrument