Ejemplo n.º 1
0
    def export_roi_to_workspace_mdevent(self,
                                        slicepoint: Sequence[Optional[float]],
                                        bin_params: Sequence[float],
                                        limits: tuple, transpose: bool):
        """
        Export 2D roi to a separate workspace.
        :param slicepoint: ND sequence of either None or float. A float defines the point
                           in that dimension for the slice.
        :param bin_params: ND sequence containing the number of bins for each dimension
        :param limits: An optional ND sequence containing limits for plotting dimensions. If
                       not provided the full extent of each dimension is used
        :param transpose: If true the limits are transposed w.r.t the data
        """
        workspace = self._get_ws()
        if transpose:
            limits = limits[1], limits[0]
        params, xindex, yindex = _roi_binmd_parameters(workspace, slicepoint,
                                                       bin_params, limits)
        params['OutputWorkspace'] = self._roi_name
        roi_ws = BinMD(InputWorkspace=self._get_ws(), **params)
        roi_ws.clearOriginalWorkspaces()
        if transpose:
            _inplace_transposemd(self._roi_name, axes=[yindex, xindex])

        return f'ROI created: {self._roi_name}'
Ejemplo n.º 2
0
    def PyExec(self):
        input_ws = self.getProperty("InputWorkspace").value

        extents = self.getProperty("Extents").value
        bins = self.getProperty("Bins").value

        # Get the UB from either the PeaksWS if provided, or from the input workspace
        if not self.getProperty("PeaksWorkspace").isDefault:
            peak_ws = self.getProperty("PeaksWorkspace").value
            self._lattice = peak_ws.sample().getOrientedLattice()
        else:
            self._lattice = input_ws.getExperimentInfo(
                0).sample().getOrientedLattice()

        # Get axis names and units from u,v,w projections, as done in ConvertWANDSCDtoQ:
        w = np.eye(3)
        w[:, 0] = self.getProperty("Uproj").value
        w[:, 1] = self.getProperty("Vproj").value
        w[:, 2] = self.getProperty("Wproj").value
        char_dict = {0: '0', 1: '{1}', -1: '-{1}'}
        chars = ['H', 'K', 'L']
        names = [
            '[' + ','.join(
                char_dict.get(j, '{0}{1}').format(
                    j, chars[np.argmax(np.abs(w[:, i]))])
                for j in w[:, i]) + ']' for i in range(3)
        ]

        q = [self._lattice.qFromHKL(w[:, i]) for i in range(3)]

        units = ['in {:.3f} A^-1'.format(q[i].norm()) for i in range(3)]

        output_name = self.getPropertyValue("OutputWorkspace")
        CloneMDWorkspace(InputWorkspace=input_ws, OutputWorkspace=output_name)
        SetMDFrame(InputWorkspace=output_name, MDFrame='HKL', Axes='0,1,2')

        mdhist = BinMD(
            InputWorkspace=output_name,
            AxisAligned=False,
            NormalizeBasisVectors=False,
            BasisVector0='{},{},{},{},{}'.format(names[0], units[0], q[0].X(),
                                                 q[0].Y(), q[0].Z()),
            BasisVector1='{},{},{},{},{}'.format(names[1], units[1], q[1].X(),
                                                 q[1].Y(), q[1].Z()),
            BasisVector2='{},{},{},{},{}'.format(names[2], units[2], q[2].X(),
                                                 q[2].Y(), q[2].Z()),
            OutputExtents=extents,
            OutputBins=bins)

        self.setProperty("OutputWorkspace", mdhist)
        mdhist.clearOriginalWorkspaces()
        DeleteWorkspace(mdhist)
Ejemplo n.º 3
0
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
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def perform_non_axis_aligned_cut_to_workspace(self, vectors, extents, nbins):
        projection_params = {}
        # construct projection string for x-axis label
        cens = np.mean(extents.reshape(2, len(vectors), order='F'), axis=0)  # in u{1..3} basis
        ix = np.where(nbins > 1)[0][0]  # index of x-axis
        ivecs = list(range(len(vectors)))
        ivecs.pop(ix)
        cen_vec = np.zeros(vectors[0].shape) # position at x = 0
        for ivec in ivecs:
            cen_vec = cen_vec + cens[ivec]*vectors[ivec]
        proj_str = '(' + ' '.join([f'{np.round(c,2)}+{np.round(x,2)}x' if abs(x) > 0 else f'{np.round(c,2)}'
                                        for c, x in zip(cen_vec, vectors[ix])]) + ')'
        proj_str = proj_str.replace('+-', '-')
        for ivec, vec in enumerate(vectors):
            # calc length
            length = None
            if self.get_frame() == SpecialCoordinateSystem.HKL:
                try:
                    lattice = self._get_ws().getExperimentInfo(0).sample().getOrientedLattice()
                    length = 2*np.pi/lattice.d(*vec)
                except:
                    pass
            else:
                length = np.sqrt(np.sum(vec**2))
            unit_str = f'in {np.round(length,2)} Ang^-1' if length is not None else 'r.l.u.'
            xlab = proj_str if ivec == ix else f'u{ivec+1}'
            vec_str = ','.join(str(v) for v in vec)
            projection_params[f'BasisVector{ivec}'] = ', '.join([xlab, unit_str, vec_str])

        BinMD(InputWorkspace=self._get_ws(), AxisAligned=False, OutputExtents=extents,
              OutputBins=nbins, NormalizeBasisVectors=False, OutputWorkspace=self._1Dcut_name, **projection_params)
        return self._1Dcut_name
Ejemplo n.º 6
0
    def get_ws_MDE(self,
                   slicepoint: Sequence[Optional[float]],
                   bin_params: Sequence[float],
                   limits: Optional[tuple] = None):
        """
        :param slicepoint: ND sequence of either None or float. A float defines the point
                        in that dimension for the slice.
        :param bin_params: ND sequence containing the number of bins for each dimension
        :param limits: An optional 2-tuple sequence containing limits for plotting dimensions. If
                       not provided the full extent of each dimension is used
        """
        workspace = self._get_ws()
        dim_limits = _dimension_limits(workspace, slicepoint, limits)
        params = {'EnableLogging': LOG_GET_WS_MDE_ALGORITHM_CALLS}
        for n in range(workspace.getNumDims()):
            dimension = workspace.getDimension(n)
            slice_pt = slicepoint[n]
            nbins = bin_params[n]
            if slice_pt is None:
                dim_min, dim_max = dim_limits[n]
            else:
                dim_min, dim_max = slice_pt - nbins / 2, slice_pt + nbins / 2
                nbins = 1
            params[
                f'AlignedDim{n}'] = f'{dimension.name},{dim_min},{dim_max},{nbins}'

        return BinMD(InputWorkspace=self._get_ws(),
                     OutputWorkspace=self._rebinned_name,
                     **params)
 def runTest(self):
     # Load processed vanadium for normalisation (bank 1)
     van = LoadNexus(Filename="WISH19612_vana_bank1_SXProcessed.nxs")
     # Load raw data (bank 1)
     ws = load_data_and_normalise(
         "WISH00038237.raw")  # default so doesn't get overwrite van
     # normalise to vanadium
     RebinToWorkspace(WorkspaceToRebin=van,
                      WorkspaceToMatch=ws,
                      OutputWorkspace=van)
     Divide(LHSWorkspace=ws, RHSWorkspace=van, OutputWorkspace=ws)
     ReplaceSpecialValues(InputWorkspace=ws,
                          OutputWorkspace=ws,
                          NaNValue=0,
                          InfinityValue=0,
                          BigNumberThreshold=1e15,
                          SmallNumberThreshold=-1e15)
     # Convert to Diffraction MD and Lorentz Correction
     wsMD = ConvertToDiffractionMDWorkspace(InputWorkspace=ws,
                                            LorentzCorrection=True,
                                            OneEventPerBin=False)
     # BinMD to 2D object and convert to histo so can compare saved workspace
     wsMD_2Dcut = BinMD(InputWorkspace=wsMD,
                        AxisAligned=False,
                        BasisVector0='Q_lab_x,Angstrom^-1,1.0,0.0,0.0',
                        BasisVector1='Q_lab_y,Angstrom^-1,0.0,1.0,0.0',
                        BasisVector2='Q_lab_z,Angstrom^-1,0.0,0.0,1.0',
                        OutputExtents='0.2,0.8,-0.4,0.4,0.05,0.1',
                        OutputBins='50,50,1')
     ConvertMDHistoToMatrixWorkspace(InputWorkspace=wsMD_2Dcut,
                                     outputWorkspace="wsHisto_2Dcut")
Ejemplo n.º 8
0
def convertQSampleToHKL(ws,
                        OutputWorkspace='__md_hkl',
                        norm=None,
                        UB=None,
                        Extents=[-10, 10, -10, 10, -10, 10],
                        Bins=[101, 101, 101],
                        Append=False):
    ol = OrientedLattice()
    ol.setUB(UB)
    q1 = ol.qFromHKL([1, 0, 0])
    q2 = ol.qFromHKL([0, 1, 0])
    q3 = ol.qFromHKL([0, 0, 1])
    BinMD(InputWorkspace=ws,
          AxisAligned=False,
          NormalizeBasisVectors=False,
          BasisVector0='[H,0,0],A^-1,{},{},{}'.format(q1.X(), q1.Y(), q1.Z()),
          BasisVector1='[0,K,0],A^-1,{},{},{}'.format(q2.X(), q2.Y(), q2.Z()),
          BasisVector2='[0,0,L],A^-1,{},{},{}'.format(q3.X(), q3.Y(), q3.Z()),
          OutputExtents=Extents,
          OutputBins=Bins,
          TemporaryDataWorkspace=OutputWorkspace
          if Append and mtd.doesExist(OutputWorkspace) else None,
          OutputWorkspace=OutputWorkspace)
    if norm is not None:
        mtd[str(norm)].run().getGoniometer().setR(
            mtd[str(ws)].getExperimentInfo(0).run().getGoniometer().getR())
        convertToHKL(norm,
                     OutputWorkspace=str(OutputWorkspace) + '_norm',
                     UB=UB,
                     Extents=Extents,
                     Bins=Bins,
                     Append=Append)
    return OutputWorkspace
Ejemplo n.º 9
0
    def export_cuts_to_workspace_mdevent(self,
                                         slicepoint: Sequence[Optional[float]],
                                         bin_params: Sequence[float],
                                         limits: tuple, transpose: bool,
                                         cut: str):
        """
        Export 1D cuts in the X/Y direction for the extent.
        :param slicepoint: ND sequence of either None or float. A float defines the point
                           in that dimension for the slice.
        :param bin_params: ND sequence containing the number of bins for each dimension.
        :param limits: An optional ND sequence containing limits for plotting dimensions. If
                       not provided the full extent of each dimension is used
        :param transpose: If true then the limits are transposed w.r.t to the data
        :param cut: A string denoting which type to export. Options=s,c,x,y.
        """
        workspace = self._get_ws()
        if transpose:
            # swap back to model order
            limits = limits[1], limits[0]
        xcut_name, ycut_name, help_msg = self._cut_names(cut)
        params, xindex, yindex = _roi_binmd_parameters(workspace, slicepoint,
                                                       bin_params, limits)
        output_bins = params['OutputBins']
        xbins, ybins = output_bins[xindex], output_bins[yindex]
        if transpose:
            xindex, yindex = yindex, xindex
            xbins, ybins = ybins, xbins

        if xcut_name:
            params['OutputWorkspace'] = xcut_name
            output_bins[xindex] = xbins
            output_bins[yindex] = 1
            params['OutputBins'] = output_bins
            BinMD(InputWorkspace=self._get_ws(), **params)
            _keep_dimensions(xcut_name, xindex)
        if ycut_name:
            params['OutputWorkspace'] = ycut_name
            output_bins[xindex] = 1
            output_bins[yindex] = ybins
            params['OutputBins'] = output_bins
            BinMD(InputWorkspace=self._get_ws(), **params)
            _keep_dimensions(ycut_name, yindex)

        return help_msg
Ejemplo n.º 10
0
    def setUpClass(cls):
        """
        Create fake workspaces, 3D and 2D
        """

        # 3D
        DeltaPDF3DTest_MDE = CreateMDWorkspace(Dimensions='3', Extents='-3.1,3.1,-3.1,3.1,-3.1,3.1', Names='[H,0,0],[0,K,0],[0,0,L]',
                                               Units='rlu,rlu,rlu', SplitInto='4',Frames='HKL,HKL,HKL')

        # Add Bragg peaks
        for h in range(-3,4):
            for k in range(-3,4):
                for l in range(-3,4):
                    FakeMDEventData(DeltaPDF3DTest_MDE, PeakParams='100,'+str(h)+','+str(k)+','+str(l)+',0.1', RandomSeed='1337')

        # Add addiontal peaks on [0.5,0.5,0.5] type positions
        # This would correspond to negative substitutional correlations
        for h in np.arange(-2.5,3):
            for k in np.arange(-2.5,3):
                for l in np.arange(-2.5,3):
                    FakeMDEventData(DeltaPDF3DTest_MDE, PeakParams='20,'+str(h)+','+str(k)+','+str(l)+',0.1', RandomSeed='13337')

        BinMD(InputWorkspace='DeltaPDF3DTest_MDE', AlignedDim0='[H,0,0],-3.05,3.05,61', AlignedDim1='[0,K,0],-3.05,3.05,61',
              AlignedDim2='[0,0,L],-3.05,3.05,61', OutputWorkspace='DeltaPDF3DTest_MDH')

        # 2D
        DeltaPDF3DTest_MDE_2 = CreateMDWorkspace(Dimensions='3', Extents='-3.1,3.1,-3.1,3.1,-0.1,0.1', Names='[H,0,0],[0,K,0],[0,0,L]',
                                                 Units='rlu,rlu,rlu', SplitInto='4',Frames='HKL,HKL,HKL')

        # Add Bragg peaks
        for h in range(-3,4):
            for k in range(-3,4):
                FakeMDEventData(DeltaPDF3DTest_MDE_2, PeakParams='100,'+str(h)+','+str(k)+',0,0.01', RandomSeed='1337')

        # Add addiontal peaks on [0.5,0.5,0.5] type positions
        # This would correspond to negative substitutional correlations
        for h in np.arange(-2.5,3):
            for k in np.arange(-2.5,3):
                FakeMDEventData(DeltaPDF3DTest_MDE_2, PeakParams='20,'+str(h)+','+str(k)+',0,0.1', RandomSeed='13337')

        BinMD(InputWorkspace='DeltaPDF3DTest_MDE_2', AlignedDim0='[H,0,0],-3.05,3.05,61', AlignedDim1='[0,K,0],-3.05,3.05,61',
              AlignedDim2='[0,0,L],-0.1,0.1,1', OutputWorkspace='DeltaPDF3DTest_MDH_2')
Ejemplo n.º 11
0
def _compute_cut_PSD(selected_workspace, cut_axis, integration_axis):
    fill_in_missing_input(cut_axis, selected_workspace)
    n_steps = get_number_of_steps(cut_axis)
    cut_binning = " ,".join(
        map(str, (cut_axis.units, cut_axis.start, cut_axis.end, n_steps)))
    integration_binning = integration_axis.units + "," + str(integration_axis.start) + "," + \
        str(integration_axis.end) + ",1"

    return BinMD(InputWorkspace=selected_workspace,
                 AxisAligned="1",
                 AlignedDim1=integration_binning,
                 AlignedDim0=cut_binning,
                 StoreInADS=False)
Ejemplo n.º 12
0
 def get_ws_MDE(self, slicepoint, bin_params):
     params = {}
     for n in range(self._get_ws().getNumDims()):
         if slicepoint[n] is None:
             params['AlignedDim{}'.format(n)] = '{},{},{},{}'.format(self._get_ws().getDimension(n).name,
                                                                     self._get_ws().getDimension(n).getMinimum(),
                                                                     self._get_ws().getDimension(n).getMaximum(),
                                                                     bin_params[n])
         else:
             params['AlignedDim{}'.format(n)] = '{},{},{},{}'.format(self._get_ws().getDimension(n).name,
                                                                     slicepoint[n]-bin_params[n]/2,
                                                                     slicepoint[n]+bin_params[n]/2,
                                                                     1)
     return BinMD(InputWorkspace=self._get_ws(),
                  OutputWorkspace=self._get_ws().name()+'_rebinned', **params)
Ejemplo n.º 13
0
    def test_mdhisto_workspace_q(self):
        from mantid.simpleapi import (CreateMDWorkspace, FakeMDEventData,
                                      BinMD)

        md_event = CreateMDWorkspace(Dimensions=3,
                                     Extents=[-10, 10, -10, 10, -10, 10],
                                     Names='Q_x,Q_y,Q_z',
                                     Units='U,U,U',
                                     Frames='QLab,QLab,QLab',
                                     StoreInADS=False)
        FakeMDEventData(InputWorkspace=md_event,
                        PeakParams=[100000, 0, 0, 0, 1],
                        StoreInADS=False)  # Add Peak
        md_histo = BinMD(InputWorkspace=md_event,
                         AlignedDim0='Q_y,-10,10,3',
                         AlignedDim1='Q_x,-10,10,4',
                         AlignedDim2='Q_z,-10,10,5',
                         StoreInADS=False)

        histo_data_array = mantidcompat.convert_MDHistoWorkspace_to_data_array(
            md_histo)

        self.assertEqual(histo_data_array.coords[sc.Dim.Qx].values.shape,
                         (4, ))
        self.assertEqual(histo_data_array.coords[sc.Dim.Qy].values.shape,
                         (3, ))
        self.assertEqual(histo_data_array.coords[sc.Dim.Qz].values.shape,
                         (5, ))
        self.assertEqual(histo_data_array.coords[sc.Dim.Qx].unit,
                         sc.units.dimensionless / sc.units.angstrom)
        self.assertEqual(histo_data_array.coords[sc.Dim.Qy].unit,
                         sc.units.dimensionless / sc.units.angstrom)
        self.assertEqual(histo_data_array.coords[sc.Dim.Qz].unit,
                         sc.units.dimensionless / sc.units.angstrom)

        self.assertEquals(histo_data_array.values.shape, (3, 4, 5))

        # Sum over 2 dimensions to simplify finding max.
        max_1d = sc.sum(sc.sum(histo_data_array, dim=sc.Dim.Qy),
                        dim=sc.Dim.Qx).values
        max_index = np.argmax(max_1d)
        # Check position of max 'peak'
        self.assertEqual(np.floor(len(max_1d) / 2), max_index)
        # All events in central 'peak'
        self.assertEqual(100000, max_1d[max_index])

        self.assertTrue('nevents' in histo_data_array.attrs)
Ejemplo n.º 14
0
 def _compute_slice_PSD(self, workspace, x_axis, y_axis, norm_to_one):
     assert isinstance(workspace, IMDEventWorkspace)
     n_x_bins = get_number_of_steps(x_axis)
     n_y_bins = get_number_of_steps(y_axis)
     x_dim_id = self.dimension_index(workspace, x_axis)
     y_dim_id = self.dimension_index(workspace, y_axis)
     x_dim = workspace.getDimension(x_dim_id)
     y_dim = workspace.getDimension(y_dim_id)
     xbinning = x_dim.getName() + "," + str(x_axis.start) + "," + str(
         x_axis.end) + "," + str(n_x_bins)
     ybinning = y_dim.getName() + "," + str(y_axis.start) + "," + str(
         y_axis.end) + "," + str(n_y_bins)
     return BinMD(InputWorkspace=workspace,
                  AxisAligned="1",
                  AlignedDim0=xbinning,
                  AlignedDim1=ybinning,
                  StoreInADS=False)
Ejemplo n.º 15
0
    def get_ws_MDE(self,
                   slicepoint: Sequence[Optional[float]],
                   bin_params: Optional[Sequence[float]],
                   limits: Optional[tuple] = None,
                   dimension_indices: Optional[tuple] = None):
        """
        :param slicepoint: ND sequence of either None or float. A float defines the point
                        in that dimension for the slice.
        :param bin_params: ND sequence containing the number of bins for each dimension or None to use
                           the existing data
        :param limits: An optional 2-tuple sequence containing limits for plotting dimensions. If
                       not provided the full extent of each dimension is used
        """
        workspace = self._get_ws()

        params, _, __ = _roi_binmd_parameters(workspace, slicepoint, bin_params, limits, dimension_indices)
        params['EnableLogging'] = LOG_GET_WS_MDE_ALGORITHM_CALLS
        binned = BinMD(InputWorkspace=workspace, OutputWorkspace=self._rebinned_name, **params)
        return binned
Ejemplo n.º 16
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
Ejemplo n.º 17
0
    def rebin_MDH(self, slicepoint: Sequence[Optional[float]],
                  limits: Sequence[tuple]):
        """Rebin an MDHistoWorkspace by going back to the original MDEventWorkspace but setting
        new limits on the output extents. It replaces the internal workspace object with the new
        MDHistoWorkspace generated.
        :param slicepoint: ND sequence of either None or float. A float defines the point
                        in that dimension for the slice.
        :param bin_params: ND sequence containing the number of bins for each dimension
        :param limits: An optional 2-tuple sequence containing limits for plotting dimensions. If
                       not provided the full extent of each dimension is used
        """
        def to_str(seq: Sequence):
            return ','.join(map(str, seq))

        # BinMD requires non-axis aligned binning when binning an MDHistoWorkspace from the original
        # MDEventWorkspace
        workspace = self._get_ws()
        limits = _binning_limits(workspace, slicepoint, limits)
        ndims = workspace.getNumDims()
        ws_basis = np.eye(ndims)
        output_extents, output_bins = [], []
        params = {'AxisAligned': False, 'EnableLogging': LOG_BINMD_CALLS}
        for n in range(ndims):
            dimension = workspace.getDimension(n)
            basis_vec_n = to_str(ws_basis[:, n])
            nbins = dimension.getNBins()
            dim_min, dim_max = limits[n]
            params[
                f'BasisVector{n}'] = f'{dimension.name},{dimension.getUnits()},{basis_vec_n}'
            output_extents.append(dim_min)
            output_extents.append(dim_max)
            output_bins.append(nbins)
        params['OutputExtents'] = to_str(output_extents)
        params['OutputBins'] = to_str(output_bins)

        self._ws = BinMD(InputWorkspace=self._get_ws(),
                         OutputWorkspace=self._rebinned_name,
                         **params)
Ejemplo n.º 18
0
 def get_histo_ws(self):
     """Converts _raw_ws from MDEventWorkspace to MDHistoWorkspace using BinMD, and caches result in _histo_ws"""
     if self._histo_ws is None:
         dim_values = []
         for x in range(6):
             try:
                 dim = self._raw_ws.getDimension(x)
                 dim_info = dim.getName() + ',' + str(
                     dim.getMinimum()) + ',' + str(
                         dim.getMaximum()) + ',' + str(100)
             except RuntimeError:
                 dim_info = None
             dim_values.append(dim_info)
         histo_workspace = BinMD(InputWorkspace=self._raw_ws,
                                 OutputWorkspace=str(self),
                                 AlignedDim0=dim_values[0],
                                 AlignedDim1=dim_values[1],
                                 AlignedDim2=dim_values[2],
                                 AlignedDim3=dim_values[3],
                                 AlignedDim4=dim_values[4],
                                 AlignedDim5=dim_values[5])
         self._histo_ws = HistogramWorkspace(histo_workspace, self.name)
     return self._histo_ws
Ejemplo n.º 19
0
    def test_mdhisto_workspace_many_dims(self):
        from mantid.simpleapi import (CreateMDWorkspace, FakeMDEventData,
                                      BinMD)

        md_event = CreateMDWorkspace(
            Dimensions=4,
            Extents=[-10, 10, -10, 10, -10, 10, -10, 10],
            Names='deltae,y,z,T',
            Units='U,U,U,U',
            StoreInADS=False)
        FakeMDEventData(InputWorkspace=md_event,
                        PeakParams=[100000, 0, 0, 0, 0, 1],
                        StoreInADS=False)  # Add Peak
        md_histo = BinMD(InputWorkspace=md_event,
                         AlignedDim0='deltae,-10,10,3',
                         AlignedDim1='y,-10,10,4',
                         AlignedDim2='z,-10,10,5',
                         AlignedDim3='T,-10,10,7',
                         StoreInADS=False)

        histo_data_array = scn.mantid.convert_MDHistoWorkspace_to_data_array(
            md_histo)
        self.assertEqual(4, len(histo_data_array.dims))
Ejemplo n.º 20
0
    with h5py.File(filename, 'r') as f_in:
        bc = np.zeros((pixels), dtype=np.int64)
        for b in range(8):
            bc += np.bincount(f_in['/entry/bank' + str(b + 1) +
                                   '_events/event_id'].value,
                              minlength=pixels)
        bc = bc.reshape((-1, 512)).T
        data_array[n] = bc
        phi_array[n] = f_in[
            'entry/DASlogs/HB2C:Mot:s1.RBV/average_value'].value[0]

t1 = time.time()
print(t1 - t0)
print(data_array.shape)

mdws = CreateMDWorkspace(Dimensions=3,
                         Extents='-10,10,-10,10,-10,10',
                         Names='A,B,C',
                         Units='U,U,U')
t2 = time.time()
binned_ws = BinMD(InputWorkspace=mdws,
                  AlignedDim0='A,0,10,1801',
                  AlignedDim1='B,-10,10,512',
                  AlignedDim2='C,-10,10,3840')
t3 = time.time()
binned_ws.setSignalArray(data_array)
t4 = time.time()
print(t2 - t1)
print(t3 - t2)
print(t4 - t3)
Ejemplo n.º 21
0
                   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,
      AlignedDim1='Q_sample_y,' + BinningDim1,
      AlignedDim2='Q_sample_z,' + BinningDim2,
      OutputWorkspace=name_MDH)

SaveMD(
    name_MDH, iptsdir + 'shared/' + name +
    '_MDH_{}_to_{}_every_{}.nxs'.format(first_run, last_run, load_every))
Ejemplo n.º 22
0
            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) + ']')
            fig.show()

        # generate a 1D multi-dimensional workspace
Ejemplo n.º 23
0
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])

bin1 = BinMD(md1,
             AlignedDim0='Q_sample_x,-10,10,1000',
             AlignedDim1='Q_sample_z,-10,10,1000',
             AlignedDim2='Q_sample_y,-10,10,1')
bin1 /= ws1.run().getProtonCharge()

s1 = bin1.getSignalArray().copy()

x = np.linspace(-1, 1, 1000)
X, Y = np.meshgrid(x, x)
mask = (X**2 + Y**2 > 1) + (X**2 + Y**2 < 0.25)

s1[mask] = 0

s1_mask = s1 < np.percentile(s1, 99.5)

mask[s1_mask[:, :, 0]] = True
Ejemplo n.º 24
0
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
Ejemplo n.º 25
0
        plot_zbins = 1
        AlignedDim2 = '{},{},{},{}'.format(AxisNames[plot_param['axis3']],
                                           plot_zmin, plot_zmax, plot_zbins)
        if have_van:
            data, norm = MDNormSCD(InputWorkspace=mde,
                                   FluxWorkspace=fl,
                                   SolidAngleWorkspace=sa,
                                   SkipSafetyCheck=True,
                                   AlignedDim0=AlignedDim0,
                                   AlignedDim1=AlignedDim1,
                                   AlignedDim2=AlignedDim2)
            mdh = data / norm
        else:
            mdh = BinMD(InputWorkspace=mde,
                        AlignedDim0=AlignedDim0,
                        AlignedDim1=AlignedDim1,
                        AlignedDim2=AlignedDim2,
                        AxisAligned=True)

        intensity = mdh.getSignalArray()
        vmin = 1
        vmax = intensity.max()
        if vmax > 1:
            fig, ax = plt.subplots()
            ax.set_title('{}=[{},{}]'.format(AxisNames[plot_param['axis3']],
                                             plot_zmin, plot_zmax))
            logNorm = colors.LogNorm(vmin=vmin, vmax=vmax)
            cm = plt.cm.get_cmap('rainbow')
            pcm = Plot2DMD(ax, mdh, NumEvNorm=False, norm=logNorm)
            fig.colorbar(pcm, ax=ax)
            #plotSlice(mdws, xydim=[plot_param['axis1'],plot_param['axis2']], slicepoint=[0,0,0.5*(plot_param['zmin']+plot_param['zmax'])], colorscalelog=True)