def setAtomsAndConnections(self):

        ignore = []
        atom_numbers = []
        Hs = []

        for line in self.lines:
            if line.split()[0].startswith("ATOM") and len(line.strip()) > 20:
                atom = Atom(line)
                atom_numbers.append(int(atom.id))

                self.graph.add_node(atom.getID())
                a = Atom(line)

                self.atoms[int(a.getID())] = a

                if a.atomname.__contains__("H"):
                    self.atoms[int(a.getID())].atomtype = "HD"
                    Hs.append(a)

        for key in self.atoms.keys():
            atom = self.atoms[key]
            if atom.atomname == "O":
                for H in Hs:
                    if distance(atom.getXYZ(), H.getXYZ()) < 1.5:
                        print("or here")
                        self.atoms[int(H.getID())].atomname = "HD"
                        self.atoms[int(atom.getID())].atomname = "OA"

            if atom.atomname == "N":
                for H in Hs:
                    if distance(atom.getXYZ(), H.getXYZ()) < 1.5:
                        print("here")
                        self.atoms[int(H.getID())].atomname = "HD"
示例#2
0
    def setAtomsAndConnections(self):

        ignore = []
        atom_numbers = []

        for line in self.lines:
            if (line.split()[0].startswith("ATOM")
                    or line.split()[0].startswith("HETATM")) and len(
                        line.strip()) > 20:
                atom = Atom(line)
                atom_numbers.append(atom.id)
                if not atom.atom_type.__contains__("H"):
                    self.graph.add_node(atom.getID())
                    a = Atom(line)
                    self.atoms[int(a.getID())] = a
                else:
                    ignore.append(int(atom.getID()))

            elif line.startswith("CONECT"):
                split = line.split()
                if int(split[1]) in atom_numbers:
                    for connection in split[2:]:
                        if int(connection) not in ignore and int(
                                split[1]) not in ignore:
                            self.atoms[int(line.split()[1])].add_connection(
                                int(connection))
                            self.graph.add_edge(int(split[1]), int(connection))
def test_disp100(nq, ne):
    """Calculates the scattering intensity for phonon dispersions
    for B2 FeAl along q // [100].
    nq = number of q points to calculate.
    ne = number of e points to calculate."""

    uc = UnitCell()
    at1 = Atom(symbol='Fe', mass=57)
    pos1 = (0.0, 0.0, 0.0)
    at2 = Atom(symbol='Al')
    pos2 = (0.5, 0.5, 0.5)
    site1 = Site(pos1, at1)
    site2 = Site(pos2, at2)
    uc.addAtom(at1, pos1, "Fe1")
    uc.addAtom(at2, pos2, "Al1")
    print uc

    kptlist = uc.getMonkhorstPackGrid((20, 20, 20)).reshape(8000, 3)
    sqecalc = AbInitio.kernelGenerator.SqeCalculator.SqeCalculator(
        uc, kpoints=kptlist)

    sqecalc.readIDFeigenvectors(filename='pols_FeAl222.idf')
    sqecalc.readEigenvaluesFromIDFomega2(filename='omega2_FeAl222.idf')

    sqecalc._DebyeWallerCalculator._energies = sqecalc._energies
    sqecalc._DebyeWallerCalculator._polvecs = sqecalc._polvecs

    estart = 0.0
    deltae = 50.0 / ne
    sqecalc._etransferTol = deltae

    deltaqx = 3.0 / nq
    sqecalc._qtransferTolRadius = deltaqx
    qstart = numpy.array([0.0, 0.0, 0.0])
    deltaq = numpy.array([deltaqx, 0.0, 0.0])

    sqe = numpy.zeros((nq, ne), dtype='float')

    for iq in range(nq):
        for ie in range(ne):
            qtransfer = qstart + iq * deltaq
            etransfer = estart + ie * deltae
            sqe[iq,
                ie] = sqecalc.calcSqeCohCreateAllmodes(qtransfer, etransfer)
            print iq, ie, sqe[iq, ie]

    pylab.imshow(sqe)
    pylab.show()
    end = raw_input()
    return
示例#4
0
    def create_atom(self, path="atom", weight=1.0, \
                    label_type = Events.AbstractLabel, contents_type=Events.AbstractContents, event_type=Events.AbstractEvent, \
                    activity_type = ActivityPatterns.ClassicActivityPattern, memory_type = MemorySpaces.NGramMemorySpace,
                    memory_file = None):
        '''creating an atom at required path'''
        atom = None
        if ":" in path:
            head, tail = Tools.parse_path(path)  # if atom in a sub-streamview
            atom = self.atoms[head].add_atom(tail, weight, label_type,
                                             contents_type, event_type,
                                             activity_type, memory_type)
            print "[ERROR] Could not add atom {0} in streamview {1}".format(
                path, self.name)

        else:
            # if atom is directly in current streamview
            if path in self.atoms:
                print "[ERROR] Atom {0} already existing in {1}".format(
                    path, self.name)
            else:
                atom = Atom.Atom(path, weight, label_type, contents_type,
                                 event_type, activity_type, memory_type,
                                 memory_file)
                self.atoms[path] = atom
        return atom
示例#5
0
文件: Reader.py 项目: arghya90/BION
def read_PQR_into_atomList(arg_pqrFile):
    """ Read lines from a PQR file and creates instances of Class Atom
    for each of them. Make a list of these instances and return it. """
    atomSerial = 0
    atomList = []
    with open(arg_pqrFile, 'r') as fPQR:
        for line in fPQR:
            line = line.strip()
            if line.startswith("ATOM") or line.startswith("HETATM"):
                atomSerial += 1
                atomArgs = {
                            'header'      : line[0:6].strip(),
                            'index'       : int(line[6:11]),
                            'atomName'    : line[12:16].strip(),
                            'resName'     : line[17:20].strip(),
                            'x'           : float(line[30:38]),
                            'y'           : float(line[38:46]),
                            'z'           : float(line[46:54]),
                            'charge'      : float(line[54:62]),
                            'radius'      : float(line[62:69])
                            }

                newAtom = Atom.Atom(arg_serial = atomSerial, **atomArgs)
                atomList.append(newAtom)
    return atomList
示例#6
0
    def newAtom(self):
        """
		function newAtom: creates and returns an atom in the current residue
		"""

        myatom = Atom()
        self.addAtom(myatom)
        return myatom
示例#7
0
    def __init__(self, index, nAtoms, atomic_type):
        self.index = index
        self.nAtoms = nAtoms
        self.atomic_type = atomic_type
        assert self.nAtoms == len(self.atomic_type)

        self.atoms = []
        for i in range(self.nAtoms):
            self.atoms.append(Atom.Atom(index, self.atomic_type[i]))
示例#8
0
def readCoord(file):
    "Read TURBOMOLE coord file, return list of Atoms"

    atoms = [Atom.Atom((0, 0, 0), 'None')]

    try:
        f = open(file, 'r')
    except IOError, x:
        print '%s: %s' % (x[1], infile)
        sys.exit(1)
示例#9
0
 def readstring(self, lines):
     lines = lines.split(os.linesep)
     numAtoms = string.atoi(lines[0])
     lines = lines[2:]
     for i in range(numAtoms):
         element, x, y, z = lines[i].split()
         x, y, z = map(string.atof, (x, y, z))
         a = Atom.Atom()
         a.fromXyz(element, x, y, z)
         self.atoms.append(a)
示例#10
0
 def fromMmp(self, line):
     atoms = self._owner.atoms
     n = len(atoms)
     a = Atom.Atom()
     try:
         a.fromMmp(line)
     except Atom.NotAtomException:
         del a
         return False
     self._index = n
     atoms.append(a)
     return True
示例#11
0
    def AddAtomTo(self, to_atom):
        if not to_atom:
            return

        newatom = Atom(graph=self)  # new atom
        b = Bond(newatom, to_atom)  # new bond

        # add to both bonds edge lists
        to_atom.AddBond(b)
        newatom.AddBond(b)

        self.atoms.append(newatom)
        self.bonds.append(b)
示例#12
0
    def AddAtomTo(self, to_atom):
        if not to_atom:
            return

        newatom = Atom(graph=self)  # luodaan uusi solmu

        b = Bond(newatom, to_atom)  # luodaan kaari 'newnode' -> 'to_node'

        # lisätään molempien solmujen kaarilistaan
        to_atom.AddBond(b)
        newatom.AddBond(b)

        # lisätään verkon listoihin uusi solmu ja kaari
        self.atoms.append(newatom)
        self.bonds.append(b)
示例#13
0
def listOfAtom2UnitCell(loa):
    """Utility to convert a ListOfAtom instance to a UnitCell instance."""

    symbols = [x.symbol for x in loa]
    cartpos = [x.position for x in loa]

    cellvectors = loa.cell
    uc = UnitCell(cellvectors)
    fracpos = [uc.cartesianToFractional(x) for x in cartpos]

    for n in range(symbols):
        atom = Atom(symbol=symbols[n])
        uc.addAtom(atom, fracpos[n], '')

    return uc
示例#14
0
def number_list(t):
    """Takes a nested list that represents a chemical formula (returned by the function make_list()), makes an analogous list of atoms, and numbers the atoms in order.

	t: list of str
	Returns: list of Atoms
	"""
    global i
    res = []
    for elem in t:
        if type(elem) == str:
            #res.append(elem + str(i))		#appends string
            res.append(Atom.Atom(elem, elem + str(i)))  #appends atom
            i += 1
        if type(elem) == list:
            res.append(number_list(elem))
    return res
示例#15
0
    def AddMoleculeGraph(self, mg, mapping):
        # we have to take care of:
        # - atoms
        # - bonds
        # - compoundatoms
        # - compoundbonds
        # - origatoms
        # - origbonds

        aidcounter = max([x.id for x in self.atoms]) + 1 if self.atoms else 0
        bidcounter = max([x.id for x in self.bonds]) + 1 if self.atoms else 0

        self.compoundatoms[mg.molecule.ligand] = []
        self.compoundbonds[mg.molecule.ligand] = []

        # go through atoms on the rhs side
        for a in mg.atoms:
            if a in mapping:
                self.origatoms.setdefault(mapping[a], []).append(a)
                self.compoundatoms.setdefault(mg.molecule.ligand, []).append(a)
            else:
                newatom = Atom(symbol=a.symbol, id=aidcounter, graph=self)
                self.AddAtom(newatom)
                aidcounter += 1
                mapping[a] = newatom
                self.origatoms.setdefault(newatom, []).append(a)
                self.compoundatoms.setdefault(mg.molecule.ligand,
                                              []).append(newatom)

        for b in mg.bonds:
            newsrc = mapping[b.source]
            newtgt = mapping[b.target]
            mbond = newsrc.GetBond(newtgt)

            if mbond:
                self.origbonds.setdefault(mbond, []).append(b)
                self.compoundbonds.setdefault(mg.molecule.ligand,
                                              []).append(mbond)
                mapping[b] = mbond
            else:
                newbond = Bond(newsrc, newtgt, b.type, bidcounter, self)
                self.AddBond(newbond)
                bidcounter += 1
                mapping[b] = newbond
                self.origbonds.setdefault(newbond, []).append(b)
                self.compoundbonds.setdefault(mg.molecule.ligand,
                                              []).append(newbond)
示例#16
0
def symbol_read_line(fun, args):
    handle = eval(args[0], fun)
    if handle not in file_handles:
        raise LispError("READ-LINE: File handle not active")
    try:
        while True:
            line = file_handles[handle].readline()
            if not line:
                raise LispError("READ-LINE: End of file")
            if line != "\n":
                break

        if line[-1] == "\n":
            line = line[:-1]
        return Atom.Atom(Atom.Atom.STRING, line)
    except Exception as e:
        raise LispError(e.__str__())
示例#17
0
def pdb2Atom(line):
    try:
        atomobj = Atom.Atom()
        atomobj.atm_type = line[0:6].strip()
        atomobj.atm_number = int(line[6:11])
        atomobj.atm_name = line[12:16].strip()
        atomobj.alt_loc = line[16].strip()
        atomobj.resi_name = line[17:20].strip()
        atomobj.chain = line[21].strip()
        atomobj.resSeq = int(line[22:26])
        atomobj.icode = line[26].strip()
        atomobj.pos = array(
            [float(line[30:38]),
             float(line[38:46]),
             float(line[46:54])])
        atomobj.occ = float(line[54:60])
        atomobj.bfac = float(line[60:66])
        atomobj.elem = line[76:78].strip()
        atomobj.charge = line[78:80].strip()
        atomobj.valid = True
        return atomobj
    except:
        pass
示例#18
0
def main(mmpInputFile, xyzInputFile=None, outf=None,
         referenceInputFile=None, generateFlag=False):
    bondLengthTerms = { }
    bondAngleTerms = { }

    def addBondLength(atm1, atm2):
        assert atm1 != atm2
        if atm2 < atm1:
            atm1, atm2 = atm2, atm1
        if bondLengthTerms.has_key(atm1):
            if atm2 not in bondLengthTerms[atm1]:
                bondLengthTerms[atm1].append(atm2)
        else:
            bondLengthTerms[atm1] = [ atm2 ]

    def getBonds(atm1):
        lst = [ ]
        if bondLengthTerms.has_key(atm1):
            for x in bondLengthTerms[atm1]:
                lst.append(x)
        for key in bondLengthTerms.keys():
            if atm1 in bondLengthTerms[key]:
                if key not in lst:
                    lst.append(key)
        lst.sort()
        return lst

    def addBondAngle(atm1, atm2, atm3):
        if atm3 < atm1:
            atm1, atm3 = atm3, atm1
        value = (atm2, atm3)
        if bondAngleTerms.has_key(atm1):
            if value not in bondAngleTerms[atm1]:
                bondAngleTerms[atm1].append(value)
        else:
            bondAngleTerms[atm1] = [ value ]

    if outf != None:
        ss, sys.stdout = sys.stdout, outf
    mmp = MmpFile()
    mmp.read(mmpInputFile)
    xyz = XyzFile()
    if xyzInputFile != None:
        xyz.read(xyzInputFile)
    else:
        # copy xyz file from mmp file
        import Atom
        for i in range(len(mmp)):
            ma = mmp.atoms[i]
            element = Atom._PeriodicTable[ma.elem]
            x, y, z = ma.x, ma.y, ma.z
            a = Atom.Atom()
            a.fromXyz(element, x, y, z)
            xyz.atoms.append(a)

    assert len(xyz) != 0
    assert len(xyz) == len(mmp)

    # store all the bonds in bondLengthTerms
    for i in range(len(mmp)):
        a = mmp.atoms[i]
        for b in a.bonds:
            addBondLength(i, b - 1)

    # generate angles from chains of two bonds
    for first in range(len(mmp)):
        for second in getBonds(first):
            for third in getBonds(second):
                if first != third:
                    addBondAngle(first, second, third)

    lengthList = [ ]
    for first in bondLengthTerms.keys():
        for second in bondLengthTerms[first]:
            lengthList.append((first, second,
                               measureLength(xyz, first, second)))
    angleList = [ ]
    for first in bondAngleTerms.keys():
        for second, third in bondAngleTerms[first]:
            angleList.append((first, second, third,
                              measureAngle(xyz, first, second, third)))

    if generateFlag:
        for a1, a2, L in lengthList:
            print "LENGTH", a1, a2, L
        for a1, a2, a3, A in angleList:
            print "ANGLE", a1, a2, a3, A

    if referenceInputFile != None:
        badness = False
        # read in LENGTH lines, compare them to this guy
        inf = open(referenceInputFile)
        lp = ap = 0
        for line in inf.readlines():
            if line.startswith("LENGTH "):
                fields = line[7:].split()
                a1, a2, L = (string.atoi(fields[0]),
                             string.atoi(fields[1]),
                             string.atof(fields[2]))
                a11, a22, LL = lengthList[lp]
                lp += 1
                if a1 != a11 or a2 != a22:
                    print ("Wrong length term (%d, %d), should be (%d, %d)"
                           % (a11, a22, a1, a2))
                    badness = True
                    break
                if abs(L - LL) > LENGTH_TOLERANCE:
                    print ("Wrong bond length at (%d, %d), it's %f, should be %f"
                           % (a1, a2, LL, L))
                    badness = True
                    break
            elif line.startswith("ANGLE "):
                fields = line[6:].split()
                a1, a2, a3, A = (string.atoi(fields[0]),
                                 string.atoi(fields[1]),
                                 string.atoi(fields[2]),
                                 string.atof(fields[3]))
                a11, a22, a33, AA = angleList[ap]
                ap += 1
                if a1 != a11 or a2 != a22 or a3 != a33:
                    print ("Wrong angle term (%d, %d, %d), should be (%d, %d, %d)"
                           % (a11, a22, a33, a1, a2, a3))
                    badness = True
                    break
                if abs(L - LL) > ANGLE_TOLERANCE:
                    print ("Wrong bond angle at (%d, %d, %d), it's %f, should be %f"
                           % (a1, a2, a3, AA, A))
                    badness = True
                    break
            else:
                print "Unknown line in reference file:", line
                badness = True
                break
        if not badness:
            print "OK"
    if outf != None:
        outf.close()
        sys.stdout = ss
示例#19
0
# ( 0.1)Detect missing seg info
test_text = [ line for line in open(sys.argv[-1]) ]
test_line = test_text[0]
if in_ver == 'web':
    test_seg = test_line[21:22]
elif in_ver == 'charmm':
    test_seg = test_line[72:76]
if test_seg in ['',' ']:
    bad_seg = True
else:
    bad_seg = False

# ( 1 ) Initialize & Cull
if not bad_seg:
    pdb_file = [ Atom.Atom(line,in_ver) for line in open(sys.argv[-1]) if line.startswith('ATOM') or line.startswith('HETATM') ]
else:
    pdb_file = []
    nTH_seg = 0
    for line in open(sys.argv[-1]):
        if line.startswith('ATOM') or line.startswith('HETATM'):
            thisAtom = Atom.Atom(line,in_ver)
            thisAtom.segid = string.uppercase[nTH_seg]
            pdb_file.append(thisAtom)
        elif line.startswith('TER'):
            nTH_seg += 1

# ( 2 ) Tag redundant atoms from each multi-model section for removal
#  This is done via the following procedure...
#   (a) First check if a line belongs to a multi-model section
#   (b) The conditions to start a multi-model section comparison:
示例#20
0
    def __init__(self, File_Name, end_groups, tangent_vector):
        File = open(
            File_Name,
            'r')  # File_Name is the name of an .xyz file outputted by Avogadro
        File_Lines = File.readlines()

        # Define Instance Variables
        self.Name = File_Name.split('.xyz')[0]
        self.N = int(File_Lines[0].strip('\n'))  # Integer
        self.Atom_List = np.empty(self.N, dtype=object)  # Numpy object array
        self.Bond_List = []
        self.Angle_List = []
        self.Dihedral_List = []
        self.Improper_List = []
        self.Ring_List = []
        self.MW = 0.0
        self.COM = np.zeros(3, float)
        self.Mol_ID = 0
        self.Missing_Dihedrals = 0
        self.UnConverged = False  # Unconverged Orca Optimization
        self.end_groups = end_groups

        print "Setting up molecule"
        print "Molecule Name:", self.Name
        print self.N, "Atoms in ", self.Name
        print "----------------------------------"
        for i in range(self.N):
            Line = File_Lines[2 + i]
            Line = Line.strip('\n').split()
            Element = Line[0]
            Position = np.array(
                [float(Line[1]),
                 float(Line[2]),
                 float(Line[3])], dtype=float)
            self.Atom_List[i] = Atom.Atom(
                Position, Element,
                i + 1)  # Instantiate Atom_List with Atom objects
            self.MW += self.Atom_List[i].Mass

        print "Initial XYZ Coordinates:\n"
        for Atom_Obj in self.Atom_List:
            print Atom_Obj.Element, Atom_Obj.Position
        print "----------------------------------"

        # Compute center of Mass
        Mass_Weighted_Sum = np.zeros(3, dtype=float)
        for Atom_Obj in self.Atom_List:
            Mass_Weighted_Sum += Atom_Obj.Position * Atom_Obj.Mass
            self.MW += Atom_Obj.Mass

        print "Molecular Weight is ", self.MW, "Grams/Mole"
        self.COM = Mass_Weighted_Sum / self.MW
        self.COM = np.asarray(self.COM)
        print "COM is", self.COM

        Mass_Weighted_Sum = 0.0
        for Atom_Obj in self.Atom_List:
            Mass_Weighted_Sum += Atom_Obj.Mass * (
                (Atom_Obj.Position[0] - self.COM[0])**2 +
                (Atom_Obj.Position[1] - self.COM[1])**2 +
                (Atom_Obj.Position[2] - self.COM[2])**2)
        Rg2 = Mass_Weighted_Sum / self.MW
        self.Rg = np.sqrt(Rg2)
        print "The Radius of Gyration is", self.Rg

        # Zero COM
        for Atom_Obj in self.Atom_List:
            Atom_Obj.Position -= self.COM

        self.COM -= self.COM
        print self.COM
        # Set end groups of the monomer
        print "End groups:", self.end_groups
        for element in self.end_groups:
            for index in element:
                self.Atom_List[index - 1].end_group = True
                print self.Atom_List[index - 1].Element, index

        # Set the tangent vector
        self.tangent_vector = self.Atom_List[
            tangent_vector[0] -
            1].Position - self.Atom_List[tangent_vector[1] - 1].Position
        print "Tangent Vector is:", self.tangent_vector, np.linalg.norm(
            self.tangent_vector)

        return
示例#21
0
 def AddAtom(self, atom=None):
     if atom:
         self.atoms.append(atom)
     else:
         self.atoms.append(Atom(symbol="X", graph=self))
示例#22
0
    def input(self, fname):
        f = open(fname)
        lines = map(str.strip, f.readlines())
        f.close()

        # set
        # - self.atoms
        # - self.bonds
        # - self.reactions
        # - self.compoundatoms
        # - self.compoundbonds

        for line in lines:
            data = line.split()[1:]

            #			print line

            if line.startswith("ATOM"):
                i = int(data[0])
                s = data[1]
                coords = {}

                for xystr in data[2].split(","):
                    c = xystr.split(":")[0]
                    x, y = xystr.split(":")[1].split("|")
                    coords[c] = Point()
                    coords[c].x = float(x)
                    coords[c].y = float(y)

                a = Atom(id=i, symbol=s)
                a.coords = coords

                self.AddAtom(a)

            elif line.startswith("BOND"):
                i = int(data[0])
                srcid = int(data[1])
                tgtid = int(data[2])
                t = int(data[3])
                source = self.atoms[srcid - 1]
                target = self.atoms[tgtid - 1]
                b = Bond(id=i, source=source, target=target, type=t)
                b.reactions = {}
                self.AddBond(b)

            elif line.startswith("COMPOUND"):
                c = data[0]
                atoms = data[1][1:-1]
                bonds = data[2][1:-1]

                # first compoundptr
                if c not in self.compoundatoms:
                    self.compoundatoms[c] = [[]]
                    self.compoundbonds[c] = [[]]
                    for aid in atoms.split(","):
                        self.compoundatoms[c][-1].append(self.atoms[int(aid) -
                                                                    1])
                    for bid in bonds.split(","):
                        if bid:
                            self.compoundbonds[c][-1].append(
                                self.bonds[int(bid) - 1])
                else:
                    self.compoundatoms[c].append([])
                    self.compoundbonds[c].append([])
                    for aid in atoms.split(","):
                        self.compoundatoms[c][-1].append(self.atoms[int(aid) -
                                                                    1])
                    for bid in bonds.split(","):
                        if bid:
                            self.compoundbonds[c][-1].append(
                                self.bonds[int(bid) - 1])

            elif line.startswith("REACTIONCHANGE"):
                bid = int(data[0])
                ligand = data[1].split(":")[0]
                type = int(data[1].split(":")[1])

                self.bonds[bid - 1].reactions[ligand] = type

            elif line.startswith("REACTION"):
                ligand = data[0]
                atoms = data[1][1:-1]
                bonds = data[2][1:-1]

                self.reactions[ligand] = []
                for aid in atoms.split(","):
                    self.reactions[ligand].append(self.atoms[int(aid) - 1])

                for bid in bonds.split(","):
                    bid = int(bid)
                    self.bonds[bid - 1].reactions[ligand] = 0
示例#23
0
    def __init__(self, Filename):
        self.Name = Filename.split('.')[1].split('_')[0]
        File = open(Filename, 'r')
        File_Lines = File.readlines()
        self.Bond_List = []
        self.Angle_List = []
        self.Dihedral_List = []
        self.Improper_List = []
        self.MW = 0.0
        self.COM = np.zeros(3, float)
        self.Mol_ID = 0
        self.basis = np.eye(3)

        j = -1
        for Line in File_Lines:
            j += 1
            Line = Line.strip('\n').split(' ')
            if len(Line) > 1:
                if Line[1] == 'atoms':
                    self.N = int(Line[0])
                    print self.N, "Atoms"
                if Line[1] == 'atom':
                    Atom_Types = int(Line[0])
                    self.Atom_List = np.empty(self.N, dtype=object)
                    Mass_List = np.empty(Atom_Types, dtype=float)
                    Pair_Coeffs = np.empty((Atom_Types, 2), dtype=float)
                if Line[1] == 'bonds':
                    Num_Bonds = Line[0]
                if Line[1] == 'bond':
                    Bond_Types = int(Line[0])
                    Bond_Coeffs = np.empty((Bond_Types, 2), dtype=float)
                if Line[1] == 'angles':
                    Num_Angles = Line[0]
                if Line[1] == 'angle':
                    Angle_Types = int(Line[0])
                    Angle_Coeffs = np.empty((Angle_Types, 2), dtype=float)
                if Line[1] == 'dihedrals':
                    Num_Dihedrals = Line[0]
                if Line[1] == 'dihedral':
                    Dihedral_Types = int(Line[0])
                    Dihedral_Coeffs = np.empty((Dihedral_Types, 4),
                                               dtype=float)
                if Line[1] == 'impropers':
                    Num_Impropers = Line[0]
                if Line[1] == 'improper':
                    Improper_Types = int(Line[0])
                    Improper_Coeffs = np.empty((Improper_Types, 3),
                                               dtype=float)
                try:
                    if Line[2] == 'xlo':
                        Box_Length = float(Line[1]) - float(Line[0])
                        print Box_Length, "Box_Length"
                except:
                    continue
                if Line[0] == 'Atoms':
                    print 'Getting Atoms'
                    for i in range(self.N):
                        Temp_Position = [
                            float(File_Lines[i + j + 2].split(' ')[4]),
                            float(File_Lines[i + j + 2].split(' ')[5]),
                            float(File_Lines[i + j + 2].split(' ')[6])
                        ]
                        I_Flags = [
                            int(File_Lines[i + j + 2].split(' ')[7]),
                            int(File_Lines[i + j + 2].split(' ')[8]),
                            int(File_Lines[i + j + 2].split(' ')[9])
                        ]
                        Temp_Position = np.asarray(Temp_Position, dtype=float)

                        I_Flags = np.asarray(I_Flags, dtype=int)
                        #print "IMAGE FLAGS", I_Flags
                        Temp_Position += I_Flags * Box_Length
                        Temp_Charge = float(File_Lines[i + j +
                                                       2].split(' ')[3])
                        Type = int(File_Lines[i + j + 2].split(' ')[2])
                        Mass = Mass_List[Type - 1]
                        Element = Element_Dict[Mass]
                        Atom_Id = int(File_Lines[i + j + 2].split(' ')[0])
                        #print Element, Mass, Atom_Id
                        self.Atom_List[i] = Atom.Atom(Temp_Position, Element,
                                                      Atom_Id)
                        self.Atom_List[i].Charge = Temp_Charge
                        self.Atom_List[i].Epsilon = Pair_Coeffs[Type - 1, 0]
                        self.Atom_List[i].Sigma = Pair_Coeffs[Type - 1, 1]
                        self.Atom_List[i].OPLS_Type = 1000 + Type

                    self.Atom_List = sorted(self.Atom_List,
                                            key=lambda AtomO: AtomO.Atom_ID)
                    for Atom_Obj in self.Atom_List:
                        print Atom_Obj.Atom_ID, Atom_Obj.Position

                if Line[0] == 'Pair':
                    print "Getting Pair Coefficients"
                    for i in range(Atom_Types):
                        Pair_Coeffs[i, 0] = float(File_Lines[i + j +
                                                             2].split(' ')[1])
                        Pair_Coeffs[i, 1] = float(File_Lines[i + j +
                                                             2].split(' ')[2])
                if Line[0] == 'Bond':
                    print "Getting Bond Coefficients"
                    for i in range(Bond_Types):
                        Bond_Coeffs[i, 0] = float(File_Lines[i + j +
                                                             2].split(' ')[1])
                        Bond_Coeffs[i, 1] = float(File_Lines[i + j +
                                                             2].split(' ')[2])
                if Line[0] == 'Angle':
                    print "Getting Angle Coefficients"
                    for i in range(Angle_Types):
                        Angle_Coeffs[i, 0] = float(File_Lines[i + j +
                                                              2].split(' ')[1])
                        Angle_Coeffs[i, 1] = float(File_Lines[i + j +
                                                              2].split(' ')[2])
                if Line[0] == 'Dihedral':
                    print "Getting Dihedral Coefficients"
                    for i in range(Dihedral_Types):
                        Dihedral_Coeffs[i, 0] = float(
                            File_Lines[i + j + 2].split(' ')[1])
                        Dihedral_Coeffs[i, 1] = float(
                            File_Lines[i + j + 2].split(' ')[2])
                        Dihedral_Coeffs[i, 2] = float(
                            File_Lines[i + j + 2].split(' ')[3])
                        Dihedral_Coeffs[i, 3] = float(
                            File_Lines[i + j + 2].split(' ')[4])
                if Line[0] == 'Improper':
                    print "Getting Improper Coefficients"
                    for i in range(Improper_Types):
                        Improper_Coeffs[i, 0] = float(
                            File_Lines[i + j + 2].split(' ')[1])
                        Improper_Coeffs[i, 1] = int(
                            File_Lines[i + j + 2].split(' ')[2])
                        Improper_Coeffs[i, 2] = int(
                            File_Lines[i + j + 2].split(' ')[3])

            if len(Line) == 1:
                if Line == ['']:
                    continue
                if Line == ['Masses']:
                    print "Extracting Masses"
                    for i in range(Atom_Types):
                        Mass_List[i] = float(File_Lines[i + j +
                                                        2].split(' ')[1])
                if Line == ['Bonds']:
                    print "Extracting Bonds"
                    for i in range(int(Num_Bonds)):
                        Bond_Info = File_Lines[i + j +
                                               2].strip('\n').split(' ')
                        Master = self.Atom_List[int(Bond_Info[2]) - 1]
                        Slave = self.Atom_List[int(Bond_Info[3]) - 1]
                        Kb = Bond_Coeffs[int(Bond_Info[1]) - 1, 0]
                        Req = Bond_Coeffs[int(Bond_Info[1]) - 1, 1]
                        Bond_ID = int(Bond_Info[0])
                        self.Bond_List.append(Bond.Bond(Master, Slave, Req))
                        self.Bond_List[i].kb = Kb
                        self.Bond_List[i].Bond_ID = Bond_ID
                if Line == ['Angles']:
                    print "Extracting Angles"
                    for i in range(int(Num_Angles)):
                        Angle_Info = File_Lines[i + j +
                                                2].strip('\n').split(' ')
                        Slave1 = self.Atom_List[int(Angle_Info[2]) - 1]
                        Master = self.Atom_List[int(Angle_Info[3]) - 1]
                        Slave2 = self.Atom_List[int(Angle_Info[4]) - 1]
                        Ka = Angle_Coeffs[int(Angle_Info[1]) - 1, 0]
                        Th0 = Angle_Coeffs[int(Angle_Info[1]) - 1, 1]
                        Angle_ID = int(Angle_Info[0])
                        self.Angle_List.append(
                            Angle.Angle(Master, Slave1, Slave2, Th0))
                        self.Angle_List[i].ka = Ka
                        self.Angle_List[i].Angle_ID = Angle_ID

                if Line == ['Dihedrals']:
                    print "Extracting Dihedrals"
                    for i in range(int(Num_Dihedrals)):
                        Dihedral_Info = File_Lines[i + j +
                                                   2].strip('\n').split(' ')
                        Slave1 = self.Atom_List[int(Dihedral_Info[2]) - 1]
                        Master1 = self.Atom_List[int(Dihedral_Info[3]) - 1]
                        Master2 = self.Atom_List[int(Dihedral_Info[4]) - 1]
                        Slave2 = self.Atom_List[int(Dihedral_Info[5]) - 1]
                        Coeffs = Dihedral_Coeffs[int(Dihedral_Info[1]) - 1]
                        Dihedral_ID = int(Dihedral_Info[0])
                        self.Dihedral_List.append(
                            Dihedral.Dihedral(Master1, Master2, Slave1, Slave2,
                                              0.0))
                        self.Dihedral_List[i].Coeffs = Coeffs
                        self.Dihedral_List[i].Dihedral_ID = Dihedral_ID

                if Line == ['Impropers']:
                    print "Extracting Impropers"
                    for i in range(int(Num_Impropers)):
                        Improper_Info = File_Lines[i + j +
                                                   2].strip('\n').split(' ')
                        Master = self.Atom_List[int(Improper_Info[2]) - 1]
                        Slave1 = self.Atom_List[int(Improper_Info[3]) - 1]
                        Slave2 = self.Atom_List[int(Improper_Info[4]) - 1]
                        Slave3 = self.Atom_List[int(Improper_Info[5]) - 1]
                        Coeff = Improper_Coeffs[int(Improper_Info[1]) - 1, 0]
                        Improper_ID = int(Improper_Info[0])
                        self.Improper_List.append(
                            Improper.Improper(Master, Slave1, Slave2, Slave3,
                                              Coeff, 180.0, Improper_ID))

        # Compute center of Mass
        Mass_Weighted_Sum = np.zeros(3, dtype=float)
        for Atom_Obj in self.Atom_List:
            Mass_Weighted_Sum += Atom_Obj.Position * Atom_Obj.Mass
            self.MW += Atom_Obj.Mass

        print "Molecular Weight is ", self.MW, "Grams/Mole"
        self.COM = Mass_Weighted_Sum / self.MW
        print "COM is", self.COM

        # Zero COM
        for Atom_Obj in self.Atom_List:
            Atom_Obj.Position -= self.COM

        self.COM -= self.COM
        print self.COM

        return
示例#24
0
    def AddReactionGraph(self, rg, mappings=None):
        # self = current reaction graph
        # rg = reaction graph to be merged
        #
        # for the mapped regions, add to those atoms the mapped atom's molecules and reactions
        # the remaining unmapped regions atoms should be transferred to this graph
        # the mapped bonds should be added to mcs parts (reactions)
        # the unmapped bonds should be transferred
        # for svg the coordinates have to be calibrated,
        #  basically just overlay the two reaction graphs on top of each other
        #  causes collisions, need aritas layout algorithm?
        #

        if not mappings:
            mappings = self.optimal_atom_mappings(rg)

        aidcounter = max([x.id for x in self.atoms]) + 1
        bidcounter = max([x.id for x in self.bonds]) + 1

        newidstart = aidcounter

        # optimal mappings, basically iso/automorphic
        mapping = mappings[0]

        # we need to handle:
        # - reactions
        # - compounds
        # - origatoms
        # - origbonds
        # - bond.reactions

        # first add atoms not yet on 'self'
        for a in rg.atoms:
            if mapping[a] is None:
                newatom = Atom(symbol=a.symbol, id=aidcounter, graph=self)
                mapping[a] = newatom
                self.AddAtom(newatom)
                aidcounter += 1

        # next add bonds
        # now we have all atoms mapped from rg to self
        # we have created all new atoms
        # we have all atom information updated
        # next we go through all bonds in rg and map them to self and create all new bonds
        #
        for b in rg.bonds:
            src = b.source
            tgt = b.target
            msrc = mapping[src]  # can be none
            mtgt = mapping[tgt]
            mb = msrc.GetBond(mtgt)

            # bond exists
            if msrc and mtgt and mb:
                mb.reactions.update(b.reactions)
                mapping[b] = mb
            # new bond
            else:
                newbond = Bond(msrc, mtgt, b.type, bidcounter, self)
                newbond.reactions = b.reactions
                # if the new bond attaches new atom to old atom, set the bond as +1
                #				if (newbond.source.id < newidstart) != (newbond.target.id < newidstart):
                #					newbond.reactions[rg.reaction] = +1
                if newbond.source.id < newidstart or newbond.target.id < newidstart:
                    newbond.reactions[rg.reaction] = +1

                bidcounter += 1
                self.AddBond(newbond)
                mapping[b] = newbond

        # next update information on the atoms
        for rhs in rg.atoms:
            lhs = mapping[rhs]

            # origatoms ( newatom -> [origatoms] )
            try:
                self.origatoms[lhs] += rg.origatoms[rhs]
            except:
                self.origatoms[lhs] = rg.origatoms[rhs]

        # finally update information on all rg bonds mapped to self
        # origbonds ( newbond -> [origbonds] )
        for rhs in rg.bonds:
            lhs = mapping[rhs]

            try:
                self.origbonds[lhs] += rg.origbonds[rhs]
            except:
                self.origbonds[lhs] = rg.origbonds[rhs]

        # TODO: a compound can exist in numerous places, the compoundatoms should be { mol: [[atoms],[atoms],..] }
        for c, pieces in rg.compoundatoms.items():
            for atoms in pieces:
                if c in self.compoundatoms:
                    indices = {}
                    for i in range(len(self.compoundatoms[c])):
                        Alist = self.compoundatoms[c][i]
                        for a in atoms:
                            if mapping[a] in Alist:
                                indices[a] = i
                    components = len(set(indices.values()))

                if c not in self.compoundatoms or components != 1:
                    self.compoundatoms.setdefault(c, []).append([])
                    for a in atoms:
                        self.compoundatoms[c][-1].append(mapping[a])

        for c, pieces in rg.compoundbonds.items():
            for bonds in pieces:
                if c in self.compoundbonds:
                    #					matching_areas = list(dict([ (B,b) for B in self.compoundbonds[c] for b in bonds if mapping[b] in B]))
                    indices = {}
                    for i in range(len(self.compoundbonds[c])):
                        Blist = self.compoundbonds[c][i]
                        for b in bonds:
                            if mapping[b] in Blist:
                                indices[b] = i
                    components = len(set(indices.values()))

                if c not in self.compoundbonds or components != 1:
                    self.compoundbonds.setdefault(c, []).append([])
                    for b in bonds:
                        self.compoundbonds[c][-1].append(mapping[b])

        for r, ats in rg.reactions.items():
            if r not in self.reactions:
                self.reactions[r] = []
                for a in ats:
                    self.reactions[r].append(mapping[a])
示例#25
0
from UnitCell import *
from Atom import *

uc = UnitCell()
at1 = Atom(symbol='Fe', mass=57)
pos1 = (0.0, 0.0, 0.0)
at2 = Atom(symbol='Al')
pos2 = (0.5, 0.5, 0.5)

site1 = Site(pos1, at1)
site2 = Site(pos2, at2)

uc.addAtom(at1, pos1, "Fe1")
uc.addAtom(at2, pos2, "Al1")

print uc
示例#26
0
from UnitCell import *
from Atom import *
import pylab
import pickle

uc = UnitCell( )
at1=Atom(symbol='Fe', mass=57) ; pos1=(0.0,0.0,0.0)
at2=Atom(symbol='Al') ; pos2=(0.5,0.5,0.5)

site1 = Site(pos1, at1)
site2 = Site(pos2, at2)

uc.addAtom( at1, pos1, "Fe1" )
uc.addAtom( at2, pos2, "Al1" )

print uc


###

import AbInitio.kernelGenerator.SqeCalculator
import numpy

kptlist = uc.getMonkhorstPackGrid((40,40,40)).reshape(64000,3)

sqecalc = AbInitio.kernelGenerator.SqeCalculator.SqeCalculator(uc, kpoints=kptlist)

#sqecalc.readIDFeigenvectors(filename='Polarizations_FeAl_8000k')
sqecalc.readIDFeigenvectors(filename='pols_FeAl222_mp40.idf')

示例#27
0
 def fromMmp(self, line):
     atoms = self._owner.atoms
     self._index = len(atoms)
     a = Atom.Atom()
     a.fromMmp(line)
     atoms.append(a)
示例#28
0
'''

# BOND_DEFINITION_LIST holds all possible bond types that belongs to the molecule.
# add/change the numbers in this list if your atoms have different bond lengths, count, etc.
BOND_DEFINITION_LIST = [
    Bond().load('C', 'H', 1, 1.040, 1.149),
    Bond().load('C', 'C', 1, 1.490, 1.599),
    Bond().load('C', 'C', 2, 1.290, 1.399),
    Bond().load('C', 'C', 3, 1.150, 1.259)
]

# ATOM_DEFINITION_LIST holds all possible atom types that belongs to the molecule.
# add/change the list elements if your molecule have different atoms and possible inhome neighbors
#TODO: dynamically load the coefficient counts based on 'qchem_input->BASIS'
ATOM_DEFINITION_MAP = {
    'C': Atom().load('C', 9, ['H']),
    'H': Atom().load('H', 2, ['C'])
}

#MOLECULE_STRUCT = MoleculeStruct().load(ATOM_DEFINITION_MAP, BOND_DEFINITION_LIST)
molecule_structure = MoleculeStruct()
molecule_structure.load(ATOM_DEFINITION_MAP, BOND_DEFINITION_LIST)

full_file = os.path.abspath(os.path.join('data', FILE_NAME))
tree = ET.parse(FILE_NAME)
root = tree.getroot()
geometry = tree.findall('geometry')
atom_list_str = (geometry[0]).get('text')
atoms = []
atoms = Atom.load_atoms_from_geometry(atom_list_str)
示例#29
0
    def read(self, mapfile=None):
        #		print self.reaction.ligand
        # read mappings

        self.reaction.read_mapping("ASTAR", mapfile)
        if not self.reaction.mappings[0].mapping:
            #			print "no mappings"
            self = None
            return

        # get sub/prod atoms, mapping both ways, compound list
        subatoms = [
            a for sub in self.reaction.subs if sub.graph
            for a in sub.graph.atoms
        ]
        prodatoms = [
            a for prod in self.reaction.prods if prod.graph
            for a in prod.graph.atoms
        ]
        mapping = self.reaction.mappings[-1].mapping
        revmapping = dict([(rhs, lhs) for lhs, rhs in mapping.items()])
        newatoms = {}

        aids = 1  # atom id counter
        bids = 1

        #		for k,v in mapping.items():
        #			print k,v
        #		print
        #		for k,v in revmapping.items():
        #			print k,v

        # go through subs and prods and create new atoms based on these
        for a in subatoms:
            newatom = Atom(a.symbol, id=aids, graph=self)
            aids += 1
            newatom.x = a.x
            newatom.y = a.y
            self.AddAtom(newatom)
            newatoms[a] = newatom

        #
        # the self.compoundatoms and self.compoundbonds contain { "C00031":[[atoms],[atoms],...] }
        # if there are multiple same reactant (eg. 2 C00031 <=> C00634 + C03259), we need to map both
        # C00031's into indices in compoundatoms-list of atoms
        # this id done with 'molindex{}'
        #
        # TODO: change .compoundatoms and .compoundbonds to have [[atoms],[atoms]...] structure!!!
        # here change so that we have multiple compounds when eg. 2 C00031 <=> C00634 + C03259
        #

        molindex = {}

        for a in subatoms:
            mol = a.graph.molecule
            reac = a.graph.molecule.reaction
            newatom = newatoms[a]
            # here for "2 C00031 <=> ******", put "C00031":[[atoms],[atoms]]
            self.compoundatoms.setdefault(mol.ligand, [])
            self.compoundbonds.setdefault(mol.ligand, [])
            self.reactions.setdefault(reac.ligand, [])

            # if mol is not seen before, add new atomlist and save its index in the outer list
            if mol not in molindex:
                molindex[mol] = len(self.compoundatoms[mol.ligand])
                self.compoundatoms[mol.ligand].append([newatom])
                self.compoundbonds[mol.ligand].append([])
            # mol is seen before, simply append
            else:
                index = molindex[mol]
                self.compoundatoms[mol.ligand][index].append(newatom)

            self.origatoms.setdefault(newatom, []).append(a)

            if newatom not in self.reactions[reac.ligand]:
                self.reactions[reac.ligand].append(newatom)

        for a in prodatoms:
            #			print a
            mol = a.graph.molecule
            newatom = newatoms[revmapping[a]]
            self.compoundatoms.setdefault(mol.ligand, [])
            self.compoundbonds.setdefault(mol.ligand, [])

            # if mol is not seen before, add new atomlist and save its index in the outer list
            if mol not in molindex:
                molindex[mol] = len(self.compoundatoms[mol.ligand])
                self.compoundatoms[mol.ligand].append([newatom])
                self.compoundbonds[mol.ligand].append([])
            # mol is seen before, simply append
            else:
                index = molindex[mol]
                self.compoundatoms[mol.ligand][index].append(newatom)

            self.origatoms.setdefault(newatom, []).append(a)

        # go through pairs of atoms, add bonds to reaction graph
        for ind1, a1 in enumerate(subatoms[:-1]):
            for a2 in subatoms[ind1 + 1:]:
                atom1mol = a1.graph.molecule.ligand
                mappedatom1mol = mapping[a1].graph.molecule.ligand

                index = molindex[a1.graph.molecule]
                mappedindex = molindex[mapping[a1].graph.molecule]

                # intact bond
                if a1 in a2.GetAtomNeighbors(
                ) and mapping[a1] in mapping[a2].GetAtomNeighbors():
                    b = a1.GetBond(a2)

                    source = newatoms[b.source]
                    target = newatoms[b.target]

                    newbond = Bond(source, target, b.type, bids, self)
                    bids += 1
                    newbond.reactions = {self.reaction: 0}  # set a new field

                    self.AddBond(newbond)
                    self.origbonds.setdefault(newbond, []).append(b)
                    self.compoundbonds[atom1mol][index].append(newbond)
                    self.compoundbonds[mappedatom1mol][mappedindex].append(
                        newbond)

                # cleaved bond
                elif a1 in a2.GetAtomNeighbors(
                ) and mapping[a1] not in mapping[a2].GetAtomNeighbors():
                    b = a1.GetBond(a2)

                    source = newatoms[b.source]
                    target = newatoms[b.target]

                    newbond = Bond(source, target, b.type, bids, self)
                    bids += 1
                    newbond.reactions = {self.reaction: -1}  # set a new field

                    self.AddBond(newbond)
                    self.origbonds.setdefault(newbond, []).append(b)
                    self.compoundbonds[atom1mol][index].append(newbond)

                # new bond
                elif a1 not in a2.GetAtomNeighbors(
                ) and mapping[a1] in mapping[a2].GetAtomNeighbors():
                    b = mapping[a1].GetBond(mapping[a2])

                    source = newatoms[a1]
                    target = newatoms[a2]

                    newbond = Bond(source, target, b.type, bids, self)
                    bids += 1
                    newbond.reactions = {self.reaction: 1}  # set a new field

                    self.AddBond(newbond)
                    self.origbonds.setdefault(newbond, []).append(b)
                    self.compoundbonds[mappedatom1mol][mappedindex].append(
                        newbond)
示例#30
0
import sys
from MmpFile import MmpFile
from XyzFile import XyzFile
import Atom

try:
    mmpInputFile = sys.argv[1]

    xyz = XyzFile()
    mmp = MmpFile()
    mmp.read(mmpInputFile)

    for i in range(len(mmp)):
        ma = mmp.atoms[i]
        element = Atom._PeriodicTable[ma.elem]
        x, y, z = ma.x, ma.y, ma.z
        a = Atom.Atom()
        a.fromXyz(element, x, y, z)
        xyz.atoms.append(a)

    xyz.write(mmpInputFile)

except Exception, e:
    if e:
        sys.stderr.write(sys.argv[0] + ": " + e.args[0] + "\n")
        import traceback
        traceback.print_tb(sys.exc_traceback, sys.stderr)
        sys.stderr.write("\n")
    sys.stderr.write(__doc__)
    sys.exit(1)