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))
Exemple #2
0
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)
    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)
    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
 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)
 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)
Exemple #7
0
 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()))
Exemple #8
0
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_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))
    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
    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)
Exemple #12
0
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_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")
    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")
    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")
Exemple #16
0
 def setUp(self):
     self._ws = CreateWorkspace(DataX=[1, 2, 3, 4, 5], DataY=[1, 2, 3, 4, 5], OutputWorkspace="dummy")
    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")
Exemple #18
0
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)
Exemple #19
0
    def PyExec(self):
        """ Alg execution. """
        instrument         = self.getProperty(INSTRUMENT_PROP).value
        run_number         = self.getProperty(RUN_NUM_PROP).value
        fit_deadtime       = self.getProperty(FIT_DEADTIME_PROP).value
        fix_phases         = self.getProperty(FIX_PHASES_PROP).value
        default_level      = self.getProperty(DEFAULT_LEVEL).value
        sigma_looseness    = self.getProperty(SIGMA_LOOSENESS_PROP).value
        groupings_file     = self.getProperty(GROUPINGS_PROP).value
        in_phases_file     = self.getProperty(PHASES_PROP).value
        in_deadtimes_file  = self.getProperty(DEADTIMES_PROP).value
        out_phases_file    = self.getProperty(PHASES_RESULT_PROP).value
        out_deadtimes_file = self.getProperty(DEADTIMES_RESULT_PROP).value

        isis = config.getFacility('ISIS')
        padding = isis.instrument(instrument).zeroPadding(0)
        run_name = instrument + str(run_number).zfill(padding)

        try:
            run_number = int(run_number)
        except:
            raise RuntimeError("'%s' is not an integer run number." % run_number)
        try:
            run_file_path = FileFinder.findRuns(run_name)[0]
        except:
            raise RuntimeError("Unable to find file for run %i" % run_number)

        if groupings_file == "":
            groupings_file = DEFAULT_GROUPINGS_FILENAME % instrument

        # Load data and other info from input files.

        def temp_hidden_ws_name():
            """Generate a unique name for a temporary, hidden workspace."""
            selection = string.ascii_lowercase + string.ascii_uppercase + string.digits
            return '__temp_MaxEnt_' + ''.join(random.choice(selection) for _ in range(20))

        input_data_ws_name = temp_hidden_ws_name()
        LoadMuonNexus(Filename=run_file_path, OutputWorkspace=input_data_ws_name)
        input_data_ws = mtd[input_data_ws_name]
        
        if isinstance(input_data_ws, WorkspaceGroup):
            Logger.get("MaxEnt").warning("Multi-period data is not currently supported.  Just using first period.")
            input_data_ws = input_data_ws[0]

        groupings_ws_name = temp_hidden_ws_name()
        LoadDetectorsGroupingFile(InputFile=groupings_file, OutputWorkspace=groupings_ws_name)
        groupings_ws = mtd[groupings_ws_name]

        def yield_floats_from_file(path):
            """Given a path to a file with a float on each line, will return
            the floats one at a time.  Throws otherwise.  Strips whitespace
            and ignores empty lines."""
            with open(path, 'r') as f:
                for i, line in enumerate(line.strip() for line in f):
                    if line == "":
                        continue
                    try:
                        yield float(line)
                    except:
                        raise RuntimeError("Parsing error in '%s': Line %d: '%s'." % 
                                           (path, i, line))

        input_phases         = np.array(list(yield_floats_from_file(in_phases_file)))
        input_phases_size    = len(input_phases)
        input_deadtimes      = np.array(list(yield_floats_from_file(in_deadtimes_file)))
        input_deadtimes_size = len(input_deadtimes)

        n_bins      = input_data_ws.blocksize()
        n_detectors = input_data_ws.getNumberHistograms()

        def time_value_to_time_channel_index(value):
            """Given a time value, will return the index of the time channel in
            which the value falls."""
            bin_width = input_data_ws.readX(0)[1] - input_data_ws.readX(0)[0]
            diff = value - input_data_ws.readX(0)[0]
            return int(diff / bin_width)

        # Mantid corrects for time zero on loading, so we want to find the actual channels
        # where 0.0 occurs, and where we have values of 0.1 onwards.
        time_zero_channel  = time_value_to_time_channel_index(0.0)
        first_good_channel = time_value_to_time_channel_index(0.1)

        input_data = np.concatenate([input_data_ws.readY(i) for i in range(n_detectors)])

        groupings = [groupings_ws.readY(row)[0] for row in range(groupings_ws.getNumberHistograms())]
        groupings = map(int, groupings)
        n_groups = len(set(groupings))

        # Cleanup.

        input_data_ws.delete()
        groupings_ws.delete()

        # We're faced with the problem of providing more than a dozen parameters to
        # the Fortran, which can be a bit messy (especially on the Fortran side of
        # things where we need to make "Cf2py" declarations).  A cleaner way of
        # doing this is to simply pass in a few callbacks -- one for each input
        # type -- and have the Fortran provide the name of the variable it wants
        # to the callback.  The callback will then look up the corresponding value
        # and feed it back to the Fortran.
        #
        # We also have a callback for printing to the results log.

        self.int_vars = {
            "RunNo"       : run_number,
            "frames"      : FRAMES,
            "res"         : RES,
            "Tzeroch"     : time_zero_channel,
            "firstgoodch" : first_good_channel,
            "ptstofit"    : POINTS_TO_FIT,
            "histolen"    : n_bins,
            "nhisto"      : n_detectors,
            "n_groups"    : n_groups,
        }

        self.float_vars = {
            "deflevel" : default_level,
            "sigloose" : sigma_looseness,
        }

        self.bool_vars = {
            "fixphase" : fix_phases,
            "fitdt"    : fit_deadtime,
        }

        self._assert_map_values_are_of_expected_type()

        def lookup(par_name, par_map, default):
            """The basis of the callbacks passed to the Fortran.  Given a parameter
            name it will consult the appropriate variable map, and return the
            corresponding value of the parameter.  Else return a default and log a
            warning if a parameter with the name does not exist."""
            par_name = par_name.strip()
            if par_name in par_map:
                return par_map[par_name]
            msg = """WARNING: tried to find a value for parameter with name %s but
            could not find one.  Default of \"%s\" provided.""" % (par_name, default)
            Logger.get("MaxEnt").warning(msg)
            return default

        def log(priority, message):
            """Log the given message with given priority."""
            try:
                logger = getattr(Logger.get("MaxEnt"), priority.lower())
            except AttributeError:
                # If we don't recognise the priority, use warning() as a default.
                logger = getattr(Logger.get("MaxEnt"), "warning")
            logger(message)
            return True

        # The Fortran expects arrays to be of a certain size, so any arrays that
        # aren't big enough need to be padded.
        input_phases    = self._pad_to_length_with_zeros(input_phases, MAX_HISTOS)
        input_deadtimes = self._pad_to_length_with_zeros(input_deadtimes, MAX_HISTOS)
        input_data      = self._pad_to_length_with_zeros(input_data, MAX_INPUT_DATA_SIZE)
        groupings       = self._pad_to_length_with_zeros(groupings, MAX_HISTOS)

        # TODO: Return the contents of "NNNNN.max", instead of writing to file.
        f_out, fchan_out, output_deadtimes, output_phases, chi_sq = maxent.mantid_maxent(
            # Input data and other info:
            input_data,
            groupings,
            input_deadtimes,
            input_phases,
            # Variable-lookup callbacks:
            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)
    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
    def createTestWorkspace2(self):
        """ Create a workspace for testing against with more situation
        """
        from mantid.simpleapi import CreateWorkspace
        from mantid.simpleapi import AddSampleLog
        import numpy
        from numpy import datetime64, timedelta64
        #from time import gmtime, strftime,mktime # in debug prints

        # 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
        dtimesec = 0.0010
        timefluc = 0.0001
        runstart = '2014-02-15T13:34:03'
        # older numpy assumes local timezone
        if LooseVersion(numpy.__version__) < LooseVersion('1.9'):
            runstart = runstart + 'Z'
        runstart = datetime64(runstart, 'us') # microsecond needed for deltas

        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 = ""

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

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

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

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

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

                deltatime = i*dtimesec + timeshift # fraction of a day
                deltatime = timedelta64(int(deltatime * 24 * 3600 * 1e6), 'us') # timedelta64 requires int
                tmptime = runstart + deltatime
                tmpvalue = float(i*i*6)+j
                logs[j].addValue(tmptime, tmpvalue)

                #dbbuf += "{}: {} = {}\n".format(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