Пример #1
0
 def test_picking_owned(self):
     '''verify pickling of envelopes owned by PDF calculators.
     '''
     pbl = makePDFEnvelope('parabolaenvelope',
             parabola_envelope, a=1, b=2, c=3)
     pbl.a = 7
     pbl.foobar = 'asdf'
     pc = PDFCalculator()
     pc.envelopes = (pbl,)
     dbpc = DebyePDFCalculator()
     dbpc.envelopes = (pbl,)
     self.assertIs(pbl, pc.envelopes[0])
     self.assertIs(pbl, dbpc.envelopes[0])
     pc.addEnvelope(self.fscale)
     dbpc.addEnvelope(self.fscale)
     self.fscale.scale = 3.5
     self.assertEqual(3.5, pc.scale)
     self.assertEqual(3.5, dbpc.scale)
     pc2 = pickle.loads(pickle.dumps(pc))
     dbpc2 = pickle.loads(pickle.dumps(dbpc))
     self.assertEqual(3.5, pc2.scale)
     self.assertEqual(3.5, dbpc2.scale)
     pblcopies = [pc2.getEnvelope("parabolaenvelope"),
                  dbpc2.getEnvelope("parabolaenvelope")]
     for pbl2 in pblcopies:
         self.assertEqual(7, pbl2.a)
         self.assertEqual('asdf', pbl2.foobar)
         self.assertEqual('parabolaenvelope', pbl2.type())
     return
Пример #2
0
def test_fq(nisph20):
    sc = SASCalculator(rmax=22)
    dbpc = DebyePDFCalculator(rmax=sc.rmax, qmax=sc.qmax, qstep=sc.qstep)
    sc.eval(nisph20)
    dbpc.eval(nisph20)
    assert numpy.array_equal(dbpc.qgrid, sc.qgrid)
    assert numpy.allclose(dbpc.fq, sc.fq)
    return
Пример #3
0
 def setUp(self):
     self.dpdfc = DebyePDFCalculator()
     if not TestDebyePDFCalculator.bucky:
         TestDebyePDFCalculator.bucky = (
             loadDiffPyStructure('C60bucky.stru'))
     if not TestDebyePDFCalculator.tio2rutile:
         TestDebyePDFCalculator.tio2rutile = (
             loadDiffPyStructure('TiO2_rutile-fit.stru'))
     return
Пример #4
0
 def __init__(self, name = "pdf"):
     """Initialize the generator.
     """
     from diffpy.srreal.pdfcalculator import DebyePDFCalculator
     BasePDFGenerator.__init__(self, name)
     self._setCalculator(DebyePDFCalculator())
     return
Пример #5
0
 def setUp(self):
     self.pc = PDFCalculator()
     self.dbpc = DebyePDFCalculator()
     self.pwm = MyPWM()
     self.pc.peakwidthmodel = self.pwm
     self.dbpc.peakwidthmodel = self.pwm
     return
Пример #6
0
    def __init__(self, name = "pdf"):
        """Initialize the generator.

        """
        BasePDFGenerator.__init__(self, name)
        self._setCalculator(DebyePDFCalculator())
        return
 def setUp(self):
     self.dpdfc = DebyePDFCalculator()
     if not TestDebyePDFCalculator.bucky:
         TestDebyePDFCalculator.bucky = (
                 loadDiffPyStructure('C60bucky.stru'))
     if not TestDebyePDFCalculator.tio2rutile:
         TestDebyePDFCalculator.tio2rutile = (
                 loadDiffPyStructure('TiO2_rutile-fit.stru'))
     return
Пример #8
0
 def test_picking_owned(self):
     '''verify pickling of envelopes owned by PDF calculators.
     '''
     pc = PDFCalculator()
     dbpc = DebyePDFCalculator()
     ltb = LocalTable()
     ltb.setCustomAs('Na', 'Na', 37)
     ltb.foo = 'bar'
     pc.scatteringfactortable = ltb
     dbpc.scatteringfactortable = ltb
     self.assertIs(ltb, pc.scatteringfactortable)
     self.assertIs(ltb, dbpc.scatteringfactortable)
     pc2 = pickle.loads(pickle.dumps(pc))
     dbpc2 = pickle.loads(pickle.dumps(dbpc))
     self.assertEqual('localtable', pc2.scatteringfactortable.type())
     self.assertEqual('localtable', dbpc2.scatteringfactortable.type())
     self.assertEqual(37, pc2.scatteringfactortable.lookup('Na'))
     self.assertEqual(37, dbpc2.scatteringfactortable.lookup('Na'))
     self.assertEqual('bar', pc2.scatteringfactortable.foo)
     self.assertEqual('bar', dbpc2.scatteringfactortable.foo)
     return
 def test_picking_owned(self):
     '''verify pickling of envelopes owned by PDF calculators.
     '''
     pc = PDFCalculator()
     dbpc = DebyePDFCalculator()
     ltb = LocalTable()
     ltb.setCustomAs('Na', 'Na', 37)
     ltb.foo = 'bar'
     pc.scatteringfactortable = ltb
     dbpc.scatteringfactortable = ltb
     self.assertIs(ltb, pc.scatteringfactortable)
     self.assertIs(ltb, dbpc.scatteringfactortable)
     pc2 = pickle.loads(pickle.dumps(pc))
     dbpc2 = pickle.loads(pickle.dumps(dbpc))
     self.assertEqual('localtable', pc2.scatteringfactortable.type())
     self.assertEqual('localtable', dbpc2.scatteringfactortable.type())
     self.assertEqual(37, pc2.scatteringfactortable.lookup('Na'))
     self.assertEqual(37, dbpc2.scatteringfactortable.lookup('Na'))
     self.assertEqual('bar', pc2.scatteringfactortable.foo)
     self.assertEqual('bar', dbpc2.scatteringfactortable.foo)
     return
Пример #10
0
def iter_bond(x_min, x_max, step=5):
    import numpy as np
    import matplotlib.pyplot as plt
    #from matplotlib.pyplot import plot

    from diffpy.Structure import Structure, Atom, Lattice
    from diffpy.srreal.pdfcalculator import DebyePDFCalculator

    dbc = DebyePDFCalculator()
    dbc.qmax = 20
    dbc.qmin = 0.5
    dbc.rmax = 20
    
    iter_range = np.linspace(x_min, x_max, step)
    fig_dim = len(iter_range)
    
    acs = Atom('Cs', [0, 0, 0])
    acl = Atom('Cl', [0.5, 0.5, 0.5])
    plt.figure()
    for ind, val in enumerate(iter_range):
        cscl = Structure(atoms=[acs, acl],
			lattice=Lattice(val, val, val, 90, 90, 90))
        dbc.setStructure(cscl)
        (r,g) = dbc()
        print(val)
        plt.subplot(fig_dim, 1, ind+1)
        plt.plot(r,g)
        plt.title('bond length = %s' % str(val))
Пример #11
0
def dbc_iter(struc_f, iter_range):
    '''change different range'''
    
    import numpy as np
    import matplotlib.pyplot as plt
    from diffpy.srreal.pdfcalculator import DebyePDFCalculator
    from diffpy.Structure import loadStructure
    
    struc = loadStructure(struc_f)
    dbc = DebyePDFCalculator()
    dbc.setStructure(struc)
    dbc.qmax = 20
    dbc.qmin = 0.5
    dbc.rmax = 20
    #par = eval(para)
    #print(dbc.par)
    for step in iter_range:
        (r,g) = dbc(delta2 = step)
        plt.plot(r,g)
Пример #12
0
class TestDebyePDFCalculator(unittest.TestCase):

    bucky = None
    tio2rutile = None

    def setUp(self):
        self.dpdfc = DebyePDFCalculator()
        if not TestDebyePDFCalculator.bucky:
            TestDebyePDFCalculator.bucky = (
                loadDiffPyStructure('C60bucky.stru'))
        if not TestDebyePDFCalculator.tio2rutile:
            TestDebyePDFCalculator.tio2rutile = (
                loadDiffPyStructure('TiO2_rutile-fit.stru'))
        return

#   def tearDown(self):
#       return
#
#   def test___call__(self):
#       """check DebyePDFCalculator.__call__()
#       """
#       return
#
#   def test___init__(self):
#       """check DebyePDFCalculator.__init__()
#       """
#       return

    def test___getattr__(self):
        """check DebyePDFCalculator.__getattr__()
        """
        self.assertEqual(0.0, self.dpdfc.qmin)
        self.dpdfc._setDoubleAttr('qmin', 1.23)
        self.assertEqual(1.23, self.dpdfc.qmin)
        return

    def test___setattr__(self):
        """check DebyePDFCalculator.__setattr__()
        """
        self.assertNotEqual(1.23, self.dpdfc._getDoubleAttr('rmin'))
        self.dpdfc.rmin = 1.23
        self.assertEqual(1.23, self.dpdfc._getDoubleAttr('rmin'))
        return

    def test__getDoubleAttr(self):
        """check DebyePDFCalculator._getDoubleAttr()
        """
        gdba = self.dpdfc._getDoubleAttr
        self.assertEqual(1.0, gdba('scale'))
        self.assertEqual(0.0, gdba('qdamp'))
        self.assertRaises(Exception, gdba, 'notanattribute')
        return

    def test__hasDoubleAttr(self):
        """check DebyePDFCalculator._hasDoubleAttr()
        """
        self.assertTrue(self.dpdfc._hasDoubleAttr('scale'))
        self.assertFalse(self.dpdfc._hasDoubleAttr('notanattribute'))
        return

    def test__namesOfDoubleAttributes(self):
        """check DebyePDFCalculator._namesOfDoubleAttributes()
        """
        self.assertTrue(type(self.dpdfc._namesOfDoubleAttributes()) is set)
        self.assertTrue('qmax' in self.dpdfc._namesOfDoubleAttributes())
        return

    def test__setDoubleAttr(self):
        """check DebyePDFCalculator._setDoubleAttr()
        """
        gdba = self.dpdfc._getDoubleAttr
        sdba = self.dpdfc._setDoubleAttr
        self.assertEqual(0.0, gdba('rmin'))
        sdba('rmin', 3.0)
        self.assertEqual(3.0, gdba('rmin'))
        return

    def test_PDF_C60bucky(self):
        """check DebyePDFCalculator.pdf for C60 Bucky ball.
        """
        qmax = self.dpdfc.qmax
        r0, g0 = PDFCalculator(qmax=qmax)(self.bucky)
        r1, g1 = self.dpdfc(self.bucky)
        mxnd = _maxNormDiff(g0, g1)
        self.assertTrue(mxnd < 0.0006)
        return

    def test_partial_pdfs(self):
        """Check calculation of partial PDFs.
        """
        dpdfc = self.dpdfc
        dpdfc.qmin = 1.0
        rutile = self.tio2rutile
        r0, g0 = dpdfc(rutile)
        # Ti-Ti
        dpdfc.maskAllPairs(False)
        dpdfc.setTypeMask("Ti", "Ti", True)
        r1, g1 = dpdfc(rutile)
        self.assertTrue(numpy.array_equal(r0, r1))
        dpdfc.invertMask()
        r1i, g1i = dpdfc(rutile)
        self.assertTrue(numpy.array_equal(r0, r1i))
        self.assertTrue(numpy.allclose(g0, g1 + g1i))
        # Ti-O
        dpdfc.maskAllPairs(False)
        dpdfc.setTypeMask('all', 'ALL', True)
        dpdfc.setTypeMask('Ti', 'Ti', False)
        dpdfc.setTypeMask('O', 'O', False)
        r2, g2 = dpdfc(rutile)
        self.assertTrue(numpy.array_equal(r0, r2))
        dpdfc.invertMask()
        r2i, g2i = dpdfc(rutile)
        self.assertTrue(numpy.allclose(g0, g2 + g2i))
        # Ti-O from type mask
        dpdfc.maskAllPairs(True)
        dpdfc.setTypeMask("Ti", "Ti", False)
        dpdfc.setTypeMask("O", "O", False)
        r2t, g2t = dpdfc(rutile)
        self.assertTrue(numpy.array_equal(r0, r2t))
        self.assertTrue(numpy.array_equal(g2, g2t))
        dpdfc.invertMask()
        r2ti, g2ti = dpdfc(rutile)
        self.assertTrue(numpy.array_equal(g2i, g2ti))
        # O-O
        dpdfc.maskAllPairs(False)
        dpdfc.setTypeMask('O', 'O', True)
        r3, g3 = dpdfc(rutile)
        dpdfc.invertMask()
        r3i, g3i = dpdfc(rutile)
        self.assertTrue(numpy.allclose(g0, g3 + g3i))
        # check the sum of all partials
        self.assertTrue(numpy.allclose(g0, g1 + g2 + g3))
        return

    def test_pickling(self):
        '''check pickling and unpickling of PDFCalculator.
        '''
        dpdfc = self.dpdfc
        dpdfc.setScatteringFactorTableByType('N')
        dpdfc.scatteringfactortable.setCustomAs('Na', 'Na', 7)
        dpdfc.addEnvelope('sphericalshape')
        dpdfc.debyeprecision = 0.001
        dpdfc.delta1 = 0.2
        dpdfc.delta2 = 0.3
        dpdfc.maxextension = 10.1
        dpdfc.qbroad = 0.01
        dpdfc.qdamp = 0.05
        dpdfc.qmax = 10
        dpdfc.qmin = 0.5
        dpdfc.rmax = 10.0
        dpdfc.rmin = 0.02
        dpdfc.rstep = 0.02
        dpdfc.scale = 1.1
        dpdfc.spdiameter = 13.3
        dpdfc.foobar = 'asdf'
        spkl = pickle.dumps(dpdfc)
        dpdfc1 = pickle.loads(spkl)
        self.assertFalse(dpdfc is dpdfc1)
        sft = dpdfc.scatteringfactortable
        sft1 = dpdfc1.scatteringfactortable
        self.assertEqual(sft.type(), sft1.type())
        self.assertEqual(7.0, sft1.lookup('Na'))
        for a in dpdfc._namesOfDoubleAttributes():
            self.assertEqual(getattr(dpdfc, a), getattr(dpdfc1, a))
        self.assertEqual(13.3, dpdfc1.getEnvelope('sphericalshape').spdiameter)
        self.assertEqual(dpdfc._namesOfDoubleAttributes(),
                         dpdfc1._namesOfDoubleAttributes())
        self.assertEqual(dpdfc.usedenvelopetypes, dpdfc1.usedenvelopetypes)
        self.assertEqual('asdf', dpdfc1.foobar)
        return

    def test_mask_pickling(self):
        '''Check if mask gets properly pickled and restored.
        '''
        self.dpdfc.maskAllPairs(False)
        self.dpdfc.setPairMask(0, 1, True)
        self.dpdfc.setTypeMask("Na", "Cl", True)
        self.assertTrue(False is self.dpdfc.getPairMask(0, 0))
        self.assertTrue(True is self.dpdfc.getPairMask(0, 1))
        self.assertTrue(True is self.dpdfc.getTypeMask("Cl", "Na"))
        dpdfc1 = pickle.loads(pickle.dumps(self.dpdfc))
        self.assertTrue(False is dpdfc1.getPairMask(0, 0))
        self.assertTrue(True is dpdfc1.getPairMask(0, 1))
        self.assertTrue(True is self.dpdfc.getTypeMask("Cl", "Na"))
        return

    def test_pickling_derived_structure(self):
        '''check pickling of DebyePDFCalculator with DerivedStructureAdapter.
        '''
        from diffpy.srreal.tests.testutils import DerivedStructureAdapter
        dpdfc = self.dpdfc
        stru0 = DerivedStructureAdapter()
        dpdfc.setStructure(stru0)
        self.assertEqual(1, stru0.cpqcount)
        spkl = pickle.dumps(dpdfc)
        dpdfc1 = pickle.loads(spkl)
        self.assertTrue(stru0 is dpdfc.getStructure())
        stru1 = dpdfc1.getStructure()
        self.assertTrue(type(stru1) is DerivedStructureAdapter)
        self.assertFalse(stru1 is stru0)
        self.assertEqual(1, stru1.cpqcount)
        return
Пример #13
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from diffpy.Structure import loadStructure
from diffpy.srreal.pdfcalculator import DebyePDFCalculator
from matplotlib.pyplot import plot, show

c60 = loadStructure('c60.stru')
dpc = DebyePDFCalculator()
dpc.qmax = 20
dpc.rmax = 20
r3, g3 = dpc(c60, qmin=0)
r4, g4 = dpc(c60, qmin=1)

plot(r3, g3, r4, g4)
show()
Пример #14
0
    stru = StructureExt()
    # stru.loadStrufile('CdS.cif', 'diffpy', periodic=True)
    stru.loadStrufile('cd35se20.xyz', 'diffpy', periodic=False)
    stru.parseDiffpyStru()

    struparaset = StructureExtParSet('test', stru)
    # a = np.zeros_like(struparaset.xyz.value)
    # struparaset.xyz = a

    # b = np.zeros_like(struparaset.occ.value)
    # struparaset.occ = b

    from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator
    from matplotlib.pyplot import plot, show

    pc1 = DebyePDFCalculator()
    pc1.rmax = 20
    pc1.qmin = 1.0
    r1, g1 = pc1(struparaset._getSrRealStructure())
    plot(r1, g1)

    # xyz = np.array(struparaset.xyz.value)
    # struparaset.xyz = xyz * 1.1
    # uij = np.array(struparaset.uij.value)
    # struparaset.uij = uij * 3.0
    struparaset.zoomscale = 1.1
    r2, g2 = pc1(struparaset._getSrRealStructure())
    plot(r2, g2)

    show()
class TestDebyePDFCalculator(unittest.TestCase):

    bucky = None
    tio2rutile = None

    def setUp(self):
        self.dpdfc = DebyePDFCalculator()
        if not TestDebyePDFCalculator.bucky:
            TestDebyePDFCalculator.bucky = (
                    loadDiffPyStructure('C60bucky.stru'))
        if not TestDebyePDFCalculator.tio2rutile:
            TestDebyePDFCalculator.tio2rutile = (
                    loadDiffPyStructure('TiO2_rutile-fit.stru'))
        return

#   def tearDown(self):
#       return
#
#   def test___call__(self):
#       """check DebyePDFCalculator.__call__()
#       """
#       return
#
#   def test___init__(self):
#       """check DebyePDFCalculator.__init__()
#       """
#       return

    def test___getattr__(self):
        """check DebyePDFCalculator.__getattr__()
        """
        self.assertEqual(0.0, self.dpdfc.qmin)
        self.dpdfc._setDoubleAttr('qmin', 1.23)
        self.assertEqual(1.23, self.dpdfc.qmin)
        return

    def test___setattr__(self):
        """check DebyePDFCalculator.__setattr__()
        """
        self.assertNotEquals(1.23, self.dpdfc._getDoubleAttr('rmin'))
        self.dpdfc.rmin = 1.23
        self.assertEqual(1.23, self.dpdfc._getDoubleAttr('rmin'))
        return

    def test__getDoubleAttr(self):
        """check DebyePDFCalculator._getDoubleAttr()
        """
        gdba = self.dpdfc._getDoubleAttr
        self.assertEqual(1.0, gdba('scale'))
        self.assertEqual(0.0, gdba('qdamp'))
        self.assertRaises(Exception, gdba, 'notanattribute')
        return

    def test__hasDoubleAttr(self):
        """check DebyePDFCalculator._hasDoubleAttr()
        """
        self.failUnless(self.dpdfc._hasDoubleAttr('scale'))
        self.failIf(self.dpdfc._hasDoubleAttr('notanattribute'))
        return

    def test__namesOfDoubleAttributes(self):
        """check DebyePDFCalculator._namesOfDoubleAttributes()
        """
        self.failUnless(type(self.dpdfc._namesOfDoubleAttributes()) is set)
        self.failUnless('qmax' in self.dpdfc._namesOfDoubleAttributes())
        return

    def test__setDoubleAttr(self):
        """check DebyePDFCalculator._setDoubleAttr()
        """
        gdba = self.dpdfc._getDoubleAttr
        sdba = self.dpdfc._setDoubleAttr
        self.assertEqual(0.0, gdba('rmin'))
        sdba('rmin', 3.0)
        self.assertEqual(3.0, gdba('rmin'))
        return

    def test_PDF_C60bucky(self):
        """check DebyePDFCalculator.pdf for C60 Bucky ball.
        """
        qmax = self.dpdfc.qmax
        r0, g0 = PDFCalculator(qmax=qmax)(self.bucky)
        r1, g1 = self.dpdfc(self.bucky)
        mxnd = _maxNormDiff(g0, g1)
        self.failUnless(mxnd < 0.0006)
        return

    def test_partial_pdfs(self):
        """Check calculation of partial PDFs.
        """
        dpdfc = self.dpdfc
        dpdfc.qmin = 1.0
        rutile = self.tio2rutile
        atomtypes = [a.element for a in rutile]
        r0, g0 = dpdfc(rutile)
        # Ti-Ti
        dpdfc.maskAllPairs(False)
        dpdfc.setTypeMask("Ti", "Ti", True)
        r1, g1 = dpdfc(rutile)
        self.failUnless(numpy.array_equal(r0, r1))
        dpdfc.invertMask()
        r1i, g1i = dpdfc(rutile)
        self.failUnless(numpy.array_equal(r0, r1i))
        self.failUnless(numpy.allclose(g0, g1 + g1i))
        # Ti-O
        dpdfc.maskAllPairs(False)
        dpdfc.setTypeMask('all', 'ALL', True)
        dpdfc.setTypeMask('Ti', 'Ti', False)
        dpdfc.setTypeMask('O', 'O', False)
        r2, g2 = dpdfc(rutile)
        self.failUnless(numpy.array_equal(r0, r2))
        dpdfc.invertMask()
        r2i, g2i = dpdfc(rutile)
        self.failUnless(numpy.allclose(g0, g2 + g2i))
        # Ti-O from type mask
        dpdfc.maskAllPairs(True)
        dpdfc.setTypeMask("Ti", "Ti", False)
        dpdfc.setTypeMask("O", "O", False)
        r2t, g2t = dpdfc(rutile)
        self.failUnless(numpy.array_equal(r0, r2t))
        self.failUnless(numpy.array_equal(g2, g2t))
        dpdfc.invertMask()
        r2ti, g2ti = dpdfc(rutile)
        self.failUnless(numpy.array_equal(g2i, g2ti))
        # O-O
        dpdfc.maskAllPairs(False)
        dpdfc.setTypeMask('O', 'O', True)
        r3, g3 = dpdfc(rutile)
        dpdfc.invertMask()
        r3i, g3i = dpdfc(rutile)
        self.failUnless(numpy.allclose(g0, g3 + g3i))
        # check the sum of all partials
        self.failUnless(numpy.allclose(g0, g1 + g2 + g3))
        return

    def test_pickling(self):
        '''check pickling and unpickling of PDFCalculator.
        '''
        dpdfc = self.dpdfc
        dpdfc.setScatteringFactorTableByType('N')
        dpdfc.scatteringfactortable.setCustomAs('Na', 'Na', 7)
        dpdfc.addEnvelopeByType('sphericalshape')
        dpdfc.debyeprecision = 0.001
        dpdfc.delta1 = 0.2
        dpdfc.delta2 = 0.3
        dpdfc.maxextension = 10.1
        dpdfc.qbroad = 0.01
        dpdfc.qdamp = 0.05
        dpdfc.qmax = 10
        dpdfc.qmin = 0.5
        dpdfc.rmax = 10.0
        dpdfc.rmin = 0.02
        dpdfc.rstep = 0.02
        dpdfc.scale = 1.1
        dpdfc.spdiameter = 13.3
        dpdfc.foobar = 'asdf'
        spkl = cPickle.dumps(dpdfc)
        dpdfc1 = cPickle.loads(spkl)
        self.failIf(dpdfc is dpdfc1)
        sft = dpdfc.scatteringfactortable
        sft1 = dpdfc1.scatteringfactortable
        self.assertEqual(sft.type(), sft1.type())
        self.assertEqual(7.0, sft1.lookup('Na'))
        for a in dpdfc._namesOfDoubleAttributes():
            self.assertEqual(getattr(dpdfc, a), getattr(dpdfc1, a))
        self.assertEqual(13.3,
                dpdfc1.getEnvelopeByType('sphericalshape').spdiameter)
        self.assertEqual(dpdfc._namesOfDoubleAttributes(),
                dpdfc1._namesOfDoubleAttributes())
        self.assertEqual(dpdfc.usedenvelopetypes, dpdfc1.usedenvelopetypes)
        self.assertEqual('asdf', dpdfc1.foobar)
        return


    def test_mask_pickling(self):
        '''Check if mask gets properly pickled and restored.
        '''
        self.dpdfc.maskAllPairs(False)
        self.dpdfc.setPairMask(0, 1, True)
        self.dpdfc.setTypeMask("Na", "Cl", True)
        self.failUnless(False is self.dpdfc.getPairMask(0, 0))
        self.failUnless(True is self.dpdfc.getPairMask(0, 1))
        self.failUnless(True is self.dpdfc.getTypeMask("Cl", "Na"))
        dpdfc1 = cPickle.loads(cPickle.dumps(self.dpdfc))
        self.failUnless(False is dpdfc1.getPairMask(0, 0))
        self.failUnless(True is dpdfc1.getPairMask(0, 1))
        self.failUnless(True is self.dpdfc.getTypeMask("Cl", "Na"))
        return
Пример #16
0
nkl_crystal.Uisoequiv = 0.005

cfg_pc = {'rmin': 0, 'rmax': 20, 'rstep': 0.01}

cfg_dpc1 = {'qmax': 100, 'qmin': 0, 'rmin': 0, 'rmax': 40, 'rstep': 0.01}

cfg_dpc2 = {'qmax': 100, 'qmin': 0, 'rmin': 0, 'rmax': 70, 'rstep': 0.01}

cfg_dpc3 = {'qmax': 100, 'qmin': 0, 'rmin': 0, 'rmax': 100, 'rstep': 0.01}

# calculate PDF by real-space summation
pc0 = PDFCalculator(**cfg_pc)
r0, g0 = pc0(nkl_crystal)

# calcualte PDF by DPC
pc1 = DebyePDFCalculator(**cfg_dpc1)
r1, g1 = pc1(nkl_crystal)

pc2 = DebyePDFCalculator(**cfg_dpc2)
r2, g2 = pc2(nkl_crystal)

pc3 = DebyePDFCalculator(**cfg_dpc3)
r3, g3 = pc3(nkl_crystal)

plt.plot(r0, g0, "b-", lw=2, label="PC")
plt.plot(r1, g1 + 30, "r-", lw=2, label="DPC, rmax = 40 A")
plt.plot(r2, g2 + 60, "k-", lw=2, label="DPC, rmax = 70 A")
plt.plot(r3, g3 + 90, "m-", lw=2, label="DPC, rmax = 100 A")

plt.legend(loc=0)
plt.xlabel("Radial Distance (r)", fontsize=15)
Пример #17
0
#            'rmin' : 0,
#            'rmax' : 70,
#            'rstep': 0.01}
#
#cfg_dpc3 = {'qmax' : 100,
#            'qmin' : 0,
#             'rmin' : 0,
#            'rmax' : 100,
#            'rstep': 0.01}

# calculate PDF by real-space summation
pc0 = PDFCalculator(**cfg_pc)
r0, g0 = pc0(nkl_crystal)

# calcualte PDF by DPC
pc1 = DebyePDFCalculator(**cfg_dpc1)
r1, g1 = pc1(nkl_crystal)

#pc2 = DebyePDFCalculator(**cfg_dpc2)
#r2, g2 = pc2(nkl_crystal)
#
#pc3 = DebyePDFCalculator(**cfg_dpc3)
#r3, g3 = pc3(nkl_crystal)
rou = 4 / 3.52**3  ## atomic density

plt.plot(r0, g0, "b-", lw=2, label="PC")
plt.plot(r1, g1, "r-", lw=2, label="DPC, rmax = 40 A")
plt.plot(r1, g1 - 4 * np.pi * rou * r1, "k-", label="DPC, minus 4*pi*rou*r")
#plt.plot(r2, g2 + 60, "k-", lw=2, label = "DPC, rmax = 70 A")
#plt.plot(r3, g3 + 90, "m-", lw=2, label = "DPC, rmax = 100 A")
Пример #18
0
    def learninglib_build(self, output_dir=None, pdfcal_cfg=None,
                          rdf=True, xrd=False, Bisoequiv=0.1,
                          rstep=None, DebyeCal=False, nosymmetry=False,
                          tth_range=None, wavelength=0.5):
        """ method to build learning lib with diffpy based on path
        of cif library. Paramters of G(r) calculation are set
        via glbl.<attribute>. "PDFCal_config.txt" file with PDFCalculator
        configuration will also be output

        Parameters
        ----------
        pdfcal_cfg : dict, optional
            configuration of PDF calculator, default is the one defined
            inside glbl class.
        rdf : bool, optional
            option to compute RDF or not. default to True, if not,
            compute pdf
        xrd : bool, optional
            option to compute XRD (which is slow). default to False.
        Bisoequiv : float, optional
            value of isotropic thermal parameter. default is 0.1.
            scientific equation: Biso = 8 (pi**2) Uiso
        rstep : float, optioanl
            space of PDF. default is pi/qmax.
        DebyeCal : bool, optional
            option to use Debye calculator. default is False.
        nosymmetry : bool, optional
            DEPRECATED for now. option to apply no symmetry.
            default is False.
        tth_range : ndarray, optional
            range of 2theta. default is [0:0.1:90]
        wavelength : float, optional
            wavelength in angstroms, default to 0.5 A which corresponds
            to Qmax ~= 17
        """
        # setup output dir
        timestr = _timestampstr(time.time())
        if output_dir is None:
            tail = "LearningLib_{}".format(timestr)
            output_dir = os.path.join(os.getcwd(), tail)
        print('=== output dir would be {} ==='.format(output_dir))
        self.output_dir = output_dir
        if tth_range is None:
            self.tth_range = np.arange(0, 90, 0.1)
        self.wavelength = wavelength
        self.std_q = theta2q(self.tth_range, self.wavelength)

        ####### configure pymatgen XRD calculator #####
        # instantiate calculators
        xrd_cal = XRDCalculator()
        xrd_cal.wavelength = self.wavelength
        xrd_cal.TWO_THETA_TOL = 10**-2
        self.calculate_params.update({'xrd_wavelength':
                                       xrd_cal.wavelength})

        xrd_list = []
        sg_list = []
        # (a,b,c, alpha, beta, gamma, volume)
        structure_list_1 = []  # primative cell
        structure_list_2 = []  # ordinary cell
        # chemical element
        composition_list_1 = []  # primative cell
        composition_list_2 = []  # ordinary cell
        fail_list = []

        ####### configure diffpy PDF calculator ######
        if DebyeCal:
            cal = DebyePDFCalculator()
            self.calculator_type = 'Debye'
        cal = PDFCalculator()
        self.calculator = cal
        self.calculator_type = 'PDF'
        self.calculate_params.update({'calculator_type':
                                      self.calculator_type})
        # setup calculator parameters
        if rstep is None:
            rstep = glbl.rstep
        self.rstep = rstep
        self.calculator.rstep = rstep  # annoying fact
        self.calculate_params.update({'rstep':rstep})

        if pdfcal_cfg is None:
            self.pdfcal_cfg = glbl.cfg
        self.calculate_params.update(self.pdfcal_cfg)

        # configure calculator
        for k,v in self.pdfcal_cfg.items():
            setattr(self.calculator, k, v)
        # empty list to store results
        gr_list = []
        rdf_list = []
        print("====== INFO: calculation parameters:====\n{}"
              .format(self.calculate_params))
        struc_df = pd.DataFrame()
        ############# loop through cifs #################
        for cif in sorted(self.cif_list):
            _cif = os.path.join(self.input_dir, cif)
            try:
                # diffpy structure
                struc = loadStructure(_cif)
                struc.Bisoequiv = Bisoequiv

                ## calculate PDF/RDF with diffpy ##
                if nosymmetry:
                    struc = nosymmetry(struc)
                cal.setStructure(struc)
                cal.eval()

                # pymatge structure
                struc_meta = CifParser(_cif)
                ## calculate XRD with pymatgen ##
                if xrd:
                    xrd = xrd_cal.get_xrd_data(struc_meta\
                            .get_structures(False).pop())
                    _xrd = np.asarray(xrd)[:,:2]
                    q, iq = _xrd.T
                    interp_q = assign_nearest(self.std_q, q, iq)
                    xrd_list.append(interp_q)
                else:
                    pass
                ## test space group info ##
                _sg = struc_meta.get_structures(False).pop()\
                        .get_space_group_info()
            except:
                print("{} fail".format(_cif))
                fail_list.append(cif)
            else:
                # no error for both pymatgen and diffpy
                gr_list.append(cal.pdf)
                rdf_list.append(cal.rdf)
                self.density_list.append(cal.slope)
                print('=== Finished evaluating PDF from structure {} ==='
                       .format(cif))
                ## update features ##
                flag = ['primitive', 'ordinary']
                option = [True, False]
                compo_list = [composition_list_1, composition_list_2]
                struc_fields = ['a','b','c','alpha','beta','gamma', 'volume']
                for f, op, compo in zip(flag, option, compo_list):
                    rv_dict = {}
                    struc = struc_meta.get_structures(op).pop()
                    a, b, c = struc.lattice.abc
                    aa, bb, cc = struc.lattice.angles
                    volume = struc.volume
                    for k, v in zip(struc_fields,
                                    [a, b, c, aa, bb, cc, volume]):
                        rv_dict.update({"{}_{}".format(f, k) : v})
                    compo.append(struc.composition.as_dict())
                    struc_df = struc_df.append(rv_dict,
                                               ignore_index=True)
                # sg info, use the ordinary setup
                sg_list.append(struc.get_space_group_info())
                print('=== Finished evaluating XRD from structure {} ==='
                      .format(cif))

        # finally, store crucial calculation results as attributes
        self.r_grid = cal.rgrid
        #4*pi * r^2 * rho(r) = R(r)  -> RDF to density 
        self.gr_array = np.asarray(gr_list)/4/np.pi/self.r_grid**2
        self.rdf_array = np.asarray(gr_list)
        self.density_list = np.asarray(self.density_list)
        self.xrd_info = np.asarray(xrd_list)
        self.sg_list = sg_list
        # 1 -> primitive , 2 -> ordinary
        self.composition_list_1 = composition_list_1
        self.composition_list_2 = composition_list_2
        self.struc_df = struc_df
        self.fail_list = fail_list