コード例 #1
0
ファイル: DirectILLCollectData.py プロジェクト: luzpaz/mantid
def _applyIncidentEnergyCalibration(ws, wsType, eiWS, wsNames, report,
                                    algorithmLogging):
    """Update incident energy and wavelength in the sample logs."""
    originalEnergy = ws.getRun().getLogData('Ei').value
    originalWavelength = ws.getRun().getLogData('wavelength').value
    energy = eiWS.readY(0)[0]
    wavelength = UnitConversion.run('Energy', 'Wavelength', energy, 0, 0, 0, Direct, 5)
    if wsType == common.WS_CONTENT_DETS:
        calibratedWSName = wsNames.withSuffix('incident_energy_calibrated_detectors')
    elif wsType == common.WS_CONTENT_MONS:
        calibratedWSName = wsNames.withSuffix('incident_energy_calibrated_monitors')
    else:
        raise RuntimeError('Unknown workspace content type')
    calibratedWS = CloneWorkspace(InputWorkspace=ws,
                                  OutputWorkspace=calibratedWSName,
                                  EnableLogging=algorithmLogging)
    AddSampleLog(Workspace=calibratedWS,
                 LogName='Ei',
                 LogText=str(energy),
                 LogType='Number',
                 NumberType='Double',
                 LogUnit='meV',
                 EnableLogging=algorithmLogging)
    AddSampleLog(Workspace=calibratedWS,
                 Logname='wavelength',
                 LogText=str(wavelength),
                 LogType='Number',
                 NumberType='Double',
                 LogUnit='Angstrom',
                 EnableLogging=algorithmLogging)
    report.notice("Applied Ei calibration to '" + str(ws) + "'.")
    report.notice('Original Ei: {} new Ei: {}.'.format(originalEnergy, energy))
    report.notice('Original wavelength: {} new wavelength {}.'.format(originalWavelength, wavelength))
    return calibratedWS
コード例 #2
0
def _applyIncidentEnergyCalibration(ws, eiWS, wsNames, report,
                                    algorithmLogging):
    """Update incident energy and wavelength in the sample logs."""
    originalEnergy = ws.getRun().getLogData('Ei').value
    originalWavelength = ws.getRun().getLogData('wavelength').value
    energy = eiWS.readY(0)[0]
    wavelength = UnitConversion.run('Energy', 'Wavelength', energy, 0, 0, 0,
                                    Direct, 5)
    AddSampleLog(Workspace=ws,
                 LogName='Ei',
                 LogText=str(energy),
                 LogType='Number',
                 NumberType='Double',
                 LogUnit='meV',
                 EnableLogging=algorithmLogging)
    AddSampleLog(Workspace=ws,
                 Logname='wavelength',
                 LogText=str(wavelength),
                 LogType='Number',
                 NumberType='Double',
                 LogUnit='Angstrom',
                 EnableLogging=algorithmLogging)
    report.notice("Applied Ei calibration to '" + str(ws) + "'.")
    report.notice('Original Ei: {} new Ei: {}.'.format(originalEnergy, energy))
    report.notice('Original wavelength: {} new wavelength {}.'.format(
        originalWavelength, wavelength))
    return ws
コード例 #3
0
    def testDetectorNormalisation(self):
        data1 =  HB3AAdjustSampleNorm('HB3A_data.nxs', OutputType='Detector', NormaliseBy='None')
        self.assertEqual(data1.getSignalArray().max(), 16)
        self.assertEqual(data1.getErrorSquaredArray().max(), 16)

        # normlise by time, data 2 seconds
        data2 =  HB3AAdjustSampleNorm('HB3A_data.nxs', OutputType='Detector', NormaliseBy='Time')
        self.assertEqual(data2.getSignalArray().max(), 16/2)
        self.assertEqual(data2.getErrorSquaredArray().max(), 16/2**2)

        # normalize by monitor, about 621 counts
        data3 =  HB3AAdjustSampleNorm('HB3A_data.nxs', OutputType='Detector', NormaliseBy='Monitor')
        self.assertAlmostEqual(data3.getSignalArray().max(), 16/621)
        self.assertAlmostEqual(data3.getErrorSquaredArray().max(), 16/621**2)

        # create van data
        van = SliceMDHisto(data1, '0,0,0', '1536,512,1')
        van.setSignalArray(np.full_like(van.getSignalArray(), 25))
        van.setErrorSquaredArray(np.full_like(van.getSignalArray(), 25))
        AddSampleLog(van, LogName='time', LogText='42', LogType='Number Series', NumberType='Double')
        AddSampleLog(van, LogName='monitor', LogText='420', LogType='Number Series', NumberType='Double')

        data1 =  HB3AAdjustSampleNorm('HB3A_data.nxs', VanadiumWorkspace=van, OutputType='Detector', NormaliseBy='None')
        self.assertAlmostEqual(data1.getSignalArray().max(), 16/25)
        self.assertAlmostEqual(data1.getErrorSquaredArray().max(), (16/25)**2*(1/16+1/25))

        # normlise by time, data 2 seconds
        data2 =  HB3AAdjustSampleNorm('HB3A_data.nxs', VanadiumWorkspace=van, OutputType='Detector', NormaliseBy='Time')
        self.assertAlmostEqual(data2.getSignalArray().max(), 16/25*42/2)
        self.assertAlmostEqual(data2.getErrorSquaredArray().max(), (16/25)**2*(1/16+1/25) * (42/2)**2)

        # normalize by monitor, about 621 counts
        data3 =  HB3AAdjustSampleNorm('HB3A_data.nxs', VanadiumWorkspace=van, OutputType='Detector', NormaliseBy='Monitor')
        self.assertAlmostEqual(data3.getSignalArray().max(), 16/25*420/621)
        self.assertAlmostEqual(data3.getErrorSquaredArray().max(), (16/25)**2*(1/16+1/25) * (420/621)**2)
コード例 #4
0
 def _addForegroundToLogs(self, ws, beamPosWS):
     """Add foreground start and end workspace indices to the sample logs of ws."""
     hws = self._foregroundWidths()
     beamPosIndex = self._foregroundCentre(beamPosWS)
     sign = self._workspaceIndexDirection(ws)
     start = beamPosIndex - sign * hws[0]
     end = beamPosIndex + sign * hws[1]
     if start > end:
         end, start = start, end
     AddSampleLog(Workspace=ws,
                  LogName=common.SampleLogs.FOREGROUND_START,
                  LogText=str(start),
                  LogType='Number',
                  NumberType='Int',
                  EnableLogging=self._subalgLogging)
     AddSampleLog(Workspace=ws,
                  LogName=common.SampleLogs.FOREGROUND_CENTRE,
                  LogText=str(beamPosIndex),
                  logType='Number',
                  NumberType='Int',
                  EnableLogging=self._subalgLogging)
     AddSampleLog(Workspace=ws,
                  LogName=common.SampleLogs.FOREGROUND_END,
                  LogText=str(end),
                  LogType='Number',
                  NumberType='Int',
                  EnableLogging=self._subalgLogging)
     return ws
コード例 #5
0
    def test_edge_case(self):
        # This is to capture the case where there are identical theta
        # values for multiple spectra which cause problems when
        # ResampleX is run with particular Xmin and Xmax causing the
        # output to be all zeros.

        # Create more real test workspace, using same properties as
        # HB2C_558131
        data = np.ones((256, 1920))
        CreateWorkspace(
            DataX=[0, 1],
            DataY=data,
            DataE=np.sqrt(data),
            UnitX='Empty',
            YUnitLabel='Counts',
            NSpec=1966080 // 4,
            OutputWorkspace='tmp_ws')
        AddSampleLog('tmp_ws', LogName='HB2C:Mot:s2.RBV', LogText='29.9774', LogType='Number Series', NumberType='Double')
        AddSampleLog('tmp_ws', LogName='HB2C:Mot:detz.RBV', LogText='0', LogType='Number Series', NumberType='Double')
        tmp_ws = mtd['tmp_ws']

        for n in range(tmp_ws.getNumberHistograms()):
            s = tmp_ws.getSpectrum(n)
            for i in range(2):
                for j in range(2):
                    s.addDetectorID(int(n * 2 % 512 + n // (512 / 2) * 512 * 2 + j + i * 512))
        LoadInstrument('tmp_ws', InstrumentName='WAND', RewriteSpectraMap=False)

        out = WANDPowderReduction('tmp_ws', Target='Theta', XMin=29, XMax=31, NumberBins=10, NormaliseBy='None')
        np.testing.assert_allclose(out.readY(0), [0, 0, 0, 0, 269.068237, 486.311606, 618.125152, 720.37274, 811.141863, 821.032586], rtol=5e-4)

        tmp_ws.delete()
        out.delete()
コード例 #6
0
 def setUp(self):
     ws = CreateWorkspace(DataX='1,11,111,1,11,111',
                          DataY='2,22,22,22',
                          DataE='1,5,5,5',
                          UnitX="TOF",
                          NSpec=2)
     AddSampleLog(ws, LogName='wavelength', LogText='6.5', LogType='Number Series')
     AddSampleLog(ws, LogName='wavelength_spread', LogText='0.1', LogType='Number Series')
コード例 #7
0
 def _add_all_sample_logs(self, ws):
     """ add all sample logs to a workspace
     :param ws: workspace where sample logs should be added
     """
     AddSampleLog(ws, "proposal_number", str(self.prop_num))
     AddSampleLog(ws, "proposal_title", self.prop_title)
     AddSampleLog(ws, "experiment_team", self.exp_team)
     AddSampleLog(ws, "temperature", str(self.temperature), LogUnit="F")
     AddSampleLog(ws, "Ei", str(self.Ei), LogUnit="meV")
コード例 #8
0
 def test_nasty_log(self):
     AddSampleLog(self.ws1, 'chopper_speed', '14000.0', 'String')
     AddSampleLog(self.ws2, 'chopper_speed', '1400q', 'String')
     wslist = [self.ws1, self.ws2]
     alg_test = run_algorithm("CompareSampleLogs", InputWorkspaces=wslist, SampleLogs='chopper_speed',
                              Tolerance=10.0)
     self.assertTrue(alg_test.isExecuted())
     result = alg_test.getProperty('Result').value
     self.assertEqual('chopper_speed', result)
コード例 #9
0
    def runTest(self):
        # create van data
        van = LoadWANDSCD('HB2C_7000.nxs.h5')
        van.setSignalArray(np.full_like(van.getSignalArray(), 25))
        van.setErrorSquaredArray(np.full_like(van.getSignalArray(), 25))
        AddSampleLog(van,
                     LogName='duration',
                     LogText='42',
                     LogType='Number Series',
                     NumberType='Double')
        AddSampleLog(van,
                     LogName='monitor_count',
                     LogText='420',
                     LogType='Number Series',
                     NumberType='Double')
        # NOTE: all reference values are copied from terminal after confirm the code is correct
        LoadWANDTest_ws = LoadWANDSCD(
            Filename='HB2C_7000.nxs.h5,HB2C_7001.nxs.h5',
            VanadiumWorkspace=van,
            NormalizedBy='Monitor')
        ref_val = 0.00012953253733973653
        self.assertAlmostEqual(LoadWANDTest_ws.getSignalArray().max(), ref_val,
                               5)
        self.assertAlmostEqual(LoadWANDTest_ws.getErrorSquaredArray().max(),
                               0.0, 5)
        #
        LoadWANDTest_ws = LoadWANDSCD(
            Filename='HB2C_7000.nxs.h5,HB2C_7001.nxs.h5',
            VanadiumWorkspace=van,
            NormalizedBy='Counts')
        ref_val = 0.0112
        self.assertAlmostEqual(LoadWANDTest_ws.getSignalArray().max(), ref_val,
                               5)
        ref_err = 2.29376e-05
        self.assertAlmostEqual(LoadWANDTest_ws.getErrorSquaredArray().max(),
                               ref_err, 5)
        #
        LoadWANDTest_ws = LoadWANDSCD(
            Filename='HB2C_7000.nxs.h5,HB2C_7001.nxs.h5',
            VanadiumWorkspace=van,
            NormalizedBy='Time')
        ref_val = 0.29363296439511044
        self.assertAlmostEqual(LoadWANDTest_ws.getSignalArray().max(), ref_val,
                               5)
        ref_err = 0.0157660
        self.assertAlmostEqual(LoadWANDTest_ws.getErrorSquaredArray().max(),
                               ref_err, 5)

        LoadWANDTest_ws.delete()
        van.delete()
コード例 #10
0
    def createTestWorkspace(self, run=23456):
        """ Create a workspace for testing against with ideal log values
        """
        from mantid.simpleapi import CreateWorkspace
        from mantid.simpleapi import AddSampleLog
        from time import gmtime, strftime,mktime
        import numpy as np

        # Create a matrix workspace
        x = np.array([1.,2.,3.,4.])
        y = np.array([1.,2.,3.])
        e = np.sqrt(np.array([1.,2.,3.]))
        wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=1,UnitX='TOF')

        # Add run_start
        tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())))
        AddSampleLog(Workspace=wksp,LogName='run_start',LogText=str(tmptime))

        tsp_a=kernel.FloatTimeSeriesProperty("proton_charge")
        tsp_b=kernel.FloatTimeSeriesProperty("SensorA")
        for i in arange(25):
            tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())+i))
            if run == 23456: 
                shift = 0
            else:
                shift = int(run)
            tsp_a.addValue(tmptime, 1.0*i*i + shift)
            tsp_b.addValue(tmptime, 1.234*(i+1))

        wksp.mutableRun()['run_number']=str(run)
        wksp.mutableRun()['duration']=342.3
        wksp.mutableRun()['SensorA'] = tsp_b
        wksp.mutableRun()['proton_charge']=tsp_a

        return wksp
コード例 #11
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')
コード例 #12
0
 def test_multiple_histograms(self):
     energyBins = np.arange(-7., 7., 0.13)
     qs = np.array([1.1, 1.3, 1.5, 1.7])
     EFixed = 8.
     Ys = np.ones(3 * (len(energyBins) - 1))
     Es = Ys
     verticalAxis = [str(q) for q in qs]
     ws = CreateWorkspace(energyBins, Ys, Es, NSpec=3, UnitX='DeltaE',
                          VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=verticalAxis, StoreInADS=False)
     LoadInstrument(ws, InstrumentName='IN4', RewriteSpectraMap=False, StoreInADS=False)
     AddSampleLog(ws, LogName='Ei', LogText=str(EFixed), LogType='Number', LogUnit='meV', StoreInADS=False)
     dos = ComputeIncoherentDOS(ws, EnergyBinning='Emin, Emax', StoreInADS=False)
     self.assertEqual(dos.getNumberHistograms(), 1)
     self.assertEqual(dos.getAxis(0).getUnit().unitID(), 'DeltaE')
     dos_Xs = dos.readX(0)
     self.assertEqual(len(dos_Xs), len(energyBins))
     dos_Ys = dos.readY(0)
     dos_Es = dos.readE(0)
     g1 = self.compute(qs[0:2], energyBins)
     g2 = self.compute(qs[1:3], energyBins)
     g3 = self.compute(qs[2:4], energyBins)
     g = (g1 + g2 + g3) / 3
     gE = np.sqrt(g1**2 + g2**2 + g3**2) / 3
     np.testing.assert_equal(dos_Xs, energyBins)
     for i in range(len(dos_Ys)):
         self.assertAlmostEquals(dos_Ys[i], g[i])
         self.assertAlmostEquals(dos_Es[i], gE[i])
コード例 #13
0
 def _sumForegroundInLambda(self, ws):
     """Sum the foreground region into a single histogram."""
     foreground = self._foregroundIndices(ws)
     sumIndices = [i for i in range(foreground[0], foreground[2] + 1)]
     beamPosIndex = foreground[1]
     foregroundWSName = self._names.withSuffix('foreground_grouped')
     foregroundWS = ExtractSingleSpectrum(InputWorkspace=ws,
                                          OutputWorkspace=foregroundWSName,
                                          WorkspaceIndex=beamPosIndex,
                                          EnableLogging=self._subalgLogging)
     maxIndex = ws.getNumberHistograms() - 1
     foregroundYs = foregroundWS.dataY(0)
     foregroundEs = foregroundWS.dataE(0)
     numpy.square(foregroundEs, out=foregroundEs)
     for i in sumIndices:
         if i == beamPosIndex:
             continue
         if i < 0 or i > maxIndex:
             self.log().warning(
                 'Foreground partially out of the workspace.')
         ys = ws.readY(i)
         foregroundYs += ys
         es = ws.readE(i)
         foregroundEs += es**2
     numpy.sqrt(foregroundEs, out=foregroundEs)
     self._cleanup.cleanup(ws)
     AddSampleLog(Workspace=foregroundWS,
                  LogName=common.SampleLogs.SUM_TYPE,
                  LogText=SumType.IN_LAMBDA,
                  LogType='String',
                  EnableLogging=self._subalgLogging)
     ConvertToDistribution(Workspace=foregroundWS,
                           EnableLogging=self._subalgLogging)
     return foregroundWS
コード例 #14
0
 def setUp(self):
     input_ws = CreateSampleWorkspace(
         Function="User Defined",
         UserDefinedFunction="name=LinearBackground, " +
         "A0=0.3;name=Gaussian, PeakCentre=5, Height=10, Sigma=0.3",
         NumBanks=2,
         BankPixelWidth=1,
         XMin=0,
         XMax=10,
         BinWidth=0.1,
         BankDistanceFromSample=4.0)
     self._input_ws = input_ws
     self._table = FindEPP(input_ws, OutputWorkspace="table")
     AddSampleLog(self._input_ws,
                  LogName='wavelength',
                  LogText='4.0',
                  LogType='Number',
                  LogUnit='Angstrom')
     for i in range(input_ws.getNumberHistograms()):
         y = input_ws.dataY(i)
         y.fill(0.)
         y[51] = 100.
         e = input_ws.dataE(i)
         e.fill(0.)
         e[51] = 10.
コード例 #15
0
    def setUpClass(cls):
        cls.sim_scattering_data = np.arange(0, 1.5,
                                            0.002).reshape(30, 25).transpose()
        cls.scattering_rotated = np.rot90(cls.sim_scattering_data, k=3)
        cls.scattering_rotated = np.flipud(cls.scattering_rotated)
        cls.e_axis = Axis('DeltaE', -10, 15, 1)
        cls.q_axis = Axis('|Q|', 0.1, 3.1, 0.1)
        cls.q_axis_degrees = Axis('Degrees', 3, 33, 1)

        cls.test_ws = CreateSampleWorkspace(OutputWorkspace='test_ws',
                                            NumBanks=1,
                                            BankPixelWidth=5,
                                            XMin=0.1,
                                            XMax=3.1,
                                            BinWidth=0.1,
                                            XUnit='DeltaE')
        for i in range(cls.test_ws.raw_ws.getNumberHistograms()):
            cls.test_ws.raw_ws.setY(i, cls.sim_scattering_data[i])
        AddSampleLog(workspace=cls.test_ws.raw_ws,
                     LogName='Ei',
                     LogText='3.',
                     LogType='Number',
                     StoreInADS=False)
        cls.test_ws.e_mode = 'Direct'
        cls.test_ws.e_fixed = 3
コード例 #16
0
 def _addSumTypeToLogs(self, ws, sumType):
     """Add a sum type entry to sample logs."""
     AddSampleLog(Workspace=ws,
                  LogName=common.SampleLogs.SUM_TYPE,
                  LogText=sumType,
                  LogType='String',
                  EnableLogging=self._subalgLogging)
コード例 #17
0
    def createTestWorkspace(self):
        """ Create a workspace for testing against with ideal log values
        """
        from mantid.simpleapi import CreateWorkspace
        from mantid.simpleapi import AddSampleLog
        from time import gmtime, strftime, mktime

        # Create a matrix workspace
        x = np.array([1., 2., 3., 4.])
        y = np.array([1., 2., 3.])
        e = np.sqrt(np.array([1., 2., 3.]))
        wksp = CreateWorkspace(DataX=x, DataY=y, DataE=e, NSpec=1, UnitX='TOF')

        # Add run_start
        tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())))
        AddSampleLog(Workspace=wksp, LogName='run_start', LogText=str(tmptime))

        tsp_a = kernel.FloatTimeSeriesProperty("SensorA")
        tsp_b = kernel.FloatTimeSeriesProperty("SensorB")
        tsp_c = kernel.FloatTimeSeriesProperty("SensorC")
        for i in np.arange(25):
            tmptime = strftime("%Y-%m-%d %H:%M:%S",
                               gmtime(mktime(gmtime()) + i))
            tsp_a.addValue(tmptime, 1.0 * i * i)
            tsp_b.addValue(tmptime, 2.0 * i * i)
            tsp_c.addValue(tmptime, 3.0 * i * i)

        wksp.mutableRun()['SensorA'] = tsp_a
        wksp.mutableRun()['SensorB'] = tsp_b
        wksp.mutableRun()['SensorC'] = tsp_c

        return wksp
コード例 #18
0
 def test_plotDOS_PlotMultiple(self):
     ws = CreateSampleWorkspace(NumBanks=1,
                                XUnit='DeltaE',
                                XMin=-12.,
                                XMax=12.,
                                BinWidth=0.2,
                                StoreInADS=False)
     MoveInstrumentComponent(ws, 'bank1', X=-0.5, StoreInADS=False)
     ws = ConvertSpectrumAxis(ws, 'Theta', 'Direct', 14., StoreInADS=False)
     SetInstrumentParameter(ws,
                            ParameterName='deltaE-mode',
                            Value='direct',
                            StoreInADS=False)
     AddSampleLog(ws,
                  LogName='Ei',
                  LogText=str(14.),
                  LogType='Number',
                  LogUnit='meV',
                  StoreInADS=False)
     stw = ComputeIncoherentDOS(ws)
     kwargs = {'workspaces': [stw, 'stw']}
     figure, axes = testhelpers.assertRaisesNothing(self,
                                                    directtools.plotDOS,
                                                    **kwargs)
     self.assertEqual(axes.get_xlabel(), 'Energy transfer ($meV$)')
     self.assertEqual(axes.get_ylabel(), '$g(E)$')
コード例 #19
0
 def setUp(self):
     input_ws = CreateSampleWorkspace(Function="User Defined",
                                      UserDefinedFunction="name=LinearBackground, A0=0.3;name=Gaussian, \
                                      PeakCentre=5, Height=10, Sigma=0.3", NumBanks=2, BankPixelWidth=1,
                                      XMin=0, XMax=10, BinWidth=0.1, BankDistanceFromSample=4.0)
     self._input_ws = input_ws
     self._table = FindEPP(input_ws, OutputWorkspace="table")
     AddSampleLog(self._input_ws, LogName='wavelength', LogText='4.0', LogType='Number', LogUnit='Angstrom')
コード例 #20
0
    def test_HFIRCalculateGoniometer_HB3A_phi(self):
        omega = np.deg2rad(42)
        chi = np.deg2rad(-3)
        phi = np.deg2rad(23)
        R1 = np.array([
            [np.cos(omega), 0, -np.sin(omega)],  # omega 0,1,0,-1
            [0, 1, 0],
            [np.sin(omega), 0, np.cos(omega)]
        ])
        R2 = np.array([
            [np.cos(chi), np.sin(chi), 0],  # chi 0,0,1,-1
            [-np.sin(chi), np.cos(chi), 0],
            [0, 0, 1]
        ])
        R3 = np.array([
            [np.cos(phi), 0, -np.sin(phi)],  # phi 0,1,0,-1
            [0, 1, 0],
            [np.sin(phi), 0, np.cos(phi)]
        ])
        R = np.dot(np.dot(R1, R2), R3)

        wl = 1.54
        k = 2 * np.pi / wl
        theta = np.deg2rad(47)
        phi = np.deg2rad(13)

        q_lab = np.array([
            -np.sin(theta) * np.cos(phi), -np.sin(theta) * np.sin(phi),
            1 - np.cos(theta)
        ]) * k

        q_sample = np.dot(np.linalg.inv(R), q_lab)

        peaks = CreatePeaksWorkspace(OutputType="LeanElasticPeak",
                                     NumberOfPeaks=0)
        AddSampleLog(peaks, "Wavelength", str(wl), "Number")
        SetGoniometer(peaks, Axis0='42,0,1,0,-1',
                      Axis1='-3,0,0,1,-1')  # don't set phi

        p = peaks.createPeakQSample(q_sample)
        peaks.addPeak(p)

        HFIRCalculateGoniometer(peaks,
                                OverrideProperty=True,
                                InnerGoniometer=True)

        g = Goniometer()
        g.setR(peaks.getPeak(0).getGoniometerMatrix())
        YZY = g.getEulerAngles('YZY')
        self.assertAlmostEqual(YZY[0], -42, delta=1e-10)  # omega
        self.assertAlmostEqual(YZY[1], 3, delta=1e-10)  # chi
        self.assertAlmostEqual(YZY[2], -23, delta=1e-1)  # phi

        self.assertAlmostEqual(peaks.getPeak(0).getWavelength(),
                               1.54,
                               delta=1e-10)
コード例 #21
0
 def test_invalid_epp(self):
     AddSampleLog(self._input_ws,
                  LogName='EPP',
                  LogText=str(0),
                  LogType='Number')
     OutputWorkspaceName = "outputws"
     self.assertRaises(RuntimeError,
                       TOFTOFConvertTofToDeltaE,
                       InputWorkspace=self._input_ws,
                       OutputWorkspace=OutputWorkspaceName)
コード例 #22
0
 def unitySTwoThetaWSingleHistogram(self, energyBins, qs):
     EFixed = 8.
     Ys = np.ones(len(energyBins) - 1)
     Es = Ys
     verticalAxis = [str(q) for q in qs]
     ws = CreateWorkspace(energyBins, Ys, Es, UnitX='DeltaE',
                          VerticalAxisUnit='Degrees', VerticalAxisValues=verticalAxis, StoreInADS=False)
     LoadInstrument(ws, InstrumentName='IN4', RewriteSpectraMap=False, StoreInADS=False)
     AddSampleLog(ws, LogName='Ei', LogText=str(EFixed), LogType='Number', LogUnit='meV', StoreInADS=False)
     return ws
コード例 #23
0
ファイル: reduce_hb2b_data.py プロジェクト: williamfgc/PyRS
def load_instrument(raw_data_ws_name, idf_name, two_theta, cal_shift_x,
                    cal_shift_y):
    """ Set up parameters to workspace and load instrument
    """
    # instrument position
    AddSampleLog(Workspace=raw_data_ws_name,
                 LogName='cal::2theta',
                 LogText='{}'.format(-two_theta),
                 LogType='Number Series',
                 LogUnit='degree',
                 NumberType='Double')

    # calibration information
    AddSampleLog(Workspace=raw_data_ws_name,
                 LogName='cal::arm',
                 LogText='0.0',
                 LogType='Number Series',
                 LogUnit='meter',
                 NumberType='Double')
    AddSampleLog(Workspace=raw_data_ws_name,
                 LogName='cal::deltax',
                 LogText='{}'.format(cal_shift_x),
                 LogType='Number Series',
                 LogUnit='meter',
                 NumberType='Double')
    AddSampleLog(Workspace=raw_data_ws_name,
                 LogName='cal::deltay',
                 LogText='{}'.format(-cal_shift_y),
                 LogType='Number Series',
                 LogUnit='meter',
                 NumberType='Double')
    AddSampleLog(Workspace=raw_data_ws_name,
                 LogName='cal::flip',
                 LogText='0.0',
                 LogType='Number Series',
                 LogUnit='degree',
                 NumberType='Double')
    AddSampleLog(Workspace=raw_data_ws_name,
                 LogName='cal::roty',
                 LogText='{}'.format(-two_theta),
                 LogType='Number Series',
                 LogUnit='degree',
                 NumberType='Double')
    AddSampleLog(Workspace=raw_data_ws_name,
                 LogName='cal::spin',
                 LogText='90.0',
                 LogType='Number Series',
                 LogUnit='degree',
                 NumberType='Double')

    # Load instrument
    LoadInstrument(Workspace=raw_data_ws_name,
                   Filename=idf_name,
                   RewriteSpectraMap=True)
    # print output
    print_position(mtd[raw_data_ws_name])

    return mtd[raw_data_ws_name]
コード例 #24
0
 def _create_workspace(self, run_number, prefix='', suffix=''):
     name = prefix + str(run_number) + suffix
     ws = CreateSampleWorkspace(WorkspaceType='Histogram',
                                NumBanks=1,
                                NumMonitors=2,
                                BankPixelWidth=2,
                                XMin=200,
                                OutputWorkspace=name)
     AddSampleLog(Workspace=ws,
                  LogName='run_number',
                  LogText=str(run_number))
コード例 #25
0
    def _prepare_sans2d_empty_ws():
        workspace = load_empty_instrument("SANS2D")

        # Taken from SANS2D00028784
        AddSampleLog(Workspace=workspace,
                     LogName="Front_Det_X",
                     LogText="-859.968")
        AddSampleLog(Workspace=workspace,
                     LogName="Front_Det_Z",
                     LogText="5001.97")
        AddSampleLog(Workspace=workspace,
                     LogName="Front_Det_ROT",
                     LogText="-9.02552")
        AddSampleLog(Workspace=workspace,
                     LogName="Rear_Det_X",
                     LogText="100.048")
        AddSampleLog(Workspace=workspace,
                     LogName="Rear_Det_Z",
                     LogText="11999.0")
        return workspace
コード例 #26
0
def sum_regular_runs(workspace_names):
    """
    Sum runs with single workspace data.

    @param workspace_names List of names of input workspaces
    @return List of names of workspaces
    """
    from mantid.simpleapi import (MergeRuns, Scale, AddSampleLog,
                                  DeleteWorkspace)

    # Use the first workspace name as the result of summation
    summed_detector_ws_name = workspace_names[0]
    summed_monitor_ws_name = workspace_names[0] + '_mon'

    # Get a list of the run numbers for the original data
    run_numbers = ','.join(
        [str(mtd[ws_name].getRunNumber()) for ws_name in workspace_names])

    # Generate lists of the detector and monitor workspaces
    detector_workspaces = ','.join(workspace_names)
    monitor_workspaces = ','.join(
        [ws_name + '_mon' for ws_name in workspace_names])

    # Merge the raw workspaces
    MergeRuns(InputWorkspaces=detector_workspaces,
              OutputWorkspace=summed_detector_ws_name)
    MergeRuns(InputWorkspaces=monitor_workspaces,
              OutputWorkspace=summed_monitor_ws_name)

    # Delete old workspaces
    for idx in range(1, len(workspace_names)):
        DeleteWorkspace(workspace_names[idx])
        DeleteWorkspace(workspace_names[idx] + '_mon')

    # Derive the scale factor based on number of merged workspaces
    scale_factor = 1.0 / len(workspace_names)
    logger.information('Scale factor for summed workspaces: %f' % scale_factor)

    # Scale the new detector and monitor workspaces
    Scale(InputWorkspace=summed_detector_ws_name,
          OutputWorkspace=summed_detector_ws_name,
          Factor=scale_factor)
    Scale(InputWorkspace=summed_monitor_ws_name,
          OutputWorkspace=summed_monitor_ws_name,
          Factor=scale_factor)

    # Add the list of run numbers to the result workspace as a sample log
    AddSampleLog(Workspace=summed_detector_ws_name,
                 LogName='multi_run_numbers',
                 LogType='String',
                 LogText=run_numbers)

    # Only have the one workspace now
    return [summed_detector_ws_name]
コード例 #27
0
ファイル: LoadWAND.py プロジェクト: freephys/mantid
    def PyExec(self):
        filename = self.getProperty("Filename").value
        wavelength = self.getProperty("wavelength").value
        outWS = self.getPropertyValue("OutputWorkspace")

        LoadEventNexus(Filename=filename,
                       OutputWorkspace=outWS,
                       LoadMonitors=True)
        Integration(InputWorkspace=outWS, OutputWorkspace=outWS)

        if self.getProperty("ApplyMask").value:
            MaskBTP(outWS, Bank='8', Tube='449-480')
            MaskBTP(outWS, Pixel='1,2,511,512')

        mtd[outWS].getAxis(0).setUnit("Wavelength")
        w = [wavelength - 0.001, wavelength + 0.001]
        for idx in range(mtd[outWS].getNumberHistograms()):
            mtd[outWS].setX(idx, w)

        SetGoniometer(outWS, Axis0="HB2C:Mot:s1,0,1,0,1")
        AddSampleLog(outWS,
                     LogName="gd_prtn_chrg",
                     LogType='Number',
                     NumberType='Double',
                     LogText=str(mtd[outWS + '_monitors'].getNumberEvents()))
        DeleteWorkspace(outWS + '_monitors')

        AddSampleLog(outWS,
                     LogName="Wavelength",
                     LogType='Number',
                     NumberType='Double',
                     LogText=str(wavelength))
        AddSampleLog(outWS,
                     LogName="Ei",
                     LogType='Number',
                     NumberType='Double',
                     LogText=str(
                         UnitConversion.run('Wavelength', 'Energy', wavelength,
                                            0, 0, 0, Elastic, 0)))

        self.setProperty('OutputWorkspace', outWS)
コード例 #28
0
    def test_log_value_combo_box_contains_sample_logs(self):
        ws1 = CreateSampleWorkspace()
        ws2 = CreateSampleWorkspace()
        workspaces = [ws1, ws2]

        for i, ws in enumerate(workspaces):
            AddSampleLog(Workspace=ws.name(), LogName="Test", LogText=str(i))

        ssd = SpectraSelectionDialog(workspaces, advanced=True)
        self.assertNotEqual(
            ssd._ui.advanced_options_widget.ui.log_value_combo_box.findText(
                "Test"), -1)
コード例 #29
0
    def _create_workspaces(self):
        cal=CreateSampleWorkspace(NumBanks=1,BinWidth=20000,PixelSpacing=0.1,BankPixelWidth=100)
        RotateInstrumentComponent(cal, ComponentName='bank1', X=1, Y=0.5, Z=2, Angle=35)
        MoveInstrumentComponent(cal, ComponentName='bank1', X=1, Y=1, Z=5)
        bkg=CloneWorkspace(cal)
        data=CloneWorkspace(cal)
        AddSampleLog(cal, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='200')
        AddSampleLog(bkg, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='50')
        AddSampleLog(data, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='100')
        AddSampleLog(cal, LogName="duration", LogType='Number', NumberType='Double', LogText='20')
        AddSampleLog(bkg, LogName="duration", LogType='Number', NumberType='Double', LogText='5')
        AddSampleLog(data, LogName="duration", LogType='Number', NumberType='Double', LogText='10')

        def get_cal_counts(n):
            if n < 5000:
                return 0.9
            else:
                return 1.0

        def get_bkg_counts(n):
            return 1.5*get_cal_counts(n)

        def get_data_counts(n,twoTheta):
            tt1=30
            tt2=45
            return get_bkg_counts(n)+10*np.exp(-(twoTheta-tt1)**2/1)+20*np.exp(-(twoTheta-tt2)**2/0.2)

        for i in range(cal.getNumberHistograms()):
            cal.setY(i, [get_cal_counts(i)*2.0])
            bkg.setY(i, [get_bkg_counts(i)/2.0])
            twoTheta=data.getInstrument().getDetector(i+10000).getTwoTheta(V3D(0,0,0),V3D(0,0,1))*180/np.pi
            data.setY(i, [get_data_counts(i,twoTheta)])

        return data, cal, bkg
コード例 #30
0
 def _create_event_workspace(self,
                             run_number,
                             prefix='',
                             includeMonitors=True):
     name = prefix + str(run_number)
     CreateSampleWorkspace(WorkspaceType='Event',
                           NumBanks=1,
                           NumMonitors=3,
                           BankPixelWidth=2,
                           XMin=200,
                           OutputWorkspace=name)
     if includeMonitors:
         CropWorkspace(InputWorkspace=name,
                       StartWorkspaceIndex=0,
                       EndWorkspaceIndex=2,
                       OutputWorkspace=name + '_monitors')
         Rebin(InputWorkspace=name + '_monitors',
               Params='0,200,20000',
               OutputWorkspace=name + '_monitors',
               PreserveEvents=False)
     CropWorkspace(InputWorkspace=name,
                   StartWorkspaceIndex=3,
                   EndWorkspaceIndex=4,
                   OutputWorkspace=name)
     AddSampleLog(Workspace=name,
                  LogName='run_number',
                  LogText=str(run_number))
     AddTimeSeriesLog(Workspace=name,
                      Name="proton_charge",
                      Time="2010-01-01T00:00:00",
                      Value=100)
     AddTimeSeriesLog(Workspace=name,
                      Name="proton_charge",
                      Time="2010-01-01T00:10:00",
                      Value=100)
     AddTimeSeriesLog(Workspace=name,
                      Name="proton_charge",
                      Time="2010-01-01T00:20:00",
                      Value=80)
     AddTimeSeriesLog(Workspace=name,
                      Name="proton_charge",
                      Time="2010-01-01T00:30:00",
                      Value=80)
     AddTimeSeriesLog(Workspace=name,
                      Name="proton_charge",
                      Time="2010-01-01T00:40:00",
                      Value=15)
     AddTimeSeriesLog(Workspace=name,
                      Name="proton_charge",
                      Time="2010-01-01T00:50:00",
                      Value=100)