• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python simpleapi.CreateWorkspace类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mantid.simpleapi.CreateWorkspace的典型用法代码示例。如果您正苦于以下问题:Python CreateWorkspace类的具体用法?Python CreateWorkspace怎么用?Python CreateWorkspace使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了CreateWorkspace类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_simple

 def test_simple(self):
     input_x = np.array([0.1,0.2,0.3,0.4,0.5])
     input_y = np.array([1.,2,3,2,1])
     input_e = np.array([0.1,0.14,0.17,0.14,0.1])
     sq = CreateWorkspace(DataX=input_x,
                          DataY=input_y,
                          DataE=input_e,
                          UnitX='MomentumTransfer')
     SetSampleMaterial(InputWorkspace=sq, ChemicalFormula='Ar')
     fq = PDConvertReciprocalSpace(InputWorkspace=sq,
                                   To='F(Q)',
                                   From='S(Q)')
     x=fq.readX(0)
     y=fq.readY(0)
     e=fq.readE(0)
     self.assertTrue(np.array_equal(x, input_x))
     self.assertTrue(np.array_equal(y, input_x*(input_y-1)))
     self.assertTrue(np.array_equal(e, input_x*input_e))
     fkq = PDConvertReciprocalSpace(InputWorkspace=sq,
                                    To='FK(Q)',
                                    From='S(Q)')
     x=fkq.readX(0)
     y=fkq.readY(0)
     e=fkq.readE(0)
     bsq = sq.sample().getMaterial().cohScatterLengthSqrd()
     self.assertTrue(np.array_equal(x, input_x))
     self.assertTrue(np.allclose(y, bsq*(input_y-1)))
     self.assertTrue(np.allclose(e, bsq*input_e))
开发者ID:mantidproject,项目名称:mantid,代码行数:28,代码来源:PDConvertReciprocalSpaceTest.py


示例2: SampleTest

class SampleTest(unittest.TestCase):

    def setUp(self):
        self._ws = CreateWorkspace(DataX=[1,2,3,4,5], DataY=[1,2,3,4,5], OutputWorkspace="dummy")

    def test_geometry_getters_and_setters(self):
        sample = self._ws.sample()

        sample.setThickness(12.5)
        self.assertEquals(sample.getThickness(), 12.5)
        sample.setHeight(10.2)
        self.assertEquals(sample.getHeight(), 10.2)
        sample.setWidth(5.9)
        self.assertEquals(sample.getWidth(), 5.9)

    def test_crystal_structure_handling(self):
        sample = self._ws.sample()

        self.assertEquals(sample.hasCrystalStructure(), False)
        self.assertRaises(RuntimeError, sample.getCrystalStructure)

        cs = CrystalStructure('5.43 5.43 5.43',
                              'F d -3 m',
                              'Si 0 0 0 1.0 0.01')

        sample.setCrystalStructure(cs)

        self.assertEquals(sample.hasCrystalStructure(), True)

        cs_from_sample = sample.getCrystalStructure()

        self.assertEquals(cs.getSpaceGroup().getHMSymbol(), cs_from_sample.getSpaceGroup().getHMSymbol())
        self.assertEquals(cs.getUnitCell().a(), cs_from_sample.getUnitCell().a())
        self.assertEquals(len(cs.getScatterers()), len(cs_from_sample.getScatterers()))
        self.assertEquals(cs.getScatterers()[0], cs_from_sample.getScatterers()[0])


        sample.clearCrystalStructure()

        self.assertEquals(sample.hasCrystalStructure(), False)
        self.assertRaises(RuntimeError, sample.getCrystalStructure)

    def test_material(self):
        SetSampleMaterial(self._ws,"Al2 O3",SampleMassDensity=4)
        material = self._ws.sample().getMaterial()

        self.assertAlmostEqual(material.numberDensity, 0.0236, places=4)
        self.assertAlmostEqual(material.relativeMolecularMass(), 101.961, places=3)

        atoms, numatoms = material.chemicalFormula()

        self.assertEquals(len(atoms), len(numatoms))
        self.assertEquals(len(atoms), 2)
        self.assertEquals(numatoms[0], 2)
        self.assertEquals(numatoms[1], 3)

        xs0 = atoms[0].neutron()
        xs1 = atoms[1].neutron()
        xs = ( xs0['coh_scatt_xs']*2 + xs1['coh_scatt_xs']*3 ) / 5
        self.assertAlmostEquals(material.cohScatterXSection(), xs, places=4)
开发者ID:liyulun,项目名称:mantid,代码行数:60,代码来源:SampleTest.py


示例3: test_disable_history

    def test_disable_history(self):
        ws_name = '__tmp_test_algorithm_history'
        ws = CreateWorkspace([0, 1, 2], [0, 1, 2], OutputWorkspace=ws_name)
        alg = self._run_algorithm('ParentAlg', child_algorithm=True, record_history=False, Workspace=ws_name)

        history = ws.getHistory()
        alg_hists = history.getAlgorithmHistories()

        self.assertEquals(history.size(), 1)
        self.assertEquals(len(alg_hists), 1)
开发者ID:DanNixon,项目名称:mantid,代码行数:10,代码来源:AlgorithmHistoryTest.py


示例4: createTestWorkspace

    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 
        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))
            tsp_a.addValue(tmptime, 1.0*i*i) 
            tsp_b.addValue(tmptime, 1.234*(i+1))

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

        return wksp
开发者ID:AlistairMills,项目名称:mantid,代码行数:31,代码来源:ExportExperimentLogTest.py


示例5: test_container_rebinning_enabled

 def test_container_rebinning_enabled(self):
     xs = numpy.array([0.0, 1.0, 0.0, 1.1])
     ys = numpy.array([2.2, 3.3])
     sample_1 = CreateWorkspace(DataX=xs, DataY=ys, NSpec=2,
                                UnitX='Wavelength')
     xs = numpy.array([-1.0, 0.0, 1.0, 2.0, -1.0, 0.0, 1.0, 2.0])
     ys = numpy.array([0.101, 0.102, 0.103, 0.104, 0.105, 0.106])
     container_1 = CreateWorkspace(DataX=xs, DataY=ys, NSpec=2,
                                   UnitX='Wavelength')
     corrected = ApplyPaalmanPingsCorrection(SampleWorkspace=sample_1,
                                             CanWorkspace=container_1,
                                             RebinCanToSample=True)
     self.assertTrue(numpy.all(sample_1.extractY() > corrected.extractY()))
     DeleteWorkspace(sample_1)
     DeleteWorkspace(container_1)
     DeleteWorkspace(corrected)
开发者ID:mantidproject,项目名称:mantid,代码行数:16,代码来源:ApplyPaalmanPingsCorrectionTest.py


示例6: test_container_input_workspace_not_unintentionally_rebinned

 def test_container_input_workspace_not_unintentionally_rebinned(self):
     xs = numpy.array([0.0, 1.0, 0.0, 1.1])
     ys = numpy.array([2.2, 3.3])
     sample_1 = CreateWorkspace(DataX=xs, DataY=ys, NSpec=2,
                                UnitX='Wavelength')
     ys = numpy.array([0.11, 0.22])
     container_1 = CreateWorkspace(DataX=xs, DataY=ys, NSpec=2,
                                   UnitX='Wavelength')
     corrected = ApplyPaalmanPingsCorrection(SampleWorkspace=sample_1,
                                             CanWorkspace=container_1)
     numHisto = container_1.getNumberHistograms()
     for i in range(numHisto):
         container_xs = container_1.readX(i)
         for j in range(len(container_xs)):
             self.assertEqual(container_xs[j], xs[i * numHisto + j])
     DeleteWorkspace(sample_1)
     DeleteWorkspace(container_1)
     DeleteWorkspace(corrected)
开发者ID:mantidproject,项目名称:mantid,代码行数:18,代码来源:ApplyPaalmanPingsCorrectionTest.py


示例7: _parseStructure

 def _parseStructure(self, structure):
     from mantid.simpleapi import mtd, LoadCIF, CreateWorkspace, DeleteWorkspace
     import uuid
     self._fromCIF = False
     if isinstance(structure, string_types):
         if mtd.doesExist(structure):
             try:
                 self._cryst = self._copyCrystalStructure(mtd[structure].sample().getCrystalStructure())
                 self._getUniqueAtoms()
             except RuntimeError:
                 raise ValueError('Workspace ''%s'' has no valid CrystalStructure' % (structure))
         else:
             tmpws = CreateWorkspace(1, 1, OutputWorkspace='_tempPointCharge_'+str(uuid.uuid4())[:8])
             try:
                 LoadCIF(tmpws, structure)
                 # Attached CrystalStructure object gets destroyed when workspace is deleted
                 self._cryst = self._copyCrystalStructure(tmpws.sample().getCrystalStructure())
             except:
                 DeleteWorkspace(tmpws)
                 raise
             else:
                 DeleteWorkspace(tmpws)
                 self._getUniqueAtoms()
     elif isinstance(structure, list):
         if (len(structure) == 4 and all([isinstance(x, (int, float)) for x in structure])):
             structure = [structure]
         if (all([isinstance(x, list) and (len(x) == 4) and
            all([isinstance(y, (int, float)) for y in x]) for x in structure])):
             self._ligands = structure
         else:
             raise ValueError('Incorrect ligands direct input. Must be a 4-element list or a list '
                              'of 4-element list. Each ligand must be of the form [charge, x, y, z]')
     elif hasattr(structure, 'getScatterers'):
         self._cryst = structure
         self._getUniqueAtoms()
     else:
         if not hasattr(structure, 'sample'):
             raise ValueError('First input must be a Mantid CrystalStructure object, workspace or string '
                              '(name of CIF file or workspace)')
         try:
             self._cryst = self._copyCrystalStructure(structure.sample().getCrystalStructure())
             self._getUniqueAtoms()
         except RuntimeError:
             raise ValueError('Workspace ''%s'' has no valid CrystalStructure' % (structure.name()))
开发者ID:DanNixon,项目名称:mantid,代码行数:44,代码来源:pointcharge.py


示例8: SampleTest

class SampleTest(unittest.TestCase):

    def setUp(self):
        self._ws = CreateWorkspace(DataX=[1,2,3,4,5], DataY=[1,2,3,4,5], OutputWorkspace="dummy")

    def test_geometry_getters_and_setters(self):
        sample = self._ws.sample()

        sample.setThickness(12.5)
        self.assertEquals(sample.getThickness(), 12.5)
        sample.setHeight(10.2)
        self.assertEquals(sample.getHeight(), 10.2)
        sample.setWidth(5.9)
        self.assertEquals(sample.getWidth(), 5.9)

    def test_crystal_structure_handling(self):
        sample = self._ws.sample()

        self.assertEquals(sample.hasCrystalStructure(), False)
        self.assertRaises(RuntimeError, sample.getCrystalStructure)

        cs = CrystalStructure('5.43 5.43 5.43',
                              'F d -3 m',
                              'Si 0 0 0 1.0 0.01')

        sample.setCrystalStructure(cs)

        self.assertEquals(sample.hasCrystalStructure(), True)

        cs_from_sample = sample.getCrystalStructure()

        self.assertEquals(cs.getSpaceGroup().getHMSymbol(), cs_from_sample.getSpaceGroup().getHMSymbol())
        self.assertEquals(cs.getUnitCell().a(), cs_from_sample.getUnitCell().a())
        self.assertEquals(len(cs.getScatterers()), len(cs_from_sample.getScatterers()))
        self.assertEquals(cs.getScatterers()[0], cs_from_sample.getScatterers()[0])


        sample.clearCrystalStructure()

        self.assertEquals(sample.hasCrystalStructure(), False)
        self.assertRaises(RuntimeError, sample.getCrystalStructure)
开发者ID:dezed,项目名称:mantid,代码行数:41,代码来源:SampleTest.py


示例9: test_simple

    def test_simple(self):
        input_x = np.array([0.1,0.2,0.3,0.4,0.5])
        input_y = np.array([1.,2,3,2,1])
        input_e = np.array([0.1,0.14,0.17,0.14,0.1])
        Gr = CreateWorkspace(DataX=input_x,
                             DataY=input_y,
                             DataE=input_e)
        SetSampleMaterial(InputWorkspace=Gr, ChemicalFormula='Ar')
        GKr = PDConvertRealSpace(InputWorkspace=Gr,
                                 To='GK(r)',
                                 From='G(r)')
        x=GKr.readX(0)
        y=GKr.readY(0)
        e=GKr.readE(0)

        bsq = Gr.sample().getMaterial().cohScatterLengthSqrd()
        rho = Gr.sample().getMaterial().numberDensity
        factor = bsq / (4. * np.pi *rho)
        self.assertTrue(np.array_equal(x, input_x))
        self.assertTrue(np.allclose(y, factor*input_y/input_x))
        self.assertTrue(np.allclose(e, factor*input_e/input_x))
开发者ID:mantidproject,项目名称:mantid,代码行数:21,代码来源:PDConvertRealSpaceTest.py


示例10: createTestWorkspace

    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
        import numpy as np

        # Create a matrix workspace
        x = np.array([1.0, 2.0, 3.0, 4.0])
        y = np.array([1.0, 2.0, 3.0])
        e = np.sqrt(np.array([1.0, 2.0, 3.0]))
        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 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
开发者ID:nimgould,项目名称:mantid,代码行数:32,代码来源:ExportSampleLogsToCSVFileTest.py


示例11: test_nested_history

    def test_nested_history(self):
        ws_name = '__tmp_test_algorithm_history'
        ws = CreateWorkspace([0, 1, 2], [0, 1, 2], OutputWorkspace=ws_name)
        alg = self._run_algorithm("ParentAlg", Workspace=ws_name)

        history = ws.getHistory()
        alg_hists = history.getAlgorithmHistories()

        self.assertEquals(history.size(), 2)
        self.assertEquals(len(alg_hists), 2)

        parent_alg = history.getAlgorithmHistory(1)

        self.assertEquals(parent_alg.name(), "ParentAlg")
        self.assertEquals(parent_alg.version(), 1)
        self.assertEquals(parent_alg.childHistorySize(), 1)

        child_alg = parent_alg.getChildAlgorithmHistory(0)

        self.assertEquals(child_alg.name(), "ChildAlg")
        self.assertEquals(child_alg.version(), 1)
        self.assertEquals(child_alg.childHistorySize(), 0)
开发者ID:DanNixon,项目名称:mantid,代码行数:22,代码来源:AlgorithmHistoryTest.py


示例12: SampleTest

class SampleTest(unittest.TestCase):

    def setUp(self):
        self._ws = CreateWorkspace(DataX=[1,2,3,4,5], DataY=[1,2,3,4,5], OutputWorkspace="dummy")

    def test_geometry_getters_and_setters(self):
        sample = self._ws.sample()

        sample.setThickness(12.5)
        self.assertEquals(sample.getThickness(), 12.5)
        sample.setHeight(10.2)
        self.assertEquals(sample.getHeight(), 10.2)
        sample.setWidth(5.9)
        self.assertEquals(sample.getWidth(), 5.9)
开发者ID:BigShows,项目名称:mantid,代码行数:14,代码来源:SampleTest.py


示例13: test_create_with_1D_numpy_array

    def test_create_with_1D_numpy_array(self):
        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')
        self.assertTrue(isinstance(wksp, MatrixWorkspace))
        self.assertEquals(wksp.getNumberHistograms(), 1)

        self.assertEquals(len(wksp.readY(0)), len(y))
        self.assertEquals(len(wksp.readX(0)), len(x))
        self.assertEquals(len(wksp.readE(0)), len(e))

        for index in range(len(y)):
            self.assertEquals(wksp.readY(0)[index], y[index])
            self.assertEquals(wksp.readE(0)[index], e[index])
            self.assertEquals(wksp.readX(0)[index], x[index])
        # Last X value
        self.assertEquals(wksp.readX(0)[len(x)-1], x[len(x)-1])
        AnalysisDataService.remove("wksp")
开发者ID:DanNixon,项目名称:mantid,代码行数:20,代码来源:CreateWorkspaceTest.py


示例14: test_create_with_2D_numpy_array

    def test_create_with_2D_numpy_array(self):
        x = np.array([1.,2.,3.,4.])
        y = np.array([[1.,2.,3.],[4.,5.,6.]])
        e = np.sqrt(y)

        wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=2,UnitX='TOF')
        self.assertTrue(isinstance(wksp, MatrixWorkspace))
        self.assertEquals(wksp.getNumberHistograms(), 2)

        for i in [0,1]:
            for j in range(len(y[0])):
                self.assertEquals(wksp.readY(i)[j], y[i][j])
                self.assertEquals(wksp.readE(i)[j], e[i][j])
                self.assertEquals(wksp.readX(i)[j], x[j])
            # Last X value
            self.assertEquals(wksp.readX(i)[len(x)-1], x[len(x)-1])

        AnalysisDataService.remove("wksp")
开发者ID:DanNixon,项目名称:mantid,代码行数:18,代码来源:CreateWorkspaceTest.py


示例15: test_with_data_from_other_workspace

    def test_with_data_from_other_workspace(self):
        wsname = 'LOQ'
        alg = run_algorithm('Load', Filename='LOQ48127.raw', OutputWorkspace=wsname, SpectrumMax=2, child=True)
        loq = alg.getProperty("OutputWorkspace").value
        
        x = loq.extractX()
        y = loq.extractY()
        e = loq.extractE()
        
        wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=2,UnitX='Wavelength')
        self.assertTrue(isinstance(wksp, MatrixWorkspace))
        self.assertEquals(wksp.getNumberHistograms(), 2)
        
        for i in [0,1]:
            for j in range(len(y[0])):
                self.assertEquals(wksp.readY(i)[j], loq.readY(i)[j])
                self.assertEquals(wksp.readE(i)[j], loq.readE(i)[j])
                self.assertEquals(wksp.readX(i)[j], loq.readX(i)[j])
            # Last X value
            self.assertEquals(wksp.readX(i)[len(x)-1], loq.readX(i)[len(x)-1])

        AnalysisDataService.remove("wksp")
开发者ID:trnielsen,项目名称:mantid,代码行数:22,代码来源:CreateWorkspaceTest.py


示例16: setUp

 def setUp(self):
     self._ws = CreateWorkspace(DataX=[1, 2, 3, 4, 5], DataY=[1, 2, 3, 4, 5], OutputWorkspace="dummy")
开发者ID:rosswhitfield,项目名称:mantid,代码行数:2,代码来源:SampleTest.py


示例17: test_with_data_from_other_workspace

    def test_with_data_from_other_workspace(self):
        wsname = 'LOQ'
        x1 = np.array([1.,2.,3.,4.])
        y1 = np.array([[1.,2.,3.],[4.,5.,6.]])
        e1 = np.sqrt(y1)
        loq = CreateWorkspace(DataX=x1, DataY=y1,DataE=e1,NSpec=2,UnitX='Wavelength')

        x2 = loq.extractX()
        y2 = loq.extractY()
        e2 = loq.extractE()

        wksp = CreateWorkspace(DataX=x2, DataY=y2,DataE=e2,NSpec=2,UnitX='Wavelength')
        self.assertTrue(isinstance(wksp, MatrixWorkspace))
        self.assertEquals(wksp.getNumberHistograms(), 2)

        for i in [0,1]:
            for j in range(len(y2[0])):
                self.assertEquals(wksp.readY(i)[j], loq.readY(i)[j])
                self.assertEquals(wksp.readE(i)[j], loq.readE(i)[j])
                self.assertEquals(wksp.readX(i)[j], loq.readX(i)[j])
            # Last X value
            self.assertEquals(wksp.readX(i)[len(x2)-1], loq.readX(i)[len(x2)-1])

        AnalysisDataService.remove("wksp")
开发者ID:DanNixon,项目名称:mantid,代码行数:24,代码来源:CreateWorkspaceTest.py


示例18: SampleTest

class SampleTest(unittest.TestCase):

    def setUp(self):
        self._ws = CreateWorkspace(DataX=[1,2,3,4,5], DataY=[1,2,3,4,5], OutputWorkspace="dummy")

    def test_geometry_getters_and_setters(self):
        sample = self._ws.sample()

        sample.setThickness(12.5)
        self.assertEquals(sample.getThickness(), 12.5)
        sample.setHeight(10.2)
        self.assertEquals(sample.getHeight(), 10.2)
        sample.setWidth(5.9)
        self.assertEquals(sample.getWidth(), 5.9)

    def test_crystal_structure_handling(self):
        sample = self._ws.sample()

        self.assertEquals(sample.hasCrystalStructure(), False)
        self.assertRaises(RuntimeError, sample.getCrystalStructure)

        cs = CrystalStructure('5.43 5.43 5.43',
                              'F d -3 m',
                              'Si 0 0 0 1.0 0.01')

        sample.setCrystalStructure(cs)

        self.assertEquals(sample.hasCrystalStructure(), True)

        cs_from_sample = sample.getCrystalStructure()

        self.assertEquals(cs.getSpaceGroup().getHMSymbol(), cs_from_sample.getSpaceGroup().getHMSymbol())
        self.assertEquals(cs.getUnitCell().a(), cs_from_sample.getUnitCell().a())
        self.assertEquals(len(cs.getScatterers()), len(cs_from_sample.getScatterers()))
        self.assertEquals(cs.getScatterers()[0], cs_from_sample.getScatterers()[0])


        sample.clearCrystalStructure()

        self.assertEquals(sample.hasCrystalStructure(), False)
        self.assertRaises(RuntimeError, sample.getCrystalStructure)

    def test_material(self):
        SetSampleMaterial(self._ws,"Al2 O3",SampleMassDensity=4)
        material = self._ws.sample().getMaterial()

        self.assertAlmostEqual(material.numberDensity, 0.1181, places=4)
        self.assertAlmostEqual(material.relativeMolecularMass(), 101.961, places=3)

        atoms, numatoms = material.chemicalFormula()

        self.assertEquals(len(atoms), len(numatoms))
        self.assertEquals(len(atoms), 2)
        self.assertEquals(numatoms[0], 2)
        self.assertEquals(numatoms[1], 3)

        xs0 = atoms[0].neutron()
        xs1 = atoms[1].neutron()
        # the correct way to calculate for coherent cross section
        # is to average the scattering lengths then convert to a cross section
        b_real = (xs0['coh_scatt_length_real']*2 + xs1['coh_scatt_length_real']*3) / 5
        b_imag = (xs0['coh_scatt_length_img']*2 + xs1['coh_scatt_length_img']*3) / 5
        xs = .04 * pi * (b_real * b_real + b_imag * b_imag)
        self.assertAlmostEquals(material.cohScatterXSection(), xs, places=4)

    def test_get_shape(self):
        sample = self._ws.sample()
        self.assertEquals(type(sample.getShape()), CSGObject)

    def test_get_shape_xml(self):
        sample = self._ws.sample()
        shape = sample.getShape()
        xml = shape.getShapeXML()
        self.assertEquals(type(xml), str)
开发者ID:mantidproject,项目名称:mantid,代码行数:74,代码来源:SampleTest.py


示例19: PyExec


#.........这里部分代码省略.........
            lambda par_name: lookup(par_name, self.int_vars,   0),
            lambda par_name: lookup(par_name, self.float_vars, 0.0),
            lambda par_name: lookup(par_name, self.bool_vars,  False),
            # Callback for logging:
            log
        )

        def write_items_to_file(path, items):
            """Given a path to a file and a list of items, will write the items
            to the file, one on each line."""
            with open(path, 'w') as f:
                for item in items:
                    f.write(str(item) + "\n")

        # Chop the padded outputs back down to the correct size.
        output_phases    = output_phases[:input_phases_size]
        output_deadtimes = output_deadtimes[:input_deadtimes_size]
        input_phases     = input_phases[:input_phases_size]
        input_deadtimes  = input_deadtimes[:input_deadtimes_size]
        fchan_out        = fchan_out[:n_bins]
        f_out            = f_out[:n_bins]

        write_items_to_file(out_phases_file,    output_phases)
        write_items_to_file(out_deadtimes_file, output_deadtimes)
                 
        log_output = "\nDead times in:\n" +  str(input_deadtimes) + "\n" +\
                     "\nDead times out:\n" + str(output_deadtimes) + "\n" +\
                     "\nPhases in:\n" +      str(input_phases) + "\n" +\
                     "\nPhases out:\n" +     str(output_phases) + "\n" + \
                     "\nGroupings:\n" +      str(groupings) + "\n" +\
                     "\nChi Squared:\n" +    str(chi_sq) + "\n" +\
                     "\nInput variables:\n"

        for type_map in self.int_vars, self.float_vars, self.bool_vars:
            for name, value in type_map.items():
                log_output += str(name) + " = " + str(value) + "\n"

        Logger.get("MaxEnt").notice(log_output)

        # Generate our own output ws name if the user has not provided one.
        out_ws_name = self.getPropertyValue(OUT_WS_PROP)
        if out_ws_name == "":
            out_ws_name = run_name + "; MaxEnt"
            self.setPropertyValue(OUT_WS_PROP, out_ws_name)

        out_ws = CreateWorkspace(OutputWorkspace=out_ws_name,
                                 DataX=fchan_out[:n_bins],
                                 DataY=f_out[:n_bins])
        self.setProperty(OUT_WS_PROP, out_ws)

        # MaxEnt inputs table.
        input_table_name = run_name + "; MaxEnt Input"
        input_table = CreateEmptyTableWorkspace(OutputWorkspace = input_table_name)
        input_table.addColumn("str", "Name")
        input_table.addColumn("str", "Value")
        inputs = itertools.chain(self.int_vars.items(), 
                                 self.float_vars.items(),
                                 self.bool_vars.items())
        for name, value in inputs:
            input_table.addRow([str(name), str(value)])

        # Deadtimes and phases input/output table.
        dead_phases_table_name = run_name + "; MaxEnt Deadtimes & Phases"
        dead_phases_table = CreateEmptyTableWorkspace(OutputWorkspace = dead_phases_table_name)
        for column_name in "Deadtimes In", "Deadtimes Out", "Phases In", "Phases Out":
          dead_phases_table.addColumn("double", column_name)
        for row in zip(input_deadtimes, output_deadtimes, input_phases, output_phases):
            dead_phases_table.addRow(list(map(float, row)))

        # Chi-squared output table.
        chisq_table_name = run_name + "; MaxEnt Chi^2"
        chisq_table = CreateEmptyTableWorkspace(OutputWorkspace = chisq_table_name)
        chisq_table.addColumn("int", "Cycle")
        for iteration in range(10):
          chisq_table.addColumn("double", "Iter " + str(iteration + 1))
        for cycle, data in enumerate(chi_sq):
            chisq_table.addRow([cycle + 1] + list(map(float,data)))

        all_output_ws = [input_table_name,
                         dead_phases_table_name,
                         chisq_table_name,
                         out_ws_name]

        # The output workspaces of this algorithm belong in the same groups
        # that are created by the muon interface.  If the appropriate group
        # doesn't exist already then it needs to be created.
        if not run_name in mtd:
            GroupWorkspaces(InputWorkspaces = all_output_ws,
                            OutputWorkspace = run_name)
        else:
            group = mtd[run_name]
            for output_ws in all_output_ws:
              if not group.contains(output_ws):
                group.add(output_ws)

        out_ws.getAxis(0).getUnit().setLabel("Field", "G")
        out_ws.setYUnitLabel("P(B)")

        if INSIDE_MANTIDPLOT:
            mantidplot.plotSpectrum(out_ws, 0)
开发者ID:Softey,项目名称:scriptrepository,代码行数:101,代码来源:MaxEnt.py


示例20: createTestWorkspace2

    def createTestWorkspace2(self):
        """ Create a workspace for testing against with more situation
        """
        from mantid.simpleapi import CreateWorkspace
        from mantid.simpleapi import AddSampleLog
        from time import gmtime, strftime,mktime
        from datetime import datetime, timedelta
        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
        year = 2014
        month = 2
        day = 15
        hour = 13
        minute = 34
        second = 3
        dtimesec = 0.0010

        timefluc = 0.0001

        #tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())))
        runstart = datetime(year, month, day, hour, minute, second)
        AddSampleLog(Workspace=wksp,LogName='run_start',LogText=str(runstart))

        tsp_a = kernel.FloatTimeSeriesProperty("SensorA")
        tsp_b = kernel.FloatTimeSeriesProperty("SensorB")
        tsp_c = kernel.FloatTimeSeriesProperty("SensorC")
        tsp_d = kernel.FloatTimeSeriesProperty("SensorD")
        logs = [tsp_a, tsp_b, tsp_c, tsp_d]

        dbbuf = ""

        random.seed(0)
        for i in arange(25):
            # Randomly pick up log without records
            # first iteration must have all the record
            skiploglist = []
            if i > 0:
                numnorecord = random.randint(-1, 4)
                if numnorecord > 0:
                    for j in xrange(numnorecord):
                        logindex = random.randint(0, 6)
                        skiploglist.append(logindex)
                    # ENDFOR (j)
                # ENDIF (numnorecord)
            # ENDIF (i)

            dbbuf += "----------- %d -------------\n" % (i)

            # Record
            for j in xrange(4):
                # Skip if selected
                if j in skiploglist:
                    continue

                # get random time shifts
                timeshift = (random.random()-0.5)*timefluc

                if i == 0:
                    # first record should have the 'exactly' same time stamps
                    timeshift *= 0.0001

                deltatime = timedelta(i*dtimesec + timeshift)
                tmptime = str(runstart + deltatime)
                tmpvalue = float(i*i*6)+j
                logs[j].addValue(tmptime, tmpvalue)

                dbbuf += "%s: %s = %d\n" % (logs[j].name, tmptime, tmpvalue)

            # ENDFOR (j)
        # ENDFOR (i)

        # print dbbuf

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

        return wksp
开发者ID:mducle,项目名称:mantid,代码行数:86,代码来源:ExportSampleLogsToCSVFileTest.py



注:本文中的mantid.simpleapi.CreateWorkspace类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python simpleapi.Load类代码示例发布时间:2022-05-27
下一篇:
Python simpleapi.AnalysisDataService类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap