Ejemplo n.º 1
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])
Ejemplo n.º 2
0
    def _createHydroxy(self, atomA, pos):
        '''
        Erstellt eine Hydroxy-Gruppe an atomA.
        Atom O wird mit einem Index an das C-Atom gehangen und mit dem anderen an ein neu erstelltes H-Atom.
        Fuer verschiedene Positionen der Hydroxy-Gruppe wird jeweils ein anderes Bindungsmodel und andere Indeizes gebraucht.

        Parameter: instance atomA - Atom-Objekt, an das die Hydroxy-Gruppe gebunden werden soll, int pos - Position der Hydroxy-Gruppe
        R�ckgabewerte: Bool/String - erfolgreich/Fehlermeldung
        '''

        indexA = self._universalIndex(atomA)
        if not indexA == "Error":
            if pos == 1 and indexA == 1:
                atomO = Atom("O", 2)
                indexO_1 = 1
                indexO_2 = 0
                atomO.updateBondModel(9)
            elif not pos % 2:
                atomO = Atom("O", 2)
                indexO_1 = 0
                indexO_2 = 1
                atomO.updateBondModel(10)
            else:
                atomO = Atom("O", 2)
                indexO_1 = 1
                indexO_2 = 0
            self._createBond(atomA, atomO, indexA, indexO_1, 1)
            atomH = Atom("H", 1)
            self._createBond(atomO, atomH, indexO_2, 0, 1)
        else:
            return "Tut uns Leid. Dieses Molekuel existiert bei uns nicht. Ueberpruefen Sie die Position des Hydroxy-Gruppe."
        return True
Ejemplo n.º 3
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
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
Archivo: x.py Proyecto: 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)
Ejemplo n.º 6
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
Ejemplo n.º 7
0
Archivo: x.py Proyecto: 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)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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)
Ejemplo n.º 10
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])
Ejemplo n.º 11
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
Ejemplo n.º 12
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)
Ejemplo n.º 13
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))
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
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 )
Ejemplo n.º 16
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
Ejemplo n.º 17
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
Ejemplo n.º 18
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
Ejemplo n.º 19
0
    def ReadFromPdb(self, fname):
        self._Residues = dict()
        self._Atoms = dict()

        with open(fname, "r") as file:
            for line in file.readlines():
                data_type = line[0:6].strip()
                if data_type not in ['ATOM', 'HETATM']:
                    continue
                atom = Atom()
                atom.DataType = line[0:6].strip()
                atom.Name = line[12:16].strip()
                atom.AltLoc = line[16].strip()
                atom.ResName = line[17:20].strip()
                atom.ChainId = line[21].strip()
                atom.ResSeq = int(line[22:26])
                atom.ResCode = line[26].strip()
                atom.Coordinate = np.array(list(map(float, [line[30:38], line[38:46], line[46:54]])))
                atom.Occup = 0.0  # float(line[54:60])
                atom.Tempfac = 0.0  # float(line[60:66])
                atom.Element = atom.Name[0]  # line[76:78].strip()
                num = int(line[6:11])

                if atom.ResSeq not in self._Residues:
                    self._Residues[atom.ResSeq] = dict()

                self._Residues[atom.ResSeq][atom.Name] = atom
                self._Atoms[num] = atom
Ejemplo n.º 20
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
Ejemplo n.º 21
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
Ejemplo n.º 22
0
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)
Ejemplo n.º 23
0
    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)
Ejemplo n.º 24
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()
Ejemplo n.º 25
0
 def __init__(self, pos):
     self.pos = pos
     self.hydrogen = []
     self.bondlength = 0.98
     self.size = 2
     self.central = Atom(self.pos, "oxygen")
     self.bonds = 0
     self.placehydrogen()
Ejemplo n.º 26
0
def make_3ter(r):
    # we add a proton at O3'
    c3, o3 = r.fetchm(['C3\'', 'O3\''])
    v = array(o3.x) - array(c3.x)
    normed = v * 1. / linalg.norm(v)
    newpos = array(o3.x) + normed  #*.1
    a = Atom(name='H3T', x=newpos)
    r.append(a)
Ejemplo n.º 27
0
 def from_pandas(df):
     '''
     '''
     return Element(cnames=[x for x in df.columns],
                    columns=[
                        Atom(df[name], mask=df[name].notnull())
                        for name in df.columns
                    ])
Ejemplo n.º 28
0
        def __set__(self, image):
            _imagedata = image.tostring("raw", "RGBA", 0, 1)
            # Convert to ARGB
            imagedata = ""
            for i in range(0, len(_imagedata), 4):
                imagedata += _imagedata[i + 3] # A
                imagedata += _imagedata[i]     # R
                imagedata += _imagedata[i + 1] # G
                imagedata += _imagedata[i + 2] # B

            data = struct.pack("II{0}s".format(len(imagedata)),
                               image.size[0], image.size[1], imagedata)
            self.connection.core.ChangeProperty(xcb.xproto.Property.NewValue,
                                                self,
                                                Atom(self.connection, "_NET_WM_ICON"),
                                                Atom(self.connection, "CARDINAL"),
                                                32, len(data) / 4, data)
Ejemplo n.º 29
0
    def load_fragments():
        from residue import Residue
        import os

        ref = Residue('REF')
        ref.append_atom(Atom( 'N', [0.000,  0.300, 0.000]))
        ref.append_atom(Atom('CA', [1.181, -0.540, 0.000]))
        ref.append_atom(Atom( 'C', [2.440,  0.300, 0.000]))
        
        # load all residues
        this_dir, this_filename = os.path.split(__file__)
        DATA_PATH = os.path.join(this_dir, "static", "residues.pdb")
        
        residue_container = Molecule.LoadFromFile(DATA_PATH)
        for fragment in residue_container.iter_residues():
            fit(ref, ('N','CA','C'), fragment, ('N','CA','C'))
            FragmentProvider.FRAGMENTS[fragment.name] = fragment
Ejemplo n.º 30
0
 def __init__(self, pos):
     self.pos = pos
     self.hydrogen = []
     self.bondlength = 1.09
     self.size = 0
     self.central = Atom(self.pos, "test-hole")
     self.bonds = 0
     self.placehydrogen()