예제 #1
0
파일: wand.py 프로젝트: rosswhitfield/wand
def convertToHKL(ws,
                 OutputWorkspace='__md_hkl',
                 norm=None,
                 UB=None,
                 Extents=[-10, 10, -10, 10, -10, 10],
                 Bins=[101, 101, 101],
                 Append=False):
    """Output MDEventWorkspace in HKL
    """

    SetUB(ws, UB=UB)
    ConvertToMD(ws,
                QDimensions='Q3D',
                QConversionScales='HKL',
                dEAnalysisMode='Elastic',
                Q3DFrames='HKL',
                OutputWorkspace='__temp')

    AlignedDim0 = "{},{},{},{}".format(mtd['__temp'].getDimension(0).name,
                                       Extents[0], Extents[1], int(Bins[0]))
    AlignedDim1 = "{},{},{},{}".format(mtd['__temp'].getDimension(1).name,
                                       Extents[2], Extents[3], int(Bins[1]))
    AlignedDim2 = "{},{},{},{}".format(mtd['__temp'].getDimension(2).name,
                                       Extents[4], Extents[5], int(Bins[2]))

    BinMD(InputWorkspace='__temp',
          TemporaryDataWorkspace=OutputWorkspace
          if Append and mtd.doesExist(OutputWorkspace) else None,
          OutputWorkspace=OutputWorkspace,
          AlignedDim0=AlignedDim0,
          AlignedDim1=AlignedDim1,
          AlignedDim2=AlignedDim2)
    DeleteWorkspace('__temp')
    if norm is not None:
        SetUB(norm, UB=UB)
        ConvertToMD(norm,
                    QDimensions='Q3D',
                    QConversionScales='HKL',
                    dEAnalysisMode='Elastic',
                    Q3DFrames='HKL',
                    OutputWorkspace='__temp_norm')
        BinMD(InputWorkspace='__temp_norm',
              TemporaryDataWorkspace=str(OutputWorkspace) + '_norm' if Append
              and mtd.doesExist(str(OutputWorkspace) + '_norm') else None,
              OutputWorkspace=str(OutputWorkspace) + '_norm',
              AlignedDim0=AlignedDim0,
              AlignedDim1=AlignedDim1,
              AlignedDim2=AlignedDim2)
        DeleteWorkspace('__temp_norm')
    return OutputWorkspace
예제 #2
0
    def test_qtohkl_corelli(self):
        Load(Filename='CORELLI_29782.nxs', OutputWorkspace='data')
        SetGoniometer(Workspace='data', Axis0='BL9:Mot:Sample:Axis1,0,1,0,1')
        LoadIsawUB(InputWorkspace='data',
                   Filename='SingleCrystalDiffuseReduction_UB.mat')
        ConvertToMD(InputWorkspace='data',
                    QDimensions='Q3D',
                    dEAnalysisMode='Elastic',
                    Q3DFrames='HKL',
                    QConversionScales='HKL',
                    OutputWorkspace='HKL',
                    Uproj='1,1,0',
                    Vproj='1,-1,0',
                    Wproj='0,0,1',
                    MinValues='-20,-20,-20',
                    MaxValues='20,20,20')
        hkl_binned = BinMD('HKL',
                           AlignedDim0='[H,H,0],-10.05,10.05,201',
                           AlignedDim1='[H,-H,0],-10.05,10.05,201',
                           AlignedDim2='[0,0,L],-1.05,1.05,21')
        ConvertToMD(InputWorkspace='data',
                    QDimensions='Q3D',
                    dEAnalysisMode='Elastic',
                    Q3DFrames='Q_sample',
                    OutputWorkspace='q_sample',
                    MinValues='-20,-20,-20',
                    MaxValues='20,20,20')

        hkl = ConvertQtoHKLMDHisto(
            InputWorkspace=mtd["q_sample"],
            Uproj="1,1,0",
            Vproj="1,-1,0",
            Wproj="0,0,1",
            Extents="-10.05,10.05,-10.05,10.05,-1.05,1.05",
            Bins="201,201,21")

        for i in range(hkl.getNumDims()):
            self.assertEqual(
                hkl_binned.getDimension(i).name,
                hkl.getDimension(i).name)

        orig_sig = hkl_binned.getSignalArray()
        new_sig = hkl.getSignalArray()

        np.testing.assert_allclose(np.asarray(new_sig),
                                   np.asarray(orig_sig),
                                   rtol=1.0e-5,
                                   atol=3)
예제 #3
0
def example_plots():
    #create slices and cuts
    w = Load(
        Filename=
        '/SNS/HYS/IPTS-14189/shared/autoreduce/4pixel/HYS_102102_4pixel_spe.nxs'
    )
    SetUB(w, 4.53, 4.53, 11.2, 90, 90, 90, "1,0,0", "0,0,1")
    mde = ConvertToMD(w, QDimensions='Q3D')
    sl1d = CutMD(InputWorkspace=mde,
                 P1Bin='-5,5',
                 P2Bin='-5,5',
                 P3Bin='2,4',
                 P4Bin='-10,0.5,15',
                 NoPix=True)
    sl2d = CutMD(InputWorkspace=mde,
                 P1Bin='-5,5',
                 P2Bin='-5,5',
                 P3Bin='-5,0.1,5',
                 P4Bin='-10,1,15',
                 NoPix=True)

    #2 subplots per page
    fig, ax = plt.subplots(2, 1)
    Plot1DMD(ax[0], sl1d, NumEvNorm=True, fmt='ro')
    ax[0].set_ylabel("Int(a.u.)")
    pcm = Plot2DMD(ax[1], sl2d, NumEvNorm=True)
    fig.colorbar(pcm, ax=ax[1])

    #save to png
    plt.tight_layout(1.08)
    fig.savefig('/tmp/test.png')
    def prepare_background(input_md, reference_sample_mde, background_md: str):
        """Prepare background MDEventWorkspace from reduced sample Matrix
        This is the previous solution to merge all the ExperimentInfo
        """
        dgs_data = CloneWorkspace(input_md)
        data_MDE = mtd[reference_sample_mde]
        if mtd.doesExist('background_MDE'):
            DeleteWorkspace('background_MDE')

        for i in range(data_MDE.getNumExperimentInfo()):
            phi, chi, omega = data_MDE.getExperimentInfo(
                i).run().getGoniometer().getEulerAngles('YZY')
            AddSampleLogMultiple(Workspace=dgs_data,
                                 LogNames='phi, chi, omega',
                                 LogValues='{},{},{}'.format(phi, chi, omega))
            SetGoniometer(Workspace=dgs_data, Goniometers='Universal')
            ConvertToMD(InputWorkspace=dgs_data,
                        QDimensions='Q3D',
                        dEAnalysisMode='Direct',
                        Q3DFrames="Q_sample",
                        MinValues='-11,-11,-11,-25',
                        MaxValues='11,11,11,49',
                        PreprocDetectorsWS='-',
                        OverwriteExisting=False,
                        OutputWorkspace=background_md)
예제 #5
0
    def setUpClass(cls):
        x = np.linspace(0, 99, 100)
        y = x * 1
        e = y * 0 + 2
        cls.m_workspace = wrap_workspace(
            CreateWorkspace(x, y, e, OutputWorkspace="m_ws"), 'm_ws')

        sim_workspace = CreateSimulationWorkspace(Instrument='MAR',
                                                  BinParams=[-10, 1, 10],
                                                  UnitX='DeltaE',
                                                  OutputWorkspace='ws1')
        AddSampleLog(sim_workspace,
                     LogName='Ei',
                     LogText='3.',
                     LogType='Number')
        cls.px_workspace = ConvertToMD(InputWorkspace=sim_workspace,
                                       OutputWorkspace="ws1",
                                       QDimensions='|Q|',
                                       dEAnalysisMode='Direct',
                                       MinValues='-10,0,0',
                                       MaxValues='10,6,500',
                                       SplitInto='50,50')
        cls.px_workspace_clone = CloneWorkspace(
            InputWorkspace=cls.px_workspace,
            OutputWorkspace='ws2',
            StoreInADS=False)
        cls.px_workspace = wrap_workspace(cls.px_workspace, 'ws1')
        cls.px_workspace_clone = wrap_workspace(cls.px_workspace_clone, 'ws2')
예제 #6
0
 def _calcQEproj(self, input_workspace, emode, axis1, axis2):
     """ Carries out either the Q-E or E-Q projections """
     # For indirect geometry and large datafiles (likely to be using a 1-to-1 mapping use ConvertToMD('|Q|')
     numSpectra = input_workspace.getNumberHistograms()
     if emode == 'Indirect' or numSpectra > 1000:
         retval = ConvertToMD(InputWorkspace=input_workspace, QDimensions=MOD_Q_LABEL,
                              PreprocDetectorsWS='-', dEAnalysisMode=emode, StoreInADS=False)
         if axis1 == DELTA_E_LABEL and axis2 == MOD_Q_LABEL:
             retval = self._flip_axes(retval)
     # Otherwise first run SofQW3 to rebin it in |Q| properly before calling ConvertToMD with CopyToMD
     else:
         limits = self.getProperty('Limits').value
         limits = ','.join([str(limits[i]) for i in [0, 2, 1]])
         retval = SofQW3(InputWorkspace=input_workspace, QAxisBinning=limits, Emode=emode, StoreInADS=False)
         retval = ConvertToMD(InputWorkspace=retval, QDimensions='CopyToMD', PreprocDetectorsWS='-',
                              dEAnalysisMode=emode, StoreInADS=False)
         if axis1 == MOD_Q_LABEL:
             retval = self._flip_axes(retval)
     return retval
예제 #7
0
def convertToQSample(ws, OutputWorkspace='__md_q_sample'):
    """Output MDEventWorkspace in Q Sample
    """
    ConvertToMD(ws,
                QDimensions='Q3D',
                dEAnalysisMode='Elastic',
                Q3DFrames='Q_sample',
                MinValues='-10,-1,-10',
                MaxValues='10,1,10',
                OutputWorkspace=OutputWorkspace)
    return OutputWorkspace
예제 #8
0
 def _calcThetaEproj(self, input_workspace, emode, axis1, axis2):
     """ Carries out either the 2Theta-E or E-2Theta projections """
     retval = ConvertSpectrumAxis(InputWorkspace=input_workspace, Target='Theta')
     # Work-around for a bug in ConvertToMD.
     wsdet = self._getDetWS(input_workspace) if emode == 'Indirect' else '-'
     retval = ConvertToMD(InputWorkspace=retval, QDimensions='CopyToMD', PreprocDetectorsWS=wsdet,
                          dEAnalysisMode=emode, StoreInADS=False)
     if emode == 'Indirect':
         DeleteWorkspace(wsdet)
     if axis1 == THETA_LABEL:
         retval = self._flip_axes(retval)
     return retval
예제 #9
0
 def setUpClass(cls):  # create (non-zero) test data
     sim_workspace = CreateSimulationWorkspace(Instrument='MAR',
                                               BinParams=[-10, 1, 10],
                                               UnitX='DeltaE',
                                               OutputWorkspace='simws')
     AddSampleLog(sim_workspace,
                  LogName='Ei',
                  LogText='3.',
                  LogType='Number')
     cls.workspace = ConvertToMD(InputWorkspace=sim_workspace,
                                 OutputWorkspace="convert_ws",
                                 QDimensions='|Q|',
                                 dEAnalysisMode='Direct',
                                 MinValues='-10,0,0',
                                 MaxValues='10,6,500',
                                 SplitInto='50,50')
     cls.workspace = PixelWorkspace(cls.workspace, 'convert_ws')
    def prepare_single_exp_info_background(input_md_name,
                                           output_md_name,
                                           target_qframe='Q_lab'):
        """Prepare a background MDE containing only 1 ExperimentInfo

        :param self:
        :return:
        """
        if target_qframe not in ['Q_sample', 'Q_lab']:
            raise ValueError(
                f'QFrame with name {target_qframe} is not recognized.')

        # Create background workspace in Q lab
        ConvertToMD(InputWorkspace=input_md_name,
                    QDimensions='Q3D',
                    Q3DFrames=target_qframe,
                    OutputWorkspace=output_md_name,
                    MinValues='-11,-11,-11,-25',
                    MaxValues='11,11,11,49')
예제 #11
0
def example_pdf():
    #create slices and cuts
    w = Load(
        Filename=
        '/SNS/HYS/IPTS-14189/shared/autoreduce/4pixel/HYS_102102_4pixel_spe.nxs'
    )
    SetUB(w, 4.53, 4.53, 11.2, 90, 90, 90, "1,0,0", "0,0,1")
    mde = ConvertToMD(w, QDimensions='Q3D')
    with PdfPages('/tmp/multipage_pdf.pdf') as pdf:
        for i in range(4):
            llims = str(i - 0.5) + ',' + str(i + 0.5)
            sl1d = CutMD(InputWorkspace=mde,
                         P1Bin='-5,5',
                         P2Bin='-5,5',
                         P3Bin=llims,
                         P4Bin='-10,0.5,15',
                         NoPix=True)
            fig, ax = plt.subplots()
            Plot1DMD(ax, sl1d, NumEvNorm=True, fmt='ko')
            ax.set_title("L=[" + llims + "]")
            pdf.savefig(fig)
    plt.close('all')
예제 #12
0
def convertToHKL(ws,
                 OutputWorkspace='__md_hkl',
                 UB=None,
                 Append=False,
                 scale=None,
                 BinningDim0='-10.05,10.05,201',
                 BinningDim1='-10.05,10.05,201',
                 BinningDim2='-10.05,10.05,201',
                 Uproj=(1, 0, 0),
                 Vproj=(0, 1, 0),
                 Wproj=(0, 0, 1)):
    """Output MDHistoWorkspace in HKL
    """

    SetUB(ws, UB=UB)

    ConvertToMD(ws,
                QDimensions='Q3D',
                QConversionScales='HKL',
                dEAnalysisMode='Elastic',
                Q3DFrames='HKL',
                OutputWorkspace='__temp',
                Uproj=Uproj,
                Vproj=Vproj,
                Wproj=Wproj)

    if scale is not None:
        mtd['__temp'] *= scale

    BinMD(InputWorkspace='__temp',
          TemporaryDataWorkspace=OutputWorkspace
          if Append and mtd.doesExist(OutputWorkspace) else None,
          OutputWorkspace=OutputWorkspace,
          AlignedDim0=mtd['__temp'].getDimension(0).name + ',' + BinningDim0,
          AlignedDim1=mtd['__temp'].getDimension(1).name + ',' + BinningDim1,
          AlignedDim2=mtd['__temp'].getDimension(2).name + ',' + BinningDim2)
    DeleteWorkspace('__temp')

    return OutputWorkspace
 def create_pixel_workspace(self, name):
     sim_workspace = CreateSimulationWorkspace(Instrument='MAR',
                                               BinParams=[-10, 1, 10],
                                               UnitX='DeltaE',
                                               OutputWorkspace=name)
     AddSampleLog(sim_workspace,
                  LogName='Ei',
                  LogText='3.',
                  LogType='Number')
     sim_workspace = ConvertToMD(InputWorkspace=sim_workspace,
                                 OutputWorkspace=name,
                                 QDimensions='|Q|',
                                 dEAnalysisMode='Direct',
                                 MinValues='-10,0,0',
                                 MaxValues='10,6,500',
                                 SplitInto='50,50')
     workspace = wrap_workspace(sim_workspace, name)
     workspace.is_PSD = True
     workspace.limits['MomentumTransfer'] = [0.1, 3.1, 0.1]
     workspace.limits['|Q|'] = [0.1, 3.1, 0.1]
     workspace.limits['DeltaE'] = [-10, 15, 1]
     workspace.e_fixed = 10
     workspace.ef_defined = True
     return workspace
    def test_property_setup(input_mde: str, reduced_background: str):
        """Test set up properties

        :return:
        """
        # Test raise exception for wrong background MDE type
        try:
            # Create background workspace in Q lab
            ConvertToMD(InputWorkspace=reduced_background,
                        QDimensions='Q3D',
                        Q3DFrames='Q_sample',
                        OutputWorkspace='bkgd_md',
                        MinValues='-11,-11,-11,-25',
                        MaxValues='11,11,11,49')

            MDNorm(InputWorkspace=input_mde,
                   BackgroundWorkspace='bkgd_md',
                   Dimension0Name='QDimension1',
                   Dimension0Binning='-5,0.05,5',
                   Dimension1Name='QDimension2',
                   Dimension1Binning='-5,0.05,5',
                   Dimension2Name='DeltaE',
                   Dimension2Binning='-2,2',
                   Dimension3Name='QDimension0',
                   Dimension3Binning='-0.5,0.5',
                   SymmetryOperations='x,y,z;x,-y,z;x,y,-z;x,-y,-z',
                   OutputWorkspace='result',
                   OutputDataWorkspace='dataMD',
                   OutputNormalizationWorkspace='normMD')

            DeleteWorkspace(Workspace='bkgd_md')
        except RuntimeError:
            pass
        else:
            raise AssertionError(
                f'Expected failure due to Background MD in Q_sample.')
예제 #15
0
    def _determine_single_crystal_diffraction(self):
        """
        All work related to the determination of the diffraction pattern
        """

        a, b, c = self.getProperty('LatticeSizes').value
        alpha, beta, gamma = self.getProperty('LatticeAngles').value

        u = self.getProperty('VectorU').value
        v = self.getProperty('VectorV').value

        uproj = self.getProperty('Uproj').value
        vproj = self.getProperty('Vproj').value
        wproj = self.getProperty('Wproj').value

        n_bins = self.getProperty('NBins').value
        self._n_bins = (n_bins, n_bins, 1)

        axis0 = '{},0,1,0,1'.format(self.getProperty('PsiAngleLog').value)
        axis1 = '{},0,1,0,1'.format(self.getProperty('PsiOffset').value)

        # Options for SetUB independent of run
        ub_args = dict(a=a,
                       b=b,
                       c=c,
                       alpha=alpha,
                       beta=beta,
                       gamma=gamma,
                       u=u,
                       v=v)
        min_values = None
        # Options for algorithm ConvertToMD independent of run
        convert_to_md_kwargs = dict(QDimensions='Q3D',
                                    dEAnalysisMode='Elastic',
                                    Q3DFrames='HKL',
                                    QConversionScales='HKL',
                                    Uproj=uproj,
                                    Vproj=vproj,
                                    Wproj=wproj)
        md_norm_scd_kwargs = None  # Options for algorithm MDNormSCD

        # Find solid angle and flux
        if self._vanadium_files:
            kwargs = dict(Filename='+'.join(self._vanadium_files),
                          MaskFile=self.getProperty("MaskFile").value,
                          MomentumMin=self._momentum_range[0],
                          MomentumMax=self._momentum_range[1])
            _t_solid_angle, _t_int_flux = \
                MDNormSCDPreprocessIncoherent(**kwargs)
        else:
            _t_solid_angle = self.nominal_solid_angle('_t_solid_angle')
            _t_int_flux = self.nominal_integrated_flux('_t_int_flux')

        # Process a sample at a time
        run_numbers = self._getRuns(self.getProperty("RunNumbers").value,
                                    doIndiv=True)
        run_numbers = list(itertools.chain.from_iterable(run_numbers))
        diffraction_reporter = Progress(self,
                                        start=0.0,
                                        end=1.0,
                                        nreports=len(run_numbers))
        for i_run, run in enumerate(run_numbers):
            _t_sample = self._mask_t0_crop(run, '_t_sample')

            # Set Goniometer and UB matrix
            SetGoniometer(_t_sample, Axis0=axis0, Axis1=axis1)
            SetUB(_t_sample, **ub_args)
            if self._bkg:
                self._bkg.run().getGoniometer().\
                    setR(_t_sample.run().getGoniometer().getR())
                SetUB(self._bkg, **ub_args)
            # Determine limits for momentum transfer in HKL space. Needs to be
            # done only once. We use the first run.
            if min_values is None:
                kwargs = dict(QDimensions='Q3D',
                              dEAnalysisMode='Elastic',
                              Q3DFrames='HKL')
                min_values, max_values = ConvertToMDMinMaxGlobal(
                    _t_sample, **kwargs)
                convert_to_md_kwargs.update({
                    'MinValues': min_values,
                    'MaxValues': max_values
                })

            # Convert to MD
            _t_md = ConvertToMD(_t_sample,
                                OutputWorkspace='_t_md',
                                **convert_to_md_kwargs)
            if self._bkg:
                _t_bkg_md = ConvertToMD(self._bkg,
                                        OutputWorkspace='_t_bkg_md',
                                        **convert_to_md_kwargs)

            # Determine aligned dimensions. Need to be done only once
            if md_norm_scd_kwargs is None:
                aligned = list()
                for i_dim in range(3):
                    kwargs = {
                        'name': _t_md.getDimension(i_dim).name,
                        'min': min_values[i_dim],
                        'max': max_values[i_dim],
                        'n_bins': self._n_bins[i_dim]
                    }
                    aligned.append(
                        '{name},{min},{max},{n_bins}'.format(**kwargs))
                md_norm_scd_kwargs = dict(AlignedDim0=aligned[0],
                                          AlignedDim1=aligned[1],
                                          AlignedDim2=aligned[2],
                                          FluxWorkspace=_t_int_flux,
                                          SolidAngleWorkspace=_t_solid_angle,
                                          SkipSafetyCheck=True)

            # Normalize sample by solid angle and integrated flux;
            # Accumulate runs into the temporary workspaces
            MDNormSCD(_t_md,
                      OutputWorkspace='_t_data',
                      OutputNormalizationWorkspace='_t_norm',
                      TemporaryDataWorkspace='_t_data'
                      if mtd.doesExist('_t_data') else None,
                      TemporaryNormalizationWorkspace='_t_norm'
                      if mtd.doesExist('_t_norm') else None,
                      **md_norm_scd_kwargs)
            if self._bkg:
                MDNormSCD(_t_bkg_md,
                          OutputWorkspace='_t_bkg_data',
                          OutputNormalizationWorkspace='_t_bkg_norm',
                          TemporaryDataWorkspace='_t_bkg_data'
                          if mtd.doesExist('_t_bkg_data') else None,
                          TemporaryNormalizationWorkspace='_t_bkg_norm'
                          if mtd.doesExist('_t_bkg_norm') else None,
                          **md_norm_scd_kwargs)
            message = 'Processing sample {} of {}'.\
                format(i_run+1, len(run_numbers))
            diffraction_reporter.report(message)
        self._temps.workspaces.append('PreprocessedDetectorsWS')  # to remove
        # Iteration over the sample runs is done.

        # Division by vanadium, subtract background, and rename workspaces
        name = self.getPropertyValue("OutputWorkspace")
        _t_data = DivideMD(LHSWorkspace='_t_data', RHSWorkspace='_t_norm')
        if self._bkg:
            _t_bkg_data = DivideMD(LHSWorkspace='_t_bkg_data',
                                   RHSWorkspace='_t_bkg_norm')
            _t_scale = CreateSingleValuedWorkspace(DataValue=self._bkg_scale)
            _t_bkg_data = MultiplyMD(_t_bkg_data, _t_scale)
            ws = MinusMD(_t_data, _t_bkg_data)
            RenameWorkspace(_t_data, OutputWorkspace=name + '_dat')
            RenameWorkspace(_t_bkg_data, OutputWorkspace=name + '_bkg')
        else:
            ws = _t_data
        RenameWorkspace(ws, OutputWorkspace=name)
        self.setProperty("OutputWorkspace", ws)
        diffraction_reporter.report(len(run_numbers), 'Done')
예제 #16
0
                  dtype=np.float).reshape(3, 3)
    sgl = np.deg2rad(ws.run().getProperty(
        'HB2C:Mot:sgl.RBV').value[0])  # 'HB2C:Mot:sgl.RBV,1,0,0,-1'
    sgu = np.deg2rad(ws.run().getProperty(
        'HB2C:Mot:sgu.RBV').value[0])  # 'HB2C:Mot:sgu.RBV,0,0,1,-1'
    sgl_a = np.array([[1, 0, 0], [0, np.cos(sgl), np.sin(sgl)],
                      [0, -np.sin(sgl), np.cos(sgl)]])
    sgu_a = np.array([[np.cos(sgu), np.sin(sgu), 0],
                      [-np.sin(sgu), np.cos(sgu), 0], [0, 0, 1]])
    UB = sgl_a.dot(sgu_a).dot(
        ub)  # Apply the Goniometer tilts to the UB matrix
    SetUB(ws, UB=UB)
    md = ConvertToMD(ws,
                     QDimensions='Q3D',
                     dEAnalysisMode='Elastic',
                     Q3DFrames='HKL',
                     QConversionScales='HKL',
                     OtherDimensions='HB2C:SE:SampleTemp',
                     MinValues='-10,-10,-10,0',
                     MaxValues='10,10,10,30')
    if 'data' in mtd:
        PlusMD(LHSWorkspace='data', RHSWorkspace='md', OutputWorkspace='data')
    else:
        CloneMDWorkspace(InputWorkspace='md', OutputWorkspace='data')

BinMD(InputWorkspace='data',
      AlignedDim0='[H,0,0],-1,3,200',
      AlignedDim1='[0,K,0],0,3,150',
      AlignedDim2='[0,0,L],-1,3,40',
      AlignedDim3='HB2C:SE:SampleTemp,0,30,10',
      OutputWorkspace='bin')
예제 #17
0
    def PyExec(self):
        # remove possible old temp workspaces
        [
            DeleteWorkspace(ws) for ws in self.temp_workspace_list
            if mtd.doesExist(ws)
        ]

        _background = bool(self.getProperty("Background").value)
        _load_inst = bool(self.getProperty("LoadInstrument").value)
        _detcal = bool(self.getProperty("DetCal").value)
        _masking = bool(self.getProperty("MaskFile").value)
        _outWS_name = self.getPropertyValue("OutputWorkspace")

        UBList = self._generate_UBList()

        dim0_min, dim0_max, dim0_bins = self.getProperty('BinningDim0').value
        dim1_min, dim1_max, dim1_bins = self.getProperty('BinningDim1').value
        dim2_min, dim2_max, dim2_bins = self.getProperty('BinningDim2').value
        MinValues = "{},{},{}".format(dim0_min, dim1_min, dim2_min)
        MaxValues = "{},{},{}".format(dim0_max, dim1_max, dim2_max)
        AlignedDim0 = ",{},{},{}".format(dim0_min, dim0_max, int(dim0_bins))
        AlignedDim1 = ",{},{},{}".format(dim1_min, dim1_max, int(dim1_bins))
        AlignedDim2 = ",{},{},{}".format(dim2_min, dim2_max, int(dim2_bins))

        LoadNexus(Filename=self.getProperty("SolidAngle").value,
                  OutputWorkspace='__sa')
        LoadNexus(Filename=self.getProperty("Flux").value,
                  OutputWorkspace='__flux')

        if _masking:
            LoadMask(Instrument=mtd['__sa'].getInstrument().getName(),
                     InputFile=self.getProperty("MaskFile").value,
                     OutputWorkspace='__mask')
            MaskDetectors(Workspace='__sa', MaskedWorkspace='__mask')
            DeleteWorkspace('__mask')

        XMin = mtd['__sa'].getXDimension().getMinimum()
        XMax = mtd['__sa'].getXDimension().getMaximum()

        if _background:
            Load(Filename=self.getProperty("Background").value,
                 OutputWorkspace='__bkg',
                 FilterByTofMin=self.getProperty("FilterByTofMin").value,
                 FilterByTofMax=self.getProperty("FilterByTofMax").value)
            if _load_inst:
                LoadInstrument(
                    Workspace='__bkg',
                    Filename=self.getProperty("LoadInstrument").value,
                    RewriteSpectraMap=False)
            if _detcal:
                LoadIsawDetCal(InputWorkspace='__bkg',
                               Filename=self.getProperty("DetCal").value)
            MaskDetectors(Workspace='__bkg', MaskedWorkspace='__sa')
            ConvertUnits(InputWorkspace='__bkg',
                         OutputWorkspace='__bkg',
                         Target='Momentum')
            CropWorkspace(InputWorkspace='__bkg',
                          OutputWorkspace='__bkg',
                          XMin=XMin,
                          XMax=XMax)

        progress = Progress(
            self, 0.0, 1.0,
            len(UBList) * len(self.getProperty("Filename").value))

        for run in self.getProperty("Filename").value:
            logger.notice("Working on " + run)

            Load(Filename=run,
                 OutputWorkspace='__run',
                 FilterByTofMin=self.getProperty("FilterByTofMin").value,
                 FilterByTofMax=self.getProperty("FilterByTofMax").value)
            if _load_inst:
                LoadInstrument(
                    Workspace='__run',
                    Filename=self.getProperty("LoadInstrument").value,
                    RewriteSpectraMap=False)
            if _detcal:
                LoadIsawDetCal(InputWorkspace='__run',
                               Filename=self.getProperty("DetCal").value)
            MaskDetectors(Workspace='__run', MaskedWorkspace='__sa')
            ConvertUnits(InputWorkspace='__run',
                         OutputWorkspace='__run',
                         Target='Momentum')
            CropWorkspace(InputWorkspace='__run',
                          OutputWorkspace='__run',
                          XMin=XMin,
                          XMax=XMax)

            if self.getProperty('SetGoniometer').value:
                SetGoniometer(
                    Workspace='__run',
                    Goniometers=self.getProperty('Goniometers').value,
                    Axis0=self.getProperty('Axis0').value,
                    Axis1=self.getProperty('Axis1').value,
                    Axis2=self.getProperty('Axis2').value)

            # Set background Goniometer to be the same as data
            if _background:
                mtd['__bkg'].run().getGoniometer().setR(
                    mtd['__run'].run().getGoniometer().getR())

            for ub in UBList:
                SetUB(Workspace='__run', UB=ub)
                ConvertToMD(InputWorkspace='__run',
                            OutputWorkspace='__md',
                            QDimensions='Q3D',
                            dEAnalysisMode='Elastic',
                            Q3DFrames='HKL',
                            QConversionScales='HKL',
                            Uproj=self.getProperty('Uproj').value,
                            Vproj=self.getProperty('Vproj').value,
                            Wproj=self.getProperty('wproj').value,
                            MinValues=MinValues,
                            MaxValues=MaxValues)
                MDNormSCD(
                    InputWorkspace=mtd['__md'],
                    FluxWorkspace='__flux',
                    SolidAngleWorkspace='__sa',
                    OutputWorkspace='__data',
                    SkipSafetyCheck=True,
                    TemporaryDataWorkspace='__data'
                    if mtd.doesExist('__data') else None,
                    OutputNormalizationWorkspace='__norm',
                    TemporaryNormalizationWorkspace='__norm'
                    if mtd.doesExist('__norm') else None,
                    AlignedDim0=mtd['__md'].getDimension(0).name + AlignedDim0,
                    AlignedDim1=mtd['__md'].getDimension(1).name + AlignedDim1,
                    AlignedDim2=mtd['__md'].getDimension(2).name + AlignedDim2)
                DeleteWorkspace('__md')

                if _background:
                    SetUB(Workspace='__bkg', UB=ub)
                    ConvertToMD(InputWorkspace='__bkg',
                                OutputWorkspace='__bkg_md',
                                QDimensions='Q3D',
                                dEAnalysisMode='Elastic',
                                Q3DFrames='HKL',
                                QConversionScales='HKL',
                                Uproj=self.getProperty('Uproj').value,
                                Vproj=self.getProperty('Vproj').value,
                                Wproj=self.getProperty('Wproj').value,
                                MinValues=MinValues,
                                MaxValues=MaxValues)
                    MDNormSCD(
                        InputWorkspace='__bkg_md',
                        FluxWorkspace='__flux',
                        SolidAngleWorkspace='__sa',
                        SkipSafetyCheck=True,
                        OutputWorkspace='__bkg_data',
                        TemporaryDataWorkspace='__bkg_data'
                        if mtd.doesExist('__bkg_data') else None,
                        OutputNormalizationWorkspace='__bkg_norm',
                        TemporaryNormalizationWorkspace='__bkg_norm'
                        if mtd.doesExist('__bkg_norm') else None,
                        AlignedDim0=mtd['__bkg_md'].getDimension(0).name +
                        AlignedDim0,
                        AlignedDim1=mtd['__bkg_md'].getDimension(1).name +
                        AlignedDim1,
                        AlignedDim2=mtd['__bkg_md'].getDimension(2).name +
                        AlignedDim2)
                    DeleteWorkspace('__bkg_md')
                progress.report()
            DeleteWorkspace('__run')

        if _background:
            # outWS = data / norm - bkg_data / bkg_norm * BackgroundScale
            DivideMD(LHSWorkspace='__data',
                     RHSWorkspace='__norm',
                     OutputWorkspace=_outWS_name + '_normalizedData')
            DivideMD(LHSWorkspace='__bkg_data',
                     RHSWorkspace='__bkg_norm',
                     OutputWorkspace=_outWS_name + '_normalizedBackground')
            CreateSingleValuedWorkspace(
                OutputWorkspace='__scale',
                DataValue=self.getProperty('BackgroundScale').value)
            MultiplyMD(LHSWorkspace=_outWS_name + '_normalizedBackground',
                       RHSWorkspace='__scale',
                       OutputWorkspace='__scaled_background')
            DeleteWorkspace('__scale')
            MinusMD(LHSWorkspace=_outWS_name + '_normalizedData',
                    RHSWorkspace='__scaled_background',
                    OutputWorkspace=_outWS_name)
            if self.getProperty('KeepTemporaryWorkspaces').value:
                RenameWorkspaces(InputWorkspaces=[
                    '__data', '__norm', '__bkg_data', '__bkg_norm'
                ],
                                 WorkspaceNames=[
                                     _outWS_name + '_data',
                                     _outWS_name + '_normalization',
                                     _outWS_name + '_background_data',
                                     _outWS_name + '_background_normalization'
                                 ])
        else:
            # outWS = data / norm
            DivideMD(LHSWorkspace='__data',
                     RHSWorkspace='__norm',
                     OutputWorkspace=_outWS_name)
            if self.getProperty('KeepTemporaryWorkspaces').value:
                RenameWorkspaces(InputWorkspaces=['__data', '__norm'],
                                 WorkspaceNames=[
                                     _outWS_name + '_data',
                                     _outWS_name + '_normalization'
                                 ])

        self.setProperty("OutputWorkspace", mtd[_outWS_name])

        # remove temp workspaces
        [
            DeleteWorkspace(ws) for ws in self.temp_workspace_list
            if mtd.doesExist(ws)
        ]
예제 #18
0
    def load_and_group(self, runs: List[str]) -> IMDHistoWorkspace:
        """
        Load the data with given grouping
        """
        # grouping config
        grouping = self.getProperty("Grouping").value
        if grouping == 'None':
            grouping = 1
        else:
            grouping = 2 if grouping == '2x2' else 4
        number_of_runs = len(runs)

        x_dim = 480 * 8 // grouping
        y_dim = 512 // grouping

        data_array = np.empty((number_of_runs, x_dim, y_dim), dtype=np.float64)

        s1_array = []
        duration_array = []
        run_number_array = []
        monitor_count_array = []

        progress = Progress(self, 0.0, 1.0, number_of_runs + 3)

        for n, run in enumerate(runs):
            progress.report('Loading: ' + run)
            with h5py.File(run, 'r') as f:
                bc = np.zeros((512 * 480 * 8), dtype=np.int64)
                for b in range(8):
                    bc += np.bincount(f['/entry/bank' + str(b + 1) +
                                        '_events/event_id'].value,
                                      minlength=512 * 480 * 8)
                bc = bc.reshape((480 * 8, 512))
                if grouping == 2:
                    bc = bc[::2, ::2] + bc[1::2, ::2] + bc[::2,
                                                           1::2] + bc[1::2,
                                                                      1::2]
                elif grouping == 4:
                    bc = bc[::4, ::4] + bc[1::4, ::4] + bc[2::4, ::4] + bc[3::4, ::4] + bc[::4, 1::4] + bc[1::4, 1::4] + bc[2::4, 1::4] + \
                         bc[3::4, 1::4] + bc[::4, 2::4] + bc[1::4, 2::4] + bc[2::4, 2::4] + bc[3::4, 2::4] + bc[::4, 3::4] + \
                         bc[1::4, 3::4] + bc[2::4, 3::4] + bc[3::4, 3::4]
                data_array[n] = bc
                s1_array.append(
                    f['/entry/DASlogs/HB2C:Mot:s1.RBV/average_value'].value[0])
                duration_array.append(float(f['/entry/duration'].value[0]))
                run_number_array.append(float(f['/entry/run_number'].value[0]))
                monitor_count_array.append(
                    float(f['/entry/monitor1/total_counts'].value[0]))

        progress.report('Creating MDHistoWorkspace')
        createWS_alg = self.createChildAlgorithm("CreateMDHistoWorkspace",
                                                 enableLogging=False)
        createWS_alg.setProperty("SignalInput", data_array)
        createWS_alg.setProperty("ErrorInput", np.sqrt(data_array))
        createWS_alg.setProperty("Dimensionality", 3)
        createWS_alg.setProperty(
            "Extents", '0.5,{},0.5,{},0.5,{}'.format(y_dim + 0.5, x_dim + 0.5,
                                                     number_of_runs + 0.5))
        createWS_alg.setProperty(
            "NumberOfBins", '{},{},{}'.format(y_dim, x_dim, number_of_runs))
        createWS_alg.setProperty("Names", 'y,x,scanIndex')
        createWS_alg.setProperty("Units", 'bin,bin,number')
        createWS_alg.execute()
        outWS = createWS_alg.getProperty("OutputWorkspace").value

        progress.report('Getting IDF')
        # Get the instrument and some logs from the first file; assume the rest are the same
        _tmp_ws = LoadEventNexus(runs[0],
                                 MetaDataOnly=True,
                                 EnableLogging=False)
        # The following logs should be the same for all runs
        RemoveLogs(
            _tmp_ws,
            KeepLogs=
            'HB2C:Mot:detz,HB2C:Mot:detz.RBV,HB2C:Mot:s2,HB2C:Mot:s2.RBV,'
            'HB2C:Mot:sgl,HB2C:Mot:sgl.RBV,HB2C:Mot:sgu,HB2C:Mot:sgu.RBV,'
            'run_title,start_time,experiment_identifier,HB2C:CS:CrystalAlign:UBMatrix',
            EnableLogging=False)

        time_ns_array = _tmp_ws.run().startTime().totalNanoseconds(
        ) + np.append(0,
                      np.cumsum(duration_array) * 1e9)[:-1]

        try:
            ub = np.array(re.findall(
                r'-?\d+\.*\d*',
                _tmp_ws.run().getProperty(
                    'HB2C:CS:CrystalAlign:UBMatrix').value[0]),
                          dtype=float).reshape(3, 3)
            sgl = np.deg2rad(_tmp_ws.run().getProperty(
                'HB2C:Mot:sgl.RBV').value[0])  # 'HB2C:Mot:sgl.RBV,1,0,0,-1'
            sgu = np.deg2rad(_tmp_ws.run().getProperty(
                'HB2C:Mot:sgu.RBV').value[0])  # 'HB2C:Mot:sgu.RBV,0,0,1,-1'
            sgl_a = np.array([[1, 0, 0], [0, np.cos(sgl),
                                          np.sin(sgl)],
                              [0, -np.sin(sgl), np.cos(sgl)]])
            sgu_a = np.array([[np.cos(sgu), np.sin(sgu), 0],
                              [-np.sin(sgu), np.cos(sgu), 0], [0, 0, 1]])
            UB = sgl_a.dot(sgu_a).dot(
                ub)  # Apply the Goniometer tilts to the UB matrix
            SetUB(_tmp_ws, UB=UB, EnableLogging=False)
        except (RuntimeError, ValueError):
            SetUB(_tmp_ws, EnableLogging=False)

        if grouping > 1:
            _tmp_group, _, _ = CreateGroupingWorkspace(InputWorkspace=_tmp_ws,
                                                       EnableLogging=False)

            group_number = 0
            for x in range(0, 480 * 8, grouping):
                for y in range(0, 512, grouping):
                    group_number += 1
                    for j in range(grouping):
                        for i in range(grouping):
                            _tmp_group.dataY(y + i +
                                             (x + j) * 512)[0] = group_number

            _tmp_ws = GroupDetectors(InputWorkspace=_tmp_ws,
                                     CopyGroupingFromWorkspace=_tmp_group,
                                     EnableLogging=False)
            DeleteWorkspace(_tmp_group, EnableLogging=False)

        progress.report('Adding logs')

        # Hack: ConvertToMD is needed so that a deep copy of the ExperimentInfo can happen
        # outWS.addExperimentInfo(_tmp_ws) # This doesn't work but should, when you delete `ws` `outWS` also loses it's ExperimentInfo
        _tmp_ws = Rebin(_tmp_ws, '0,1,2', EnableLogging=False)
        _tmp_ws = ConvertToMD(_tmp_ws,
                              dEAnalysisMode='Elastic',
                              EnableLogging=False,
                              PreprocDetectorsWS='__PreprocessedDetectorsWS')

        preprocWS = mtd['__PreprocessedDetectorsWS']
        twotheta = preprocWS.column(2)
        azimuthal = preprocWS.column(3)

        outWS.copyExperimentInfos(_tmp_ws)
        DeleteWorkspace(_tmp_ws, EnableLogging=False)
        DeleteWorkspace('__PreprocessedDetectorsWS', EnableLogging=False)
        # end Hack

        add_time_series_property('s1',
                                 outWS.getExperimentInfo(0).run(),
                                 time_ns_array, s1_array)
        outWS.getExperimentInfo(0).run().getProperty('s1').units = 'deg'
        add_time_series_property('duration',
                                 outWS.getExperimentInfo(0).run(),
                                 time_ns_array, duration_array)
        outWS.getExperimentInfo(0).run().getProperty(
            'duration').units = 'second'
        outWS.getExperimentInfo(0).run().addProperty('run_number',
                                                     run_number_array, True)
        add_time_series_property('monitor_count',
                                 outWS.getExperimentInfo(0).run(),
                                 time_ns_array, monitor_count_array)
        outWS.getExperimentInfo(0).run().addProperty('twotheta', twotheta,
                                                     True)
        outWS.getExperimentInfo(0).run().addProperty('azimuthal', azimuthal,
                                                     True)

        setGoniometer_alg = self.createChildAlgorithm("SetGoniometer",
                                                      enableLogging=False)
        setGoniometer_alg.setProperty("Workspace", outWS)
        setGoniometer_alg.setProperty("Axis0", 's1,0,1,0,1')
        setGoniometer_alg.setProperty("Average", False)
        setGoniometer_alg.execute()

        return outWS
예제 #19
0
파일: md.py 프로젝트: rosswhitfield/corelli
run1 = 'CORELLI_48505'
run2 = 'CORELLI_48513'

run1 = 'CORELLI_48508'
run2 = 'CORELLI_48516'

ws1 = Load(run1)
ws2 = Load(run2)

SetGoniometer(ws1, Axis0="BL9:Mot:Sample:Axis2,0,1,0,1")
SetGoniometer(ws2, Axis0="BL9:Mot:Sample:Axis2,0,1,0,1")

md1 = ConvertToMD(ws1,
                  QDimensions='Q3D',
                  dEAnalysisMode='Elastic',
                  Q3DFrames='Q_sample',
                  MinValues=[-10, -10, -10],
                  MaxValues=[10, 10, 10])
md2 = ConvertToMD(ws2,
                  QDimensions='Q3D',
                  dEAnalysisMode='Elastic',
                  Q3DFrames='Q_sample',
                  MinValues=[-10, -10, -10],
                  MaxValues=[10, 10, 10])

bin1 = BinMD(md1,
             AlignedDim0='Q_sample_x,-10,10,1000',
             AlignedDim1='Q_sample_z,-10,10,1000',
             AlignedDim2='Q_sample_y,-10,10,1')
bin2 = BinMD(md2,
             AlignedDim0='Q_sample_x,-10,10,1000',
예제 #20
0
    def PyExec(self):
        # remove possible old temp workspaces
        [
            DeleteWorkspace(ws) for ws in self.temp_workspace_list
            if mtd.doesExist(ws)
        ]

        _background = bool(self.getProperty("Background").value)
        self._load_inst = bool(self.getProperty("LoadInstrument").value)
        self._apply_cal = bool(self.getProperty("ApplyCalibration").value)
        self._detcal = bool(self.getProperty("DetCal").value)
        self._copy_params = bool(
            self.getProperty("CopyInstrumentParameters").value)
        _masking = bool(self.getProperty("MaskFile").value)
        _outWS_name = self.getPropertyValue("OutputWorkspace")
        _UB = self.getProperty("UBMatrix").value
        if len(_UB) == 1:
            _UB = np.tile(_UB, len(self.getProperty("Filename").value))
        _offsets = self.getProperty("OmegaOffset").value
        if len(_offsets) == 0:
            _offsets = np.zeros(len(self.getProperty("Filename").value))

        if self.getProperty("ReuseSAFlux").value and mtd.doesExist(
                '__sa') and mtd.doesExist('__flux'):
            logger.notice(
                "Reusing previously loaded SolidAngle and Flux workspaces. "
                "Set ReuseSAFlux to False if new files are selected or you change the momentum range."
            )
        else:
            logger.notice("Loading SolidAngle and Flux from file")
            LoadNexus(Filename=self.getProperty("SolidAngle").value,
                      OutputWorkspace='__sa')
            LoadNexus(Filename=self.getProperty("Flux").value,
                      OutputWorkspace='__flux')

        if _masking:
            LoadMask(Instrument=mtd['__sa'].getInstrument().getName(),
                     InputFile=self.getProperty("MaskFile").value,
                     OutputWorkspace='__mask')
            MaskDetectors(Workspace='__sa', MaskedWorkspace='__mask')
            DeleteWorkspace('__mask')

        self.XMin = mtd['__sa'].getXDimension().getMinimum()
        self.XMax = mtd['__sa'].getXDimension().getMaximum()

        newXMin = self.getProperty("MomentumMin").value
        newXMax = self.getProperty("MomentumMax").value
        if newXMin != Property.EMPTY_DBL or newXMax != Property.EMPTY_DBL:
            if newXMin != Property.EMPTY_DBL:
                self.XMin = max(self.XMin, newXMin)
            if newXMax != Property.EMPTY_DBL:
                self.XMax = min(self.XMax, newXMax)
            logger.notice("Using momentum range {} to {} A^-1".format(
                self.XMin, self.XMax))
            CropWorkspace(InputWorkspace='__flux',
                          OutputWorkspace='__flux',
                          XMin=self.XMin,
                          XMax=self.XMax)
            for spectrumNumber in range(mtd['__flux'].getNumberHistograms()):
                Y = mtd['__flux'].readY(spectrumNumber)
                mtd['__flux'].setY(spectrumNumber,
                                   (Y - Y.min()) / (Y.max() - Y.min()))

        MinValues = [-self.XMax * 2] * 3
        MaxValues = [self.XMax * 2] * 3

        if _background:
            self.load_file_and_apply(
                self.getProperty("Background").value, '__bkg', 0)

        progress = Progress(self, 0.0, 1.0,
                            len(self.getProperty("Filename").value))

        for n, run in enumerate(self.getProperty("Filename").value):
            logger.notice("Working on " + run)

            self.load_file_and_apply(run, '__run', _offsets[n])
            LoadIsawUB('__run', _UB[n])

            ConvertToMD(InputWorkspace='__run',
                        OutputWorkspace='__md',
                        QDimensions='Q3D',
                        dEAnalysisMode='Elastic',
                        Q3DFrames='Q_sample',
                        MinValues=MinValues,
                        MaxValues=MaxValues)
            RecalculateTrajectoriesExtents(InputWorkspace='__md',
                                           OutputWorkspace='__md')
            MDNorm(
                InputWorkspace='__md',
                FluxWorkspace='__flux',
                SolidAngleWorkspace='__sa',
                OutputDataWorkspace='__data',
                TemporaryDataWorkspace='__data'
                if mtd.doesExist('__data') else None,
                OutputNormalizationWorkspace='__norm',
                TemporaryNormalizationWorkspace='__norm'
                if mtd.doesExist('__norm') else None,
                OutputWorkspace=_outWS_name,
                QDimension0=self.getProperty('QDimension0').value,
                QDimension1=self.getProperty('QDimension1').value,
                QDimension2=self.getProperty('QDimension2').value,
                Dimension0Binning=self.getProperty('Dimension0Binning').value,
                Dimension1Binning=self.getProperty('Dimension1Binning').value,
                Dimension2Binning=self.getProperty('Dimension2Binning').value,
                SymmetryOperations=self.getProperty(
                    'SymmetryOperations').value)
            DeleteWorkspace('__md')

            if _background:
                # Set background Goniometer and UB to be the same as data
                CopySample(InputWorkspace='__run',
                           OutputWorkspace='__bkg',
                           CopyName=False,
                           CopyMaterial=False,
                           CopyEnvironment=False,
                           CopyShape=False,
                           CopyLattice=True)
                mtd['__bkg'].run().getGoniometer().setR(
                    mtd['__run'].run().getGoniometer().getR())

                ConvertToMD(InputWorkspace='__bkg',
                            OutputWorkspace='__bkg_md',
                            QDimensions='Q3D',
                            dEAnalysisMode='Elastic',
                            Q3DFrames='Q_sample',
                            MinValues=MinValues,
                            MaxValues=MaxValues)
                RecalculateTrajectoriesExtents(InputWorkspace='__bkg_md',
                                               OutputWorkspace='__bkg_md')
                MDNorm(InputWorkspace='__bkg_md',
                       FluxWorkspace='__flux',
                       SolidAngleWorkspace='__sa',
                       OutputDataWorkspace='__bkg_data',
                       TemporaryDataWorkspace='__bkg_data'
                       if mtd.doesExist('__bkg_data') else None,
                       OutputNormalizationWorkspace='__bkg_norm',
                       TemporaryNormalizationWorkspace='__bkg_norm'
                       if mtd.doesExist('__bkg_norm') else None,
                       OutputWorkspace='__normalizedBackground',
                       QDimension0=self.getProperty('QDimension0').value,
                       QDimension1=self.getProperty('QDimension1').value,
                       QDimension2=self.getProperty('QDimension2').value,
                       Dimension0Binning=self.getProperty(
                           'Dimension0Binning').value,
                       Dimension1Binning=self.getProperty(
                           'Dimension1Binning').value,
                       Dimension2Binning=self.getProperty(
                           'Dimension2Binning').value,
                       SymmetryOperations=self.getProperty(
                           'SymmetryOperations').value)
                DeleteWorkspace('__bkg_md')
            progress.report()
            DeleteWorkspace('__run')

        if _background:
            # outWS = data / norm - bkg_data / bkg_norm * BackgroundScale
            CreateSingleValuedWorkspace(
                OutputWorkspace='__scale',
                DataValue=self.getProperty('BackgroundScale').value)
            MultiplyMD(LHSWorkspace='__normalizedBackground',
                       RHSWorkspace='__scale',
                       OutputWorkspace='__normalizedBackground')
            DeleteWorkspace('__scale')
            MinusMD(LHSWorkspace=_outWS_name,
                    RHSWorkspace='__normalizedBackground',
                    OutputWorkspace=_outWS_name)
            if self.getProperty('KeepTemporaryWorkspaces').value:
                RenameWorkspaces(InputWorkspaces=[
                    '__data', '__norm', '__bkg_data', '__bkg_norm'
                ],
                                 WorkspaceNames=[
                                     _outWS_name + '_data',
                                     _outWS_name + '_normalization',
                                     _outWS_name + '_background_data',
                                     _outWS_name + '_background_normalization'
                                 ])
        else:
            if self.getProperty('KeepTemporaryWorkspaces').value:
                RenameWorkspaces(InputWorkspaces=['__data', '__norm'],
                                 WorkspaceNames=[
                                     _outWS_name + '_data',
                                     _outWS_name + '_normalization'
                                 ])

        self.setProperty("OutputWorkspace", mtd[_outWS_name])

        # remove temp workspaces
        [
            DeleteWorkspace(ws) for ws in self.temp_workspace_list
            if mtd.doesExist(ws)
        ]
예제 #21
0
        elif Chopperpos < 1:
            Chopper = 1
        else:
            Chopper = 0

        # generate a nice 2D multi-dimensional workspace
        data = LoadNXSPE(datadir + 'ARCS_' + str(RunNumber) +
                         '_autoreduced.nxspe')
        values = ConvertToMDMinMaxLocal('data',
                                        QDimensions='|Q|',
                                        dEAnalysisMode='Direct')
        minQ, minE = values.MinValues
        maxQ, maxE = values.MaxValues

        md = ConvertToMD(InputWorkspace=data,
                         QDimensions='|Q|',
                         dEAnalysisMode='Direct')
        sqw = BinMD(InputWorkspace=md,
                    AlignedDim0='|Q|,' + str(minQ) + ',' + str(maxQ) + ',100',
                    AlignedDim1='DeltaE,' + str(minE) + ',' + str(maxE * 0.8) +
                    ',100')

        #2D plot
        if PlotTag == 1:
            fig, ax = plt.subplots(subplot_kw={'projection': 'mantid'})
            c = ax.pcolormesh(sqw, vmin=0., vmax=0.5e-3)
            cbar = fig.colorbar(c)
            cbar.set_label('Intensity (arb. units)')  #add text to colorbar
            ax.set_title('Run ' + str(RunNumber) + ',Ei=' + str(Energy) +
                         'meVChoppers=[' + str(Chopper1) + ',' +
                         str(Chopper2) + ',' + str(Chopper3) + ']')
예제 #22
0
        #
    #Subtract instrument background
    temp = bkg * (proton_charge /
                  bkg_proton_charge) * (float(BN_aperture_size) / 2.0)
    # Ratio of background counts to 2 mm diameter BN aperture
    event_ws = Minus(LHSWorkspace=event_ws, RHSWorkspace=temp)

#
# Make MD workspace using Lorentz correction, to find peaks
#
MDEW = ConvertToMD(InputWorkspace=event_ws,
                   QDimensions="Q3D",
                   dEAnalysisMode="Elastic",
                   QConversionScales="Q in A^-1",
                   LorentzCorrection='1',
                   MinValues=minQ,
                   MaxValues=maxQ,
                   SplitInto='2',
                   SplitThreshold=split_threshold,
                   MaxRecursionDepth='11')
#
# Find the requested number of peaks.  Once the peaks are found, we no longer
# need the weighted MD event workspace, so delete it.
#
distance_threshold = 0.9 * 6.28 / float(max_d)
peaks_ws = FindPeaksMD(MDEW,
                       MaxPeaks=num_peaks_to_find,
                       DensityThresholdFactor='5',
                       PeakDistanceThreshold=distance_threshold)

#Remove peaks on detector edge
예제 #23
0
    def PyExec(self):
        self._load_inst = bool(self.getProperty("LoadInstrument").value)
        self._apply_cal = bool(self.getProperty("ApplyCalibration").value)
        self._detcal = bool(self.getProperty("DetCal").value)
        self._copy_params = bool(
            self.getProperty("CopyInstrumentParameters").value)
        self._masking = bool(self.getProperty("MaskFile").value)
        _outWS_name = self.getPropertyValue("OutputWorkspace")
        _UB = bool(self.getProperty("UBMatrix").value)

        self.XMin = self.getProperty("MomentumMin").value
        self.XMax = self.getProperty("MomentumMax").value

        MinValues = self.getProperty("MinValues").value
        MaxValues = self.getProperty("MaxValues").value

        if self.getProperty("OverwriteExisting").value:
            if mtd.doesExist(_outWS_name):
                DeleteWorkspace(_outWS_name)

        progress = Progress(self, 0.0, 1.0,
                            len(self.getProperty("Filename").value))

        for run in self.getProperty("Filename").value:
            logger.notice("Working on " + run)

            self.load_file_and_apply(run, '__run')

            if self.getProperty('SetGoniometer').value:
                SetGoniometer(
                    Workspace='__run',
                    Goniometers=self.getProperty('Goniometers').value,
                    Axis0=self.getProperty('Axis0').value,
                    Axis1=self.getProperty('Axis1').value,
                    Axis2=self.getProperty('Axis2').value)

            if _UB:
                LoadIsawUB(InputWorkspace='__run',
                           Filename=self.getProperty("UBMatrix").value)

            if len(MinValues) == 0 or len(MaxValues) == 0:
                MinValues, MaxValues = ConvertToMDMinMaxGlobal(
                    '__run',
                    dEAnalysisMode='Elastic',
                    Q3DFrames='Q' if self.getProperty('QFrame').value
                    == 'Q_sample' else 'HKL',
                    QDimensions='Q3D')

            ConvertToMD(
                InputWorkspace='__run',
                OutputWorkspace=_outWS_name,
                QDimensions='Q3D',
                dEAnalysisMode='Elastic',
                Q3DFrames=self.getProperty('QFrame').value,
                QConversionScales='Q in A^-1'
                if self.getProperty('QFrame').value == 'Q_sample' else 'HKL',
                Uproj=self.getProperty('Uproj').value,
                Vproj=self.getProperty('Vproj').value,
                Wproj=self.getProperty('Wproj').value,
                MinValues=MinValues,
                MaxValues=MaxValues,
                SplitInto=self.getProperty('SplitInto').value,
                SplitThreshold=self.getProperty('SplitThreshold').value,
                MaxRecursionDepth=self.getProperty('MaxRecursionDepth').value,
                OverwriteExisting=False)
            DeleteWorkspace('__run')
            progress.report()

        if mtd.doesExist('__mask'):
            DeleteWorkspace('__mask')

        self.setProperty("OutputWorkspace", mtd[_outWS_name])
    def prepare_md(input_ws_name, merged_md_name, min_log_value, max_log_value,
                   log_step, prefix) -> str:
        """Load raw event Nexus file and reduce to MDEventWorkspace
        """
        # Filter
        gef_kw_dict = dict()
        if log_step <= max_log_value - min_log_value:
            LogValueInterval = log_step
            gef_kw_dict['LogValueInterval'] = LogValueInterval
        GenerateEventsFilter(InputWorkspace=input_ws_name,
                             OutputWorkspace='splboth',
                             InformationWorkspace='info',
                             UnitOfTime='Nanoseconds',
                             LogName='s1',
                             MinimumLogValue=min_log_value,
                             MaximumLogValue=max_log_value,
                             **gef_kw_dict)
        FilterEvents(InputWorkspace=input_ws_name,
                     SplitterWorkspace='splboth',
                     InformationWorkspace='info',
                     FilterByPulseTime=True,
                     GroupWorkspaces=True,
                     OutputWorkspaceIndexedFrom1=True,
                     OutputWorkspaceBaseName='split')
        # Clean memory
        DeleteWorkspace('splboth')
        DeleteWorkspace('info')

        reduced_ws_group = f'reduced_{prefix}'
        DgsReduction(SampleInputWorkspace='split',
                     SampleInputMonitorWorkspace='split_1',
                     IncidentEnergyGuess=50,
                     SofPhiEIsDistribution=False,
                     TimeIndepBackgroundSub=True,
                     TibTofRangeStart=10400,
                     TibTofRangeEnd=12400,
                     OutputWorkspace=reduced_ws_group)
        # Clean memory
        DeleteWorkspace('split')

        SetUB(Workspace=reduced_ws_group,
              a=5.823,
              b=6.475,
              c=3.186,
              u='0,1,0',
              v='0,0,1')
        CropWorkspaceForMDNorm(InputWorkspace=reduced_ws_group,
                               XMin=-25,
                               XMax=49,
                               OutputWorkspace=reduced_ws_group)
        ConvertToMD(InputWorkspace=reduced_ws_group,
                    QDimensions='Q3D',
                    Q3DFrames='Q_sample',
                    OutputWorkspace='md',
                    MinValues='-11,-11,-11,-25',
                    MaxValues='11,11,11,49')

        if mtd['md'].getNumberOfEntries() == 1:
            RenameWorkspace(mtd['md'][0], merged_md_name)
        else:
            MergeMD(InputWorkspaces='md', OutputWorkspace=merged_md_name)

        return reduced_ws_group
예제 #25
0
    DeleteWorkspace(name_MDE)

for run in range(first_run, last_run + 1, load_every):
    if use_autoreduced:
        filename = iptsdir + 'shared/autoreduce/HB2C_{}_MDE.nxs'.format(run)
        try:
            LoadMD(Filename=filename,
                   LoadHistory=False,
                   OutputWorkspace='__md')
        except ValueError:
            filename = iptsdir + 'nexus/HB2C_{}.nxs.h5'.format(run)
            LoadWAND(filename, OutputWorkspace='__ws')
            ConvertToMD('__ws',
                        QDimensions='Q3D',
                        dEAnalysisMode='Elastic',
                        Q3DFrames='Q_sample',
                        OutputWorkspace='__md',
                        MinValues='-10,-1,-10',
                        MaxValues='10,1,10')
    accumulateMD('__md', OutputWorkspace=name_MDE)

SaveMD(
    name_MDE, iptsdir + 'shared/' + name +
    '_MDE_{}_to_{}_every_{}.nxs'.format(first_run, last_run, load_every))

# Convert MD Event workspace to MD Histo workspace

name_MDH = name + '_MDH'

BinMD(InputWorkspace=name_MDE,
      AlignedDim0='Q_sample_x,' + BinningDim0,
예제 #26
0
    def _determine_single_crystal_diffraction(self):
        """
        All work related to the determination of the diffraction pattern
        """

        a, b, c = self.getProperty('LatticeSizes').value
        alpha, beta, gamma = self.getProperty('LatticeAngles').value

        u = self.getProperty('VectorU').value
        v = self.getProperty('VectorV').value

        uproj = self.getProperty('Uproj').value
        vproj = self.getProperty('Vproj').value
        wproj = self.getProperty('Wproj').value

        n_bins = self.getProperty('NBins').value
        self._n_bins = (n_bins, n_bins, 1)

        axis0 = '{},0,1,0,1'.format(self.getProperty('PsiAngleLog').value)
        axis1 = '{},0,1,0,1'.format(self.getProperty('PsiOffset').value)

        # Options for SetUB independent of run
        ub_args = dict(a=a, b=b, c=c,
                       alpha=alpha, beta=beta, gamma=gamma,
                       u=u, v=v)
        min_values = None
        # Options for algorithm ConvertToMD independent of run
        cmd_args = dict(QDimensions='Q3D', dEAnalysisMode='Elastic',
                        Q3DFrames='HKL', QConversionScales='HKL',
                        Uproj=uproj, Vproj=vproj, Wproj=wproj)
        mdn_args = None  # Options for algorithm MDNormSCD

        # Find solid angle and flux
        if self._vanadium_files:
            kwargs = dict(Filename='+'.join(self._vanadium_files),
                          MaskFile=self.getProperty("MaskFile").value,
                          MomentumMin=self._momentum_range[0],
                          MomentumMax=self._momentum_range[1])
            _t_solid_angle, _t_int_flux = \
                MDNormSCDPreprocessIncoherent(**kwargs)
        else:
            _t_solid_angle = self.nominal_solid_angle('_t_solid_angle')
            _t_int_flux = self.nominal_integrated_flux('_t_int_flux')

        # Process a sample at a time
        run_numbers = self._getRuns(self.getProperty("RunNumbers").value,
                                    doIndiv=True)
        run_numbers = list(itertools.chain.from_iterable(run_numbers))
        diffraction_reporter = Progress(self, start=0.0, end=1.0,
                                        nreports=len(run_numbers))
        for i_run, run in enumerate(run_numbers):
            _t_sample = self._mask_t0_crop(run, '_t_sample')

            # Set Goniometer and UB matrix
            SetGoniometer(_t_sample, Axis0=axis0, Axis1=axis1)
            SetUB(_t_sample, **ub_args)
            if self._bkg:
                self._bkg.run().getGoniometer().\
                    setR(_t_sample.run().getGoniometer().getR())
                SetUB(self._bkg, **ub_args)
            # Determine limits for momentum transfer in HKL space. Needs to be
            # done only once. We use the first run.
            if min_values is None:
                kwargs = dict(QDimensions='Q3D',
                              dEAnalysisMode='Elastic',
                              Q3DFrames='HKL')
                min_values, max_values = ConvertToMDMinMaxGlobal(_t_sample, **kwargs)
                cmd_args.update({'MinValues': min_values,
                                 'MaxValues': max_values})

            # Convert to MD
            _t_md = ConvertToMD(_t_sample, OutputWorkspace='_t_md',
                                **cmd_args)
            if self._bkg:
                _t_bkg_md = ConvertToMD(self._bkg, OutputWorkspace='_t_bkg_md',
                                        **cmd_args)

            # Determine aligned dimensions. Need to be done only once
            if mdn_args is None:
                aligned = list()
                for i_dim in range(3):
                    kwargs = {'name': _t_md.getDimension(i_dim).name,
                              'min': min_values[i_dim],
                              'max': max_values[i_dim],
                              'n_bins': self._n_bins[i_dim]}
                    aligned.append(
                        '{name},{min},{max},{n_bins}'.format(**kwargs))
                mdn_args = dict(AlignedDim0=aligned[0],
                                AlignedDim1=aligned[1],
                                AlignedDim2=aligned[2],
                                FluxWorkspace=_t_int_flux,
                                SolidAngleWorkspace=_t_solid_angle,
                                SkipSafetyCheck=True)

            # Normalize sample by solid angle and integrated flux;
            # Accumulate runs into the temporary workspaces
            MDNormSCD(_t_md,
                      OutputWorkspace='_t_data',
                      OutputNormalizationWorkspace='_t_norm',
                      TemporaryDataWorkspace='_t_data' if
                      mtd.doesExist('_t_data') else None,
                      TemporaryNormalizationWorkspace='_t_norm' if
                      mtd.doesExist('_t_norm') else None,
                      **mdn_args)
            if self._bkg:
                MDNormSCD(_t_bkg_md,
                          OutputWorkspace='_t_bkg_data',
                          OutputNormalizationWorkspace='_t_bkg_norm',
                          TemporaryDataWorkspace='_t_bkg_data' if
                          mtd.doesExist('_t_bkg_data') else None,
                          TemporaryNormalizationWorkspace='_t_bkg_norm'
                          if mtd.doesExist('_t_bkg_norm') else None,
                          **mdn_args)
            message = 'Processing sample {} of {}'.\
                format(i_run+1, len(run_numbers))
            diffraction_reporter.report(message)
        self._temps.workspaces.append('PreprocessedDetectorsWS')  # to remove
        # Iteration over the sample runs is done.

        # Division by vanadium, subtract background, and rename workspaces
        name = self.getPropertyValue("OutputWorkspace")
        _t_data = DivideMD(LHSWorkspace='_t_data', RHSWorkspace='_t_norm')
        if self._bkg:
            _t_bkg_data = DivideMD(LHSWorkspace='_t_bkg_data',
                                   RHSWorkspace='_t_bkg_norm')
            _t_scale = CreateSingleValuedWorkspace(DataValue=self._bkg_scale)
            _t_bkg_data = MultiplyMD(_t_bkg_data, _t_scale)
            ws = MinusMD(_t_data, _t_bkg_data)
            RenameWorkspace(_t_data, OutputWorkspace=name + '_dat')
            RenameWorkspace(_t_bkg_data, OutputWorkspace=name + '_bkg')
        else:
            ws = _t_data
        RenameWorkspace(ws, OutputWorkspace=name)
        self.setProperty("OutputWorkspace", ws)
        diffraction_reporter.report(len(run_numbers), 'Done')
예제 #27
0
    def PyExec(self):
        _load_inst = bool(self.getProperty("LoadInstrument").value)
        _detcal = bool(self.getProperty("DetCal").value)
        _masking = bool(self.getProperty("MaskFile").value)
        _outWS_name = self.getPropertyValue("OutputWorkspace")
        _UB = bool(self.getProperty("UBMatrix").value)

        MinValues = self.getProperty("MinValues").value
        MaxValues = self.getProperty("MaxValues").value

        if self.getProperty("OverwriteExisting").value:
            if mtd.doesExist(_outWS_name):
                DeleteWorkspace(_outWS_name)

        progress = Progress(self, 0.0, 1.0,
                            len(self.getProperty("Filename").value))

        for run in self.getProperty("Filename").value:
            logger.notice("Working on " + run)

            Load(Filename=run,
                 OutputWorkspace='__run',
                 FilterByTofMin=self.getProperty("FilterByTofMin").value,
                 FilterByTofMax=self.getProperty("FilterByTofMax").value,
                 FilterByTimeStop=self.getProperty("FilterByTimeStop").value)

            if _load_inst:
                LoadInstrument(
                    Workspace='__run',
                    Filename=self.getProperty("LoadInstrument").value,
                    RewriteSpectraMap=False)

            if _detcal:
                LoadIsawDetCal(InputWorkspace='__run',
                               Filename=self.getProperty("DetCal").value)

            if _masking:
                if not mtd.doesExist('__mask'):
                    LoadMask(Instrument=mtd['__run'].getInstrument().getName(),
                             InputFile=self.getProperty("MaskFile").value,
                             OutputWorkspace='__mask')
                MaskDetectors(Workspace='__run', MaskedWorkspace='__mask')

            if self.getProperty('SetGoniometer').value:
                SetGoniometer(
                    Workspace='__run',
                    Goniometers=self.getProperty('Goniometers').value,
                    Axis0=self.getProperty('Axis0').value,
                    Axis1=self.getProperty('Axis1').value,
                    Axis2=self.getProperty('Axis2').value)

            if _UB:
                LoadIsawUB(InputWorkspace='__run',
                           Filename=self.getProperty("UBMatrix").value)
                if len(MinValues) == 0 or len(MaxValues) == 0:
                    MinValues, MaxValues = ConvertToMDMinMaxGlobal(
                        '__run',
                        dEAnalysisMode='Elastic',
                        Q3DFrames='HKL',
                        QDimensions='Q3D')
                ConvertToMD(
                    InputWorkspace='__run',
                    OutputWorkspace=_outWS_name,
                    QDimensions='Q3D',
                    dEAnalysisMode='Elastic',
                    Q3DFrames='HKL',
                    QConversionScales='HKL',
                    Uproj=self.getProperty('Uproj').value,
                    Vproj=self.getProperty('Vproj').value,
                    Wproj=self.getProperty('Wproj').value,
                    MinValues=MinValues,
                    MaxValues=MaxValues,
                    SplitInto=self.getProperty('SplitInto').value,
                    SplitThreshold=self.getProperty('SplitThreshold').value,
                    MaxRecursionDepth=self.getProperty(
                        'MaxRecursionDepth').value,
                    OverwriteExisting=False)
            else:
                if len(MinValues) == 0 or len(MaxValues) == 0:
                    MinValues, MaxValues = ConvertToMDMinMaxGlobal(
                        '__run',
                        dEAnalysisMode='Elastic',
                        Q3DFrames='Q',
                        QDimensions='Q3D')
                ConvertToMD(
                    InputWorkspace='__run',
                    OutputWorkspace=_outWS_name,
                    QDimensions='Q3D',
                    dEAnalysisMode='Elastic',
                    Q3DFrames='Q_sample',
                    Uproj=self.getProperty('Uproj').value,
                    Vproj=self.getProperty('Vproj').value,
                    Wproj=self.getProperty('Wproj').value,
                    MinValues=MinValues,
                    MaxValues=MaxValues,
                    SplitInto=self.getProperty('SplitInto').value,
                    SplitThreshold=self.getProperty('SplitThreshold').value,
                    MaxRecursionDepth=self.getProperty(
                        'MaxRecursionDepth').value,
                    OverwriteExisting=False)
            DeleteWorkspace('__run')
            progress.report()

        if mtd.doesExist('__mask'):
            DeleteWorkspace('__mask')

        self.setProperty("OutputWorkspace", mtd[_outWS_name])
예제 #28
0
파일: nxs.py 프로젝트: mcvine/instruments
def reduce(nxsfile,
           qaxis,
           outfile,
           use_ei_guess=False,
           ei_guess=None,
           eaxis=None,
           tof2E=True,
           ibnorm='ByCurrent'):
    from mantid.simpleapi import DgsReduction, SofQW3, SaveNexus, LoadInstrument, Load, MoveInstrumentComponent, \
        MaskBTP, ConvertToMD, BinMD, ConvertMDHistoToMatrixWorkspace, GetEiT0atSNS, GetEi
    from mantid import mtd
    ws = Load(nxsfile)

    if tof2E == 'guess':
        axis = ws.getAxis(0).getUnit().caption().lower()
        # axis name should be "Time-of-flight"
        tof2E = "time" in axis and "flight" in axis

    if tof2E:
        # mask packs around beam
        # MaskBTP(ws, Bank="98-102")
        if not use_ei_guess:
            run = ws.getRun()
            Efixed = run.getLogData('mcvine-Ei').value
            T0 = run.getLogData('mcvine-t0').value
        else:
            Efixed, T0 = ei_guess, 0

        DgsReduction(
            SampleInputWorkspace=ws,
            IncidentEnergyGuess=Efixed,
            UseIncidentEnergyGuess=True,
            TimeZeroGuess=T0,
            OutputWorkspace='reduced',
            EnergyTransferRange=eaxis,
            IncidentBeamNormalisation=ibnorm,
        )
        reduced = mtd['reduced']
    else:
        reduced = Load(nxsfile)

    # if eaxis is not specified, use the data in reduced workspace
    if eaxis is None:
        Edim = reduced.getXDimension()
        emin = Edim.getMinimum()
        emax = Edim.getMaximum()
        de = Edim.getX(1) - Edim.getX(0)
        eaxis = emin, de, emax

    qmin, dq, qmax = qaxis
    nq = int(round((qmax - qmin) / dq))
    emin, de, emax = eaxis
    ne = int(round((emax - emin) / de))
    md = ConvertToMD(
        InputWorkspace='reduced',
        QDimensions='|Q|',
        dEAnalysisMode='Direct',
        MinValues="%s,%s" % (qmin, emin),
        MaxValues="%s,%s" % (qmax, emax),
        SplitInto="%s,%s" % (nq, ne),
    )
    binned = BinMD(
        InputWorkspace=md,
        AxisAligned=1,
        AlignedDim0="|Q|,%s,%s,%s" % (qmin, qmax, nq),
        AlignedDim1="DeltaE,%s,%s,%s" % (emin, emax, ne),
    )
    # convert to histogram
    import histogram as H, histogram.hdf as hh
    data = binned.getSignalArray().copy()
    err2 = binned.getErrorSquaredArray().copy()
    nev = binned.getNumEventsArray()
    data /= nev
    err2 /= (nev * nev)
    qaxis = H.axis('Q',
                   boundaries=np.arange(qmin, qmax + dq / 2., dq),
                   unit='1./angstrom')
    eaxis = H.axis('E',
                   boundaries=np.arange(emin, emax + de / 2., de),
                   unit='meV')
    hist = H.histogram('IQE', (qaxis, eaxis), data=data, errors=err2)
    if outfile.endswith('.nxs'):
        import warnings
        warnings.warn(
            "reduce function no longer writes iqe.nxs nexus file. it only writes iqe.h5 histogram file"
        )
        outfile = outfile[:-4] + '.h5'
    hh.dump(hist, outfile)
    return
예제 #29
0
max_d = 20
tolerance = 0.12

minVals = "-" + max_Q + ",-" + max_Q + ",-" + max_Q
maxVals = max_Q + "," + max_Q + "," + max_Q

distance_threshold = 0.9 * 6.28 / float(max_d)

for f in files:
    data = Load(f)
    SetGoniometer(data, Axis0="BL9:Mot:Sample:Axis1,0,1,0,1")
    MDEW = ConvertToMD(InputWorkspace=data,
                       QDimensions="Q3D",
                       dEAnalysisMode="Elastic",
                       QConversionScales="Q in A^-1",
                       LorentzCorrection='0',
                       MinValues=minVals,
                       MaxValues=maxVals,
                       SplitInto='2',
                       SplitThreshold='50',
                       MaxRecursionDepth='11')
    peaks_ws = FindPeaksMD(MDEW,
                           MaxPeaks=num_peaks_to_find,
                           PeakDistanceThreshold=distance_threshold,
                           AppendPeaks=True)

FindUBUsingFFT(PeaksWorkspace=peaks_ws,
               MinD=min_d,
               MaxD=max_d,
               Tolerance=tolerance)
IndexPeaks(PeaksWorkspace=peaks_ws, Tolerance=tolerance)
#SaveIsawUB( InputWorkspace=peaks_ws,Filename=run_niggli_matrix_file )