コード例 #1
0
 def test_rwStr_pdb_CdSe(self):
     """check conversion to PDB file format"""
     stru = self.stru
     stru.read(datafile('CdSe_bulk.stru'), 'pdffit')
     #print stru.description
     s = stru.writeStr(self.format)
     # all lines should be 80 characters long
     linelens = [len(l) for l in s.split('\n') if l != ""]
     self.assertEqual(linelens, len(linelens) * [80])
     # now clean and re-read structure
     stru = Structure()
     stru.readStr(s, self.format)
     #print stru.description
     s_els = [a.symbol for a in stru]
     f_els = ['Cd', 'Cd', 'Se', 'Se']
     self.assertEqual(s_els, f_els)
     s_lat = [
         stru.lattice.a, stru.lattice.b, stru.lattice.c, stru.lattice.alpha,
         stru.lattice.beta, stru.lattice.gamma
     ]
     f_lat = [4.235204, 4.235204, 6.906027, 90.0, 90.0, 120.0]
     self.assertListAlmostEqual(s_lat, f_lat)
     a0 = stru[0]
     s_Uii = [a0.U[i, i] for i in range(3)]
     f_Uii = [0.01303035, 0.01303035, 0.01401959]
     self.assertListAlmostEqual(s_Uii, f_Uii)
     s_sigUii = [a0.sigU[i, i] for i in range(3)]
     f_sigUii = [0.00011127, 0.00011127, 0.00019575]
     self.assertListAlmostEqual(s_sigUii, f_sigUii)
     s_title = stru.description
     f_title = "Cell structure file of CdSe #186"
     self.assertEqual(s_title, f_title)
コード例 #2
0
 def test_rwStr_pdb_CdSe(self):
     """check conversion to PDB file format"""
     stru = self.stru
     stru.read(datafile('CdSe_bulk.stru'), 'pdffit')
     #print stru.description
     s = stru.writeStr(self.format)
     # all lines should be 80 characters long
     linelens = [ len(l) for l in s.split('\n') if l != "" ]
     self.assertEqual(linelens, len(linelens)*[80])
     # now clean and re-read structure
     stru = Structure()
     stru.readStr(s, self.format)
     #print stru.description
     s_els = [a.symbol for a in stru]
     f_els = ['Cd', 'Cd', 'Se', 'Se']
     self.assertEqual(s_els, f_els)
     s_lat = [ stru.lattice.a, stru.lattice.b, stru.lattice.c,
         stru.lattice.alpha, stru.lattice.beta, stru.lattice.gamma ]
     f_lat = [ 4.235204,  4.235204,  6.906027, 90.0, 90.0, 120.0 ]
     self.assertListAlmostEqual(s_lat, f_lat)
     a0 = stru[0]
     s_Uii = [ a0.U[i,i] for i in range(3) ]
     f_Uii = [ 0.01303035, 0.01303035, 0.01401959 ]
     self.assertListAlmostEqual(s_Uii, f_Uii)
     s_sigUii = [ a0.sigU[i,i] for i in range(3) ]
     f_sigUii = [ 0.00011127, 0.00011127, 0.00019575 ]
     self.assertListAlmostEqual(s_sigUii, f_sigUii)
     s_title = stru.description
     f_title = "Cell structure file of CdSe #186"
     self.assertEqual(s_title, f_title)
コード例 #3
0
    def parseLines(self, lines):
        """Parse list of lines in RAWXYZ 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
        # 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 start >= stop:
            return stru
        # here we have at least one valid record line
        # figure out xyz layout from the first line for plain and raw formats
        floatfields = [ isfloat(f) for f in linefields[start] ]
        nfields = len(linefields[start])
        if nfields not in (3, 4):
            emsg = ("%d: invalid RAWXYZ format, expected 3 or 4 columns" %
                    (start + 1))
            raise StructureFormatError(emsg)
        if floatfields[:3] == [True, True, True]:
            el_idx, x_idx = (None, 0)
        elif floatfields[:4] == [False, True, True, True]:
            el_idx, x_idx = (0, 1)
        else:
            emsg = "%d: invalid RAWXYZ format" % (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) != nfields:
                    emsg = ('%d: all lines must have ' +
                            'the same number of columns') % p_nl
                    raise StructureFormatError, emsg
                symbol = el_idx is not None and fields[el_idx] or ""
                xyz = [ float(f) for f in fields[x_idx:x_idx+3] ]
                if len(xyz) == 2:
                    xyz.append(0.0)
                stru.addNewAtom(symbol, xyz=xyz)
        except ValueError:
            emsg = "%d: invalid number" % p_nl
            exc_type, exc_value, exc_traceback = sys.exc_info()
            raise StructureFormatError, emsg, exc_traceback
        return stru
コード例 #4
0
def supercell(S, mno):
    """Perform supercell expansion for a structure.

    New lattice parameters are multiplied and fractional coordinates
    divided by corresponding multiplier.  New atoms are grouped with
    their source in the original cell.

    S   -- an instance of Structure from matter.
    mno -- sequence of 3 integers for cell multipliers along
           the a, b and c axes.

    Return a new expanded structure instance.
    Raise TypeError when S is not Structure instance.
    Raise ValueError for invalid mno argument.
    """
    # check arguments
    if len(mno) != 3:
        emsg = "Argument mno must contain 3 numbers."
        raise ValueError, emsg
    elif min(mno) < 1:
        emsg = "Multipliers must be greater or equal 1"
        raise ValueError, emsg
    if not isinstance(S, Structure):
        emsg = "The first argument must be a Structure instance."
        raise TypeError, emsg

    # convert mno to a tuple of integers so it can be used as range limit.
    mno = (int(mno[0]), int(mno[1]), int(mno[2]))

    # create return instance
    newS = Structure(S)
    if mno == (1, 1, 1):
        return newS

    # back to business
    ijklist = [(i,j,k)
                for i in range(mno[0])
                    for j in range(mno[1])
                        for k in range(mno[2])]
    # numpy.floor returns float array
    mnofloats = numpy.array(mno, dtype=float)

    # build a list of new atoms
    newAtoms = []
    for a in S:
        for ijk in ijklist:
            adup = Atom(a)
            adup.xyz = (a.xyz + ijk)/mnofloats
            newAtoms.append(adup)
    # newS can own references in newAtoms, no need to make copies
    newS.__setslice__(0, len(newS), newAtoms, copy=False)

    # take care of lattice parameters
    newS.lattice.setLatPar(
            a=mno[0]*S.lattice.a,
            b=mno[1]*S.lattice.b,
            c=mno[2]*S.lattice.c )
    return newS
コード例 #5
0
    def parseLines(self, lines):
        """Parse list of lines in RAWXYZ 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
        # 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 start >= stop:
            return stru
        # here we have at least one valid record line
        # figure out xyz layout from the first line for plain and raw formats
        floatfields = [isfloat(f) for f in linefields[start]]
        nfields = len(linefields[start])
        if nfields not in (3, 4):
            emsg = ("%d: invalid RAWXYZ format, expected 3 or 4 columns" %
                    (start + 1))
            raise StructureFormatError(emsg)
        if floatfields[:3] == [True, True, True]:
            el_idx, x_idx = (None, 0)
        elif floatfields[:4] == [False, True, True, True]:
            el_idx, x_idx = (0, 1)
        else:
            emsg = "%d: invalid RAWXYZ format" % (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) != nfields:
                    emsg = ('%d: all lines must have ' +
                            'the same number of columns') % p_nl
                    raise StructureFormatError, emsg
                symbol = el_idx is not None and fields[el_idx] or ""
                xyz = [float(f) for f in fields[x_idx:x_idx + 3]]
                if len(xyz) == 2:
                    xyz.append(0.0)
                stru.addNewAtom(symbol, xyz=xyz)
        except ValueError:
            emsg = "%d: invalid number" % p_nl
            exc_type, exc_value, exc_traceback = sys.exc_info()
            raise StructureFormatError, emsg, exc_traceback
        return stru
コード例 #6
0
 def setUp(self):
     # load test structures once
     if TestSuperCell.stru_cdse is None:
         cdsefile = os.path.join(testdata_dir, "CdSe_bulk.stru")
         TestSuperCell.stru_cdse = Structure(filename=cdsefile)
     if TestSuperCell.stru_ni is None:
         nifile = os.path.join(testdata_dir, "Ni.stru")
         TestSuperCell.stru_ni = Structure(filename=nifile)
     # bring them to the instance
     self.stru_cdse = TestSuperCell.stru_cdse
     self.stru_ni = TestSuperCell.stru_ni
     return
コード例 #7
0
    def test_dsaworm(self):
        'Structure: dsaw orm'
        Fe57 = Atom('Fe', mass=57)
        Al = Atom('Al')
        atoms = [Fe57, Al]

        lattice = Lattice(a=1, b=2, c=3, alpha=89, beta=91, gamma=92)

        struct = Structure(atoms=atoms, lattice=lattice)

        orm = self.orm
        structrecord = orm(struct)

        orm.save(struct)

        struct_loaded = orm.load(Structure, structrecord.id)

        props = ['sg', 'description']
        for prop in props:
            self.assertEqual(getattr(struct_loaded, prop),
                             getattr(struct, prop))
            continue

        props = ['a', 'b', 'c', 'alpha', 'beta', 'gamma']
        for prop in props:
            self.assertEqual(getattr(struct_loaded.lattice, prop),
                             getattr(struct.lattice, prop))
            continue

        self.assertEqual(len(struct_loaded), 2)
        for atom in struct_loaded:
            self.assertEqual(atom.__class__, Atom)
        return
コード例 #8
0
 def test_NaI(self):
     """check supercell expansion for Al.
     """       
     at1 = Atom('Na', [0.0, 0.0, 0.0])
     at2 = Atom('Na', [0.0, 0.5, 0.5])
     at3 = Atom('Na', [0.5, 0.0, 0.5])
     at4 = Atom('Na', [0.5, 0.5, 0.0])
     at5 = Atom('I', [0.5, 0.5, 0.5])
     at6 = Atom('I', [0.0, 0.0, 0.5])
     at7 = Atom('I', [0.0, 0.5, 0.0])
     at8 = Atom('I', [0.5, 0.0, 0.0])
     naI = Structure( [ at1, at2, at3, at4, at5, at6, at7, at8], 
                            lattice = Lattice(6.482, 6.482, 6.482, 90, 90, 90),
                            sgid = 225 )
     lines = []
     for sym,pos in zip(naI.symbols, naI.xyz_cartn):
         lines.append( sym+' %f %f %f' % tuple(pos) )
     lines.append('\n')
     naI_sup = supercell(naI, (2,2,2))
     for sym,pos in zip(naI_sup.symbols, naI_sup.xyz_cartn):
         lines.append(sym+' %f %f %f' % tuple(pos))
     expected = open('expected-test_NaI-TestSuperCell').readlines()
     self.assertEqual(len(lines), len(expected))
     for l1, l2 in zip(lines, expected):
         self.assertEqual(l1.strip(), l2.strip())
     return
コード例 #9
0
def makeUnitcell():
    from matter import Atom, Structure, Lattice
    atoms = [Atom('Ni')]
    # positions = [(0,0,0)]
    cellvectors = [ (3.57,0,0), (0,3.57,0), (0,0,3.57) ]
    lattice = Lattice(base=cellvectors)
    return Structure(lattice=lattice, atoms=atoms)
コード例 #10
0
 def __init__(self, *args, **kwargs):
     Structure.__init__(self, *args, **kwargs)
     # do not overwrite self.pdffit, when instantiated as a copy
     # of existing PDFFitStructure
     if not hasattr(self, 'pdffit'):
         self.pdffit = {
             'scale' : 1.0,
             'delta1' : 0.0,
             'delta2' : 0.0,
             'sratio' : 1.0,
             'rcut' : 0.0,
             'spcgr' : 'P1',
             'spdiameter' : 0.0,
             'stepcut' : 0.0,
             'dcell' : 6*[0.0],
             'ncell' : [1, 1, 1, 0],
         }
     return
コード例 #11
0
 def test_rwStr_xcfg_CdSe(self):
     """check conversion to XCFG file format"""
     stru = self.stru
     stru.read(datafile('CdSe_bulk.stru'), 'pdffit')
     s = stru.writeStr(self.format)
     stru = Structure()
     stru.readStr(s, self.format)
     s_els = [a.symbol for a in stru]
     f_els = ['Cd', 'Cd', 'Se', 'Se']
     self.assertEqual(s_els, f_els)
     s_lat = [ stru.lattice.a, stru.lattice.b, stru.lattice.c,
         stru.lattice.alpha, stru.lattice.beta, stru.lattice.gamma ]
     f_lat = [ 4.235204,  4.235204,  6.906027, 90.0, 90.0, 120.0 ]
     self.assertListAlmostEqual(s_lat, f_lat)
     a0 = stru[0]
     s_Uii = [ a0.U[i,i] for i in range(3) ]
     f_Uii = [ 0.01303035, 0.01303035, 0.01401959 ]
     self.assertListAlmostEqual(s_Uii, f_Uii)
コード例 #12
0
 def __init__(self, *args, **kwargs):
     Structure.__init__(self, *args, **kwargs)
     # do not overwrite self.pdffit, when instantiated as a copy
     # of existing PDFFitStructure
     if not hasattr(self, 'pdffit'):
         self.pdffit = {
             'scale': 1.0,
             'delta1': 0.0,
             'delta2': 0.0,
             'sratio': 1.0,
             'rcut': 0.0,
             'spcgr': 'P1',
             'spdiameter': 0.0,
             'stepcut': 0.0,
             'dcell': 6 * [0.0],
             'ncell': [1, 1, 1, 0],
         }
     return
コード例 #13
0
 def test_rwStr_xcfg_CdSe(self):
     """check conversion to XCFG file format"""
     stru = self.stru
     stru.read(datafile('CdSe_bulk.stru'), 'pdffit')
     s = stru.writeStr(self.format)
     stru = Structure()
     stru.readStr(s, self.format)
     s_els = [a.symbol for a in stru]
     f_els = ['Cd', 'Cd', 'Se', 'Se']
     self.assertEqual(s_els, f_els)
     s_lat = [ stru.lattice.a, stru.lattice.b, stru.lattice.c,
         stru.lattice.alpha, stru.lattice.beta, stru.lattice.gamma ]
     f_lat = [ 4.235204,  4.235204,  6.906027, 90.0, 90.0, 120.0 ]
     self.assertListAlmostEqual(s_lat, f_lat)
     a0 = stru[0]
     s_Uii = [ a0.U[i,i] for i in range(3) ]
     f_Uii = [ 0.01303035, 0.01303035, 0.01401959 ]
     self.assertListAlmostEqual(s_Uii, f_Uii)
コード例 #14
0
    def readStr(self, s, format='auto'):
        """Same as Structure.readStr, but update spcgr value in
        self.pdffit when parser can get spacegroup.

        Return instance of StructureParser used to load the data.
        See Structure.readStr() for more info.
        """
        p = Structure.readStr(self, s, format)
        sg = getattr(p, 'spacegroup', None)
        if sg:  self.pdffit['spcgr'] = sg.short_name
        return p
コード例 #15
0
 def test_writeStr_xyz_Supercell(self):
     at1 = Atom('Al', [0.0, 0.0, 0.0])
     at2 = Atom('Al', [0.0, 0.5, 0.5])
     at3 = Atom('Al', [0.5, 0.0, 0.5])
     at4 = Atom('Al', [0.5, 0.5, 0.0])
     self.stru4 = Structure([at1, at2, at3, at4],
                            lattice=Lattice(4.05, 4.05, 4.05, 90, 90, 90),
                            sgid=225)
     from matter.expansion import supercell
     al_333 = supercell(self.stru4, (3, 3, 3))
     s1 = al_333.writeStr(self.format)
コード例 #16
0
    def readStr(self, s, format='auto'):
        """Same as Structure.readStr, but update spcgr value in
        self.pdffit when parser can get spacegroup.

        Return instance of StructureParser used to load the data.
        See Structure.readStr() for more info.
        """
        p = Structure.readStr(self, s, format)
        sg = getattr(p, 'spacegroup', None)
        if sg: self.pdffit['spcgr'] = sg.short_name
        return p
コード例 #17
0
 def test1(self):
     'makeXYZfileContent'
     from matter import Lattice, Atom, Structure
     Al = Atom('Al', (0, 0, 0))
     Fe = Atom('Fe', (0.5, 0.5, 0.5))
     atoms = [Al, Fe]
     lattice = Lattice(1, 1, 1, 90, 90, 90)
     s = Structure(atoms, lattice)
     content = struct_utils.makeXYZfileContent(s, latticeAsDescription=True)
     self.assertEqual(len(content), 4)
     self.assertEqual(int(content[0]), 2)
     self.assertEqual(len(content[1].split(' ')), 9)
     return
コード例 #18
0
 def test_al_supercell(self):
     """check supercell expansion for Al.
     """       
     at1 = Atom('Al', [0.0, 0.0, 0.0])
     at2 = Atom('Al', [0.0, 0.5, 0.5])
     at3 = Atom('Al', [0.5, 0.0, 0.5])
     at4 = Atom('Al', [0.5, 0.5, 0.0])
     self.stru4 = Structure( [ at1, at2, at3, at4], 
                            lattice=Lattice(4.05, 4.05, 4.05, 90, 90, 90),
                            sgid = 225 )
     al_sup = supercell(self.stru4, (3,3,3))
     #print al_sup
     return
コード例 #19
0
 def test_naI_supercell(self):
     """check supercell expansion for Al.
     """
     at1 = Atom('Na', [0.0, 0.0, 0.0])
     at2 = Atom('Na', [0.0, 0.5, 0.5])
     at3 = Atom('Na', [0.5, 0.0, 0.5])
     at4 = Atom('Na', [0.5, 0.5, 0.0])
     at5 = Atom('I', [0.5, 0.5, 0.5])
     at6 = Atom('I', [0.0, 0.0, 0.5])
     at7 = Atom('I', [0.0, 0.5, 0.0])
     at8 = Atom('I', [0.5, 0.0, 0.0])
     naI = Structure([at1, at2, at3, at4, at5, at6, at7, at8],
                     lattice=Lattice(6.482, 6.482, 6.482, 90, 90, 90),
                     sgid=225)
     for sym, pos in zip(naI.symbols, naI.xyz_cartn):
         print sym + ' %f %f %f' % tuple(pos)
     print
     naI_sup = supercell(naI, (2, 2, 2))
     for sym, pos in zip(naI_sup.symbols, naI_sup.xyz_cartn):
         print sym + ' %f %f %f' % tuple(pos)
コード例 #20
0
def save(filename, material):
    for geo in material.get_geos():
        atoms = geo.get_atoms()
        from matter import Structure, Lattice
        import matter.Atom as matterAtom
        for atom in atoms:
            x, y, z = atom.get_xyz()
            atno = atom.get_atno()
            atoms.append(matterAtom(symbol[atno], [x, y, z]))
        cell = geo.get_cell()
        a, b, c, alph, bet, gam = cell.abcabg
        lattice = Lattice(a, b, c, alph, bet, gam)
        stru = Structure(atoms, lattice)
    import pickle
    output = open(filename, 'wb')
    from Utilities import assureCorrectFileEnding
    filename = assureCorrectFileEnding(filename, 'pkl')
    pickle.dump(stru, output)
    output.close()

    return
コード例 #21
0
    def testWriter(self):
        p = getParser()
        import matter
        a = 1.5
        lattice = matter.Lattice(2 * a, 2 * a, 2 * a, 90, 90, 90)
        atoms = [matter.Atom('Ni'), matter.Atom('Ni', (0.5, 0.5, 0.5))]
        struct = Structure(lattice=lattice, atoms=atoms, sgid=229)

        print 'original unitcell, cartesian coords'
        print '\n'.join(p.toLines(struct))

        print 'original unitcell, fractional coords'
        print '\n'.join(p.toLines(struct, use_fractional_coordinates=1))

        print 'primitive unitcell, cartesian coords'
        print '\n'.join(p.toLines(struct, use_primitive_unitcell=1))

        print 'primitive unitcell, fractional coords'
        print '\n'.join(
            p.toLines(struct,
                      use_primitive_unitcell=1,
                      use_fractional_coordinates=1))

        return
コード例 #22
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 = map(float, linefields[start+1])
                    assert len(latticeVecs)==9
                    from matter.Lattice import Lattice
                    reshaped = [latticeVecs[0:3], latticeVecs[3:6], latticeVecs[6:9]]
                    stru.lattice = Lattice(base=reshaped) 
                    needsDescription = True
                except:
                    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, 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, charge=charge)
        except ValueError:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            emsg = "%d: invalid number format" % p_nl
            raise StructureFormatError, emsg, 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
コード例 #23
0
    def test_load_matter(self):
        from matter import Structure, Atom, Lattice
        at1 = Atom('V', [0., 0., 0.])
        at2 = Atom('V', [0.5, 0., 0.])
        at3 = Atom('V', [0., 0.5, 0.])
        at4 = Atom('V', [0., 0., 0.5])
        at5 = Atom('V', [0.5, 0.5, 0.])
        at6 = Atom('V', [0., 0.5, 0.5])
        at7 = Atom('V', [0.5, 0., 0.5])
        at8 = Atom('V', [0.5, 0.5, 0.5])
        at9 = Atom('V', [0.25, 0.25, 0.25])
        at10 = Atom('Fe', [0.75, 0.25, 0.25])
        at11 = Atom('V', [0.75, 0.75, 0.25])
        at12 = Atom('Fe', [0.25, 0.75, 0.25])
        at13 = Atom('Fe', [0.25, 0.25, 0.75])
        at14 = Atom('V', [0.75, 0.25, 0.75])
        at15 = Atom('Fe', [0.75, 0.75, 0.75])
        at16 = Atom('V', [0.25, 0.75, 0.75])
        a = 2. * 5.663 / 1.889725989  # set a in angstrom
        struct = Structure( [ at1, at2, at3, at4, at5, at6, at7, at8, at9, \
                             at10, at11, at12, at13, at14, at15, at16], \
                             lattice = Lattice(a, a, a, 90, 90, 90))
        #print struct
        massList = [50.9415, 55.847]
        psList = ['V.pbe-n-van.UPF', 'Fe.pbe-nd-rrkjus.UPF']
        #self.input.structure.load(structure = struct, ibrav = 2, massList = massList, psList = psList)
        self.input.structure.load(structure=struct,
                                  ibrav=2,
                                  massList=massList,
                                  psList=psList)
        answer1 = """"Face Centered Cubic" cell:
-5.66300000  0.00000000  5.66300000
 0.00000000  5.66300000  5.66300000
-5.66300000  5.66300000  0.00000000

Atomic positions in units of lattice parametr "a":
V       0.00000000  0.00000000  0.00000000  
V       0.50000000  0.00000000  0.00000000  
V       0.25000000  0.25000000  0.25000000  
Fe      0.75000000  0.25000000  0.25000000  

V   50.9415 V.pbe-n-van.UPF
Fe  55.8470 Fe.pbe-nd-rrkjus.UPF
"""
        #print str(self.input.structure)
        self.assertEqual(str(self.input.structure), answer1)
        at1 = Atom('V', [0., 0., 0.])
        at2 = Atom('V', [0.5, 0., 0.])
        at3 = Atom('V', [0., 0.5, 0.])
        at4 = Atom('V', [0., 0., 0.5])
        at5 = Atom('V', [0.5, 0.5, 0.])
        at6 = Atom('V', [0., 0.5, 0.5])
        at7 = Atom('V', [0.5, 0., 0.5])
        at8 = Atom('V', [0.5, 0.5, 0.5])
        at9 = Atom('V', [0.25, 0.25, 0.25])
        at10 = Atom('Fe', [0.75, 0.25, 0.25])
        at11 = Atom('V', [0.75, 0.75, 0.25])
        at12 = Atom('Fe', [0.25, 0.75, 0.25])
        at13 = Atom('Fe', [0.25, 0.25, 0.75])
        at14 = Atom('V', [0.75, 0.25, 0.75])
        at15 = Atom('Fe', [0.75, 0.75, 0.75])
        at16 = Atom('V', [0.25, 0.75, 0.75])
        a = 2. * 5.663 / 1.889725989  # set a in angstrom
        struct2 = Structure( [ at1, at2, at3, at4, at5, at6, at7, at8, at9, \
                             at10, at11, at12, at13, at14, at15, at16], \
                             lattice = Lattice(a, a, a, 90, 90, 90))
        self.input.structure.load(structure=struct2,
                                  massList=massList,
                                  psList=psList)
        answer2 = """"generic" cell:
 11.32600000  0.00000000  0.00000000
 0.00000000  11.32600000  0.00000000
 0.00000000  0.00000000  11.32600000

Atomic positions in units of lattice parametr "a":
V       0.00000000  0.00000000  0.00000000  
V       2.99673076  0.00000000  0.00000000  
V       0.00000000  2.99673076  0.00000000  
V       0.00000000  0.00000000  2.99673076  
V       2.99673076  2.99673076  0.00000000  
V       0.00000000  2.99673076  2.99673076  
V       2.99673076  0.00000000  2.99673076  
V       2.99673076  2.99673076  2.99673076  
V       1.49836538  1.49836538  1.49836538  
Fe      4.49509614  1.49836538  1.49836538  
V       4.49509614  4.49509614  1.49836538  
Fe      1.49836538  4.49509614  1.49836538  
Fe      1.49836538  1.49836538  4.49509614  
V       4.49509614  1.49836538  4.49509614  
Fe      4.49509614  4.49509614  4.49509614  
V       1.49836538  4.49509614  4.49509614  

V   50.9415 V.pbe-n-van.UPF
Fe  55.8470 Fe.pbe-nd-rrkjus.UPF
"""
        #print str(self.input.structure)
        self.assertEqual(str(self.input.structure), answer2)
コード例 #24
0
def makeMatter():
    from matter import Structure, Atom, Lattice
    atoms = [Atom('Fe', xyz=(0, 0, 0)), Atom('Al', xyz=(0.5, 0.5, 0.5))]
    lattice = Lattice(base=((1., 0, 0), (0, 1., 0), (0, 0, 1.)))
    return Structure(atoms, lattice)
コード例 #25
0
        d = sum(darray)**0.5

        # Discard atom if (x/a)**2 + (y/b)**2 + (z/c)**2 > 1
        if d > 1:
            delList.append(j)

    for i in delList:
        newS.pop(i)

    return newS

if __name__ == "__main__":

    import os.path
    datadir = "../../tests/testdata"
    S = Structure()
    S.read(os.path.join(datadir, "CdSe_bulk.stru"), "pdffit")
    newS = makeEllipsoid(S, 12)
    newS.write("CdSe_d24.stru", "pdffit")
    newS = makeEllipsoid(S, 20, 10, 10)
    newS.write("CdSe_a20_b10_c10.stru", "pdffit")
    newS = makeEllipsoid(S, 20, 15, 10)
    newS.write("CdSe_a20_b15_c10.stru", "pdffit")
    S = Structure()
    S.read(os.path.join(datadir, "Ni.stru"), "pdffit")
    newS = makeEllipsoid(S, 10)
    newS.write("Ni_d20.stru", "pdffit")
    newS = makeEllipsoid(S, 20, 4)
    newS.write("Ni_a20_b4_c20.stru", "pdffit")
    newS = makeEllipsoid(S, 20, 15, 10)
    newS.write("Ni_a20_b15_c10.stru", "pdffit")
コード例 #26
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
# USA

# read and view pickled structure object
from matter import Structure, Lattice, Atom
at1 = Atom('C', [0.333333333333333, 0.666666666666667, 0])
at2 = Atom('C', [0.666666666666667, 0.333333333333333, 0])
a = 2.4612
c = 6.7079
graphite = Structure([at1, at2], lattice=Lattice(a, a, c, 90, 90, 120))
print graphite

import pickle
output = open('graphite.pkl', 'wb')
pickle.dump(graphite, output)
output.close()

pkl_file = open('graphite.pkl', 'rb')
g2 = pickle.load(pkl_file)
print g2

#m2 = create_nanotube(10,10,10)
#save_file("nano.xyz", m2)

#atoms = m1.get_atoms()
コード例 #27
0
    def parseLines(self, lines):
        """Parse list of lines in PDB format.

        Return Structure object or raise StructureFormatError.
        """
        xcfg_Number_of_particles = None
        xcfg_A = None
        xcfg_H0 = numpy.zeros((3,3), dtype=float)
        xcfg_H0_set = numpy.zeros((3,3), dtype=bool)
        xcfg_NO_VELOCITY = False
        xcfg_entry_count = None
        xcfg_auxiliary = []
        p_nl = 0
        p_auxiliary_re = re.compile(r"^auxiliary\[(\d+)\] =")
        p_auxiliary = {}
        try:
            stru = Structure()
            # ignore trailing blank lines
            stop = len(lines)
            while stop>0 and lines[stop-1].strip() == "":
                stop -= 1
            ilines = iter(lines[:stop])
            # read XCFG header
            for line in ilines:
                p_nl += 1
                stripped_line = line.strip()
                # blank lines and lines starting with # are ignored
                if stripped_line == "" or line[0] == '#':
                    continue
                elif xcfg_Number_of_particles is None:
                    if line.find("Number of particles =") != 0:
                        emsg = ("%d: first line must " +
                                "contain 'Number of particles ='") % p_nl
                        raise StructureFormatError(emsg)
                    xcfg_Number_of_particles = int(line[21:].split(None, 1)[0])
                    p_natoms = xcfg_Number_of_particles
                elif line.find("A =") == 0:
                    xcfg_A = float(line[3:].split(None, 1)[0])
                elif line.find("H0(") == 0:
                    i, j = ( int(line[3])-1 ,  int(line[5])-1 )
                    xcfg_H0[i,j] = float(line[10:].split(None, 1)[0])
                    xcfg_H0_set[i,j] = True
                elif line.find(".NO_VELOCITY.") == 0:
                    xcfg_NO_VELOCITY = True
                elif line.find("entry_count =") == 0:
                    xcfg_entry_count = int(line[13:].split(None, 1)[0])
                elif p_auxiliary_re.match(line):
                    m = p_auxiliary_re.match(line)
                    idx = int(m.group(1))
                    p_auxiliary[idx] = line[m.end():].split(None, 1)[0]
                else:
                    break
            # check header for consistency
            if numpy.any(xcfg_H0_set == False):
                emsg = "H0 tensor is not properly defined"
                raise StructureFormatError(emsg)
            p_auxnum = len(p_auxiliary) and max(p_auxiliary.keys())+1
            for i in range(p_auxnum):
                if not i in p_auxiliary:
                    p_auxiliary[i] = "aux%d" % i
            sorted_aux_keys = p_auxiliary.keys()
            sorted_aux_keys.sort()
            if p_auxnum != 0:
                stru.xcfg = {
                    'auxiliaries' : [ p_auxiliary[k]
                                      for k in sorted_aux_keys ]
                }
            if 6-3*xcfg_NO_VELOCITY+len(p_auxiliary) != xcfg_entry_count:
                emsg = ("%d: auxiliary fields " +
                        "not consistent with entry_count") % p_nl
                raise StructureFormatError(emsg)
            # define proper lattice
            stru.lattice.setLatBase(xcfg_H0)
            # build p_assign_atom function to assign entries to proper fields
            p_exprs = [ "a.xyz[0]=fields[0]",
                        "a.xyz[1]=fields[1]",
                        "a.xyz[2]=fields[2]" ]
            if not xcfg_NO_VELOCITY:
                p_exprs += [  "a.v=numpy.zeros(3, dtype=float)",
                              "a.v[0]=fields[3]",
                              "a.v[1]=fields[4]",
                              "a.v[2]=fields[5]" ]
            for idx in sorted_aux_keys:
                prop = p_auxiliary[idx]
                col = idx + 6 - 3*xcfg_NO_VELOCITY
                if prop == "Uiso":
                    p_exprs.append("a.U[0,0]=a.U[1,1]=a.U[2,2]=" +
                        "fields[%d]" % col)
                elif re.match(r"^U\d\d$", prop) \
                and 1<=int(prop[1])<=3 and 1<=int(prop[2])<=3 :
                    i, j = int(prop[1])-1, int(prop[2])-1
                    if i==j:
                        p_exprs.append("a.U[%i,%i]=fields[%d]" % (i, j, col) )
                    else:
                        p_exprs.append("a.U[%i,%i]=a.U[%i,%i]=fields[%d]" % \
                                (i, j, j, i, col) )
                else:
                    p_exprs.append( "a.__dict__[%r]=fields[%d]" % \
                            (prop, col) )
            p_assign_expr = "pass; " + "; ".join(p_exprs[3:])
            exec "def p_assign_atom(a, fields) : %s" % p_assign_expr
            # here we are inside data
            p_element = None
            p_nl -= 1
            for line in lines[p_nl:stop]:
                p_nl += 1
                words = line.split()
                # ignore atom mass
                if len(words) == 1 and isfloat(words[0]):
                    continue
                # parse element allowing empty symbol
                elif len(words) <= 1:
                    w = line.strip()
                    p_element = w[:1].upper() + w[1:].lower()
                elif len(words) == xcfg_entry_count and p_element is not None:
                    fields = [ float(w) for w in words ]
                    stru.addNewAtom(p_element, fields[:3])
                    a = stru.getLastAtom()
                    a.xyz *= xcfg_A
                    p_assign_atom(a, fields)
                else:
                    emsg = "%d: invalid record" % p_nl
                    raise StructureFormatError(emsg)
            if len(stru) != p_natoms:
                emsg = "expected %d atoms, read %d" % (p_natoms, len(stru))
                raise StructureFormatError(emsg)
        except (ValueError, IndexError):
            emsg = "%d: file is not in XCFG format" % p_nl
            exc_type, exc_value, exc_traceback = sys.exc_info()
            raise StructureFormatError, emsg, exc_traceback
        return stru
コード例 #28
0
    def parseLines(self, lines):
        """Parse list of lines in PDB format.

        Return Structure object or raise StructureFormatError.
        """
        xcfg_Number_of_particles = None
        xcfg_A = None
        xcfg_H0 = numpy.zeros((3, 3), dtype=float)
        xcfg_H0_set = numpy.zeros((3, 3), dtype=bool)
        xcfg_NO_VELOCITY = False
        xcfg_entry_count = None
        xcfg_auxiliary = []
        p_nl = 0
        p_auxiliary_re = re.compile(r"^auxiliary\[(\d+)\] =")
        p_auxiliary = {}
        try:
            stru = Structure()
            # ignore trailing blank lines
            stop = len(lines)
            while stop > 0 and lines[stop - 1].strip() == "":
                stop -= 1
            ilines = iter(lines[:stop])
            # read XCFG header
            for line in ilines:
                p_nl += 1
                stripped_line = line.strip()
                # blank lines and lines starting with # are ignored
                if stripped_line == "" or line[0] == '#':
                    continue
                elif xcfg_Number_of_particles is None:
                    if line.find("Number of particles =") != 0:
                        emsg = ("%d: first line must " +
                                "contain 'Number of particles ='") % p_nl
                        raise StructureFormatError(emsg)
                    xcfg_Number_of_particles = int(line[21:].split(None, 1)[0])
                    p_natoms = xcfg_Number_of_particles
                elif line.find("A =") == 0:
                    xcfg_A = float(line[3:].split(None, 1)[0])
                elif line.find("H0(") == 0:
                    i, j = (int(line[3]) - 1, int(line[5]) - 1)
                    xcfg_H0[i, j] = float(line[10:].split(None, 1)[0])
                    xcfg_H0_set[i, j] = True
                elif line.find(".NO_VELOCITY.") == 0:
                    xcfg_NO_VELOCITY = True
                elif line.find("entry_count =") == 0:
                    xcfg_entry_count = int(line[13:].split(None, 1)[0])
                elif p_auxiliary_re.match(line):
                    m = p_auxiliary_re.match(line)
                    idx = int(m.group(1))
                    p_auxiliary[idx] = line[m.end():].split(None, 1)[0]
                else:
                    break
            # check header for consistency
            if numpy.any(xcfg_H0_set == False):
                emsg = "H0 tensor is not properly defined"
                raise StructureFormatError(emsg)
            p_auxnum = len(p_auxiliary) and max(p_auxiliary.keys()) + 1
            for i in range(p_auxnum):
                if not i in p_auxiliary:
                    p_auxiliary[i] = "aux%d" % i
            sorted_aux_keys = p_auxiliary.keys()
            sorted_aux_keys.sort()
            if p_auxnum != 0:
                stru.xcfg = {
                    'auxiliaries': [p_auxiliary[k] for k in sorted_aux_keys]
                }
            if 6 - 3 * xcfg_NO_VELOCITY + len(p_auxiliary) != xcfg_entry_count:
                emsg = ("%d: auxiliary fields " +
                        "not consistent with entry_count") % p_nl
                raise StructureFormatError(emsg)
            # define proper lattice
            stru.lattice.setLatBase(xcfg_H0)
            # build p_assign_atom function to assign entries to proper fields
            p_exprs = [
                "a.xyz[0]=fields[0]", "a.xyz[1]=fields[1]",
                "a.xyz[2]=fields[2]"
            ]
            if not xcfg_NO_VELOCITY:
                p_exprs += [
                    "a.v=numpy.zeros(3, dtype=float)", "a.v[0]=fields[3]",
                    "a.v[1]=fields[4]", "a.v[2]=fields[5]"
                ]
            for idx in sorted_aux_keys:
                prop = p_auxiliary[idx]
                col = idx + 6 - 3 * xcfg_NO_VELOCITY
                if prop == "Uiso":
                    p_exprs.append("a.U[0,0]=a.U[1,1]=a.U[2,2]=" +
                                   "fields[%d]" % col)
                elif re.match(r"^U\d\d$", prop) \
                and 1<=int(prop[1])<=3 and 1<=int(prop[2])<=3 :
                    i, j = int(prop[1]) - 1, int(prop[2]) - 1
                    if i == j:
                        p_exprs.append("a.U[%i,%i]=fields[%d]" % (i, j, col))
                    else:
                        p_exprs.append("a.U[%i,%i]=a.U[%i,%i]=fields[%d]" % \
                                (i, j, j, i, col) )
                else:
                    p_exprs.append( "a.__dict__[%r]=fields[%d]" % \
                            (prop, col) )
            p_assign_expr = "pass; " + "; ".join(p_exprs[3:])
            exec "def p_assign_atom(a, fields) : %s" % p_assign_expr
            # here we are inside data
            p_element = None
            p_nl -= 1
            for line in lines[p_nl:stop]:
                p_nl += 1
                words = line.split()
                # ignore atom mass
                if len(words) == 1 and isfloat(words[0]):
                    continue
                # parse element allowing empty symbol
                elif len(words) <= 1:
                    w = line.strip()
                    p_element = w[:1].upper() + w[1:].lower()
                elif len(words) == xcfg_entry_count and p_element is not None:
                    fields = [float(w) for w in words]
                    stru.addNewAtom(p_element, fields[:3])
                    a = stru.getLastAtom()
                    a.xyz *= xcfg_A
                    p_assign_atom(a, fields)
                else:
                    emsg = "%d: invalid record" % p_nl
                    raise StructureFormatError(emsg)
            if len(stru) != p_natoms:
                emsg = "expected %d atoms, read %d" % (p_natoms, len(stru))
                raise StructureFormatError(emsg)
        except (ValueError, IndexError):
            emsg = "%d: file is not in XCFG format" % p_nl
            exc_type, exc_value, exc_traceback = sys.exc_info()
            raise StructureFormatError, emsg, exc_traceback
        return stru
コード例 #29
0
 def setUp(self):
     self.stru = Structure()
     self.format = "xcfg"
     self.places = 6
コード例 #30
0
 def setUp(self):
     self.stru = Structure()
     self.format = "pdb"
     self.places = 3
コード例 #31
0
 def setUp(self):
     self.stru = Structure()
     self.format = "rawxyz"
コード例 #32
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 = map(float, linefields[start + 1])
                    assert len(latticeVecs) == 9
                    from matter.Lattice import Lattice
                    reshaped = [
                        latticeVecs[0:3], latticeVecs[3:6], latticeVecs[6:9]
                    ]
                    stru.lattice = Lattice(base=reshaped)
                    needsDescription = True
                except:
                    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, 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, charge=charge)
        except ValueError:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            emsg = "%d: invalid number format" % p_nl
            raise StructureFormatError, emsg, 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
コード例 #33
0
    from geometry.composites import cuboctahedron
    from geometry.operations import translate, rotate
    c0 = translate(cuboctahedron(dist), lat.cartesian(newS[ncenter].xyz))

    # Cut out an octahedron
    from geometry import locate

    N = len(newS)
    j = N
    for i in xrange(N):

        xyz = lat.cartesian(newS[N - 1 - i].xyz)
        if locate(xyz, c0) == 1:
            newS.pop(N - 1 - i)

    return newS


if __name__ == "__main__":

    import os.path
    datadir = "../../../tests/testdata"
    S = Structure()
    S.read(os.path.join(datadir, "CdSe_bulk.stru"), "pdffit")
    newS = makeCuboctahedron(S, 12)
    newS.write("CdSe_cuboct24.stru", "pdffit")
    S = Structure()
    S.read(os.path.join(datadir, "Ni.stru"), "pdffit")
    newS = makeCuboctahedron(S, 10)
    newS.write("Ni_cuboct20.stru", "pdffit")
コード例 #34
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)
                stru.title = 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, 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:
            emsg = "%d: invalid XYZ format, expected 4 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) != nfields:
                    emsg = ('%d: all lines must have ' +
                            'the same number of columns') % p_nl
                    raise StructureFormatError(emsg)
                symbol = fields[0]
                symbol = symbol[0].upper() + symbol[1:].lower()
                xyz = [ float(f) for f in fields[1:4] ]
                stru.addNewAtom(symbol, xyz=xyz)
        except ValueError:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            emsg = "%d: invalid number format" % p_nl
            raise StructureFormatError, emsg, 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)
        return stru
コード例 #35
0
 def setUp(self):
     self.stru = Structure()
     self.format = 'xyz'
     import tempfile
     handle, self.tmpname = tempfile.mkstemp()
     os.close(handle)
コード例 #36
0
    def parseLines(self, lines):
        """Parse list of lines in PDB format.

        Return Structure instance or raise StructureFormatError.
        """
        try:
            stru = Structure()
            scale = numpy.identity(3, dtype=float)
            scaleU = numpy.zeros(3, dtype=float)
            p_nl = 0
            for line in lines:
                p_nl += 1
                # skip blank lines
                if not line.strip():    continue
                # make sure line has 80 characters
                if len(line) < 80:
                    line = "%-80s" % line
                words = line.split()
                record = words[0]
                if record == "TITLE":
                    continuation = line[8:10]
                    if continuation.strip():
                        stru.description += line[10:].rstrip()
                    else:
                        stru.description = line[10:].rstrip()
                elif record == "CRYST1":
                    a = float(line[7:15])
                    b = float(line[15:24])
                    c = float(line[24:33])
                    alpha = float(line[33:40])
                    beta = float(line[40:47])
                    gamma = float(line[47:54])
                    stru.lattice.setLatPar(a, b, c, alpha, beta, gamma)
                    scale = numpy.transpose(stru.lattice.recbase)
                elif record == "SCALE1":
                    sc = numpy.zeros((3,3), dtype=float)
                    sc[0,:] = [float(x) for x in line[10:40].split()]
                    scaleU[0] = float(line[45:55])
                elif record == "SCALE2":
                    sc[1,:] = [float(x) for x in line[10:40].split()]
                    scaleU[1] = float(line[45:55])
                elif record == "SCALE3":
                    sc[2,:] = [float(x) for x in line[10:40].split()]
                    scaleU[2] = float(line[45:55])
                    base = numpy.transpose(numpy.linalg.inv(sc))
                    abcABGcryst = numpy.array(stru.lattice.abcABG())
                    stru.lattice.setLatBase(base)
                    abcABGscale = numpy.array(stru.lattice.abcABG())
                    reldiff = numpy.fabs(1.0 - abcABGscale/abcABGcryst)
                    if not numpy.all(reldiff < self.epsilon):
                        emsg = "%d: " % p_nl + \
                                "SCALE and CRYST1 are not consistent."
                        raise StructureFormatError(emsg)
                    if numpy.any(scaleU != 0.0):
                        emsg = "Origin offset not yet implemented."
                        raise NotImplementedError(emsg)
                elif record in ("ATOM", "HETATM"):
                    name = line[12:16].strip()
                    rc = [float(x) for x in line[30:54].split()]
                    xyz = numpy.dot(scale, rc) + scaleU
                    try:
                        occupancy = float(line[54:60])
                    except ValueError:
                        occupancy = 1.0
                    try:
                        B = float(line[60:66])
                        U = numpy.identity(3)*B/(8*pi**2)
                    except ValueError:
                        U = numpy.zeros((3,3), dtype=float)
                    symbol = line[76:78].strip()
                    if symbol == "":
                        # get symbol from the first 2 characters of name
                        symbol = line[12:14].strip()
                        symbol = symbol[0].upper() + symbol[1:].lower()
                    #stru.addNewAtom(symbol, occupancy=occupancy, name=name, U=U)
                    stru.addNewAtom(symbol, occupancy=occupancy, label=name, U=U)
                    last_atom = stru.getLastAtom()
                    last_atom.xyz_cartn = rc
                elif record == "SIGATM":
                    sigrc = [float(x) for x in line[30:54].split()]
                    sigxyz = numpy.dot(scale, sigrc)
                    try:
                        sigo = float(line[54:60])
                    except ValueError:
                        sigo = 0.0
                    try:
                        sigB = float(line[60:66])
                        sigU = numpy.identity(3)*sigB/(8*pi**2)
                    except ValueError:
                        sigU = numpy.zeros((3,3), dtype=float)
                    last_atom.sigxyz = sigxyz
                    last_atom.sigo = sigo
                    last_atom.sigU = sigU
                elif record == "ANISOU":
                    Uij = [ float(x)*1.0e-4 for x in line[28:70].split() ]
                    for i in range(3):
                        last_atom.U[i,i] = Uij[i]
                    last_atom.U[0,1] = last_atom.U[1,0] = Uij[3]
                    last_atom.U[0,2] = last_atom.U[2,0] = Uij[4]
                    last_atom.U[1,2] = last_atom.U[2,1] = Uij[5]
                elif record == "SIGUIJ":
                    sigUij = [ float(x)*1.0e-4 for x in line[28:70].split() ]
                    for i in range(3):
                        last_atom.sigU[i,i] = sigUij[i]
                    last_atom.sigU[0,1] = last_atom.sigU[1,0] = sigUij[3]
                    last_atom.sigU[0,2] = last_atom.sigU[2,0] = sigUij[4]
                    last_atom.sigU[1,2] = last_atom.sigU[2,1] = sigUij[5]
                elif record in P_pdb.validRecords:
                    pass
                else:
                    emsg = "%d: invalid record name '%r'" % (p_nl, record)
                    raise StructureFormatError(emsg)
        except (ValueError, IndexError):
            emsg = "%d: invalid PDB record" % p_nl
            exc_type, exc_value, exc_traceback = sys.exc_info()
            raise StructureFormatError, emsg, exc_traceback
        return stru
コード例 #37
0
def testMatter():

    pwInput = PWInput(config=testSCFString)

    struct = matter.Structure()
    struct.read('data/graphite.cif', format='cif')
    #struct.read('data/PbTe.cif', format='cif')
    #struct.read('data/Ni.stru', format='pdffit')
    #struct.read('data/CdSe-wurtzite.stru', format='pdffit')

    print struct
    print struct.lattice.base

    #struct = Structure(filename='data/Ni.stru')
    #struct = Structure(filename='data/graphite.cif')
    #struct = Structure(filename='data/PbTe.cif')
    #struct = Structure(filename='data/CdSe-wurtzite.stru')
    #struct = Structure(pbte)

    # does not work well in matter:
    #s = pbte.writeStr(format='cif')

    at1 = Atom('V', [0., 0., 0.])
    at2 = Atom('V', [0.5, 0., 0.])
    at3 = Atom('V', [0., 0.5, 0.])
    at4 = Atom('V', [0., 0., 0.5])
    at5 = Atom('V', [0.5, 0.5, 0.])
    at6 = Atom('V', [0., 0.5, 0.5])
    at7 = Atom('V', [0.5, 0., 0.5])
    at8 = Atom('V', [0.5, 0.5, 0.5])

    at9 = Atom('V', [0.25, 0.25, 0.25])
    at10 = Atom('Fe', [0.75, 0.25, 0.25])
    at11 = Atom('V', [0.75, 0.75, 0.25])
    at12 = Atom('Fe', [0.25, 0.75, 0.25])

    at13 = Atom('Fe', [0.25, 0.25, 0.75])
    at14 = Atom('V', [0.75, 0.25, 0.75])
    at15 = Atom('Fe', [0.75, 0.75, 0.75])
    at16 = Atom('V', [0.25, 0.75, 0.75])
    struct2 = Structure([
        at1, at2, at3, at4, at5, at6, at7, at8, at9, at10, at11, at12, at13,
        at14, at15, at16
    ],
                        lattice=Lattice(2, 2, 2, 90, 90, 90))
    #print struct
    massList = [50., 55.]
    psList = ['ps1', 'ps2']

    #massList = [1, 2, 3, 4, 5, 6,1, 2, 3, 4, 5, 6]
    #psList  = ['ps1', 'ps2', 'ps2', 'ps3', 'ps4','ps1', 'ps2', 'ps2', 'ps3', 'ps4']

    #    pwInput.structure.load(ibrav = 0, structure = struct, \
    #                           massList = massList, psList = psList)

    #pwInput.structure.load(structure = struct )

    #print pwInput.structure.atomLabels()

    pwInput.structure.load(structure = struct, ibrav = 2, \
                           massList = massList, psList = psList)

    #    pwInput.structure.setStructureFromDiffpyStructure(struct, \
    #                                                            massList = massList,\
    #                                                            psList = psList)

    #    pwInput.structure.setReducedStructureFromDiffpyStructure(struct, ibrav = 2, \
    #                                                            massList = massList,\
    #                                                            psList = psList)
    # this will update string s:
    #s = ''
    #s = pwInput.structure.toString(string = s)

    #pwInput.removeNamelist('system')
    #pwInput.removeCard('atomic_species')
    #pwInput.removeCard('atomic_positions')
    #pwInput.removeCard('cell_parameters')
    #pwInput.structure.parseInput()

    s = pwInput.structure.toString()

    #pwInput.structure.atomicPositionsType = 'alat'

    #s = pwInput.structure.toString()

    #pwInput.structure.save('scf.in')

    print s