Example #1
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)
Example #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)
Example #3
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)
Example #4
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)
Example #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
Example #6
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
Example #7
0
def convertQSampleToHKL(ws,
                        OutputWorkspace='__md_hkl',
                        norm=None,
                        UB=None,
                        Extents=[-10, 10, -10, 10, -10, 10],
                        Bins=[101, 101, 101],
                        Append=False,
                        Uproj=(1, 0, 0),
                        Vproj=(0, 1, 0),
                        Wproj=(0, 0, 1)):
    ol = OrientedLattice()
    ol.setUB(UB)
    q1 = ol.qFromHKL(Uproj)
    q2 = ol.qFromHKL(Vproj)
    q3 = ol.qFromHKL(Wproj)
    BinMD(InputWorkspace=ws,
          AxisAligned=False,
          NormalizeBasisVectors=False,
          BasisVector0='Q1,A^-1,{},{},{}'.format(q1.X(), q1.Y(), q1.Z()),
          BasisVector1='Q2,A^-1,{},{},{}'.format(q2.X(), q2.Y(), q2.Z()),
          BasisVector2='Q3,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,
            Scale=mtd[ws].getExperimentInfo(0).run().getProtonCharge(),
            Uproj=Uproj,
            Vproj=Vproj,
            Wproj=Wproj)
    return OutputWorkspace
Example #8
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)]

        mdhist = BinMD(InputWorkspace=input_ws, 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)

        SetMDFrame(mdhist, MDFrame='HKL', Axes='0, 1, 2')

        self.setProperty("OutputWorkspace", mdhist)

        DeleteWorkspace(mdhist)
Example #9
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
Example #10
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)
Example #11
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
Example #12
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))
Example #13
0
    def export_roi_to_workspace_mdevent(self, slicepoint: Sequence[Optional[float]],
                                        bin_params: Sequence[float], limits: tuple,
                                        transpose: bool, dimension_indices: Sequence[int]):
        """
        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 dimension_indices: A list where the value (None, 0, or 1) at index i denotes the index of the axis
                                  dimension i is displayed on
        :param transpose: If true the limits are transposed w.r.t the data
        """
        workspace = self._get_ws()
        params, xindex, yindex = _roi_binmd_parameters(workspace, slicepoint, bin_params, limits, dimension_indices)
        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}'
Example #14
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
Example #15
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))
            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
Example #17
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
Example #18
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)
Example #19
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)
Example #20
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.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):
                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')