Esempio n. 1
0
 def test_eapi3(self):
     self.check_use(3)
     atom("dev-util/foon:1", eapi=3)
     atom("dev-util/foon:2", eapi=3)
     atom("!dev-util/foon:1", eapi=3)
     atom("dev-util/foon:1[x]", eapi=3)
     atom("dev-util/foon:1[x?]", eapi=3)
Esempio n. 2
0
 def convertToUnitcell(self):
   from coor import coor
   paraDict = self.paraDict
   s = paraDict['scalingFactor']
   a = coor(tuple(paraDict['latticeVectors'][0]))
   b = coor(tuple(paraDict['latticeVectors'][1]))
   c = coor(tuple(paraDict['latticeVectors'][2]))
   speciesNumber = paraDict['speciesNumber']
   speciesLabel = paraDict['speciesLabel']
   coordinateSystem = paraDict['coordinateSystem']
   atomPositions = paraDict['atomPositions']
   # Get the total number of atoms specified in poscar
   atomNumberCount = sum(speciesNumber)
   # Scale the latticeMatrix
   a = a * s; b = b * s; c = c * s;
   # Construct the siteList (Recall that unitcell always use reduced coor)
   from element import element
   elementList = [element(speciesLabel[index])\
                 for index in range(len(speciesLabel))\
                 for count in range(speciesNumber[index])]
   if coordinateSystem == 'Direct':
     reducedCoorList = [coor(tuple(position)) for position in atomPositions]
   else:
     raise StandardError("Coordinate system not direct")
   from atom import atom
   alist = [atom(element, coor)\
              for (element, coor) in zip(elementList, reducedCoorList)]
   from unitcell import unitcell
   return unitcell(a, b, c, alist)
Esempio n. 3
0
def atom_template(atom_string):
    split_string = atom_string.split()
    label = split_string[0]
    cartesian = list(map(float, split_string[1:4]))

    return atom.atom(atom.dict_inv_enquiry(label, atom.PERIODIC_TABLE),
                     cartesian=cartesian)
Esempio n. 4
0
 def readXYZfile(self,filename):
     try:    
         f=open(filename)
     except Exception:
         print 'ERROR LOADING ',filename
         return 1
     natoms=int(f.readline().strip())
     try:
         line=f.readline().strip()
         if len(line.split())==1:    
             self.charge=int(line)
         elif len(line.split())==2:
             self.charge=int(line.split()[1])
     except Exception:
         print line.split(),filename
         print 'ERROR reading XYZ file. Please put the charge on line 2.'
         exit()    
     fl=f.readlines()
     f.close()
     atomlist=[]
     for i in range(natoms):
         try:
             atomlist.append(atom(fl[i].split()[0],fl[i].split()[1],fl[i].split()[2],fl[i].split()[3]))    
             self.molweight+=sym2mass(atomlist[-1].atsym.upper())
         except Exception:
             print 'ERROR reading XYZ file. Check line', str(fl.index(i)+3),' of ',filename,'.'
             break
     return atomlist
Esempio n. 5
0
 def pybel_to_oasa_atom(self, patom):
     oatom = atom()
     psymbol = num2symbol[patom.atomicnum]
     oatom.symbol = psymbol
     oatom.x, oatom.y, oatom.z = patom.coords
     oatom.charge = patom.formalcharge
     return oatom
Esempio n. 6
0
 def pybel_to_oasa_atom( self, patom):
   oatom = atom()
   psymbol = num2symbol[patom.atomicnum]
   oatom.symbol = psymbol
   oatom.x, oatom.y, oatom.z = patom.coords
   oatom.charge = patom.formalcharge
   return oatom
Esempio n. 7
0
 def _read_atom(self, at, mol):
     a = atom(self.paper, molecule=mol)
     a.set_name(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(at, "symbol")))
     coords = dom_ext.getFirstChildNamed(at, "coordinates")
     a.x = float(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(coords, "x")))
     a.y = float(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(coords, "y")))
     a.z = float(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(coords, "z")))
     a.show_hydrogens = int(a.name != 'C')
     # charge
     chel = dom_ext.getFirstChildNamed(at, "charge")
     if chel:
         a.charge = int(dom_ext.getAllTextFromElement(chel))
     # multiplicity
     radical = dom_ext.getFirstChildNamed(at, "radical")
     if radical:
         a.multiplicity = 1 + int(dom_ext.getAllTextFromElement(radical))
     # remap of ids
     self._atom_id_remap[at.getAttribute('id')] = a
     return a
Esempio n. 8
0
 def test_intersects(self):
     for this, that, result in [
         ('cat/pkg', 'pkg/cat', False),
         ('cat/pkg', 'cat/pkg', True),
         ('cat/pkg:1', 'cat/pkg:1', True),
         ('cat/pkg:1', 'cat/pkg:2', False),
         ('cat/pkg:1', 'cat/pkg[foo]', True),
         ('cat/pkg[foo]', 'cat/pkg[-bar]', True),
         ('cat/pkg[foo]', 'cat/pkg[-foo]', False),
         ('>cat/pkg-3', '>cat/pkg-1', True),
         ('>cat/pkg-3', '<cat/pkg-3', False),
         ('>=cat/pkg-3', '<cat/pkg-3', False),
         ('>cat/pkg-2', '=cat/pkg-2*', True),
         ('<cat/pkg-2_alpha1', '=cat/pkg-2*', True),
         ('=cat/pkg-2', '=cat/pkg-2', True),
         ('=cat/pkg-3', '=cat/pkg-2', False),
         ('=cat/pkg-2', '>cat/pkg-2', False),
         ('=cat/pkg-2', '>=cat/pkg-2', True),
         ('~cat/pkg-2', '~cat/pkg-2', True),
         ('~cat/pkg-2', '~cat/pkg-2.1', False),
         ('=cat/pkg-2*', '=cat/pkg-2.3*', True),
         ('>cat/pkg-2.4', '=cat/pkg-2*', True),
         ('<cat/pkg-2.4', '=cat/pkg-2*', True),
         ('<cat/pkg-1', '=cat/pkg-2*', False),
         ('~cat/pkg-2', '>=cat/pkg-2-r1', True),
         ('~cat/pkg-2', '<=cat/pkg-2', True),
         ('=cat/pkg-2-r2*', '<=cat/pkg-2-r20', True),
         ('=cat/pkg-2-r2*', '<cat/pkg-2-r20', True),
         ('=cat/pkg-2-r2*', '<=cat/pkg-2-r2', True),
         ('~cat/pkg-2', '<cat/pkg-2', False),
         ('=cat/pkg-1-r10*', '~cat/pkg-1', True),
         ('=cat/pkg-1-r1*', '<cat/pkg-1-r1', False),
         ('=cat/pkg-1*', '>cat/pkg-2', True),
         ('>=cat/pkg-8.4', '=cat/pkg-8.3.4*', False),
         ('cat/pkg::gentoo', 'cat/pkg', True),
         ('cat/pkg::gentoo', 'cat/pkg::foo', False),
         ('=sys-devel/gcc-4.1.1-r3', '=sys-devel/gcc-3.3*', False),
         ('=sys-libs/db-4*', '~sys-libs/db-4.3.29', True),
         ]:
         this_atom = atom(this)
         that_atom = atom(that)
         self.assertEqual(
             result, this_atom.intersects(that_atom),
             '%s intersecting %s should be %s' % (this, that, result))
         self.assertEqual(
             result, that_atom.intersects(this_atom),
             '%s intersecting %s should be %s' % (that, this, result))
Esempio n. 9
0
    def test_random_batch(self):
        for atom_str in invalid_atoms:
            print "%50s <-- invalid" % atom_str
            self.assertRaises(InvalidAtom, atom, atom_str)

        for atom_str in valid_atoms:
            print "%50s < -- valid" % atom_str
            self.assertIsInstance(atom(atom_str), atom)
    def __evaluate__(self,expression):
        fullstack=[]
        if len(expression)<3:fullstack.append(at.atom(self.dualspace[expression[len(expression)-1]],-1,len(expression)-1))
        else:
            left=expression.find("(")
            if left not in [0,1]:
                negate=int(expression[0]=='!')
                fullstack.append(at.atom(self.dualspace[expression[0+negate]],expression[1+negate],negate))
                fullstack.append(self.__evaluate__(expression[2+negate:]))
            else:
                pos=helper.closure(expression,left)
                if len(expression)==pos:fullstack.append(at.atom(self.__evaluate__(expression[1+left:pos-1]).element,-1,left))
                else:
                    fullstack.append(at.atom(self.__evaluate__(expression[1+left:pos-1]).element,expression[pos],left))
                    fullstack.append(self.__evaluate__(expression[pos+1:]))

        return self.reduceExp(fullstack)
Esempio n. 11
0
    def nodes_to_atoms(self, nodes):
        """Creates an atom array out of the atoms names
		:param nodes: names of atoms
		:type nodes: list of strings
		"""
        for node in nodes:
            self.nodes.append(atom.atom(node))
        return self.nodes
Esempio n. 12
0
def read_cdml(text):
    """returns the last molecule for now"""
    doc = dom.parseString(text)
    #if doc.childNodes()[0].nodeName == 'svg':
    #  path = "/svg/cdml/molecule"
    #else:
    #  path = "/cdml/molecule"
    path = "//molecule"
    do_not_continue_this_mol = 0
    for mol_el in dom_ext.simpleXPathSearch(doc, path):
        atom_id_remap = {}
        mol = molecule()
        groups = []
        for atom_el in dom_ext.simpleXPathSearch(mol_el, "atom"):
            name = atom_el.getAttribute('name')
            if not name:
                #print "this molecule has an invalid symbol"
                do_not_continue_this_mol = 1
                break
            pos = dom_ext.simpleXPathSearch(atom_el, 'point')[0]
            x = cm_to_float_coord(pos.getAttribute('x'))
            y = cm_to_float_coord(pos.getAttribute('y'))
            z = cm_to_float_coord(pos.getAttribute('z'))
            if name in PT:
                # its really an atom
                a = atom(symbol=name,
                         charge=atom_el.getAttribute('charge')
                         and int(atom_el.getAttribute('charge')) or 0,
                         coords=(x, y, z))
                mol.add_vertex(v=a)
            elif name in cdml_to_smiles:
                # its a known group
                group = smiles.text_to_mol(cdml_to_smiles[name], calc_coords=0)
                a = group.vertices[0]
                a.x = x
                a.y = y
                a.z = z
                mol.insert_a_graph(group)
            atom_id_remap[atom_el.getAttribute('id')] = a
        if do_not_continue_this_mol:
            break

        for bond_el in dom_ext.simpleXPathSearch(mol_el, "bond"):
            type = bond_el.getAttribute('type')
            if type[1] == u'0':
                # we ignore bonds with order 0
                continue
            v1 = atom_id_remap[bond_el.getAttribute('start')]
            v2 = atom_id_remap[bond_el.getAttribute('end')]
            e = bond(order=int(type[1]), type=type[0])
            mol.add_edge(v1, v2, e=e)

        if mol.is_connected():
            # this is here to handle diborane and similar weird things
            yield mol
        else:
            for comp in mol.get_disconnected_subgraphs():
                yield comp
Esempio n. 13
0
def read_cdml( text):
  """returns the last molecule for now"""
  doc = dom.parseString( text)
  #if doc.childNodes()[0].nodeName == 'svg':
  #  path = "/svg/cdml/molecule"
  #else:
  #  path = "/cdml/molecule"
  path = "//molecule"
  do_not_continue_this_mol = 0
  for mol_el in dom_ext.simpleXPathSearch( doc, path):
    atom_id_remap = {}
    mol = molecule()
    groups = []
    for atom_el in dom_ext.simpleXPathSearch( mol_el, "atom"):
      name = atom_el.getAttribute( 'name')
      if not name:
        #print "this molecule has an invalid symbol"
        do_not_continue_this_mol = 1
        break
      pos = dom_ext.simpleXPathSearch( atom_el, 'point')[0]
      x = cm_to_float_coord( pos.getAttribute('x'))
      y = cm_to_float_coord( pos.getAttribute('y'))
      z = cm_to_float_coord( pos.getAttribute('z'))
      if name in PT:
        # its really an atom 
        a = atom( symbol=name,
                  charge=atom_el.getAttribute( 'charge') and int( atom_el.getAttribute( 'charge')) or 0,
                  coords=( x, y, z))
        mol.add_vertex( v=a)
      elif name in cdml_to_smiles:
        # its a known group
        group = smiles.text_to_mol( cdml_to_smiles[ name], calc_coords=0)
        a = group.vertices[0]
        a.x = x
        a.y = y
        a.z = z
        mol.insert_a_graph( group) 
      atom_id_remap[ atom_el.getAttribute( 'id')] = a
    if do_not_continue_this_mol:
      break

    for bond_el in dom_ext.simpleXPathSearch( mol_el, "bond"):
      type = bond_el.getAttribute( 'type')
      if type[1] == u'0':
        # we ignore bonds with order 0
        continue
      v1 = atom_id_remap[ bond_el.getAttribute( 'start')]
      v2 = atom_id_remap[ bond_el.getAttribute( 'end')]
      e = bond( order=int( type[1]), type=type[0])
      mol.add_edge( v1, v2, e=e)

    if mol.is_connected():
      # this is here to handle diborane and similar weird things
      yield mol
    else:
      for comp in mol.get_disconnected_subgraphs():
        yield comp
 def stackCollapse(self,stack,symbol,fun,isLastinEngine):
     orstack=[]
     i=0
     while i+1<len(stack):
         if stack[i].condition!=symbol:orstack.append(stack[i])
         else:stack[i+1]=at.atom(fun(stack[i].element,stack[i+1].element),stack[i+1].condition)
         i=i+1
     if not isLastinEngine:
         orstack.append(stack[-1])
         return orstack
     else: return stack
Esempio n. 15
0
def oasa_atom_to_bkchem_atom(a, paper, m):
    at = atom.atom(standard=paper.standard, molecule=m)
    at.x = a.x
    at.y = a.y
    at.z = a.z
    at.set_name(a.symbol, interpret=1)
    at.charge = a.charge
    at.number = a.properties_.get('inchi_number', None)
    at.show_number = False
    at.isotope = a.isotope
    at.valency = a.valency
    at.multiplicity = at.multiplicity
    return at
Esempio n. 16
0
def oasa_atom_to_bkchem_atom( a, paper, m):
  at = atom.atom( standard=paper.standard, molecule=m)
  at.x = a.x
  at.y = a.y
  at.z = a.z
  at.set_name( a.symbol, interpret=1)
  at.charge = a.charge
  at.number = a.properties_.get( 'inchi_number', None)
  at.show_number = False
  at.isotope = a.isotope
  at.valency = a.valency
  at.multiplicity = at.multiplicity
  return at
Esempio n. 17
0
    def __init__(self, pdbname, chain = 'all', top='', pfam='', center='CA', cutoff=5, scutoff=1, flag=0, desc='', nbcutoff=4):
        self.atoms=[]
        #dictionary for pairwise distance
        self.pairwiseDict={}
        self.clusters=[]

        #pdb, top, pfam, str, pdbidx, seqheader, alignstr, alignidx, center, cutoff, scutoff, flag, desc
        #self.pdb = pdbname[len(pdbname)-8:len(pdbname)-4]
        self.pdbfile = pdbname
        self.pdb = pdbname[:-4]
        self.chain = chain
        self.top = top
        self.pfam = pfam
        self.center = center
        self.cutoff = cutoff
        self.scutoff = scutoff
        self.seqheader = self.pdb
        self.flag = flag
        self.desc = desc
        
        self.nbcutoff = nbcutoff
        
        
        fin=open(pdbname, 'r')
        lines=fin.readlines()
        fin.close()
        
        aamap = AAmap()
        for i in xrange(0,len(lines)):
            line = lines[i]
            # load only one model
            if 'END' in line[0:6]:
                break
            if line[17:20].strip() not in aamap.AAA2A:
                continue
            if self.chain != 'all':
                if (self.chain != line[21]):
                    continue
            if line[0:6]=='ATOM  ' and (line[16]==' ' or line[16]=='A'): # to avoid alternative location
                self.atoms.append(atom(lines[i]))

        # map for Chain+Resi : (index in sequence, ResName)
        # 'B529': (132, 'V')
        self.resDict = {} # assigned in self.getSeq() function
        self.seq = self.getSeq()

        # map for sequence index: Chain+Resi(ResName)
        # 132 : 'B529(V)'
        self.seqDict = {-1: '.'}
        for r in self.resDict:
            self.seqDict[self.resDict[r][0]] = '%s(%s)' % (r, self.resDict[r][1])
Esempio n. 18
0
def divide_and_conquer(mol, final_detla, scaling, allow_inversion, split = [], vary_rings = 1):
    if not split:
        group_ids = divide_natural(mol, split)
    else:
        group_ids = divide_linear(mol, split)
    group_mols = [mol.copy_subset(i) for i in group_ids]
    mol_to_subset = [{q: i.index(q) for q in range(len(mol.atoms)) if q in i} for i in group_ids]
    subset_to_mol = [{v:k for k, v in i.items()} for i in mol_to_subset]
    # Cap broken bonds with dummy atoms to guarantee that rotatable bonds stay rotatable
    for each_group, each_mts, each_stm in zip(group_mols, mol_to_subset, subset_to_mol):
        tmp = [i for i in each_group.atoms]
        for each_subgroup_atom in tmp:
            each_mol_atom = mol.atoms[each_stm[each_subgroup_atom.get_id()]]
            if len(each_mol_atom.get_bond_ids()) > len(each_subgroup_atom.get_bond_ids()):
                missing_neighbour = [ i for i in each_mol_atom.get_bond_ids() if i not in each_mts]
                for each_missing_id in missing_neighbour:
                    each_group.add_atom(atom.atom(0, *mol.atoms[each_missing_id].coords))
                    each_group.add_bond(each_subgroup_atom.get_id(), len(each_group.atoms) - 1, 1)
                    each_mts[each_missing_id] = len(each_group.atoms) - 1
                    each_stm[len(each_group.atoms) - 1] = each_missing_id
    # Make a list of bonds that will be rotated around in the subgroups
    # Also mark bonds in subgroups that are in rings in the base mol as unrotatable
    mol_fix = []
    sub_fix = []
    sub_rotated = []
    for each_submol, each_sub_to_mol in zip(group_mols, subset_to_mol):
        each_sub_fix = []
        each_sub_rotated = []
        for each_rotatable_bond in find_rotatable_bonds(each_submol):
            full_mol_bond = [each_sub_to_mol[i] for i in each_rotatable_bond]
            if mol.is_in_ring(full_mol_bond[1], full_mol_bond[2]):
                each_sub_fix.append(each_rotatable_bond[1:3])
            else:
                mol_fix.append(full_mol_bond[1:3])
                each_sub_rotated.append(each_rotatable_bond)
        sub_fix.append(each_sub_fix)
        sub_rotated.append(each_sub_rotated)
    # Make the conformer ensembles for each section of the molecule
    group_conformers = []
    for each_subset, each_fix in zip(group_mols, sub_fix):
        base_ensemble = [q for q in make_all_rotations(each_subset, final_detla, scaling, allow_inversion, each_fix, False)]
        group_conformers.append(base_ensemble)
        allow_inversion = False # Only the first subgroup should have its first bond restricted
    # Recombine
    for recombined_mol in recombine(mol, group_conformers, sub_rotated, subset_to_mol):
        count = 0
        for each_conformer in make_all_rotations(recombined_mol, final_detla, scaling, allow_inversion, mol_fix, vary_rings):
            count += 1
            yield each_conformer
Esempio n. 19
0
def read_coord_from_log(log_str):

    coords_sets = []

    for i in gaussian_match.LOG_COORD_MATCH.finditer(log_str):
        i = i.groupdict()['coords'].split('\n')
        i.remove('')
        i.remove(' ')
        coords_sets.append(
            list(
                map(
                    lambda x: atom.atom(int(x.split()[1]),
                                        cartesian=list(
                                            map(float,
                                                x.split()[3:]))), i)))

    return coords_sets
Esempio n. 20
0
 def _read_atom(self, at, mol):
     a = atom(self.paper, molecule=mol)
     a.set_name(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(at, "symbol")))
     coords = dom_ext.getFirstChildNamed(at, "coordinates")
     a.x = float(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(coords, "x")))
     a.y = float(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(coords, "y")))
     a.z = float(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(coords, "z")))
     a.show_hydrogens = int(a.name != "C")
     # charge
     chel = dom_ext.getFirstChildNamed(at, "charge")
     if chel:
         a.charge = int(dom_ext.getAllTextFromElement(chel))
     # multiplicity
     radical = dom_ext.getFirstChildNamed(at, "radical")
     if radical:
         a.multiplicity = 1 + int(dom_ext.getAllTextFromElement(radical))
     # remap of ids
     self._atom_id_remap[at.getAttribute("id")] = a
     return a
Esempio n. 21
0
 def readMOLfile(self,filename):
     try:
         f=open(filename)
     except Exception:
         print 'ERROR LOADING ',filename
         return 1
     for i in xrange(3):
         f.readline()
     natoms=int(f.readline().split()[0])
     atomlist=[]
     for i in xrange(natoms):
         try:
             line=f.readline()
             atomlist.append(atom(line.split()[3],line.split()[0],line.split()[1],line.split()[2]))
             self.molweight+=sym2mass[atomlist[-1].atsym.upper()]
         except Exception:
             print 'ERROR Reading MOL file at line:', line.split()
             break
     f.close()
     return atomlist
Esempio n. 22
0
 def readPDBfile(self,filename):
     try:    
         f=open(filename)
     except Exception:
         print 'ERROR LOADING ',filename
         exit()
     atomlist=[]
     firstatominres=[]
     res='1'    
     firstatominres.append(1)
     resnames=[]
     for line in f.readlines():
         if line.split()[0].strip()=='ATOM':
             atomlist.append(atom(line.split()[2][0],line.split()[5],line.split()[6],line.split()[7],line.split()[2]))
             if len(resnames)==0:
                 resnames.append(line.split()[3])
             if line.split()[4] != res:
                 firstatominres.append(len(atomlist))
                 resnames.append(line.split()[3])
             res=line.split()[4]
     return (atomlist,firstatominres,resnames)
Esempio n. 23
0
    def __read_Atoms(self, DataFile):
        line = DataFile.readline()  # empty line
        self.At = []

        for iAt in range(0, self.NAtoms):
            line = DataFile.readline()
            lineArgs = clean_and_split(line)

            idx = int(lineArgs[0]) - 1
            iSpc = int(lineArgs[1]) - 1
            Type = int(lineArgs[2]) - 1
            charge = float(lineArgs[3])
            xyz = [float(r) for r in lineArgs[4:7]]

            if (len(lineArgs) > 7):
                # we read the image flags as well
                Imag = [int(i) for i in lineArgs[7:]]
            else:
                Imag = np.zeros(3, np.integer)

            AtomIn = atom(idx, iSpc, Type, charge, xyz, Imag)

            self.At.append(AtomIn)
Esempio n. 24
0
	"""
    pass


def proton_decay(parent):
    """
	A proton is ejected from the nucleus. 
	Z is not conserved. 

	Parameters:
	-----------
	parent : atom object
		The parent atom/nucleus

	Returns:
	-------- 
	daughters : atom object or list atom objects
		The daughters produced by the decay mode.
	"""
    pass


if __name__ == '__main__':
    Si_excited = atom.atom([28, 14, 27.976927], excitation=1.779)
    Si, gamma = gamma(Si_excited, 1.779)

    print(Si.energy / 931.5)
    print(gamma.energy)

    print(groundstate(Si))
    # gamma(atom.proton)
Esempio n. 25
0
    #zoom camera
    elif command == '-':
        gui.zoom_out()
    elif command == '+' or command == '=':
        gui.zoom_in()

    #change display colors
    elif command == 'v':
        gui.cycle_display()

    #add atom
    elif command == 'a':
        gui.set_console('Adding Atom')
        position = gui.get_mouse_position()        
        if position != None:
            c.atoms.append(atom.atom(next_atomic_number, position))

    #add electron
    elif command == 'e':
        gui.set_console('Adding Electron')

    #add neutron
    elif command == 'n':
        gui.set_console('Adding Neutron')

    #add photon
    elif command == 'p':
        gui.set_console('Adding Photon')

    #change next atomic number
    elif command == ',' or command == '<':
Esempio n. 26
0
 def create_vertex( self, vertex_class=None):
   if not vertex_class:
     return atom()
   else:
     return vertex_class()
Esempio n. 27
0
	"""
    MeV = 931.5  # a conversion factor

    if charge_balanced(reactants, products):
        qvalue = mass_sum(reactants) - mass_sum(products)

    else:
        reac_balanced, prod_balanced = balance_charge(reactants, products)
        qvalue = mass_sum(reac_balanced) - mass_sum(prod_balanced)

    return qvalue * MeV


if __name__ == '__main__':

    C13 = atom.atom([13, 6, 13.0033548378])
    C12 = atom.atom([12, 6, 12.0])
    C14 = atom.atom([14, 6, 14.003241988])
    N14 = atom.atom([14, 7, 14.003074])
    He4 = atom.atom([4, 2, 4.002603])
    deuteron = atom.atom([2, 1, 2.0135532127], charge=1)
    tritium = atom.atom([3, 1, 3.0160492])
    O16 = atom.atom([16, 8, 15.994915])
    B11 = atom.atom([11, 5, 11.0093055])

    print("13C(d,t)12C")
    print("Q = ", qvalue([C13, deuteron], [C12, tritium]),
          "\n")  #this is correct

    print("14N(n, alpha)11B --> using 4He")
    print("Q = ", qvalue([N14, atom.neutron], [B11, He4]), "\n")
Esempio n. 28
0
 def create_vertex(self, vertex_class=None):
     if not vertex_class:
         return atom()
     else:
         return vertex_class()
Esempio n. 29
0
def divide_and_conquer(mol, final_delta, scaling, allow_inversion, split=[], vary_rings=1):
    '''
    Generate a conformer ensemble using a divide-and-conquer algorithm
    Accepts:
        mol: a molecule object
        final_delta: the smallest step size to use when scannig torsions, in degrees
        scaling: a scaling factor for van der Waals radii, typically 0.7-0.9
        allow_inversion: whether to treat enantiomeric conformers as identical or not
        split: an optional list of bonds as pairs of atom ids to divide on. If not provided,
               the algorithm determines where to split based on the structure of the molecule
        vary rings: How many ring conformers to generate.
            0 => Rings are held fixed in the input geometries
            1 => Rings are flipped
            2 => 2-atom groups within rings are flipped
    Yields:
        A series of conformers as molecule objects
    '''
    if not split:
        group_ids = divide_natural(mol, split)
    else:
        group_ids = divide_linear(mol, split)
    group_mols = [mol.copy_subset(i) for i in group_ids]
    mol_to_subset = [{q: i.index(q) for q in range(len(mol.atoms)) if q in i}
                     for i in group_ids]
    subset_to_mol = [{v: k for k, v in i.items()} for i in mol_to_subset]
    # Cap broken bonds with dummy atoms to guarantee that rotatable bonds stay rotatable
    for each_group, each_mts, each_stm in zip(group_mols, mol_to_subset, subset_to_mol):
        tmp = [i for i in each_group.atoms]
        for each_subgroup_atom in tmp:
            each_mol_atom = mol.atoms[each_stm[each_subgroup_atom.get_id()]]
            if len(each_mol_atom.get_bond_ids()) > len(each_subgroup_atom.get_bond_ids()):
                missing_neighbour = [i for i in each_mol_atom.get_bond_ids()
                                     if i not in each_mts]
                for each_missing_id in missing_neighbour:
                    each_group.add_atom(atom.atom(0, *mol.atoms[each_missing_id].coords))
                    each_group.add_bond(each_subgroup_atom.get_id(), len(each_group.atoms) - 1, 1)
                    each_mts[each_missing_id] = len(each_group.atoms) - 1
                    each_stm[len(each_group.atoms) - 1] = each_missing_id
    # Make a list of bonds that will be rotated around in the subgroups
    # Also mark bonds in subgroups that are in rings in the base mol as unrotatable
    mol_fix = []
    sub_fix = []
    sub_rotated = []
    for each_submol, each_sub_to_mol in zip(group_mols, subset_to_mol):
        each_sub_fix = []
        each_sub_rotated = []
        for each_rotatable_bond in find_rotatable_bonds(each_submol):
            full_mol_bond = [each_sub_to_mol[i] for i in each_rotatable_bond]
            if mol.is_in_ring(full_mol_bond[1], full_mol_bond[2]):
                each_sub_fix.append(each_rotatable_bond[1:3])
            else:
                mol_fix.append(full_mol_bond[1:3])
                each_sub_rotated.append(each_rotatable_bond)
        sub_fix.append(each_sub_fix)
        sub_rotated.append(each_sub_rotated)
    # Make the conformer ensembles for each section of the molecule
    group_conformers = []
    for each_subset, each_fix in zip(group_mols, sub_fix):
        base_ensemble = [q for q in make_all_rotations(each_subset, final_delta, scaling, allow_inversion, each_fix, False)]
        group_conformers.append(base_ensemble)
        allow_inversion = False  # Only the first subgroup should have its first bond restricted
    # Recombine
    for recombined_mol in recombine(mol, group_conformers, sub_rotated, subset_to_mol):
        count = 0
        for each_conformer in make_all_rotations(recombined_mol, final_delta, scaling, allow_inversion, mol_fix, vary_rings):
            count += 1
            yield each_conformer
Esempio n. 30
0
import numpy as np
import sys

WaterDataFile = 'data.singleTIP4P-2005'
NWaters = 2134
NCations = 29
NAnions = 29
DataFileOut = 'data.test'

# read a datafile that contains the water molecule
DataWat = data_lammps(WaterDataFile)

water = data_to_molecule(
    DataWat)  # create a molecule object from the Data input
Cat = atom(idx=0, iSpc=1, Type=2, charge=+1.0, xyz=np.zeros(3, np.double))
An = atom(idx=0, iSpc=2, Type=3, charge=-1.0, xyz=np.zeros(3, np.double))

# what to build is an array of tuples that contains the molecule/atom
# and the corresponding num of the species to be created
what_to_build = [None] * 3
what_to_build[0] = (water, NWaters)
what_to_build[1] = (Cat, NCations)
what_to_build[2] = (An, NAnions)

NSpecies = NWaters + NCations + NAnions

edgeUC = [3.1] * 3
latt = lattice(
    'cub', edgeUC, NSpecies
)  # type of latt, edge lengths of the UC, minimum # of Nodes in the latt
Esempio n. 31
0
    def __init__(self,
                 pdbname,
                 chain='all',
                 top='',
                 pfam='',
                 center='CA',
                 cutoff=5,
                 scutoff=1,
                 flag=0,
                 desc='',
                 nbcutoff=4):
        self.atoms = []
        #dictionary for pairwise distance
        self.pairwiseDict = {}
        self.clusters = []

        #pdb, top, pfam, str, pdbidx, seqheader, alignstr, alignidx, center, cutoff, scutoff, flag, desc
        #self.pdb = pdbname[len(pdbname)-8:len(pdbname)-4]
        self.pdbfile = pdbname
        self.pdb = pdbname[:-4]
        self.chain = chain
        self.top = top
        self.pfam = pfam
        self.center = center
        self.cutoff = cutoff
        self.scutoff = scutoff
        self.seqheader = self.pdb
        self.flag = flag
        self.desc = desc

        self.nbcutoff = nbcutoff
        self.ca = []

        fin = open(pdbname, 'r')
        lines = fin.readlines()
        fin.close()

        lastname = ''
        lastres = ''
        aamap = AAmap()
        for i in xrange(0, len(lines)):
            line = lines[i]
            # load only one model
            if 'END' in line[0:6]:
                break
            if line[17:20].strip() not in aamap.AAA2A:
                continue
            if self.chain != 'all':
                if (self.chain != line[21]):
                    continue
            if line[0:6] == 'ATOM  ':
                at = atom(lines[i])
                if (at.name == lastname) and (at.resSeq == lastres):
                    #print '[%s]::alter loc:\n%s' % (self.pdbfile, lines[i])
                    #if (line[16]==' ' or line[16]=='A'): # to avoid alternative location
                    continue
                else:
                    self.atoms.append(at)
                    if at.name.strip() == 'CA':
                        self.ca.append(at)
                    lastname = at.name
                    lastres = at.resSeq

        # map for Chain+Resi : (index in sequence, ResName)
        # 'B529': (132, 'V')
        self.resDict = {}  # assigned in self.getSeq() function
        # resAtoms, a list of lists, each (element) list contains atoms of residues
        # resArray, gives a list of keys eg. (A,Q,70), (A,I,71), (A,V,72)
        self.seq, self.resArray, self.resAtoms = self.getSeq()

        # some residue does not have CA!! 1e6i.aln.pdb the last residue
        #aamap = AAmap()
        #self.seq = ''.join([aamap.getAAmap(a.resName) for a in self.ca])

        # map for sequence index: Chain+Resi(ResName)
        # 132 : 'B529(V)'
        self.seqDict = {-1: '.'}
        for r in self.resDict:
            self.seqDict[self.resDict[r][0]] = '%s(%s)' % (r,
                                                           self.resDict[r][1])