Exemplo n.º 1
0
    def _load_monitors(self, target):
        """
        Load monitor data for all target runs into a single workspace

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

        Returns
        -------
        Mantid.EventWorkspace
        """
        valid_targets = ('sample', 'background', 'vanadium')
        if target not in valid_targets:
            raise KeyError('Target must be one of ' + ', '.join(valid_targets))
        target_to_runs = dict(sample='RunNumbers',
                              background='BackgroundRuns',
                              vanadium='VanadiumRuns')
        #
        # Load monitors files together
        #
        rl = self._run_lists(self.getProperty(target_to_runs[target]).value)
        _t_all_w = None
        for run in rl:
            file_name = "{0}_{1}_event.nxs".format(self._short_inst, str(run))
            _t_w = LoadNexusMonitors(file_name)
            if _t_all_w is None:
                _t_all_w = CloneWorkspace(_t_w)
            else:
                _t_all_w += _t_w
        return _t_all_w
def GetIncidentSpectrumFromMonitor(Filename,
                                   OutputWorkspace="IncidentWorkspace",
                                   IncidentIndex=0,
                                   TransmissionIndex=1,
                                   Binning=".1,6000,2.9",
                                   BinType="ResampleX"):

    # -------------------------------------------------
    # Joerg's read_bm.pro code

    # Loop workspaces to get each incident spectrum
    monitor = 'monitor'
    LoadNexusMonitors(Filename=Filename, OutputWorkspace=monitor)
    ConvertUnits(InputWorkspace=monitor,
                 OutputWorkspace=monitor,
                 Target='Wavelength',
                 EMode='Elastic')
    lambdaMin, lambdaBinning, lambdaMax = [
        float(x) for x in Binning.split(',')
    ]
    for x in [lambdaMin, lambdaBinning, lambdaMax]:
        print(x, type(x))
    if BinType == 'ResampleX':
        ResampleX(
            InputWorkspace=monitor,
            OutputWorkspace=monitor,
            XMin=[lambdaMin],  # TODO change ResampleX
            XMax=[lambdaMax],
            NumberBins=abs(int(lambdaBinning)),
            LogBinning=(int(lambdaBinning) < 0),
            PreserveEvents=True)
    elif BinType == 'Rebin':
        Rebin(InputWorkspace=monitor,
              OutputWorkspace=monitor,
              Params=[lambdaMin, lambdaBinning, lambdaMax],
              PreserveEvents=True)
    ConvertToPointData(InputWorkspace=monitor, OutputWorkspace=monitor)

    lam = mtd[monitor].readX(IncidentIndex)  # wavelength in A
    bm = mtd[monitor].readY(IncidentIndex)  # neutron counts / microsecond
    p = 0.000794807  # Pressure
    thickness = .1  # 1 mm = .1 cm
    abs_xs_3He = 5333.0  # barns for lambda == 1.798 A
    p_to_rho = 2.43e-5  # pressure to rho (atoms/angstroms^3)
    # p is set to give efficiency of 1.03 10^-5 at 1.8 A
    e0 = abs_xs_3He * lam / 1.798 * p_to_rho * p * thickness
    print('Efficiency:', 1. - np.exp(-e0))
    bmeff = bm / (1. - np.exp(-e0))  # neutron counts / microsecond
    print(bmeff)
    # bmeff = bmeff / constants.micro      # neutron counts / second

    CreateWorkspace(DataX=lam,
                    DataY=bmeff,
                    OutputWorkspace=OutputWorkspace,
                    UnitX='Wavelength')
    mtd[OutputWorkspace].setYUnit('Counts')
    return mtd[OutputWorkspace]
        if nomad_test:
            runs[0] = "NOM_33943"
            binning = "0.0212406,0.00022,3.39828"  # matches read_bm.pro for lambda[100:15999]
        print("Processing Scan: ", runs[0])

        monitor = 'monitor'
        incident_ws = 'incident_ws'

        fig, (ax_bm,
              ax_bmeff) = plt.subplots(2,
                                       subplot_kw={'projection': 'mantid'},
                                       sharex=True)

        # Beam Monitor
        LoadNexusMonitors(Filename=runs[0], OutputWorkspace=monitor)
        ConvertUnits(InputWorkspace=monitor,
                     OutputWorkspace=monitor,
                     Target='Wavelength',
                     EMode='Elastic')

        Rebin(InputWorkspace=monitor,
              OutputWorkspace=monitor,
              Params=binning,
              PreserveEvents=False)

        ax_bm.plot(mtd[monitor],
                   '-',
                   wkspIndex=0,
                   label='Monitor',
                   distribution=True)
Exemplo n.º 4
0
    def _flux_normalization(self, w, target):
        """
        Divide data by integrated flux intensity

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

        Returns
        -------
        Mantid.EventWorkspace
        """
        valid_targets = ('sample', 'background', 'vanadium')
        if target not in valid_targets:
            raise KeyError('Target must be one of ' + ', '.join(valid_targets))
        w_nor = None
        if self._flux_normalization_type == 'Monitor':
            _t_flux = None
            _t_flux_name = tws('monitor_aggregate')
            target_to_runs = dict(sample='RunNumbers',
                                  background='BackgroundRuns',
                                  vanadium='VanadiumRuns')
            rl = self._run_list(self.getProperty(target_to_runs[target]).value)

            _t_w_name = tws('monitor')
            for run in rl:
                run_name = '{0}_{1}'.format(self._short_inst, str(run))
                _t_w = LoadNexusMonitors(run_name, OutputWorkspace=_t_w_name)
                if _t_flux is None:
                    _t_flux = CloneWorkspace(_t_w,
                                             OutputWorkspace=_t_flux_name)
                else:
                    _t_flux = Plus(_t_flux, _t_w, OutputWorkspace=_t_flux_name)

            _t_flux = ConvertUnits(_t_flux,
                                   Target='Wavelength',
                                   Emode='Elastic',
                                   OutputWorkspace=_t_flux_name)
            _t_flux = CropWorkspace(_t_flux,
                                    XMin=self._wavelength_band[0],
                                    XMax=self._wavelength_band[1],
                                    OutputWorkspace=_t_flux_name)
            _t_flux = OneMinusExponentialCor(_t_flux,
                                             C='0.20749999999999999',
                                             C1='0.001276',
                                             OutputWorkspace=_t_flux_name)
            _t_flux = Scale(_t_flux,
                            Factor='1e-06',
                            Operation='Multiply',
                            OutputWorkspace=_t_flux_name)
            _t_flux = Integration(_t_flux,
                                  RangeLower=self._wavelength_band[0],
                                  RangeUpper=self._wavelength_band[1],
                                  OutputWorkspace=_t_flux_name)
            w_nor = Divide(w, _t_flux, OutputWorkspace=w.name())
        else:
            aggregate_flux = None
            if self._flux_normalization_type == 'Proton Charge':
                aggregate_flux = w.getRun().getProtonCharge()
            elif self._flux_normalization_type == 'Duration':
                aggregate_flux = w.getRun().getProperty('duration').value
            w_nor = Scale(w,
                          Operation='Multiply',
                          Factor=1.0 / aggregate_flux,
                          OutputWorkspace=w.name())
        return w_nor
Exemplo n.º 5
0
def calculate_ei(input_file):
    # Auto Find Eis by finding maximum data point in m2 (excluding end points)
    # and looking for neighbouring reps according to Fermi speed
    # Doesn't deal with cases where the peaks enter the 2nd frame (i.e 2 meV on MARI)
    print(input_file)
    w1 = Load(input_file)
    mon = LoadNexusMonitors(input_file)
    run = w1.getRun()

    # set up ==================================================
    monitor_spectra_2  = 41475
    monitor_spectra_3  = 41476
    monitor_index_2 = 2
    monitor_index_3 = 3
    log  = 'Fermi_Speed'

    # Get instrument parameters ===============================
    inst = w1.getInstrument()
    source = inst.getSource()
    L_m2 = mon.getDetector(monitor_index_2).getDistance(source)
    L_m3 = mon.getDetector(monitor_index_3).getDistance(source)
    L_Fermi = inst.getComponentByName("chopper-position").getDistance(source)
    freq = run.getLogData(log).value[-1]
    period = L_m2 / L_Fermi * 1.e6 / freq / 2. # include pi-pulses

    # Find maximum value and identify strongest rep ===========
    m2spec = ExtractSingleSpectrum(mon,monitor_index_2)
    m2spec = Rebin(m2spec,"200,2,18000")
    maxm2 = Max(m2spec)
    TOF = maxm2.readX(0)[0]

    # Generate list of possible reps in m2 ====================
    irep = -5
    while True:
        t = TOF + irep*period
        if t > 0:
            ireps = numpy.array(range(irep,irep+20))
            reps = TOF + period * ireps
            break
        else:
            irep += 1

    # exclude all reps that go past the frame in m3 ===========       
    reps_m3 = reps * L_m3 / L_m2
    reps_m3 = [x for x in reps_m3 if x < 19999.]
    reps = reps[0:len(reps_m3)]
    # exclude all reps at short times
    reps = [x for x in reps if x > 200.]

    # try GetEi for the reps ==================================
    Ei = []
    TOF = []
    for t in reps:
        v_i = L_m2 / t                    # m/mus
        Ei_guess = 5.227e6 * v_i**2       # meV
        try:
            (En,TOF2,dummy,tzero) = GetEi(mon, monitor_spectra_2, monitor_spectra_3, Ei_guess)
        except:
            continue
        if abs(t - TOF2) > 20. or abs(tzero) > 100.: continue
        Ei.append(Ei_guess)
        TOF.append(TOF2)

    #=========================================================
    for ii in range(len(Ei)):
        print("%f meV at TOF = %f mus" % (Ei[ii],TOF[ii]))
    return Ei