示例#1
0
 def compositeToBasicRules(self, pred, body, varOrder = None):
     variables = set()
     rules = []
     rule = Rule()
     passOperator = ''
     for literal in body:
         newLiteral = None        
         if isinstance(literal, string_types):
             for literalString in literal.split('^'):
                 if re.match('[!#]?[a-z]+[_0-9\([a-zA-Z,]+\)]?' , literalString):
                     newLiteral = Literal.fromString(literalString)
                     rule.body.append(newLiteral)
                     variables = variables.union(newLiteral.vars())
                 elif re.match('[!#]', literalString):
                     passOperator = literalString
         else:            
             freshPred = freshPredicate()
             (newLiteralVars, newLiteralRules) = Rule.compositeToBasicRules(freshPred, literal)
             rules += newLiteralRules
             newLiteral = Literal.fromString( passOperator + freshPred + '(' + ','.join(newLiteralVars) + ')')
             rule.body.append(newLiteral)
             variables = variables.union(newLiteral.vars())
             passOperator = ''
     if varOrder is not None:
         rule.head = Atom.fromString(pred + '(' + varOrder + ')')        
     else:
         rule.head = Atom.fromString(pred + '(' + ','.join(map(str, variables)) + ')')
     rules.append(rule)  
     return (variables, rules)
示例#2
0
    def __init__(self, sequence):
        self.atoms = []
        initialCoor = coor = (0, 0, 0)
        j = 0
        for i in sequence:
            if j == 0:
                newAtom = Atom(initialCoor, 0.3, i)
                self.addAtom(newAtom)
            else:
                if j % 2 == 1:
                    coor = (j * 1.299, -0.75, 0)
                else:
                    coor = (j * 1.299, 0, 0)
                newAtom = Atom(coor, 0.3, i)
                self.addAtom(newAtom)
            j = j + 1

        #config = MKTFLILALL

        #self.aminoacids = []
        #j = 0
        #angledistance = 4/math.sqrt(3)
        #for i, val in enumerate(chain):
        #for i in chain:
        #    r=4
        #coor = (0,1*(r-1),0)
        #    if i%2 == 1:
        #        coor = (angledistance,r*j,0)
        #    else:
        #        coor = (0,r*j,0)
        #    self.aminoacids.append(Aminoacid(val,coor,config[val]["radius"]))
        #    j = j + 1
        self.disulfideBonds = None
示例#3
0
文件: rule.py 项目: ptsankov/bellog
 def toDatalogRules(self):
     if self.body.operator == '':
         ruleTop = str(self.head.toDatalog('top')) + ' :- ' + str(self.body.subqueries[0].toDatalog('top'))
         ruleBot = str(self.head.toDatalog('bot')) + ' :- ' + str(self.body.subqueries[0].toDatalog('bot'))
         return [ruleTop, ruleBot]        
     elif self.body.operator == '!':
         freshAtom = Atom.freshWithArgs(self.body.getArgs())                             
         ruleTop = str(self.head.toDatalog('top')) + ' :- not_exists(' + str(freshAtom.toDatalog('bot')) + ')'
         ruleBot = str(self.head.toDatalog('bot')) + ' :- not_exists(' + str(freshAtom.toDatalog('top')) + ')'
         subqueryRule = Rule()
         subqueryRule.head = freshAtom
         subqueryRule.body = self.body.subqueries[0]             
         return [ruleTop, ruleBot] + subqueryRule.toDatalogRules()
     elif self.body.operator == '~':
         freshAtom = Atom.freshWithArgs(self.body.getArgs())                             
         ruleTop = str(self.head.toDatalog('top')) + ' :- ' + str(freshAtom.toDatalog('bot'))
         ruleBot = str(self.head.toDatalog('bot')) + ' :- ' + str(freshAtom.toDatalog('top'))
         subqueryRule = Rule()
         subqueryRule.head = freshAtom
         subqueryRule.body = self.body.subqueries[0]             
         return [ruleTop, ruleBot] + subqueryRule.toDatalogRules()
     elif self.body.operator == '^':
         freshAtoms = []
         datalogRules = []
         for subquery in self.body.subqueries:
             freshAtom = Atom.freshWithArgs(subquery.getArgs())
             freshAtoms.append(freshAtom)
             newRule = Rule()
             newRule.head = freshAtom
             newRule.body = subquery
             datalogRules += newRule.toDatalogRules()
         ruleTop = str(self.head.toDatalog('top')) + ' :- ' + ','.join([str(x.toDatalog('top')) for x in freshAtoms])
         ruleBot = str(self.head.toDatalog('bot')) + ' :- ' + ','.join([str(x.toDatalog('bot')) for x in freshAtoms])    
         datalogRules += [ruleTop, ruleBot]
         return datalogRules        
示例#4
0
 def repeat(self,n1,n2,n3):
     #...unit vectors to be repeated
     self.a1= self.a1*n1
     self.a2= self.a2*n2
     self.a3= self.a3*n3
     n123= n1*n2*n3
     nsid= 0
     for ai in self.atoms:
         nsid= max(nsid,ai.sid)
     natm0= self.num_atoms()
     atoms0= copy.copy(self.atoms)
     self.atoms= []
     aid= 0
     for i1 in range(n1):
         for i2 in range(n2):
             for i3 in range(n3):
                 for ai0 in atoms0:
                     aid += 1
                     ai= Atom()
                     ai.sid= ai0.sid
                     ai.symbol= ai0.symbol
                     ai.ifmv= ai0.ifmv
                     x= ai0.pos[0]/n1 +1.0/n1*i1
                     y= ai0.pos[1]/n2 +1.0/n2*i2
                     z= ai0.pos[2]/n3 +1.0/n3*i3
                     ai.set_pos(x,y,z)
                     ai.set_vel(ai0.vel[0],ai0.vel[1],ai0.vel[2])
                     ai.set_id(aid)
                     self.atoms.append(ai)
示例#5
0
 def __get__(self):
     prop = self.connection.core.GetProperty(False, self,
                                             Atom(self.connection, "WM_TRANSIENT_FOR"),
                                             Atom(self.connection, "WINDOW"),
                                             0, 1).reply()
     if prop.value:
         return Window(byte_list_to_uint32(prop.value)[0])
示例#6
0
 def __getattr__(self, name):
     attr = None
     if self.__cachedir__ and Atom.is_cached(self.__cachedir__, name):
         attr = Atom.load(self.__cachedir__,
                          name,
                          is_client=self.__is_client__)
         setattr(self, name, attr)
         return attr
     if self.__source__ is None and self.__factory__ is not None:
         source = self.__factory__()
         self.__source__ = source
         #Not really the right place for this.
         #if self.__cachedir__ is not None:
         #    print '%s = %s' % (self.__cachedir__, len(self))
     if self.__source__ is not None:
         attr = getattr(self.__source__, name)
     if attr is not None and self.__index__ is not None:
         #Although this is simple and effective it is not very efficienct
         #    a = Ai(Bi(C[xy])))
         #Using this method:
         #    ax = Cx[Bi][Ai], xy = ay[Bi][Ai]
         #A better approach is to calculate the index then apply it
         #    bai = Bi[Ai], ax = Cx[bai], ay = Cx[bai]
         attr = attr[self.__index__]
     if attr is not None:
         setattr(self, name, attr)
     return attr
示例#7
0
 def __getattr__(self, name):
     attr = None
     if self.__cachedir__ and Atom.is_cached(self.__cachedir__, name):
         attr = Atom.load(self.__cachedir__, name, is_client=self.__is_client__)
         setattr(self, name, attr)
         return attr
     if self.__source__ is None and self.__factory__ is not None:
         source = self.__factory__()
         self.__source__ = source
         #Not really the right place for this.
         #if self.__cachedir__ is not None:
         #    print '%s = %s' % (self.__cachedir__, len(self))
     if self.__source__ is not None:
         attr = getattr(self.__source__, name)
     if attr is not None and self.__index__ is not None:
         #Although this is simple and effective it is not very efficienct
         #    a = Ai(Bi(C[xy])))
         #Using this method:
         #    ax = Cx[Bi][Ai], xy = ay[Bi][Ai]
         #A better approach is to calculate the index then apply it
         #    bai = Bi[Ai], ax = Cx[bai], ay = Cx[bai]
         attr = attr[self.__index__]
     if attr is not None:
         setattr(self, name, attr)
     return attr
示例#8
0
    def setup_atoms(self):
        # Load atom images
        self.atomImage = pygame.image.load('images/osmos.png')
        self.enemyImage = pygame.image.load('images/osmos-enemy.png')

        self.atoms = []
        add = self.atoms.append

        self.playerAtom = Atom(self.worldWidth / 2, self.worldHeight / 2,
                               self.atomImage.get_width() / 4,
                               self.atomImage.get_height() / 4, self.atomImage,
                               True)

        add(self.playerAtom)
        self.camera.follow(self.playerAtom)

        for x in xrange(ENEMY_COUNT):
            generalSize = random.randint(20, 45)
            multiplier = random.randint(1, 3)

            x = random.randint(1, self.worldWidth)
            y = random.randint(1, self.worldHeight)

            width = (generalSize + random.randint(5, 10)) * multiplier
            height = (generalSize + random.randint(5, 10)) * multiplier

            atom = Atom(x, y, width, height, self.enemyImage)

            self.totalEnemyAtomMass += atom.mass

            add(atom)
示例#9
0
 def __init__(self, file):
     fh = open(file, 'rb')
     size = os.stat(file).st_size
     while fh.tell() < size:
         root_atom = Atom( stream=fh, offset=fh.tell() )
         root_atom.seek( 0, os.SEEK_END )
         self.append( root_atom )
示例#10
0
    def __init__(self, source=None, factory=None, cachedir=None, index=None,
                 cnames=None, name=None, columns=None, is_client=True, kw={}):
        if cachedir and not os.path.exists(cachedir):
            os.makedirs(cachedir)
        self.__cachedir__ = cachedir
        self.__source__ = source
        self.__factory__ = factory
        self.__index__ = index

        #cnames and source.cnames
        def __cnames():
            __cnames = None
            if cnames:
                if hasattr(cnames, '__call__'):
                    __cnames = cnames(self)
                elif isinstance(cnames, str):
                    __cnames = cnames.split(',')
                else:
                    __cnames = cnames
            else:
                __cnames = []
                if source is not None:
                    __cnames += source.__cnames__
                if kw:
                    __cnames += [x for x in kw.keys() if x not in __cnames]
            return __cnames
        self.__cnames__ = __cnames()

        if columns is not None:
            for name, value in zip(self.__cnames__, columns):
                setattr(self, name, value)

        if name is None:
            if source is not None:
                name = source.__name__
            else:
                name = 'element_%s' % id(self)
        self.__name__ = name

        self.__columns__ = columns
        self.__is_client__ = is_client
        for name, value in kw.items():
            if isinstance(value, str):
                value = getcolumn(self, value)
            elif hasattr(value, '__call__'):
                value = value(self)
                if isinstance(value, list):
                    value = Atom.fromlist(value)
                value = value
            if isinstance(value, list):
                value = Atom.fromlist(value)
            elif isinstance(value, np.ndarray) and not isinstance(value, Atom):
                value = Atom(value)
            setattr(self, name, value)

        if cachedir is not None:
            for name in self.__cnames__:
                if not Atom.is_cached(cachedir, name):
                    getattr(self, name).persist(cachedir, name)
示例#11
0
 def WriteAtomToFile(self, elem: Atom) -> None:
     try:
         testFile = open(elem.IDType().Get('Name') + '.txt', 'r')
         testFile.close()
     except (IOError):
         auxFile = open(elem.IDType().Get('Name') + '.txt', 'w')
         auxFile.write(str(elem))
         auxFile.close()
示例#12
0
 def __init__(self, pos):
     self.pos = pos
     self.hydrogen = []
     self.bondlength = 1
     self.central = Atom(self.pos, "carbon")
     self.size = 1
     self.bonds = 0
     self.placehydrogen()
示例#13
0
文件: x.py 项目: jd/bazinga
 def get_text_property(self, window, atom_name):
     prop = self.core.GetProperty(False, window,
                                  Atom(self, atom_name).value,
                                  xcb.xproto.GetPropertyType.Any,
                                  0, 4096).reply()
     if prop.type == Atom(self, "UTF8_STRING").value:
         return unicode(byte_list_to_str(prop.value), "UTF-8")
     elif prop.type == Atom(self, "STRING").value:
         return byte_list_to_str(prop.value)
示例#14
0
文件: window.py 项目: Belluka/pytyle
    def __init__(self):
        if RootWindow._singleton is not None:
            raise RootWindow._singleton

        self.wid = connection.setup.roots[0].root
        Atom.build_cache()
        self.windows = set()

        self.listen()
示例#15
0
 def __init__(self, file_name):
     '''
     Protein class constructor
     Receives the file from which it is to be read. It needs to be in pdb or gro formats.
     Proteins must be ungapped (all resiude numbers must be consecutive).
     Only standard residues are considered.
     '''
     super(Protein, self).__init__()
     ext = file_name.split('.')[-1].lower()
     if ext == 'pdb':
         with open(fileName, 'r') as f:
             fileContent = f.read().split('\n')
         for line in fileContent:
             if line[0:6] in ['TER   ', 'END   ']:
                 return None
             elif line[0:6] == 'ATOM  ':
                 index = int(line[6:11])
                 name = line[12:16].strip()
                 resName = line[17:20].strip()
                 if res_name in ['HIP', 'HIE', 'HID']:
                     res_name = 'HIS'
                 assert res_name in AMINO_ACID_NAMES, \
                         "Only standard residues are considered."
                 resId = int(line[22:26])
                 x = float(line[30:38])
                 y = float(line[38:46])
                 z = float(line[46:54])
                 if resId > 0:
                     try:
                         self.addResidue(Residue(resId, resName))
                     except AssertionError:
                         pass
                     self.addAtom(Atom(index, name, x, y, z), resId)
         q = [x for x in self if x != None]
         assert None not in self[self.index(q[0]):self.index(q[-1])+1], \
                 "Protein contains gaps."
     elif ext == 'gro':
         with open(file_name, 'r') as read_file:
             file_content = read_file.read().split('\n')
         number_of_atoms = int(file_content[1])
         for index in range(number_of_atoms):
             line = file_content[2 + index].split()
             index = int(line[2])
             name = line[1]
             res_name = line[0][-3:]
             res_id = int(line[0][:-3])
             pos_x = float(line[3]) * 10
             pos_y = float(line[4]) * 10
             pos_z = float(line[5]) * 10
             try:
                 self.add_residue(Residue(res_id, res_name))
             except AssertionError:
                 pass
             self.add_atom(Atom(index, name, (pos_x, pos_y, pos_z)), res_id)
     else:
         raise NameError('Unknown file extension')
     return None
示例#16
0
文件: window.py 项目: Belluka/pytyle
    def set_below(self, below):
        self._send_client_event(
            Atom.get_atom('_NET_WM_STATE'),
            [
                1 if below else 0,
                Atom.get_atom('_NET_WM_STATE_BELOW'),
            ]
        )

        connection.push()
示例#17
0
 def read_akr(self,fname='akr0000'):
     f=open(fname,'r')
     # 1st: lattice constant
     self.alc= float(f.readline().split()[0])
     # 2nd-4th: cell vectors
     for i in range(3):
         data= f.readline().split()
         self.a1[i]= float(data[0])
         self.a2[i]= float(data[1])
         self.a3[i]= float(data[2])
     # 5th: num of atoms
     natm= int(f.readline().split()[0])
     # 9th-: atom positions
     self.atoms= []
     symbol = None
     for i in range(natm):
         data= [float(x) for x in f.readline().split()]
         ai= Atom()
         ai.set_sid(data[0])
         ai.set_pos(data[1],data[2],data[3])
         ai.set_vel(data[4],data[5],data[6])
         if self.specorder:
             symbol = self.specorder[ai.sid-1]
         if symbol and ai.symbol != symbol:
             ai.set_symbol(symbol)
         self.atoms.append(ai)
     f.close()
示例#18
0
 def __get__(self):
     prop = self.connection.core.GetProperty(False, self,
                                             Atom(self.connection, "WM_PROTOCOLS"),
                                             Atom(self.connection, "ATOM"),
                                             0, 1024).reply()
     atoms = byte_list_to_uint32(prop.value)
     if atoms:
         protos = set()
         for a in atoms:
             protos.add(Atom(self.connection, a))
         return protos
示例#19
0
 def __init__(self, join, container, outer, axis, *keys):
     self.size           = len(container)
     self.join           = join
     self.axis           = axis
     self.outer          = outer
     _sort_index         = sort_index(container, *keys)
     self.columns        = getcolumns(container[_sort_index], *keys)
     self.bin_counts     = rl.encode(*self.columns)
     self.unique         = [Atom(column, bincounts=[self.bin_counts]).first
                            for column in self.columns]
     self.inverted_index = Atom(_sort_index, bincounts=[self.bin_counts])
示例#20
0
文件: window.py 项目: Belluka/pytyle
    def restore(self):
        self._send_client_event(
            Atom.get_atom('_NET_WM_STATE'),
            [
                0, # _NET_WM_STATE_REMOVE = 0, _NET_WM_STATE_ADD = 1, _NET_WM_STATE_TOGGLE = 2
                Atom.get_atom('_NET_WM_STATE_MAXIMIZED_VERT'),
                Atom.get_atom('_NET_WM_STATE_MAXIMIZED_HORZ')
            ]
        )

        connection.push()
示例#21
0
 def takefocus(self):
     """Send a take focus request to a window."""
     # XXX Seriously, we need to do some stuff for xpyb about this.
     buf = struct.pack("BB2xIIII12x",
                       33, # XCB_CLIENT_MESSAGE
                       32, self, Atom(self.connection, "WM_PROTOCOLS"),
                       Atom(self.connection, "WM_TAKE_FOCUS"),
                       xcb.xproto.Time.CurrentTime)
     self.connection.core.SendEvent(False, self,
                                    xcb.xproto.EventMask.NoEvent,
                                    buf)
示例#22
0
文件: x.py 项目: jd/bazinga
 def set_text_property(self, window, atom_name, value):
     if isinstance(value, unicode):
         string_atom = Atom(self, "UTF8_STRING")
         value = value.encode("UTF-8")
     else:
         string_atom = Atom(self, "STRING")
     self.core.ChangeProperty(xcb.xproto.Property.NewValue,
                              window,
                              Atom(self, atom_name).value,
                              string_atom,
                              8, len(value), value)
示例#23
0
def test_atom_coordination():
    a = Atom(6)
    assert a.get_coordination() == 4
    with pytest.raises(TypeError):
        a.set_coordination(1.0)

    with pytest.raises(ValueError):
        a.set_coordination(5)

    a.set_coordination(3)
    assert a.get_coordination() == 3
示例#24
0
 def test_atomness(self):
     foo = Atom("foo")
     another_foo = Atom("foo")
     bar = Atom("bar")
     baz = Atom("baz")
     
     self.assertTrue(foo == foo)
     self.assertTrue(foo == another_foo)
     self.assertTrue(foo != bar)
     self.assertTrue(baz != bar)
     self.assertTrue(foo != bar != baz)
示例#25
0
 def fromString(self, string):
     newLiteral = Literal()
     if string[0] == '!':
         newLiteral.op = '!'
         newLiteral.atom = Atom.fromString(string[1:])
     elif string[0] == '#':
         newLiteral.op = '#'
         newLiteral.atom = Atom.fromString(string[1:])
     else:
         newLiteral.op = None
         newLiteral.atom = Atom.fromString(string)
     return newLiteral
示例#26
0
文件: window.py 项目: Belluka/pytyle
    def remove_decorations(self):
        if XROOT.wm() == 'openbox':
            self._send_client_event(
                Atom.get_atom('_NET_WM_STATE'),
                [
                    1,
                    Atom.get_atom('_OB_WM_STATE_UNDECORATED')
                ]
            )
        else:
            self._set_property('_MOTIF_WM_HINTS', [2, 0, 0, 0, 0])

        connection.push()
示例#27
0
 def __get__(self):
     prop = self.connection.core.GetProperty(False, self,
                                             Atom(self.connection, "_NET_WM_ICON"),
                                             Atom(self.connection, "CARDINAL"),
                                             # Max icon size is:
                                             #  w  *  h  * (rgba)
                                             0, 256*256*4).reply()
     if len(prop.value) % 4 == 0:
         width, height = byte_list_to_uint32(prop.value[:8])
         return Image.frombuffer("RGBA",
                                 (width, height),
                                 byte_list_to_str(prop.value[8:]),
                                 "raw", "ARGB", 0, 1)
示例#28
0
 def read_POSCAR(self,fname='POSCAR'):
     with open(fname,'r') as f:
         # 1st line: comment
         f.readline()
         # 2nd: lattice constant
         self.alc= float(f.readline().split()[0])
         # 3rd-5th: cell vectors
         self.a1= np.array([float(x) for x in f.readline().split()])
         self.a2= np.array([float(x) for x in f.readline().split()])
         self.a3= np.array([float(x) for x in f.readline().split()])
         # 6th: species names or number of each species
         buff= f.readline().split()
         if not buff[0].isdigit():
             spcs = copy.deepcopy(buff)
             buff= f.readline().split()
             if not self.specorder:
                 self.specorder = spcs
         num_species= np.array([ int(n) for n in buff])
         natm= 0
         for n in num_species:
             natm += n
         #print("Number of atoms = {0:5d}".format(natm))
         # 7th or 8th line: comment
         c7= f.readline()
         if c7[0] in ('s','S'):
             c8= f.readline()
         # Atom positions hereafter
         self.atoms= []
         for i in range(natm):
             buff= f.readline().split()
             ai= Atom()
             sid= 1
             m= 0
             sindex=0
             symbol = None
             for n in num_species:
                 m += n
                 if i < m:
                     if spcs and self.specorder:
                         sid = self.specorder.index(spcs[sindex]) + 1
                         symbol = spcs[sindex]
                     break
                 sid += 1
                 sindex += 1
             ai.set_id(i+1)
             ai.set_sid(sid)
             if symbol:
                 ai.symbol = symbol
             ai.set_pos(float(buff[0]),float(buff[1]),float(buff[2]))
             ai.set_vel(0.0,0.0,0.0)
             self.atoms.append(ai)
示例#29
0
def buildProtein(url_target):
    backboneList, sidechainList, proteinList = [], [], []
    currentPos = 0
    currentAminoAcid, currentSeq = "", ""
    stream = urllib2.urlopen(url_target)
    for line in stream:
        #All Lines Indexes are found: https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/tutorials/pdbintro.html
        if (line[0:4] == "ATOM"):
            """
			This check is in here because, PDB Files do not necessarily have to start their amino acid count
			at 0. Most proteins will have non-amino acid residues before the start of their chain which is
			why the position differs. Additionally, each PDB File defines their amino acids as a single number
			representing the residue number. Which is why we can use that number as a way to detect when the
			start of a new amino acid occurs.

			Therefore, everytime the amino acid residue number changes (and that change is not from 0 to residue
			number) we can assume it is the start of a new amino acid residue.
			"""
            if ((currentPos != int(line[22:26])) and currentPos != 0):
                #When a new amino acid is started, append the completed one
                #Amino Acid, SEQRES, Position, Backbone Atoms [N][Ca][C], Sidechain Atoms [1]...[n]
                proteinList.append(
                    AminoAcid(currentAminoAcid, currentSeq, currentPos,
                              list(backboneList), list(sidechainList)))
                backboneList, sidechainList = [], []  #Reset the lists to empty

            #The index is defined by looking at the PDB Files, they are consistent across all PDB Files
            currentAminoAcid = str(line[17:20])
            currentSeq = str(line[21:22])
            currentPos = int(line[22:26])

            atomName = line[12:16].strip()
            if (atomName in BACKBONE_ATOMS):
                backboneList.append(
                    Atom(atomName, float(line[31:38]), float(line[39:46]),
                         float(line[47:54]), str(line[76:78].replace(" ",
                                                                     ""))))
            else:
                sidechainList.append(
                    Atom(atomName, float(line[31:38]), float(line[39:46]),
                         float(line[47:54]), str(line[76:78].replace(" ",
                                                                     ""))))
    """
	Because we always add the completed Atom after we detect its completion by examining whether or not the 
	residue number changed, we need to do one more append for the LAST amino acid, since there won't be a
	residue change after the last amino acid has been completed
	"""
    proteinList.append(
        AminoAcid(currentAminoAcid, currentSeq, currentPos, list(backboneList),
                  list(sidechainList)))
    return Protein(list(proteinList))
示例#30
0
文件: window.py 项目: Belluka/pytyle
    def _get_property(self, atom_name):
        try:
            if not Atom.get_type_name(atom_name):
                return ''

            rsp = connection.get_core().GetProperty(
                False,
                self.wid,
                Atom.get_atom(atom_name),
                Atom.get_atom_type(atom_name),
                0,
                (2 ** 32) - 1
            ).reply()

            if Atom.get_type_name(atom_name) in ('UTF8_STRING', 'STRING'):
                if atom_name == 'WM_CLASS':
                    return Atom.null_terminated_to_strarray(rsp.value)
                else:
                    return Atom.ords_to_str(rsp.value)
            elif Atom.get_type_name(atom_name) in ('UTF8_STRING[]', 'STRING[]'):
                return Atom.null_terminated_to_strarray(rsp.value)
            else:
                return list(struct.unpack('I' * (len(rsp.value) / 4), rsp.value.buf()))
        except:
            pass
示例#31
0
def structure2aSys(structure, idoffset=1):
    """
    Converts Structure object of pymatgen to NAPSystem object in nap.

    Args:
        structure (Structure): pymatgen Structure object to be converted
        to NAPSystem object..

    Returns:
        aSys (NAPSystem): 
    """
    lattice = structure.lattice
    alc = 1.0
    a1 = np.array(lattice.matrix[0])
    a2 = np.array(lattice.matrix[1])
    a3 = np.array(lattice.matrix[2])
    #... rescale a? vectors
    a1 = a1 / alc
    a2 = a2 / alc
    a3 = a3 / alc
    aSys = NAPSystem()
    aSys.set_lattice(alc, a1, a2, a3)
    for ia in range(structure.num_sites):
        ai = Atom()
        si = structure[ia]
        crd = si.frac_coords
        ai.set_pos(crd[0], crd[1], crd[2])
        sid = structure.symbol_set.index(si.species_string) + idoffset
        ai.set_sid(sid)
        ai.set_id(ia + 1)
        aSys.add_atom(ai)
    return aSys
    def _createBranch(self, position, lenBranch):
        '''
        Erstellt alle Atom-Objekte der Nebenkette. Der Index variiert je nachdem, wo die Nebenkette liegt.
        An die Statusabfragen sind genauere Kommentare geschrieben.

        Parameter: str position - Position in der Hauptkette, an der die Nebenkette liegen soll.
        R�ckgabewerte: Bool/String  - nur zur Ueberpruefung von Fehlermeldungen
        '''
        self._branchNumber += 1
        branch = []
        position = int(position)
        atomA = self._atoms[position - 1]
        firstSideCarbon = Atom("C", 4)
        branch.append(firstSideCarbon)
        if lenBranch > 1 or (position != 3 and position != 7
                             and position % 4 != 0):
            status = self._findStatus(atomA, position)
        else:
            status = self._statusLastAtom(atomA, position)
        if type(status) == str:
            return status
        indexA = self._universalIndex(atomA)
        indexC = self._branchIndex(firstSideCarbon, status)
        self._createBond(atomA, firstSideCarbon, indexA, indexC,
                         1)  # C wird an Hauptkette rangehangen

        for bPos in range(
                0, (lenBranch - 1)):  #  -1 weil oben schon eins erstellt wurde
            atomB = Atom("C", 4)
            branch.append(atomB)
            atomC = branch[bPos]
            if bPos == lenBranch - 2 and (position % 4 == 0 or position == 3
                                          or position == 7):
                status2 = self._statusLastAtom(atomA, position)
                indexB = self._longBranchIndex(atomB, atomC, status2)
                if type(status) == str:
                    return status
            else:
                indexB = self._longBranchIndex(atomB, atomC, status)
            indexC = self._universalIndex(atomC)
            self._createBond(atomC, atomB, indexC, indexB, 1)

        self._addHydrogen(branch)
        self._description += (
            "Zeichne jetzt ueber/unter das " + str(position) +
            ". 'C' der Hauptkette " + str(lenBranch) +
            " weitere/s 'C' und verbinde das 'C', das direkt ueber dem der Hauptkette steht mit diesem."
        )
        return True
示例#33
0
 def dipole(self):
     self.parameter['dipole'] = []
     for k in range(len(self.parameter['e_amp'])):
         if self.d1 == 1:
             j2 = 1.0 / 2.0
         else:
             j2 = 3.0 / 2.0
         n = self.parameter['n']
         tmp = [[0 for i in range(n)] for j in range(n)]
         cs = Atom()
         for i in range(n):
             for j in range(n):
                 d1 = self.index2lfm(i)
                 d2 = self.index2lfm(j)
                 if d1[0] == 0 and d2[0] == 1:
                     q_arr = self.parameter['e_amp'][k][1]
                     for q in q_arr:
                         coef = {
                             'q': q,
                             'L1': 0,
                             'L2': 1,
                             'F1': d1[1],
                             'F2': d2[1],
                             'mf1': d1[2],
                             'mf2': d2[2] + q,
                             'J1': 1.0 / 2.0,
                             'J2': j2,
                             'I': 7.0 / 2.0
                         }
                         tmp[i][j] += cs.dipole_element(**coef)
                 elif d2[0] == 0 and d1[0] == 1:
                     q_arr = self.parameter['e_amp'][k][1]
                     for q in q_arr:
                         coef = {
                             'q': q,
                             'L1': 0,
                             'L2': 1,
                             'F1': d2[1],
                             'F2': d1[1],
                             'mf1': d2[2],
                             'mf2': d1[2] + q,
                             'J1': 1.0 / 2.0,
                             'J2': j2,
                             'I': 7.0 / 2.0
                         }
                         tmp[i][j] += cs.dipole_element(**coef)
                 else:
                     tmp[i][j] = 0.0
         self.parameter['dipole'].append(tmp)
示例#34
0
def read_xyz(path, name, spg, a, b, c, alpha, beta, gamma):
    """
    from C21 database.txt extract infomation to form 21(22) molecules/fragemets
    in a unit cell and return a list of them
    """
    with open(path, "r") as data:
        line = data.readline().strip()
        line = data.readline().strip()
        line = data.readline().strip()
        mol = Molecule()
        while line:
            info = []
            for part in line.split(" "):
                if len(part) > 0:
                    info.append(part)
            mol.addAtom(
                Atom(typ=info[0],
                     coordinate=np.array(
                         [float(info[1]),
                          float(info[2]),
                          float(info[3])])))
            line = data.readline().strip()
        mol.setCellpara(a, b, c, alpha, beta, gamma)
        mol.setSpg(spg)
        mol.setName(name)
    return mol
示例#35
0
def make_sc(latconst=1.0):
    """
    Make a cell of simple cubic structure.
    """
    s= NAPSystem(specorder=_default_specorder)
    #...lattice
    a1= np.array([ 1.0, 0.0, 0.0 ])
    a2= np.array([ 0.0, 1.0, 0.0 ])
    a3= np.array([ 0.0, 0.0, 1.0 ])
    s.set_lattice(latconst,a1,a2,a3)
    p=[0.00, 0.00, 0.00]
    atom= Atom()
    atom.set_pos(p[0],p[1],p[2])
    atom.set_symbol(_default_specorder[0])
    s.add_atom(atom)
    return s
示例#36
0
 def fromCompositeString(self, string):
     newRule = Rule()
     newRule.head = Atom.fromString(string.split(':-')[0])
     body = string.split(':-')[1].replace(' ', '')
     expressions = nestedExpr('[', ']').parseString(body).asList()
     (notused, rules) = Rule.compositeToBasicRules(newRule.head.pred, expressions[0], varOrder = ','.join(newRule.head.args))
     return reversed(rules)
示例#37
0
文件: query.py 项目: ptsankov/bellog
 def fromElements(self, elements):
     query = Query()
     query.subqueries = []
     if elements[0] == '!':
         # negated query
         query.operator = '!'
         subquery = Query.fromElements(elements[1])
         query.subqueries.append(subquery)          
     elif elements[0] == '~':
         # inverted query
         query.operator = '~'
         subquery = Query.fromElements(elements[1])
         query.subqueries.append(subquery)
     elif elements[0] == '(':
         # infix query
         if elements[2] == '^':
             # conjunction            
             query.operator = '^'
             for subqueryElements in elements[1:-1:2]:
                 subquery = Query.fromElements(subqueryElements)                 
                 query.subqueries.append(subquery)
         elif elements[2] in ['-false->', '-bot->', '-top->', '-true->']:
             return Query.fromElements(Query.getOverride(elements[1], elements[2][1:-2], elements[3]))
         elif elements[2] == '-plus-':
             return Query.fromElements(Query.getPlus(elements[1], elements[3]))
         elif elements[2] == '-times-':
             return Query.fromElements(Query.getTimes(elements[1], elements[3]))
         elif elements[2] == '<':
             return Query.fromElements(['!', ['(', ['!', ['(', Query.getEq(elements[3], 'true'), '^', elements[1], ')'] ], '^', ['!', ['(', ['!', Query.getEq(elements[3], 'true')], '^', elements[5], ')'] ], ')' ] ])
     else:
         # atomic query
         query.operator = ''
         query.subqueries.append(Atom.fromElements(elements))
     return query
    def read_from_file(cls, filepath):
        """
        Create an instance of Sentences from an input file.  This file format is given by the
        professor for this class.

        Args:
            filepath <str>: the filepath to the input file.

        Returns:
            <sentences.Sentences>: an instance of the Sentences class with the given clauses in the
                                   input file.
        """
        clauses = []
        f = open(filepath)

        # First read in the clauses
        for line in f:
            clause = []
            if line[0] == '0':
                break
            else:
                line = line.strip().split(' ')
                for l in line:
                    clause.append(Atom(l))
            clauses.append(Clause(clause))

        # Then read in the rest of the input file for the translation
        rest_of_input = []
        for line in f:
            rest_of_input.append(line)
        return cls(clauses, rest_of_input)
示例#39
0
def read(fileObject):
    """Method to read XYZ files.

    atomic coord in Angstroem, atom types in lowercase, format:
    <number of atoms>
    <comment line>
    <atomType x y z>
    <atomType x y z>
    """

    lines = fileObject.readlines()

    atoms = None

    if atoms is None:
        atoms = []

    # by convention the first thing in the xyz is the number of atoms
    nat = int(lines[0])

    # loop over the nat lines
    for line in lines[2:nat + 2]:
        # check if new section begins
        if line.startswith("$"):
            break
        else:
            symbolRaw, x, y, z = line.split()[:4]
            symbolShort = symbolRaw.strip()
            atomSymbol = symbolShort[0].upper() + symbolShort[1:].lower()
            atomPosition = [float(x) / Bohr, float(y) / Bohr, float(z) / Bohr]
            atom = Atom(symbol=atomSymbol, position=atomPosition)
            atoms.append(atom)

    return atoms
示例#40
0
    def make_argument(self, conclusion: Atom):
        """
        Constructs an argument that leads to conclusion.

        :param conclusion: Atom - conclusion
        :return: str - string that describes argument
        """
        if not (conclusion.is_ground()):
            raise ValueError('Invalid conclusion')
        else:
            query_conclusion_str = ':-' + str(conclusion) + '.'
            if self.ask(HornClause.from_str(query_conclusion_str))[0]:
                s = ''
                known_clauses = self.get_clauses(conclusion.predicate)
                for known_clause in known_clauses:
                    subs_dict = unify(known_clause.conclusion, conclusion)
                    if subs_dict:
                        substituted_clause = known_clause.substitute(subs_dict)
                        query = HornClause(None, substituted_clause.premises)
                        found, solutions = self.ask(query)
                        if found:
                            if solutions:
                                substituted_query = query.substitute(solutions[0])
                            else:
                                substituted_query = query
                            for p in substituted_query.premises:
                                s += str(p) + '.\n'
                            s += str(known_clause) + '\n'
                            s += '\u2234 ' + str(conclusion)
                            break
            else:
                s = 'Argument does not exist.'
        return s
示例#41
0
文件: runWeb.py 项目: ptsankov/bellog
def main():
    webStr = None
    queryString = None
    opts, args = getopt.getopt(sys.argv[1:], "i:q:", ["input", "query"])
    for o, a in opts:
        if o == "-i":
            webStr = a
        elif o == "-q":
            queryString = a

    if webStr is None or queryString is None:
        print "Incorrect usage"
        sys.exit(-1)

    xsb = XSB()
    try:
        webStr = webStr.replace("<newline>", "\n")
        polStr = "\n".join([l for l in webStr.split("\n") if ":-" in l])
        policy = Policy.fromString(escapeCharacters(polStr))
        query = Atom.fromElements(Grammar.parseAtom(escapeCharacters(queryString)))
        policy.processPolicy()
        policy.checkQuery(query)
        xsb.loadPolicy(policy)
        print xsb.query(query)
        xsb.close()
    except Exception as e:
        print "Error:", e
        xsb.close()
        sys.exit(-1)
示例#42
0
    def _createDoubleO(self, atomA, pos, suffix):
        '''
        Erstellt eine Doppelbindung zu einem O-Atom-Objekt.
        Reduziert die Anzahl der Bindugen, die atomA hat.
        Setzt fuer verschiedene Positionen verschiedene 'BondModel' , die in graphicMolecule verwendet werden.

        Parameter: instance atomA - Atom-Objekt, an das das O-Objekt mit einer Doppelbindung gebunden wird,
                   int pos - Position des O-Atoms
                   str suffix - funktionelle Gruppe
        R�ckgabewerte: Bool/String - erfolgreich/Fehlermeldung
        '''

        atomA.updateBondNumber(3)
        if suffix == "al":
            if pos == 1:
                atomA.updateBondModel(8)
            elif pos % 2:
                atomA.updateBondModel(4)
            else:
                atomA.updateBondModel(5)
        else:
            if pos % 2:
                atomA.updateBondModel(7)
            else:
                atomA.updateBondModel(6)
        indexA = self._universalIndex(atomA)
        if not indexA == "Error":
            atomO = Atom("O", 1)
            indexO = 0
            self._createBond(atomA, atomO, indexA, indexO, 2)
        else:
            return "Tut uns Leid. Dieses Molekuel existiert bei uns nicht. Ueberpruefen Sie die Anzahl der Bindungen am " + str(
                pos) + ". Atom."
        return True
def generate_AF(p, ruleset):
    """Generates the abstract AF given the ruleset. Note that the appropriate pref relationship is invoked via the argument file."""
    finished = False
    argsOld = set()

    #there is a hack going on here; we generate arguments, and then iterate through to generate rebutters and undercutters in multiple iterations as needed.
    while not finished:
        t = argsOld.union(generate_arguments(p, ruleset, set()))
        args = deepcopy(t)
        for a in t:
            args = args.union(a.subarguments)
        t = deepcopy(args)
        for a in t:
            args = args.union(
                generate_arguments(a.toprule.con.neg(), ruleset, set()))
            args = args.union(
                generate_arguments(Atom(True, a.toprule.name), ruleset, set()))
        if args == argsOld:
            finished = True
        else:
            argsOld = args

    #still better to generate attacks with arguments
    attacks = generate_defeats(args)
    return (args, attacks)
示例#44
0
def read_molecule(r):
    """ (reader) -> Molecule
	Read a single molecule from r and return it
	or return None to signal end of file
	"""
    # if there isnt another line, we're at the end of the file
    line = r.readline()
    if not line:
        return None

    # name of the molecule: "COMPND		name"
    key, name = line.split()

    # other lines are either "END" or "ATOM num kind x y z"
    molecule = Molecule(name)
    reading = True

    while reading:
        line = r.readline()
        if line.startswith('END'):
            reading = False
        else:
            key, num, kind, x, y, z = line.split()
            molecule.add(Atom(num, kind, float(x), float(y), float(z)))

    return molecule
示例#45
0
文件: window.py 项目: Belluka/pytyle
 def set_desktop(self, desk):
     self._send_client_event(
         Atom.get_atom('_NET_WM_DESKTOP'),
         [
             desk,
             2
         ]
     )
示例#46
0
def structure2aSys(structure,idoffset=1):
    """
    Converts Structure object of pymatgen to NAPSystem object in nap.

    Args:
        structure (Structure): pymatgen Structure object to be converted
        to NAPSystem object..

    Returns:
        aSys (NAPSystem): 
    """
    lattice= structure.lattice
    alc= 1.0
    a1= np.array(lattice.matrix[0])
    a2= np.array(lattice.matrix[1])
    a3= np.array(lattice.matrix[2])
    #... rescale a? vectors
    a1= a1/alc
    a2= a2/alc
    a3= a3/alc
    aSys= NAPSystem()
    aSys.set_lattice(alc,a1,a2,a3)
    for ia in range(structure.num_sites):
        ai= Atom()
        si= structure[ia]
        crd= si.frac_coords
        ai.set_pos(crd[0],crd[1],crd[2])
        sid= structure.symbol_set.index(si.species_string)+idoffset
        ai.set_sid(sid)
        ai.set_id(ia+1)
        aSys.add_atom(ai)
    return aSys
示例#47
0
 def dipole(self):
     self.parameter['dipole'] = []
     for k in range(len(self.parameter['e_amp'])):
         if self.d1 == 1:
             j2 = 1.0/2.0
         else:
             j2 = 3.0/2.0
         n=self.parameter['n']
         tmp = [[0 for i in range(n)] for j in range(n)]
         cs = Atom()
         for i in range(n):
             for j in range(n):
                 d1 = self.index2lfm(i)
                 d2 = self.index2lfm(j)
                 if d1[0] == 0 and d2[0] == 1:
                     q_arr=self.parameter['e_amp'][k][1]
                     for q in q_arr:
                         coef = {'q':q,
                                  'L1':0,
                                  'L2':1,
                                  'F1':d1[1],
                                  'F2':d2[1],
                                  'mf1':d1[2],
                                  'mf2':d2[2]+q,
                                  'J1':1.0/2.0,
                                  'J2':j2,
                                  'I':7.0/2.0}
                         tmp[i][j] += cs.dipole_element(**coef)
                 elif d2[0] == 0 and d1[0] == 1:
                     q_arr=self.parameter['e_amp'][k][1]
                     for q in q_arr:
                         coef = {'q':q,
                                  'L1':0,
                                  'L2':1,
                                  'F1':d2[1],
                                  'F2':d1[1],
                                  'mf1':d2[2],
                                  'mf2':d1[2]+q,
                                  'J1':1.0/2.0,
                                  'J2':j2,
                                  'I':7.0/2.0}
                         tmp[i][j] += cs.dipole_element(**coef)
                 else:
                     tmp[i][j] = 0.0
         self.parameter['dipole'].append(tmp)
示例#48
0
文件: window.py 项目: Belluka/pytyle
 def restack(self, below=False):
     self._send_client_event(
         Atom.get_atom('_NET_RESTACK_WINDOW'),
         [
             2 if not below else 1,
             self.wid,
             0
         ]
     )
示例#49
0
def make_bcc(latconst=1.0):
    """
    Make a cell of bcc structure.
    """
    s= NAPSystem(specorder=_default_specorder)
    #...lattice
    a1= np.array([ 1.0, 0.0, 0.0 ])
    a2= np.array([ 0.0, 1.0, 0.0 ])
    a3= np.array([ 0.0, 0.0, 1.0 ])
    s.set_lattice(latconst,a1,a2,a3)
    positions=[(0.00, 0.00, 0.00),
               (0.50, 0.50, 0.50)]
    for p in positions:
        atom= Atom()
        atom.set_pos(p[0],p[1],p[2])
        atom.set_symbol(_default_specorder[0])
        s.add_atom(atom)
    return s
示例#50
0
文件: window.py 项目: Belluka/pytyle
 def activate(self):
     self._send_client_event(
         Atom.get_atom('_NET_ACTIVE_WINDOW'),
         [
             2,
             xcb.xcb.CurrentTime,
             self.wid
         ]
     )
     self.stack(True)
示例#51
0
def attrs(self, **new_columns):
    cnames = self.__cnames__[:]
    new    = Element(source=self)
    for name, val in new_columns.items():
        if isinstance(val, str):
            attr = getcolumn(new, val)
        elif hasattr(val, '__call__'):
            val = val(self)
            if isinstance(val, list):
                val = Atom.fromlist(val)
            attr = val
        elif isinstance(val, list):
            attr = Atom.fromlist(val)
        else:
            attr = val
        setattr(new, name, attr)
        if name not in cnames:
            cnames.append(name)
    new.__cnames__ = cnames
    return new
示例#52
0
文件: run.py 项目: ptsankov/bellog
def main():  
    bellogFilename = None
    queryString = None
    datalogFilename = None    
    opts, args = getopt.getopt(sys.argv[1:], 'i:q:o:', ['input', 'query'])
    for o, a in opts:
        if o == '-i':
            bellogFilename = a
        elif o == '-q':
            queryString = a
        elif o == '-o':
            datalogFilename = a
            
    if bellogFilename is None and (queryString is None or datalogFilename is None):
        print 'Usage: python', sys.argv[0], '-i <BelLog file> -q <query> [-o <Datalog filename>]'
        sys.exit(-1)
       
    fileStr = open(bellogFilename, 'r').read().strip()
    polStr = '\n'.join([l for l in fileStr.split('\n') if ':-' in l])
    try:                
        policy = Policy.fromString(escapeCharacters(polStr))
        if queryString is not None:
            query = Atom.fromElements(Grammar.parseAtom(escapeCharacters(queryString)))
        policy.processPolicy()            
    except Exception as e:
        print 'Error parsing the policy:', e
        sys.exit(-1)                             
       
       
    if queryString is not None:        
        xsb = XSB()    
        try:
            policy.checkQuery(query)                    
            xsb.loadPolicy(policy)        
            print 'Query', queryString, ':', xsb.query(query)
            xsb.close()
        except Exception as e:
            print 'Error loading the policy:', e
            sys.exit(-1)
            xsb.close()
                  
    if datalogFilename is not None:
        if os.path.isfile(datalogFilename):
            msg = 'Override ' + datalogFilename + '?'
            shall = True if raw_input("%s (y/N) " % msg).lower() == 'y' else False
            if not shall:
                sys.exit(-1)
        outFile = open(datalogFilename, 'w')        
        for rule in policy.rules:
            for datalogRule in rule.toDatalogRules():
                outFile.write(datalogRule + '.\n') 
        for datalogRule in XSB.STATIC_RULES:
            outFile.write(datalogRule + '.\n')        
        outFile.close()            
示例#53
0
文件: window.py 项目: Belluka/pytyle
 def close(self):
     self._send_client_event(
         Atom.get_atom('_NET_CLOSE_WINDOW'),
         [
             xcb.xproto.Time.CurrentTime,
             2,
             0,
             0,
             0
         ]
     )
示例#54
0
文件: mdb2fitpot.py 项目: ryokbys/nap
def doc_to_pos(doc,conf):
    """
    Make a pos file, which has pmd format, from a document in MongoDB.
    """
    psys= NAPSystem()
    matrix=doc['calculations'][-1]['output']['crystal']['lattice']['matrix']
    a1= matrix[0]
    a2= matrix[1]
    a3= matrix[2]
    psys.set_lattice(1.0,a1,a2,a3)

    species_ids=conf['species_ids']

    sites= doc['calculations'][-1]['output']['crystal']['sites']
    for site in sites:
        ra= site['abc']
        ai= Atom()
        ai.set_pos(ra[0],ra[1],ra[2])
        ai.set_sid(species_ids[site['species'][0]['element']])
        psys.add_atom(ai)
    return psys
示例#55
0
文件: window.py 项目: Belluka/pytyle
    def _set_property(self, atom_name, value):
        try:
            if isinstance(value, list):
                data = struct.pack(len(value) * 'I', *value)
                data_len = len(value)
            else:
                value = str(value)
                data_len = len(value)
                data = value

            connection.get_core().ChangeProperty(
                xcb.xproto.PropMode.Replace,
                self.wid,
                Atom.get_atom(atom_name),
                Atom.get_atom_type(atom_name),
                Atom.get_atom_length(atom_name),
                data_len,
                data
            )
        except:
            print traceback.format_exc()
示例#56
0
文件: window.py 项目: Belluka/pytyle
    def __init__(self, wsid, x, y, width, height, color=0x000000):
        self._root_depth = connection.setup.roots[0].root_depth
        self._root_visual = connection.setup.roots[0].root_visual
        self._pixel = color

        self.wid  = connection.conn.generate_id()

        connection.get_core().CreateWindow(
            self._root_depth,
            self.wid,
            XROOT.wid,
            x,
            y,
            width,
            height,
            0,
            xcb.xproto.WindowClass.InputOutput,
            self._root_visual,
            xcb.xproto.CW.BackPixel,
            [self._pixel]
        )

        self._set_property('_NET_WM_NAME', 'Place holder')
        self.set_desktop(wsid)
        self._set_property('WM_NAME', 'pytyle-internal-window')
        self._set_property('WM_PROTOCOLS', [Atom.get_atom('WM_DELETE_WINDOW')])
        self._set_property(
            '_PYTYLE_TYPE',
            [
                Atom.get_atom('_PYTYLE_TYPE_PLACE_HOLDER')
            ]
        )

        #self.set_override_redirect(True)
        connection.get_core().MapWindow(self.wid)
        connection.push()
        self._moveresize(x, y, width, height)
        connection.push()
        #self.set_override_redirect(False)
        connection.push()
示例#57
0
def dipole(parameter):
    n = parameter["n"]
    parameter["dipole"] = [[0 for i in range(n)] for j in range(n)]
    cs = Atom()
    for i in range(n):
        for j in range(n):
            d1 = index2lfm(i)
            d2 = index2lfm(j)
            if d1[0] == 0 and d2[0] == 1:
                coef = {
                    "q": 0,
                    "L1": 0,
                    "L2": 1,
                    "F1": d1[1],
                    "F2": d2[1],
                    "mf1": d1[2],
                    "mf2": d2[2],
                    "J1": 1.0 / 2.0,
                    "J2": 1.0 / 2.0,
                    "I": 7.0 / 2.0,
                }
                parameter["dipole"][i][j] = cs.dipole_element(**coef)
            elif d2[0] == 0 and d1[0] == 1:
                coef = {
                    "q": 0,
                    "L1": 0,
                    "L2": 1,
                    "F1": d2[1],
                    "F2": d1[1],
                    "mf1": d2[2],
                    "mf2": d1[2],
                    "J1": 1.0 / 2.0,
                    "J2": 1.0 / 2.0,
                    "I": 7.0 / 2.0,
                }
                parameter["dipole"][i][j] = cs.dipole_element(**coef)
            else:
                parameter["dipole"][i][j] = 0.0
    return parameter
示例#58
0
文件: window.py 项目: Belluka/pytyle
    def _moveresize(self, x, y, width, height):
        #print self.get_wmname(), x, y, width, height
        self._send_client_event(
            Atom.get_atom('_NET_MOVERESIZE_WINDOW'),
            [
                xcb.xproto.Gravity.NorthWest
                | 1 << 8 | 1 << 9 | 1 << 10 | 1 << 11 | 1 << 13,
                x,
                y,
                width,
                height
            ],
            32,
            xcb.xproto.EventMask.StructureNotify
        )

        connection.push()
示例#59
0
文件: builder.py 项目: esguerra/pmx
def make_residue(key,hydrogens = True):
    """ returns a molecule object with
    default geometry"""

    if not library._aacids.has_key(key):
        raise KeyError, "Residue %s not known" % key
    m = Molecule()
    m.unity = 'A'
    m.resname = key
    for i, entry in enumerate(library._aacids[key]):
        if hydrogens == False and entry[0][0] == 'H':
            continue
        else:
            a = Atom()
            a.id = i+1
            a.name = entry[0]
            a.symbol = a.name[0]
            a.x = entry[1]
            a.occ = 1.
            a.resname = key
            a.m = library._atommass[a.symbol]
            a.unity = 'A'
            m.atoms.append(a)
    return m