Exemplo n.º 1
0
 def test_reciprocal(self):
     '''check calculation of reciprocal lattice.'''
     r1 = self.lattice.reciprocal()
     self.assertEqual((1, 1, 1, 90, 90, 90), r1.abcABG())
     L2 = Lattice(2, 4, 8, 90, 90, 90)
     r2 = L2.reciprocal()
     self.assertEqual((0.5, 0.25, 0.125, 90, 90, 90), r2.abcABG())
     rr2 = r2.reciprocal()
     self.assertTrue(numpy.array_equal(L2.base, rr2.base))
     return
Exemplo n.º 2
0
 def test_reciprocal(self):
     '''check calculation of reciprocal lattice.'''
     r1 = self.lattice.reciprocal()
     self.assertEqual((1, 1, 1, 90, 90, 90), r1.abcABG())
     L2 = Lattice(2, 4, 8, 90, 90, 90)
     r2 = L2.reciprocal()
     self.assertEqual((0.5, 0.25, 0.125, 90, 90, 90), r2.abcABG())
     rr2 = r2.reciprocal()
     self.assertTrue(numpy.array_equal(L2.base, rr2.base))
     return
Exemplo n.º 3
0
Arquivo: sample.py Projeto: mcvine/ui
 def generate(self):
     c = self.context
     excitation = dict(type=c.excitation_type)
     excitation.update(c.excitation_params)
     shape = {c.shape_type: c.shape_params}
     d = dict(
         name=c.name,
         packing_factor=c.packing_factor,
         excitation=excitation,
         shape=shape,
         temperature='300*K',
     )
     from diffpy.Structure import Lattice
     if c.lattice:
         lattice_constants = c.lattice.totuple()
         lattice = Lattice(*lattice_constants)
         base = [','.join(map(str, v)) for v in lattice.base]
         lattice = dict(
             constants=','.join(map(str, lattice_constants)),
             basis_vectors=base,
         )
         d['chemical_formula'] = c.chemical_formula
         d['lattice'] = lattice
     else:
         assert c.structure_file
         sf = c.structure_file
         # if isinstance(sf, str): sf = sf.encode()
         d['structure_file'] = sf
     path = os.path.join(c.work_dir, c.name + '.yaml')
     print("writing to %s" % path)
     import yaml
     with open(path, 'w') as outfile:
         yaml.safe_dump(d, outfile, default_flow_style=False)
     return
Exemplo n.º 4
0
 def test__set_lattice(self):
     """check Structure._set_lattice()
     """
     lat = Lattice()
     self.stru.lattice = lat
     self.assertEqual(2 * [lat], [a.lattice for a in self.stru])
     return
Exemplo n.º 5
0
    def parseLines(self, lines):
        """Parse list of lines in DISCUS format.

        Return PDFFitStructure instance or raise StructureFormatError.
        """
        self.lines = lines
        ilines = self._linesIterator()
        self.stru = PDFFitStructure()
        record_parsers = {
            "cell": self._parse_cell,
            "format": self._parse_format,
            "generator": self._parse_not_implemented,
            "molecule": self._parse_not_implemented,
            "ncell": self._parse_ncell,
            "spcgr": self._parse_spcgr,
            "symmetry": self._parse_not_implemented,
            "title": self._parse_title,
            "shape": self._parse_shape,
        }
        try:
            # parse header
            for self.line in ilines:
                words = self.line.split()
                if not words or words[0][0] == '#': continue
                if words[0] == 'atoms': break
                rp = record_parsers.get(words[0], self._parse_unknown_record)
                rp(words)
            # check if cell has been defined
            if not self.cell_read:
                emsg = "%d: unit cell not defined" % self.nl
                raise StructureFormatError(emsg)
            # parse atoms
            for self.line in ilines:
                words = self.line.split()
                if not words or words[0][0] == '#': continue
                self._parse_atom(words)
            # self consistency check
            exp_natoms = reduce(lambda x, y: x * y, self.stru.pdffit['ncell'])
            # only check if ncell record exists
            if self.ncell_read and exp_natoms != len(self.stru):
                emsg = 'Expected %d atoms, read %d.' % \
                    (exp_natoms, len(self.stru))
                raise StructureFormatError(emsg)
            # take care of superlattice
            if self.stru.pdffit['ncell'][:3] != [1, 1, 1]:
                latpars = list(self.stru.lattice.abcABG())
                superlatpars = [
                    latpars[i] * self.stru.pdffit['ncell'][i] for i in range(3)
                ] + latpars[3:]
                superlattice = Lattice(*superlatpars)
                self.stru.placeInLattice(superlattice)
                self.stru.pdffit['ncell'] = [1, 1, 1, exp_natoms]
        except (ValueError, IndexError):
            exc_type, exc_value, exc_traceback = sys.exc_info()
            emsg = "%d: file is not in DISCUS format" % self.nl
            raise StructureFormatError, emsg, exc_traceback
        return self.stru
Exemplo n.º 6
0
 def test__get_lattice(self):
     """check Structure._get_lattice()
     """
     lat = Lattice()
     stru = Structure()
     self.assertEqual((1, 1, 1, 90, 90, 90), stru.lattice.abcABG())
     stru2 = Structure(lattice=lat)
     self.failUnless(lat is stru2.lattice)
     return
Exemplo n.º 7
0
 def test_placeInLattice(self):
     """check Structure.placeInLattice() -- conversion of coordinates
     """
     stru = self.stru
     new_lattice = Lattice(.5, .5, .5, 90, 90, 60)
     stru.placeInLattice(new_lattice)
     a0 = stru[0]
     self.assertTrue(numpy.allclose(a0.xyz, [0.0, 0.0, 0.0]))
     a1 = stru[1]
     self.assertTrue(numpy.allclose(a1.xyz, [2.0, 0.0, 2.0]))
Exemplo n.º 8
0
 def test_writeStr_xyz(self):
     """check string representation of normal xyz file"""
     stru = self.stru
     stru.title = "test of writeStr"
     stru.lattice = Lattice(1.0, 2.0, 3.0, 90.0, 90.0, 90.0)
     stru[:] = [Atom('H', [1., 1., 1.]), Atom('Cl', [3., 2., 1.])]
     s1 = stru.writeStr(self.format)
     s1 = re.sub('[ \t]+', ' ', s1)
     s0 = "2\n%s\nH 1 2 3\nCl 3 4 3\n" % stru.title
     self.assertEqual(s1, s0)
Exemplo n.º 9
0
 def test_placeInLattice(self):
     """check Structure.placeInLattice() -- conversion of coordinates
     """
     stru = self.stru
     new_lattice = Lattice(.5, .5, .5, 90, 90, 60)
     stru.placeInLattice(new_lattice)
     a0 = stru[0]
     self.assertListAlmostEqual(a0.xyz, 3*[0.0])
     a1 = stru[1]
     self.assertListAlmostEqual(a1.xyz, [2.0, 0.0, 2.0])
Exemplo n.º 10
0
 def test___repr__(self):
     """Test representation of DiffpyStructureParSet objects.
     """
     lat = Lattice(3, 3, 2, 90, 90, 90)
     atom = Atom("C", [0, 0.2, 0.5])
     stru = Structure([atom], lattice=lat)
     dsps = DiffpyStructureParSet("dsps", stru)
     self.assertEqual(repr(stru), repr(dsps))
     self.assertEqual(repr(lat), repr(dsps.lattice))
     self.assertEqual(repr(atom), repr(dsps.atoms[0]))
     return
Exemplo n.º 11
0
def fccNi():
    atoms = [
        Atom('Ni', (0, 0, 0)),
        Atom('Ni', (0.5, 0.5, 0)),
        Atom('Ni', (0.5, 0, 0.5)),
        Atom('Ni', (0, 0.5, 0.5))
    ]
    a = 3.5238
    alpha = 90.
    lattice = Lattice(a=a, b=a, c=a, alpha=alpha, beta=alpha, gamma=alpha)
    return Structure(atoms, lattice, sgid=225)
Exemplo n.º 12
0
def fccAl():
    atoms = [
        Atom('Al', (0, 0, 0)),
        Atom('Al', (0.5, 0.5, 0)),
        Atom('Al', (0.5, 0, 0.5)),
        Atom('Al', (0, 0.5, 0.5))
    ]
    a = 4.046
    alpha = 90.
    lattice = Lattice(a=a, b=a, c=a, alpha=alpha, beta=alpha, gamma=alpha)
    return Structure(atoms, lattice, sgid=225)
Exemplo n.º 13
0
 def test_write_xyz(self):
     """check writing of normal xyz file"""
     stru = self.stru
     stru.title = "test of writeStr"
     stru.lattice = Lattice(1.0, 2.0, 3.0, 90.0, 90.0, 90.0)
     stru[:] = [Atom('H', [1., 1., 1.]), Atom('Cl', [3., 2., 1.])]
     stru.write(self.tmpname, self.format)
     f_s = open(self.tmpname).read()
     f_s = re.sub('[ \t]+', ' ', f_s)
     s_s = "2\n%s\nH 1 2 3\nCl 3 4 3\n" % stru.title
     self.assertEqual(f_s, s_s)
Exemplo n.º 14
0
 def test___init__(self):
     '''Check Lattice.__init__ processing of arguments.
     '''
     self.assertRaises(ValueError, Lattice, self.lattice, c=4)
     self.assertRaises(ValueError,
                       Lattice,
                       base=self.lattice.base,
                       baserot=self.lattice.baserot)
     self.assertRaises(ValueError, Lattice, 1, 2, 3)
     self.assertRaises(ValueError, Lattice, 1, 2, 3, 80, 90)
     L0 = self.lattice
     L0.setLatBase(L0.cartesian([[1, 1, 0], [0, 1, 1], [1, 0, 1]]))
     L1 = Lattice(L0)
     self.assertTrue(numpy.array_equal(L0.base, L1.base))
     L2 = Lattice(base=L0.base)
     self.assertTrue(numpy.array_equal(L0.base, L2.base))
     self.assertTrue(numpy.array_equal(L0.isotropicunit, L2.isotropicunit))
     L3 = Lattice(*L0.abcABG(), baserot=L0.baserot)
     self.assertTrue(numpy.allclose(L0.base, L3.base))
     self.assertTrue(numpy.allclose(L0.isotropicunit, L3.isotropicunit))
     return
Exemplo n.º 15
0
 def setUp(self):
     self.stru = Structure( [ Atom('C', [0,0,0]), Atom('C', [1,1,1]) ],
             lattice=Lattice(1, 1, 1, 90, 90, 120) )
     if not self._loaded_structures:
         self._loaded_structures.update([
             ('cdse', Structure(filename=cdsefile)),
             ('tei', Structure(filename=teifile)),
             ('pbte', Structure(filename=pbtefile)),
             ])
     self.__dict__.update(self._loaded_structures)
     self.places = 12
     return
Exemplo n.º 16
0
 def test_latpar_properties(self):
     '''check assignment to a, b, c, alpha, beta, gamma.
     '''
     lat = self.lattice
     lat.a = 2
     lat.b = 4
     lat.c = 6
     lat.alpha = 80
     lat.beta = 100
     lat.gamma = 120
     lat1 = Lattice(2, 4, 6, 80, 100, 120)
     self.assertAlmostEqual(-0.5, lat.cg, self.places)
     self.assertTrue(numpy.array_equal(lat1.base, lat.base))
     return
Exemplo n.º 17
0
 def test_writeStr_rawxyz(self):
     """check writing of normal xyz file"""
     stru = self.stru
     stru.title = "test of writeStr"
     stru.lattice = Lattice(1.0, 2.0, 3.0, 90.0, 90.0, 90.0)
     # plain version
     stru[:] = [Atom('H', [1., 1., 1.])]
     s1 = stru.writeStr(self.format)
     s1 = re.sub('[ \t]+', ' ', s1)
     s0 = "H 1 2 3\n"
     # brutal raw version
     stru[0].element = ""
     s1 = stru.writeStr(self.format)
     s0 = "1 2 3\n"
     self.assertEqual(s1, s0)
Exemplo n.º 18
0
 def test___init__(self):
     """check Structure.__init__()
     """
     atoms = [Atom('C', [0, 0, 0]), Atom('C', [0.5, 0.5, 0.5])]
     self.assertRaises(ValueError, Structure, atoms, filename=teifile)
     self.assertRaises(ValueError,
                       Structure,
                       lattice=Lattice(),
                       filename=teifile)
     self.assertRaises(ValueError,
                       Structure,
                       title='test',
                       filename=teifile)
     stru1 = Structure(title='my title')
     self.assertEqual('my title', stru1.title)
     stru2a = Structure(atoms)
     stru2b = Structure(iter(atoms))
     stru2c = Structure(a for a in atoms)
     s2a = str(stru2a)
     self.assertEqual(s2a, str(stru2b))
     self.assertEqual(s2a, str(stru2c))
     return
Exemplo n.º 19
0
class TestLattice(unittest.TestCase):
    """test methods of Lattice class"""

    def setUp(self):
        self.lattice = Lattice()
        self.places = 12
        return

    def assertListAlmostEqual(self, l1, l2, places=None):
        """wrapper for list comparison"""
        if places is None: places = self.places
        self.assertEqual(len(l1), len(l2))
        for i in range(len(l1)):
            self.assertAlmostEqual(l1[i], l2[i], places)
        return


    def test___init__(self):
        '''Check Lattice.__init__ processing of arguments.
        '''
        self.assertRaises(ValueError, Lattice,
                          self.lattice, c=4)
        self.assertRaises(ValueError, Lattice,
                          base=self.lattice.base,
                          baserot=self.lattice.baserot)
        self.assertRaises(ValueError, Lattice, 1, 2, 3)
        self.assertRaises(ValueError, Lattice, 1, 2, 3, 80, 90)
        L0 = self.lattice
        L0.setLatBase(L0.cartesian([[1, 1, 0], [0, 1, 1], [1, 0, 1]]))
        L1 = Lattice(L0)
        self.assertTrue(numpy.array_equal(L0.base, L1.base))
        L2 = Lattice(base=L0.base)
        self.assertTrue(numpy.array_equal(L0.base, L2.base))
        self.assertTrue(numpy.array_equal(L0.isotropicunit, L2.isotropicunit))
        L3 = Lattice(*L0.abcABG(), baserot=L0.baserot)
        self.assertTrue(numpy.allclose(L0.base, L3.base))
        self.assertTrue(numpy.allclose(L0.isotropicunit, L3.isotropicunit))
        return


    def test_setLatPar(self):
        """check calculation of standard unit cell vectors"""
        from numpy import dot
        from math import radians, sqrt, cos
        norm = lambda x : sqrt(sum([xi**2 for xi in x]))
        cosd = lambda x : cos(radians(x))
        self.lattice.setLatPar(1.0, 2.0, 3.0, 80, 100, 120)
        base = self.lattice.base
        self.assertAlmostEqual(1.0, norm(base[0]), self.places)
        self.assertAlmostEqual(2.0, norm(base[1]), self.places)
        self.assertAlmostEqual(3.0, norm(base[2]), self.places)
        self.assertAlmostEqual(cosd(80.0),
                dot(base[1],base[2])/(2*3), self.places)
        self.assertAlmostEqual(cosd(100.0),
                dot(base[0],base[2])/(1*3), self.places)
        self.assertAlmostEqual(cosd(120.0),
                dot(base[0],base[1])/(1*2), self.places)
        return


    def test_latpar_properties(self):
        '''check assignment to a, b, c, alpha, beta, gamma.
        '''
        lat = self.lattice
        lat.a = 2
        lat.b = 4
        lat.c = 6
        lat.alpha = 80
        lat.beta = 100
        lat.gamma = 120
        lat1 = Lattice(2, 4, 6, 80, 100, 120)
        self.assertAlmostEqual(-0.5, lat.cg, self.places)
        self.assertTrue(numpy.array_equal(lat1.base, lat.base))
        return


    def test_readonly_properties(self):
        '''Check that read-only properties are indeed such.
        '''
        lat = self.lattice
        lat.b = 2
        lat.c = 6
        self.assertEqual(1.0, lat.unitvolume)
        self.assertRaises(AttributeError, setattr,
                lat, 'unitvolume', 3.33)
        self.assertEqual(12, lat.volume)
        self.assertRaises(AttributeError, setattr,
                lat, 'volume', 3.33)
        self.assertEqual(0.0, lat.ca)
        self.assertRaises(AttributeError, setattr,
                lat, 'ca', 3.33)
        self.assertEqual(0.0, lat.cb)
        self.assertRaises(AttributeError, setattr,
                lat, 'cb', 3.33)
        self.assertEqual(0.0, lat.cg)
        self.assertRaises(AttributeError, setattr,
                lat, 'cg', 3.33)
        self.assertEqual(1.0, lat.sa)
        self.assertRaises(AttributeError, setattr,
                lat, 'sa', 3.33)
        self.assertEqual(1.0, lat.sb)
        self.assertRaises(AttributeError, setattr,
                lat, 'sb', 3.33)
        self.assertEqual(1.0, lat.sg)
        self.assertRaises(AttributeError, setattr,
                lat, 'sg', 3.33)
        self.assertEqual(1.0, lat.ar)
        self.assertRaises(AttributeError, setattr,
                lat, 'ar', 3.33)
        self.assertEqual(0.5, lat.br)
        self.assertRaises(AttributeError, setattr,
                lat, 'br', 3.33)
        self.assertAlmostEqual(1.0/6, lat.cr, self.places)
        self.assertRaises(AttributeError, setattr,
                lat, 'cr', 3.33)
        self.assertEqual(90.0, lat.alphar)
        self.assertRaises(AttributeError, setattr,
                lat, 'alphar', 3.33)
        self.assertEqual(90.0, lat.betar)
        self.assertRaises(AttributeError, setattr,
                lat, 'betar', 3.33)
        self.assertEqual(90.0, lat.gammar)
        self.assertRaises(AttributeError, setattr,
                lat, 'gammar', 3.33)
        self.assertEqual(0.0, lat.car)
        self.assertRaises(AttributeError, setattr,
                lat, 'car', 3.33)
        self.assertEqual(0.0, lat.cbr)
        self.assertRaises(AttributeError, setattr,
                lat, 'cbr', 3.33)
        self.assertEqual(0.0, lat.cgr)
        self.assertRaises(AttributeError, setattr,
                lat, 'cgr', 3.33)
        self.assertEqual(1.0, lat.sar)
        self.assertRaises(AttributeError, setattr,
                lat, 'sar', 3.33)
        self.assertEqual(1.0, lat.sbr)
        self.assertRaises(AttributeError, setattr,
                lat, 'sbr', 3.33)
        self.assertEqual(1.0, lat.sgr)
        self.assertRaises(AttributeError, setattr,
                lat, 'sgr', 3.33)
        return


    def test_setLatBase(self):
        """check calculation of unit cell rotation"""
        base = numpy.array([[ 1.0,  1.0,  0.0],
                          [ 0.0,  1.0,  1.0],
                          [ 1.0,  0.0,  1.0]])
        self.lattice.setLatBase(base)
        self.assertAlmostEqual(self.lattice.a, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.b, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.c, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.alpha, 60.0, self.places)
        self.assertAlmostEqual(self.lattice.beta,  60.0, self.places)
        self.assertAlmostEqual(self.lattice.gamma, 60.0, self.places)
        detR0 = numalg.det(self.lattice.baserot)
        self.assertAlmostEqual(detR0, 1.0, self.places)
        # try if rotation matrix works
        self.assertEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=44, beta=66, gamma=88)
        self.assertNotEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=60, beta=60, gamma=60)
        self.assertListAlmostEqual(base[0], self.lattice.base[0])
        self.assertListAlmostEqual(base[1], self.lattice.base[1])
        self.assertListAlmostEqual(base[2], self.lattice.base[2])
        # try base checking
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                [[1, 0, 0], [1,0,0], [0,0,1]])
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                [[1, 0, 0], [0,0,1], [0,1,0]])
        return


    def test_reciprocal(self):
        '''check calculation of reciprocal lattice.'''
        r1 = self.lattice.reciprocal()
        self.assertEqual((1, 1, 1, 90, 90, 90), r1.abcABG())
        L2 = Lattice(2, 4, 8, 90, 90, 90)
        r2 = L2.reciprocal()
        self.assertEqual((0.5, 0.25, 0.125, 90, 90, 90), r2.abcABG())
        rr2 = r2.reciprocal()
        self.assertTrue(numpy.array_equal(L2.base, rr2.base))
        return


    def test_dot(self):
        '''check dot product of lattice vectors.'''
        L = self.lattice
        L.setLatPar(gamma=120)
        self.assertAlmostEqual(-0.5, L.dot([1, 0, 0], [0, 1, 0]), self.places)
        va5 = numpy.tile([1.0, 0.0, 0.0], (5, 1))
        vb5 = numpy.tile([0.0, 1.0, 0.0], (5, 1))
        self.assertTrue(numpy.array_equal(5 * [-0.5], L.dot(va5, vb5)))
        self.assertTrue(numpy.array_equal(5 * [-0.5], L.dot(va5[0], vb5)))
        self.assertTrue(numpy.array_equal(5 * [-0.5], L.dot(va5, vb5[0])))
        return


    def test_norm(self):
        '''check norm of a lattice vector.'''
        self.assertEqual(1, self.lattice.norm([1, 0, 0]))
        u = numpy.array([[3, 4, 0], [1, 1, 1]])
        self.assertListAlmostEqual([5, 3**0.5], self.lattice.norm(u))
        self.lattice.setLatPar(gamma=120)
        self.assertAlmostEqual(1, self.lattice.norm([1, 1, 0]), self.places)
        return


    def test_rnorm(self):
        '''check norm of a reciprocal vector.'''
        L = self.lattice
        L.setLatPar(1, 1.5, 2.3, 80, 95, 115)
        r = L.reciprocal()
        hkl = [0.5, 0.3, 0.2]
        self.assertAlmostEqual(r.norm(hkl), L.rnorm(hkl), self.places)
        hkl5 = numpy.tile(hkl, (5, 1))
        self.assertListAlmostEqual(5 * [r.norm(hkl)], L.rnorm(hkl5))
        return


    def test_dist(self):
        '''check dist function for distance between lattice points.'''
        L = self.lattice
        L.setLatPar(1, 1.5, 2.3, 80, 95, 115)
        u = [0.1, 0.3, 0.7]
        v = [0.3, 0.7, 0.7]
        d0 = numalg.norm(L.cartesian(numpy.array(u) - v))
        self.assertAlmostEqual(d0, L.dist(u, v), self.places)
        self.assertAlmostEqual(d0, L.dist(v, u), self.places)
        u5 = numpy.tile(u, (5, 1))
        v5 = numpy.tile(v, (5, 1))
        self.assertListAlmostEqual(5 * [d0], L.dist(u, v5))
        self.assertListAlmostEqual(5 * [d0], L.dist(u5, v))
        self.assertListAlmostEqual(5 * [d0], L.dist(v5, u5))
        return


    def test_angle(self):
        '''check angle calculation between lattice vectors.'''
        from math import degrees, acos
        L = self.lattice
        L.setLatPar(1, 1.5, 2.3, 80, 95, 115)
        u = [0.1, 0.3, 0.7]
        v = [0.3, 0.7, 0.7]
        uc = L.cartesian(u)
        vc = L.cartesian(v)
        a0 = degrees(acos(numpy.dot(uc, vc) /
                          (numalg.norm(uc) * numalg.norm(vc))))
        self.assertAlmostEqual(a0, L.angle(u, v), self.places)
        self.assertAlmostEqual(a0, L.angle(v, u), self.places)
        u5 = numpy.tile(u, (5, 1))
        v5 = numpy.tile(v, (5, 1))
        self.assertListAlmostEqual(5 * [a0], L.angle(u, v5))
        self.assertListAlmostEqual(5 * [a0], L.angle(u5, v))
        self.assertListAlmostEqual(5 * [a0], L.angle(v5, u5))
        return



    def test_repr(self):
        """check string representation of this lattice"""
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice()")
        self.lattice.setLatPar(1, 2, 3, 10, 20, 30)
        r = repr(self.lattice)
        r0 = "Lattice(a=1, b=2, c=3, alpha=10, beta=20, gamma=30)"
        self.assertEqual(r, r0)
        base = [[ 1.0,  1.0,  0.0],
                [ 0.0,  2.0,  2.0],
                [ 3.0,  0.0,  3.0]]
        self.lattice.setLatBase(base)
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice(base=%r)" % self.lattice.base)
Exemplo n.º 20
0
class TestLattice(unittest.TestCase):
    """test methods of Lattice class"""

    def setUp(self):
        self.lattice = Lattice()
        self.places = 12
        return

    def assertListAlmostEqual(self, l1, l2, places=None):
        """wrapper for list comparison"""
        if places is None: places = self.places
        self.assertEqual(len(l1), len(l2))
        for i in range(len(l1)):
            self.assertAlmostEqual(l1[i], l2[i], places)
        return


    def test_setLatPar(self):
        """check calculation of standard unit cell vectors"""
        from numpy import dot
        from math import radians, sqrt, cos, sin
        norm = lambda x : sqrt(sum([xi**2 for xi in x]))
        cosd = lambda x : cos(radians(x))
        sind = lambda x : sin(radians(x))
        self.lattice.setLatPar(1.0, 2.0, 3.0, 80, 100, 120)
        base = self.lattice.base
        self.assertAlmostEqual(1.0, norm(base[0]), self.places)
        self.assertAlmostEqual(2.0, norm(base[1]), self.places)
        self.assertAlmostEqual(3.0, norm(base[2]), self.places)
        self.assertAlmostEqual(cosd(80.0),
                dot(base[1],base[2])/(2*3), self.places)
        self.assertAlmostEqual(cosd(100.0),
                dot(base[0],base[2])/(1*3), self.places)
        self.assertAlmostEqual(cosd(120.0),
                dot(base[0],base[1])/(1*2), self.places)
        return


    def test_latpar_properties(self):
        '''check assignment to a, b, c, alpha, beta, gamma.
        '''
        lat = self.lattice
        lat.a = 2
        lat.b = 4
        lat.c = 6
        lat.alpha = 80
        lat.beta = 100
        lat.gamma = 120
        lat1 = Lattice(2, 4, 6, 80, 100, 120)
        self.assertAlmostEqual(-0.5, lat.cg, self.places)
        self.failUnless(numpy.array_equal(lat1.base, lat.base))
        return


    def test_readonly_properties(self):
        '''Check that read-only properties are indeed such.
        '''
        lat = self.lattice
        lat.b = 2
        lat.c = 6
        self.assertEqual(1.0, lat.unitvolume)
        self.assertRaises(AttributeError, setattr,
                lat, 'unitvolume', 3.33)
        self.assertEqual(12, lat.volume)
        self.assertRaises(AttributeError, setattr,
                lat, 'volume', 3.33)
        self.assertEqual(0.0, lat.ca)
        self.assertRaises(AttributeError, setattr,
                lat, 'ca', 3.33)
        self.assertEqual(0.0, lat.cb)
        self.assertRaises(AttributeError, setattr,
                lat, 'cb', 3.33)
        self.assertEqual(0.0, lat.cg)
        self.assertRaises(AttributeError, setattr,
                lat, 'cg', 3.33)
        self.assertEqual(1.0, lat.sa)
        self.assertRaises(AttributeError, setattr,
                lat, 'sa', 3.33)
        self.assertEqual(1.0, lat.sb)
        self.assertRaises(AttributeError, setattr,
                lat, 'sb', 3.33)
        self.assertEqual(1.0, lat.sg)
        self.assertRaises(AttributeError, setattr,
                lat, 'sg', 3.33)
        self.assertEqual(1.0, lat.ar)
        self.assertRaises(AttributeError, setattr,
                lat, 'ar', 3.33)
        self.assertEqual(0.5, lat.br)
        self.assertRaises(AttributeError, setattr,
                lat, 'br', 3.33)
        self.assertAlmostEqual(1.0/6, lat.cr, self.places)
        self.assertRaises(AttributeError, setattr,
                lat, 'cr', 3.33)
        self.assertEqual(90.0, lat.alphar)
        self.assertRaises(AttributeError, setattr,
                lat, 'alphar', 3.33)
        self.assertEqual(90.0, lat.betar)
        self.assertRaises(AttributeError, setattr,
                lat, 'betar', 3.33)
        self.assertEqual(90.0, lat.gammar)
        self.assertRaises(AttributeError, setattr,
                lat, 'gammar', 3.33)
        self.assertEqual(0.0, lat.car)
        self.assertRaises(AttributeError, setattr,
                lat, 'car', 3.33)
        self.assertEqual(0.0, lat.cbr)
        self.assertRaises(AttributeError, setattr,
                lat, 'cbr', 3.33)
        self.assertEqual(0.0, lat.cgr)
        self.assertRaises(AttributeError, setattr,
                lat, 'cgr', 3.33)
        self.assertEqual(1.0, lat.sar)
        self.assertRaises(AttributeError, setattr,
                lat, 'sar', 3.33)
        self.assertEqual(1.0, lat.sbr)
        self.assertRaises(AttributeError, setattr,
                lat, 'sbr', 3.33)
        self.assertEqual(1.0, lat.sgr)
        self.assertRaises(AttributeError, setattr,
                lat, 'sgr', 3.33)
        return


    def test_setLatBase(self):
        """check calculation of unit cell rotation"""
        import numpy
        import numpy.linalg as numalg
        base = numpy.array([[ 1.0,  1.0,  0.0],
                          [ 0.0,  1.0,  1.0],
                          [ 1.0,  0.0,  1.0]])
        self.lattice.setLatBase(base)
        self.assertAlmostEqual(self.lattice.a, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.b, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.c, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.alpha, 60.0, self.places)
        self.assertAlmostEqual(self.lattice.beta,  60.0, self.places)
        self.assertAlmostEqual(self.lattice.gamma, 60.0, self.places)
        detR0 = numalg.det(self.lattice.baserot)
        self.assertAlmostEqual(detR0, 1.0, self.places)
        # try if rotation matrix works
        self.assertEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=44, beta=66, gamma=88)
        self.assertNotEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=60, beta=60, gamma=60)
        self.assertListAlmostEqual(base[0], self.lattice.base[0])
        self.assertListAlmostEqual(base[1], self.lattice.base[1])
        self.assertListAlmostEqual(base[2], self.lattice.base[2])
        # try base checking
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                [[1, 0, 0], [1,0,0], [0,0,1]])
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                [[1, 0, 0], [0,0,1], [0,1,0]])
        return

    def test_repr(self):
        """check string representation of this lattice"""
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice()")
        self.lattice.setLatPar(1, 2, 3, 10, 20, 30)
        r = repr(self.lattice)
        r0 = "Lattice(a=1, b=2, c=3, alpha=10, beta=20, gamma=30)"
        self.assertEqual(r, r0)
        base = [[ 1.0,  1.0,  0.0],
                [ 0.0,  2.0,  2.0],
                [ 3.0,  0.0,  3.0]]
        self.lattice.setLatBase(base)
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice(base=%r)" % self.lattice.base)
Exemplo n.º 21
0
    def parseLines(self, lines):
        """Parse list of lines in PDFfit format.

        Return Structure object or raise StructureFormatError.
        """
        p_nl = 0
        rlist = []
        try:
            self.stru = PDFFitStructure()
            stru = self.stru
            cell_line_read = False
            stop = len(lines)
            while stop > 0 and lines[stop - 1].strip() == "":
                stop -= 1
            ilines = iter(lines[:stop])
            # read header of PDFFit file
            for l in ilines:
                p_nl += 1
                words = l.split()
                if len(words) == 0 or words[0][0] == '#':
                    continue
                elif words[0] == 'title':
                    stru.title = l.lstrip()[5:].strip()
                elif words[0] == 'scale':
                    stru.pdffit['scale'] = float(words[1])
                elif words[0] == 'sharp':
                    l1 = l.replace(',', ' ')
                    sharp_pars = [float(w) for w in l1.split()[1:]]
                    if len(sharp_pars) < 4:
                        stru.pdffit['delta2'] = sharp_pars[0]
                        stru.pdffit['sratio'] = sharp_pars[1]
                        stru.pdffit['rcut'] = sharp_pars[2]
                    else:
                        stru.pdffit['delta2'] = sharp_pars[0]
                        stru.pdffit['delta1'] = sharp_pars[1]
                        stru.pdffit['sratio'] = sharp_pars[2]
                        stru.pdffit['rcut'] = sharp_pars[3]
                elif words[0] == 'spcgr':
                    key = 'spcgr'
                    start = l.find(key) + len(key)
                    value = l[start:].strip()
                    stru.pdffit['spcgr'] = value
                elif words[0] == 'shape':
                    self._parse_shape(l)
                elif words[0] == 'cell':
                    cell_line_read = True
                    l1 = l.replace(',', ' ')
                    latpars = [float(w) for w in l1.split()[1:7]]
                    stru.lattice = Lattice(*latpars)
                elif words[0] == 'dcell':
                    l1 = l.replace(',', ' ')
                    stru.pdffit['dcell'] = [float(w) for w in l1.split()[1:7]]
                elif words[0] == 'ncell':
                    l1 = l.replace(',', ' ')
                    stru.pdffit['ncell'] = [int(w) for w in l1.split()[1:5]]
                elif words[0] == 'format':
                    if words[1] != 'pdffit':
                        emsg = "%d: file is not in PDFfit format" % p_nl
                        raise StructureFormatError(emsg)
                elif words[0] == 'atoms' and cell_line_read:
                    break
                else:
                    self.ignored_lines.append(l)
            # Header reading finished, check if required lines were present.
            if not cell_line_read:
                emsg = "%d: file is not in PDFfit format" % p_nl
                raise StructureFormatError(emsg)
            # Load data from atom entries.
            p_natoms = reduce(lambda x, y: x * y, stru.pdffit['ncell'])
            # we are now inside data block
            for l in ilines:
                p_nl += 1
                wl1 = l.split()
                element = wl1[0][0].upper() + wl1[0][1:].lower()
                xyz = [float(w) for w in wl1[1:4]]
                occ = float(wl1[4])
                stru.addNewAtom(element, xyz=xyz, occupancy=occ)
                a = stru.getLastAtom()
                p_nl += 1
                wl2 = ilines.next().split()
                a.sigxyz = [float(w) for w in wl2[0:3]]
                a.sigo = float(wl2[3])
                p_nl += 1
                wl3 = ilines.next().split()
                p_nl += 1
                wl4 = ilines.next().split()
                p_nl += 1
                wl5 = ilines.next().split()
                p_nl += 1
                wl6 = ilines.next().split()
                a.sigU = numpy.zeros((3, 3), dtype=float)
                a.U11 = float(wl3[0])
                a.U22 = float(wl3[1])
                a.U33 = float(wl3[2])
                a.sigU[0, 0] = float(wl4[0])
                a.sigU[1, 1] = float(wl4[1])
                a.sigU[2, 2] = float(wl4[2])
                a.U12 = float(wl5[0])
                a.U13 = float(wl5[1])
                a.U23 = float(wl5[2])
                a.sigU[0, 1] = a.sigU[1, 0] = float(wl6[0])
                a.sigU[0, 2] = a.sigU[2, 0] = float(wl6[1])
                a.sigU[1, 2] = a.sigU[2, 1] = float(wl6[2])
            if len(stru) != p_natoms:
                emsg = "expected %d atoms, read %d" % (p_natoms, len(stru))
                raise StructureFormatError(emsg)
            if stru.pdffit['ncell'][:3] != [1, 1, 1]:
                superlatpars = [
                    latpars[i] * stru.pdffit['ncell'][i] for i in range(3)
                ] + latpars[3:]
                superlattice = Lattice(*superlatpars)
                stru.placeInLattice(superlattice)
                stru.pdffit['ncell'] = [1, 1, 1, p_natoms]
        except (ValueError, IndexError):
            emsg = "%d: file is not in PDFfit format" % p_nl
            exc_type, exc_value, exc_traceback = sys.exc_info()
            raise StructureFormatError, emsg, exc_traceback
        return stru
Exemplo n.º 22
0
class P_bratoms(StructureParser):
    """Parser for Bruce Ravel's Atoms structure format.
    """

    plist = ["a", "b", "c", "alpha", "beta", "gamma"]

    def __init__(self):
        StructureParser.__init__(self)
        self.format = "bratoms"
        return

    def parseLines(self, lines):
        """Parse list of lines in atoms format.

        Return Structure object or raise StructureFormatError.
        """

        comlist = ["#", "%", "!", "*"]
        atoms = []
        title = ""
        anext = False
        sg = None
        structure = BRAtomsStructure()
        meta = structure.bratoms
        pdict = dict.fromkeys(self.plist)


        # Count the lines
        ln = 0
        try:

            for line in lines:
                ln += 1

                # Strip comments from the line
                for c in comlist:
                    idx = line.find(c)
                    if idx != -1:
                        line = line[:idx]

                # Move on if there is not a line
                if not line: continue

                # Move on if there was only white space in the line
                sline = line.split()
                if not sline: continue

                # Check if we have atoms following
                if sline[0].startswith("atom"):
                    anext = True
                    continue

                # Check for title
                if sline[0].startswith("title"):
                    if title: title += "\n"
                    title += line[5:]
                    continue

                # Get rid of pesky "=" and "," signs
                while "=" in sline: sline.remove("=")
                while "," in sline: sline.remove(",")

                # space group
                if sline and sline[0].startswith("space"):
                    meta["space"] = line[5:].strip()
                    continue

                # output
                if sline and sline[0].startswith("output"):
                    meta["output"] = line[6:].strip()
                    continue

                # shift
                if sline and sline[0].startswith("shift"):
                    meta["shift"] = line[5:].strip()
                    continue

                # Check for other metadata
                while sline and sline[0].strip() in meta:
                    key = sline.pop(0).strip()
                    if key == "central": key = "core"
                    meta[key] = sline.pop(0).strip()

                # Check for lattice information.
                while sline and sline[0].strip() in self.plist:
                    key = sline.pop(0).strip()
                    pdict[key] = float(sline.pop(0))

                # Check for atom information
                if sline and anext:

                    elraw = sline.pop(0).strip()
                    el = elraw[:1].upper() + elraw[1:].lower()
                    x = float(sline.pop(0))
                    y = float(sline.pop(0))
                    z = float(sline.pop(0))

                    tag = ""
                    if sline:
                        tag = sline.pop(0).strip()
                    occ = 1.0
                    if sline:
                        occ = float(sline.pop(0))

                    a = Atom( atype = el,
                        xyz = [x,y,z],
                        name = tag,
                        occupancy = occ)

                    atoms.append(a)

        except (ValueError, IndexError), e:
            emsg = "%d: file is not in Atoms format" % ln
            raise StructureFormatError(emsg)

        # Make sure we have atoms.
        if len(atoms) == 0:
            raise StructureFormatError("File contains no atoms")

        # Make sure we have unit cell parameters
        if pdict["a"] is None:
            emsg = "Missing definition of cell parameter"
            raise StructureFormatError(emsg)

        # Fill in optional information if it was missing.
        if pdict["alpha"] is None:
            pdict["alpha"] = 90.0
        if pdict["beta"] is None:
            pdict["beta"] = pdict["alpha"]
        if pdict["gamma"] is None:
            pdict["gamma"] = pdict["alpha"]
        if pdict["b"] is None:
            pdict["b"] = pdict["a"]
        if pdict["c"] is None:
            pdict["c"] = pdict["a"]

        if meta['core'] is None:
            meta['core'] = atoms[0].element

        lat = Lattice(**pdict)
        structure.title = title
        structure.lattice = lat
        structure.extend(atoms)
        return structure
Exemplo n.º 23
0
    def parseLines(self, lines):
        """Parse list of lines in XYZ format.

        Return Structure object or raise StructureFormatError.
        """
        linefields = [l.split() for l in lines]
        # prepare output structure
        stru = Structure()
        # find first valid record
        start = 0
        for field in linefields:
            if len(field) == 0 or field[0] == "#":
                start += 1
            else:
                break
        # first valid line gives number of atoms
        try:
            lfs = linefields[start]
            w1 = linefields[start][0]
            if len(lfs) == 1 and str(int(w1)) == w1:
                p_natoms = int(w1)
                #try to get lattice vectors from description line
                try:
                    latticeVecs = list(map(float, linefields[start+1]))
                    assert len(latticeVecs)==9, "Expect 9 numbers for the 3 basis vectors"
                    reshaped = [latticeVecs[0:3], latticeVecs[3:6], latticeVecs[6:9]]
                    stru.lattice = Lattice(base=reshaped) 
                    needsDescription = True
                except:
                    import traceback as tb
                    import warnings
                    warnings.warn("Failed to parse lattice vectors: \n{}".format(tb.format_exc()))
                    needsDescription = False
                    stru.description = lines[start+1].strip()
                start += 2
            else:
                emsg = ("%d: invalid XYZ format, missing number of atoms" %
                        (start + 1))
                raise StructureFormatError(emsg)
        except (IndexError, ValueError):
            exc_type, exc_value, exc_traceback = sys.exc_info()
            emsg = ("%d: invalid XYZ format, missing number of atoms" %
                    (start + 1))
            raise StructureFormatError(emsg).with_traceback(exc_traceback)
        # find the last valid record
        stop = len(lines)
        while stop > start and len(linefields[stop-1]) == 0:
            stop -= 1
        # get out for empty structure
        if p_natoms == 0 or start >= stop:
            return stru
        # here we have at least one valid record line
        nfields = len(linefields[start])
        if nfields != 4 and nfields != 5:
            emsg = "%d: invalid XYZ format, expected 4 or 5 columns" % (start + 1)
            raise StructureFormatError(emsg)
        # now try to read all record lines
        try:
            p_nl = start
            for fields in linefields[start:] :
                p_nl += 1
                if fields == []:
                    continue
                elif len(fields) != 4 and len(fields) !=5:
                    emsg = ('%d: all lines must have ' +
                            'a symbol, position, and optionally charge') % p_nl
                    raise StructureFormatError(emsg)
                symbol = fields[0]
                symbol = symbol[0].upper() + symbol[1:].lower()
                xyz = [ float(f) for f in fields[1:4] ]                 
                if len(fields)==5:
                    charge = float(fields[4])
                else:
                    charge = 0.0
                stru.addNewAtom(symbol, xyz=xyz)
                stru.getLastAtom().charge=charge
        except ValueError:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            emsg = "%d: invalid number format" % p_nl
            raise StructureFormatError(emsg).with_traceback(exc_traceback)
        # finally check if all the atoms have been read
        if p_natoms is not None and len(stru) != p_natoms:
            emsg = "expected %d atoms, read %d" % (p_natoms, len(stru))
            raise StructureFormatError(emsg)
        # if needsDescription:
        #     stru.generateDescription()
        return stru
Exemplo n.º 24
0
def bccFe():
    atoms = [Atom('Fe', (0, 0, 0)), Atom('Fe', (0.5, 0.5, 0.5))]
    a = 2.856
    alpha = 90.
    lattice = Lattice(a=a, b=a, c=a, alpha=alpha, beta=alpha, gamma=alpha)
    return Structure(atoms, lattice, sgid=229)
Exemplo n.º 25
0
class TestLattice(unittest.TestCase):
    """test methods of Lattice class"""
    def setUp(self):
        self.lattice = Lattice()
        self.places = 12
        return

    def assertListAlmostEqual(self, l1, l2, places=None):
        """wrapper for list comparison"""
        if places is None: places = self.places
        self.assertEqual(len(l1), len(l2))
        for i in range(len(l1)):
            self.assertAlmostEqual(l1[i], l2[i], places)
        return

    def test_setLatPar(self):
        """check calculation of standard unit cell vectors"""
        from numpy import dot
        from math import radians, sqrt, cos, sin
        norm = lambda x: sqrt(sum([xi**2 for xi in x]))
        cosd = lambda x: cos(radians(x))
        sind = lambda x: sin(radians(x))
        self.lattice.setLatPar(1.0, 2.0, 3.0, 80, 100, 120)
        base = self.lattice.base
        self.assertAlmostEqual(1.0, norm(base[0]), self.places)
        self.assertAlmostEqual(2.0, norm(base[1]), self.places)
        self.assertAlmostEqual(3.0, norm(base[2]), self.places)
        self.assertAlmostEqual(cosd(80.0),
                               dot(base[1], base[2]) / (2 * 3), self.places)
        self.assertAlmostEqual(cosd(100.0),
                               dot(base[0], base[2]) / (1 * 3), self.places)
        self.assertAlmostEqual(cosd(120.0),
                               dot(base[0], base[1]) / (1 * 2), self.places)
        return

    def test_latpar_properties(self):
        '''check assignment to a, b, c, alpha, beta, gamma.
        '''
        lat = self.lattice
        lat.a = 2
        lat.b = 4
        lat.c = 6
        lat.alpha = 80
        lat.beta = 100
        lat.gamma = 120
        lat1 = Lattice(2, 4, 6, 80, 100, 120)
        self.assertAlmostEqual(-0.5, lat.cg, self.places)
        self.failUnless(numpy.array_equal(lat1.base, lat.base))
        return

    def test_readonly_properties(self):
        '''Check that read-only properties are indeed such.
        '''
        lat = self.lattice
        lat.b = 2
        lat.c = 6
        self.assertEqual(1.0, lat.unitvolume)
        self.assertRaises(AttributeError, setattr, lat, 'unitvolume', 3.33)
        self.assertEqual(12, lat.volume)
        self.assertRaises(AttributeError, setattr, lat, 'volume', 3.33)
        self.assertEqual(0.0, lat.ca)
        self.assertRaises(AttributeError, setattr, lat, 'ca', 3.33)
        self.assertEqual(0.0, lat.cb)
        self.assertRaises(AttributeError, setattr, lat, 'cb', 3.33)
        self.assertEqual(0.0, lat.cg)
        self.assertRaises(AttributeError, setattr, lat, 'cg', 3.33)
        self.assertEqual(1.0, lat.sa)
        self.assertRaises(AttributeError, setattr, lat, 'sa', 3.33)
        self.assertEqual(1.0, lat.sb)
        self.assertRaises(AttributeError, setattr, lat, 'sb', 3.33)
        self.assertEqual(1.0, lat.sg)
        self.assertRaises(AttributeError, setattr, lat, 'sg', 3.33)
        self.assertEqual(1.0, lat.ar)
        self.assertRaises(AttributeError, setattr, lat, 'ar', 3.33)
        self.assertEqual(0.5, lat.br)
        self.assertRaises(AttributeError, setattr, lat, 'br', 3.33)
        self.assertAlmostEqual(1.0 / 6, lat.cr, self.places)
        self.assertRaises(AttributeError, setattr, lat, 'cr', 3.33)
        self.assertEqual(90.0, lat.alphar)
        self.assertRaises(AttributeError, setattr, lat, 'alphar', 3.33)
        self.assertEqual(90.0, lat.betar)
        self.assertRaises(AttributeError, setattr, lat, 'betar', 3.33)
        self.assertEqual(90.0, lat.gammar)
        self.assertRaises(AttributeError, setattr, lat, 'gammar', 3.33)
        self.assertEqual(0.0, lat.car)
        self.assertRaises(AttributeError, setattr, lat, 'car', 3.33)
        self.assertEqual(0.0, lat.cbr)
        self.assertRaises(AttributeError, setattr, lat, 'cbr', 3.33)
        self.assertEqual(0.0, lat.cgr)
        self.assertRaises(AttributeError, setattr, lat, 'cgr', 3.33)
        self.assertEqual(1.0, lat.sar)
        self.assertRaises(AttributeError, setattr, lat, 'sar', 3.33)
        self.assertEqual(1.0, lat.sbr)
        self.assertRaises(AttributeError, setattr, lat, 'sbr', 3.33)
        self.assertEqual(1.0, lat.sgr)
        self.assertRaises(AttributeError, setattr, lat, 'sgr', 3.33)
        return

    def test_setLatBase(self):
        """check calculation of unit cell rotation"""
        import numpy
        import numpy.linalg as numalg
        base = numpy.array([[1.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0]])
        self.lattice.setLatBase(base)
        self.assertAlmostEqual(self.lattice.a, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.b, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.c, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.alpha, 60.0, self.places)
        self.assertAlmostEqual(self.lattice.beta, 60.0, self.places)
        self.assertAlmostEqual(self.lattice.gamma, 60.0, self.places)
        detR0 = numalg.det(self.lattice.baserot)
        self.assertAlmostEqual(detR0, 1.0, self.places)
        # try if rotation matrix works
        self.assertEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=44, beta=66, gamma=88)
        self.assertNotEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=60, beta=60, gamma=60)
        self.assertListAlmostEqual(base[0], self.lattice.base[0])
        self.assertListAlmostEqual(base[1], self.lattice.base[1])
        self.assertListAlmostEqual(base[2], self.lattice.base[2])
        # try base checking
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                          [[1, 0, 0], [1, 0, 0], [0, 0, 1]])
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                          [[1, 0, 0], [0, 0, 1], [0, 1, 0]])
        return

    def test_repr(self):
        """check string representation of this lattice"""
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice()")
        self.lattice.setLatPar(1, 2, 3, 10, 20, 30)
        r = repr(self.lattice)
        r0 = "Lattice(a=1, b=2, c=3, alpha=10, beta=20, gamma=30)"
        self.assertEqual(r, r0)
        base = [[1.0, 1.0, 0.0], [0.0, 2.0, 2.0], [3.0, 0.0, 3.0]]
        self.lattice.setLatBase(base)
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice(base=%r)" % self.lattice.base)
Exemplo n.º 26
0
class TestLattice(unittest.TestCase):
    """test methods of Lattice class"""
    def setUp(self):
        self.lattice = Lattice()
        self.places = 12
        return

    def assertListAlmostEqual(self, l1, l2, places=None):
        """wrapper for list comparison"""
        if places is None: places = self.places
        self.assertEqual(len(l1), len(l2))
        for i in range(len(l1)):
            self.assertAlmostEqual(l1[i], l2[i], places)
        return

    def test___init__(self):
        '''Check Lattice.__init__ processing of arguments.
        '''
        self.assertRaises(ValueError, Lattice, self.lattice, c=4)
        self.assertRaises(ValueError,
                          Lattice,
                          base=self.lattice.base,
                          baserot=self.lattice.baserot)
        self.assertRaises(ValueError, Lattice, 1, 2, 3)
        self.assertRaises(ValueError, Lattice, 1, 2, 3, 80, 90)
        L0 = self.lattice
        L0.setLatBase(L0.cartesian([[1, 1, 0], [0, 1, 1], [1, 0, 1]]))
        L1 = Lattice(L0)
        self.assertTrue(numpy.array_equal(L0.base, L1.base))
        L2 = Lattice(base=L0.base)
        self.assertTrue(numpy.array_equal(L0.base, L2.base))
        self.assertTrue(numpy.array_equal(L0.isotropicunit, L2.isotropicunit))
        L3 = Lattice(*L0.abcABG(), baserot=L0.baserot)
        self.assertTrue(numpy.allclose(L0.base, L3.base))
        self.assertTrue(numpy.allclose(L0.isotropicunit, L3.isotropicunit))
        return

    def test_setLatPar(self):
        """check calculation of standard unit cell vectors"""
        from numpy import dot
        from math import radians, sqrt, cos
        norm = lambda x: sqrt(sum([xi**2 for xi in x]))
        cosd = lambda x: cos(radians(x))
        self.lattice.setLatPar(1.0, 2.0, 3.0, 80, 100, 120)
        base = self.lattice.base
        self.assertAlmostEqual(1.0, norm(base[0]), self.places)
        self.assertAlmostEqual(2.0, norm(base[1]), self.places)
        self.assertAlmostEqual(3.0, norm(base[2]), self.places)
        self.assertAlmostEqual(cosd(80.0),
                               dot(base[1], base[2]) / (2 * 3), self.places)
        self.assertAlmostEqual(cosd(100.0),
                               dot(base[0], base[2]) / (1 * 3), self.places)
        self.assertAlmostEqual(cosd(120.0),
                               dot(base[0], base[1]) / (1 * 2), self.places)
        return

    def test_latpar_properties(self):
        '''check assignment to a, b, c, alpha, beta, gamma.
        '''
        lat = self.lattice
        lat.a = 2
        lat.b = 4
        lat.c = 6
        lat.alpha = 80
        lat.beta = 100
        lat.gamma = 120
        lat1 = Lattice(2, 4, 6, 80, 100, 120)
        self.assertAlmostEqual(-0.5, lat.cg, self.places)
        self.assertTrue(numpy.array_equal(lat1.base, lat.base))
        return

    def test_readonly_properties(self):
        '''Check that read-only properties are indeed such.
        '''
        lat = self.lattice
        lat.b = 2
        lat.c = 6
        self.assertEqual(1.0, lat.unitvolume)
        self.assertRaises(AttributeError, setattr, lat, 'unitvolume', 3.33)
        self.assertEqual(12, lat.volume)
        self.assertRaises(AttributeError, setattr, lat, 'volume', 3.33)
        self.assertEqual(0.0, lat.ca)
        self.assertRaises(AttributeError, setattr, lat, 'ca', 3.33)
        self.assertEqual(0.0, lat.cb)
        self.assertRaises(AttributeError, setattr, lat, 'cb', 3.33)
        self.assertEqual(0.0, lat.cg)
        self.assertRaises(AttributeError, setattr, lat, 'cg', 3.33)
        self.assertEqual(1.0, lat.sa)
        self.assertRaises(AttributeError, setattr, lat, 'sa', 3.33)
        self.assertEqual(1.0, lat.sb)
        self.assertRaises(AttributeError, setattr, lat, 'sb', 3.33)
        self.assertEqual(1.0, lat.sg)
        self.assertRaises(AttributeError, setattr, lat, 'sg', 3.33)
        self.assertEqual(1.0, lat.ar)
        self.assertRaises(AttributeError, setattr, lat, 'ar', 3.33)
        self.assertEqual(0.5, lat.br)
        self.assertRaises(AttributeError, setattr, lat, 'br', 3.33)
        self.assertAlmostEqual(1.0 / 6, lat.cr, self.places)
        self.assertRaises(AttributeError, setattr, lat, 'cr', 3.33)
        self.assertEqual(90.0, lat.alphar)
        self.assertRaises(AttributeError, setattr, lat, 'alphar', 3.33)
        self.assertEqual(90.0, lat.betar)
        self.assertRaises(AttributeError, setattr, lat, 'betar', 3.33)
        self.assertEqual(90.0, lat.gammar)
        self.assertRaises(AttributeError, setattr, lat, 'gammar', 3.33)
        self.assertEqual(0.0, lat.car)
        self.assertRaises(AttributeError, setattr, lat, 'car', 3.33)
        self.assertEqual(0.0, lat.cbr)
        self.assertRaises(AttributeError, setattr, lat, 'cbr', 3.33)
        self.assertEqual(0.0, lat.cgr)
        self.assertRaises(AttributeError, setattr, lat, 'cgr', 3.33)
        self.assertEqual(1.0, lat.sar)
        self.assertRaises(AttributeError, setattr, lat, 'sar', 3.33)
        self.assertEqual(1.0, lat.sbr)
        self.assertRaises(AttributeError, setattr, lat, 'sbr', 3.33)
        self.assertEqual(1.0, lat.sgr)
        self.assertRaises(AttributeError, setattr, lat, 'sgr', 3.33)
        return

    def test_setLatBase(self):
        """check calculation of unit cell rotation"""
        base = numpy.array([[1.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0]])
        self.lattice.setLatBase(base)
        self.assertAlmostEqual(self.lattice.a, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.b, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.c, numpy.sqrt(2.0), self.places)
        self.assertAlmostEqual(self.lattice.alpha, 60.0, self.places)
        self.assertAlmostEqual(self.lattice.beta, 60.0, self.places)
        self.assertAlmostEqual(self.lattice.gamma, 60.0, self.places)
        detR0 = numalg.det(self.lattice.baserot)
        self.assertAlmostEqual(detR0, 1.0, self.places)
        # try if rotation matrix works
        self.assertEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=44, beta=66, gamma=88)
        self.assertNotEqual(numpy.all(base == self.lattice.base), True)
        self.lattice.setLatPar(alpha=60, beta=60, gamma=60)
        self.assertListAlmostEqual(base[0], self.lattice.base[0])
        self.assertListAlmostEqual(base[1], self.lattice.base[1])
        self.assertListAlmostEqual(base[2], self.lattice.base[2])
        # try base checking
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                          [[1, 0, 0], [1, 0, 0], [0, 0, 1]])
        self.assertRaises(LatticeError, self.lattice.setLatBase,
                          [[1, 0, 0], [0, 0, 1], [0, 1, 0]])
        return

    def test_reciprocal(self):
        '''check calculation of reciprocal lattice.'''
        r1 = self.lattice.reciprocal()
        self.assertEqual((1, 1, 1, 90, 90, 90), r1.abcABG())
        L2 = Lattice(2, 4, 8, 90, 90, 90)
        r2 = L2.reciprocal()
        self.assertEqual((0.5, 0.25, 0.125, 90, 90, 90), r2.abcABG())
        rr2 = r2.reciprocal()
        self.assertTrue(numpy.array_equal(L2.base, rr2.base))
        return

    def test_dot(self):
        '''check dot product of lattice vectors.'''
        L = self.lattice
        L.setLatPar(gamma=120)
        self.assertAlmostEqual(-0.5, L.dot([1, 0, 0], [0, 1, 0]), self.places)
        va5 = numpy.tile([1.0, 0.0, 0.0], (5, 1))
        vb5 = numpy.tile([0.0, 1.0, 0.0], (5, 1))
        self.assertTrue(numpy.array_equal(5 * [-0.5], L.dot(va5, vb5)))
        self.assertTrue(numpy.array_equal(5 * [-0.5], L.dot(va5[0], vb5)))
        self.assertTrue(numpy.array_equal(5 * [-0.5], L.dot(va5, vb5[0])))
        return

    def test_norm(self):
        '''check norm of a lattice vector.'''
        self.assertEqual(1, self.lattice.norm([1, 0, 0]))
        u = numpy.array([[3, 4, 0], [1, 1, 1]])
        self.assertListAlmostEqual([5, 3**0.5], self.lattice.norm(u))
        self.lattice.setLatPar(gamma=120)
        self.assertAlmostEqual(1, self.lattice.norm([1, 1, 0]), self.places)
        return

    def test_rnorm(self):
        '''check norm of a reciprocal vector.'''
        L = self.lattice
        L.setLatPar(1, 1.5, 2.3, 80, 95, 115)
        r = L.reciprocal()
        hkl = [0.5, 0.3, 0.2]
        self.assertAlmostEqual(r.norm(hkl), L.rnorm(hkl), self.places)
        hkl5 = numpy.tile(hkl, (5, 1))
        self.assertListAlmostEqual(5 * [r.norm(hkl)], L.rnorm(hkl5))
        return

    def test_dist(self):
        '''check dist function for distance between lattice points.'''
        L = self.lattice
        L.setLatPar(1, 1.5, 2.3, 80, 95, 115)
        u = [0.1, 0.3, 0.7]
        v = [0.3, 0.7, 0.7]
        d0 = numalg.norm(L.cartesian(numpy.array(u) - v))
        self.assertAlmostEqual(d0, L.dist(u, v), self.places)
        self.assertAlmostEqual(d0, L.dist(v, u), self.places)
        u5 = numpy.tile(u, (5, 1))
        v5 = numpy.tile(v, (5, 1))
        self.assertListAlmostEqual(5 * [d0], L.dist(u, v5))
        self.assertListAlmostEqual(5 * [d0], L.dist(u5, v))
        self.assertListAlmostEqual(5 * [d0], L.dist(v5, u5))
        return

    def test_angle(self):
        '''check angle calculation between lattice vectors.'''
        from math import degrees, acos
        L = self.lattice
        L.setLatPar(1, 1.5, 2.3, 80, 95, 115)
        u = [0.1, 0.3, 0.7]
        v = [0.3, 0.7, 0.7]
        uc = L.cartesian(u)
        vc = L.cartesian(v)
        a0 = degrees(
            acos(numpy.dot(uc, vc) / (numalg.norm(uc) * numalg.norm(vc))))
        self.assertAlmostEqual(a0, L.angle(u, v), self.places)
        self.assertAlmostEqual(a0, L.angle(v, u), self.places)
        u5 = numpy.tile(u, (5, 1))
        v5 = numpy.tile(v, (5, 1))
        self.assertListAlmostEqual(5 * [a0], L.angle(u, v5))
        self.assertListAlmostEqual(5 * [a0], L.angle(u5, v))
        self.assertListAlmostEqual(5 * [a0], L.angle(v5, u5))
        return

    def test_repr(self):
        """check string representation of this lattice"""
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice()")
        self.lattice.setLatPar(1, 2, 3, 10, 20, 30)
        r = repr(self.lattice)
        r0 = "Lattice(a=1, b=2, c=3, alpha=10, beta=20, gamma=30)"
        self.assertEqual(r, r0)
        base = [[1.0, 1.0, 0.0], [0.0, 2.0, 2.0], [3.0, 0.0, 3.0]]
        self.lattice.setLatBase(base)
        r = repr(self.lattice)
        self.assertEqual(r, "Lattice(base=%r)" % self.lattice.base)
Exemplo n.º 27
0
    def testDiffpyStructureParSet(self):
        """Test the structure conversion."""

        a1 = Atom("Cu", xyz = numpy.array([.0, .1, .2]), Uisoequiv = 0.003)
        a2 = Atom("Ag", xyz = numpy.array([.3, .4, .5]), Uisoequiv = 0.002)
        l = Lattice(2.5, 2.5, 2.5, 90, 90, 90)

        dsstru = Structure([a1,a2], l)
        # Structure makes copies
        a1 = dsstru[0]
        a2 = dsstru[1]

        s = DiffpyStructureParSet("CuAg", dsstru)

        self.assertEquals(s.name, "CuAg")

        def _testAtoms():
            # Check the atoms thoroughly
            self.assertEquals(a1.element, s.Cu0.element)
            self.assertEquals(a2.element, s.Ag0.element)
            self.assertEquals(a1.Uisoequiv, s.Cu0.Uiso.getValue())
            self.assertEquals(a2.Uisoequiv, s.Ag0.Uiso.getValue())
            self.assertEquals(a1.Bisoequiv, s.Cu0.Biso.getValue())
            self.assertEquals(a2.Bisoequiv, s.Ag0.Biso.getValue())
            for i in xrange(1,4):
                for j in xrange(i,4):
                    uijstru = getattr(a1, "U%i%i"%(i,j))
                    uij = getattr(s.Cu0, "U%i%i"%(i,j)).getValue()
                    uji = getattr(s.Cu0, "U%i%i"%(j,i)).getValue()
                    self.assertEquals(uijstru, uij)
                    self.assertEquals(uijstru, uji)
                    bijstru = getattr(a1, "B%i%i"%(i,j))
                    bij = getattr(s.Cu0, "B%i%i"%(i,j)).getValue()
                    bji = getattr(s.Cu0, "B%i%i"%(j,i)).getValue()
                    self.assertEquals(bijstru, bij)
                    self.assertEquals(bijstru, bji)

            self.assertEquals(a1.xyz[0], s.Cu0.x.getValue())
            self.assertEquals(a1.xyz[1], s.Cu0.y.getValue())
            self.assertEquals(a1.xyz[2], s.Cu0.z.getValue())
            return

        def _testLattice():

            # Test the lattice
            self.assertEquals(dsstru.lattice.a, s.lattice.a.getValue())
            self.assertEquals(dsstru.lattice.b, s.lattice.b.getValue())
            self.assertEquals(dsstru.lattice.c, s.lattice.c.getValue())
            self.assertEquals(dsstru.lattice.alpha, s.lattice.alpha.getValue())
            self.assertEquals(dsstru.lattice.beta, s.lattice.beta.getValue())
            self.assertEquals(dsstru.lattice.gamma, s.lattice.gamma.getValue())

        _testAtoms()
        _testLattice()

        # Now change some values from the diffpy Structure
        a1.xyz[1] = 0.123
        a1.U11 = 0.321
        a1.B32 = 0.111
        dsstru.lattice.setLatPar(a=3.0, gamma=121)
        _testAtoms()
        _testLattice()

        # Now change values from the srfit DiffpyStructureParSet
        s.Cu0.x.setValue(0.456)
        s.Cu0.U22.setValue(0.441)
        s.Cu0.B13.setValue(0.550)
        d = dsstru.lattice.dist(a1.xyz, a2.xyz)
        s.lattice.b.setValue(4.6)
        s.lattice.alpha.setValue(91.3)
        _testAtoms()
        _testLattice()
        # Make sure the distance changed
        self.assertNotEquals(d, dsstru.lattice.dist(a1.xyz, a2.xyz))
        return
Exemplo n.º 28
0
 def setUp(self):
     self.lattice = Lattice()
     self.places = 12
     return
Exemplo n.º 29
0
 def setUp(self):
     self.lattice = Lattice()
     self.places = 12
     return
Exemplo n.º 30
0
#!/usr/bin/env python
"""Express Ni FCC structure in its rhombohedral primitive cell.
"""

from diffpy.Structure import Structure
from diffpy.Structure import Lattice
from diffpy.Structure.SymmetryUtilities import equalPositions

# load Ni fcc structure, Ni.stru is in tests/testdata/
nifcc = Structure(filename='Ni.stru')
# base vectors for rhombohedral lattice in Cartesian coordinates
rhombbase = nifcc.lattice.cartesian([[0.5, 0.5, 0.0], [0.0, 0.5, 0.5],
                                     [0.5, 0, 0.5]])

# make a deep copy of nifcc
nirhomb = Structure(nifcc)
nirhomb.placeInLattice(Lattice(base=rhombbase))

# collect atoms that are at equivalent position to some previous atom
duplicates = set([
    a1 for i0, a0 in enumerate(nirhomb) for a1 in nirhomb[i0 + 1:]
    if equalPositions(a0.xyz, a1.xyz, eps=1e-4)
])

# Filter out duplicate atoms.  Use slice assignment so that
# nirhomb is not replaced with a list.
nirhomb[:] = [a for a in nirhomb if not a in duplicates]

# use rstrip to avoid duplicate line feed
print nirhomb.writeStr(format='discus').rstrip()