Example #1
0
 def __init__(self, blueprint, memo = None):
     if type(blueprint) is type(()):
         self.a1 = blueprint[0]
         self.a2 = blueprint[1]
     else:
         self.a1 = Database.instantiate(blueprint.a1, memo)
         self.a2 = Database.instantiate(blueprint.a2, memo)
     if Utility.uniqueID(self.a2) < Utility.uniqueID(self.a1):
         self.a1, self.a2 = self.a2, self.a1
     Utility.uniqueID.registerObject(self)
Example #2
0
 def __init__(self, blueprint, memo=None):
     if type(blueprint) is type(()):
         self.a1 = blueprint[0]
         self.a2 = blueprint[1]
     else:
         self.a1 = Database.instantiate(blueprint.a1, memo)
         self.a2 = Database.instantiate(blueprint.a2, memo)
     if Utility.uniqueID(self.a2) < Utility.uniqueID(self.a1):
         self.a1, self.a2 = self.a2, self.a1
     Utility.uniqueID.registerObject(self)
Example #3
0
 def __init__(self, blueprint, memo):
     if isinstance(blueprint, basestring):
         blueprint = self.blueprintclass(blueprint)
     self.type = blueprint.type
     if hasattr(blueprint, 'name'):
         self.name = blueprint.name
     if memo is None: memo = {}
     memo[id(blueprint)] = self
     for attr in blueprint.instance:
         setattr(self, attr,
                 Database.instantiate(getattr(blueprint, attr), memo))
Example #4
0
 def __init__(self, blueprint, memo):
     if isinstance(blueprint, basestring):
         blueprint = self.blueprintclass(blueprint)
     self.type = blueprint.type
     if hasattr(blueprint, 'name'):
         self.name = blueprint.name
     if memo is None: memo = {}
     memo[id(blueprint)] = self
     for attr in blueprint.instance:
         setattr(self, attr,
                 Database.instantiate(getattr(blueprint, attr), memo))
Example #5
0
def _residueBlueprint(name, model):
    try:
        blueprint = _residue_blueprints[(name, model)]
    except KeyError:
        if model == 'polar':
            name = name + '_uni'
        elif model == 'polar_charmm':
            name = name + '_uni2'
        elif model == 'none':
            name = name + '_noh'
        blueprint = Database.BlueprintGroup(name)
        _residue_blueprints[(name, model)] = blueprint
    return blueprint
Example #6
0
    def __init__(self, file_or_filename, model = 0, alternate_code = 'A'):
        """
        :param file_or_filename: the name of a PDB file, or a file object
        :param model: the number of the model to be used from a
                      multiple model file
        :type model: int
        :param alternate_code: the alternate code to be used for atoms that
                               have multiple positions
        :type alternate_code: str
        """

        if isinstance(file_or_filename, basestring):
            file_or_filename = Database.PDBPath(file_or_filename)
        Scientific.IO.PDB.Structure.__init__(self, file_or_filename,
                                             model, alternate_code)
        self._numberAtoms()
        self._convertUnits()
Example #7
0
 def _init(self):
     # construct PDB map and alternative names
     type = self.type
     if not hasattr(type, 'pdbmap'):
         pdb_dict = {}
         type.pdbmap = [(type.symbol, pdb_dict)]
         offset = 0
         for g in type.groups:
             for name, atom in g.pdbmap[0][1].items():
                 pdb_dict[name] = Database.AtomReference(atom.number + \
                                                         offset)
             offset = offset + len(g.atoms)
     if not hasattr(type, 'pdb_alternative'):
         alt_dict = {}
         for g in type.groups:
             if hasattr(g, 'pdb_alternative'):
                 for key, value in g.pdb_alternative.items():
                     alt_dict[key] = value
         setattr(type, 'pdb_alternative', alt_dict)
Example #8
0
def setPreferences(prefs):

    for k, v in prefs.items():

        if k in PREFERENCES.keys():

            if k == "database_version":

                PREFERENCES[k] = v.lower()

                if PREFERENCES[k] == "nmoldyn":
                    path = os.path.join(GVAR['nmoldyn_path'], 'Database')
                else:
                    path = os.path.join(GVAR['mmtk_path'], 'Database')

                if path not in Database.path:
                    Database.path.insert(0, path)
                else:
                    idx = Database.path.index(path)
                    if idx != 0:
                        Database.path.insert(0, Database.path.pop(idx))
                        Database.atom_types = Database.Database(
                            'Atoms', Database.AtomType)
                        Database.group_types = Database.Database(
                            'Groups', Database.GroupType)
                        Database.molecule_types = Database.Database(
                            'Molecules', Database.MoleculeType)
                        Database.crystal_types = Database.Database(
                            'Crystals', Database.CrystalType)
                        Database.complex_types = Database.Database(
                            'Complexes', Database.ComplexType)
                        Database.protein_types = Database.Database(
                            'Proteins', Database.ProteinType)
                        Proteins._residue_blueprints = {}

            elif k in ["documentation_style", "warning_check_for_new_version"]:
                PREFERENCES[k] = v.lower()

            else:
                PREFERENCES[k] = v
Example #9
0
    def __init__(self, *items, **properties):
        """
        :param items: either a sequence of peptide chain objects, or
                      a string, which is interpreted as the name of a
                      database definition for a protein.
                      If that definition does not exist, the string
                      is taken to be the name of a PDB file, from which
                      all peptide chains are constructed and
                      assembled into a protein.
        :keyword model: one of "all" (all-atom), "no_hydrogens" or "none"
                        (no hydrogens),"polar_hydrogens" or "polar"
                        (united-atom with only polar hydrogens),
                        "polar_charmm" (like "polar", but defining
                        polar hydrogens like in the CHARMM force field),
                        "polar_opls" (like "polar", but defining
                        polar hydrogens like in the latest OPLS force field),
                        "calpha" (only the |C_alpha| atom of each residue).
                        Default is "all".
        :type model: str
        :keyword position: the center-of-mass position of the protein
        :type position: Scientific.Geometry.Vector
        :keyword name: a name for the protein
        :type name: str
        """
        if items == (None,):
            return
        self.name = ''
        if len(items) == 1 and type(items[0]) == type(''):
            try:
                filename = Database.databasePath(items[0], 'Proteins')
                found = 1
            except IOError:
                found = 0
            if found:
                blueprint = Database.BlueprintProtein(items[0])
                items = blueprint.chains
                for attr, value in vars(blueprint).items():
                    if attr not in ['type', 'chains']:
                        setattr(self, attr, value)
            else:
                import PDB
                conf = PDB.PDBConfiguration(items[0])
                model = properties.get('model', 'all')
                items = conf.createPeptideChains(model)
        molecules = []
        for i in items:
            if ChemicalObjects.isChemicalObject(i):
                molecules.append(i)
            else:
                molecules = molecules + list(i)
        for m, i in zip(molecules, range(len(molecules))):
            m._numbers = [i]
            if not m.name:
                m.name = 'chain'+`i`
        ss = self._findSSBridges(molecules)
        new_mol = {}
        for m in molecules:
            new_mol[m] = ([m],[])
        for bond in ss:
            m1 = new_mol[bond[0].topLevelChemicalObject()]
            m2 = new_mol[bond[1].topLevelChemicalObject()]
            if m1 == m2:
                m1[1].append(bond)
            else:
                combined = (m1[0] + m2[0], m1[1] + m2[1] + [bond])
                for m in combined[0]:
                    new_mol[m] = combined
        self.molecules = []
        while new_mol:
            m = new_mol.values()[0]
            for i in m[0]:
                del new_mol[i]
            bonds = m[1]
            if len(m[0]) == 1:
                m = m[0][0]
                m._addSSBridges(bonds)
            else:
                numbers = sum((i._numbers for i in m[0]), [])
                m = ConnectedChains(m[0])
                m._numbers = numbers
                m._addSSBridges(bonds)
                m._finalize()
                for c in m:
                    c.parent = self
            m.parent = self
            self.molecules.append(m)

        self.atoms = []
        self.chains = []
        for m in self.molecules:
            self.atoms.extend(m.atoms)
            if hasattr(m, 'is_connected_chains'):
                for c, name, i in zip(range(len(m)),
                                   m.chain_names, m._numbers):
                    self.chains.append((m, c, name, i))
            else:
                try: name = m.name
                except AttributeError: name = ''
                self.chains.append((m, None, name, m._numbers[0]))
        self.chains.sort(lambda c1, c2: cmp(c1[3], c2[3]))
        self.chains = map(lambda c: c[:3], self.chains)

        self.parent = None
        self.type = None
        self.configurations = {}
        try:
            self.name = properties['name']
            del properties['name']
        except KeyError: pass
        if properties.has_key('position'):
            self.translateTo(properties['position'])
            del properties['position']
        self.addProperties(properties)

        undefined = 0
        for a in self.atoms:
            if a.position() is None:
                undefined += 1
        if undefined > 0 and undefined != len(self.atoms):
            Utility.warning('Some atoms in a protein ' +
                            'have undefined positions.')
Example #10
0
                        module.Line(p2, p2 - bond_vector, material=material2))
                else:
                    objects.append(
                        module.Cylinder(p1,
                                        p1 + bond_vector,
                                        radius,
                                        material=material1))
                    objects.append(
                        module.Cylinder(p2,
                                        p2 - bond_vector,
                                        radius,
                                        material=material2))
        return objects


Database.registerInstanceClass(Bond.blueprintclass, Bond)


#
# Bond angles
#
class BondAngle(object):
    """
    Bond angle
    
    A bond angle is the angle between two bonds that share a common atom.
    It is defined by two bond objects (attributes b1 and b2) and an atom
    object (the common atom, attribute ca).
    """
    def __init__(self, b1, b2, ca):
        self.b1 = b1  # bond 1
Example #11
0
 def createMolecules(self, names = None, permit_undefined=True):
     """
     :param names: If a list of molecule names (as defined in the
                   chemical database) and/or PDB residue names,
                   only molecules mentioned in this list will be
                   constructed. If a dictionary, it is used to map
                   PDB residue names to molecule names. With the
                   default (None), only water molecules are
                   built.
     :type names: list
     :param permit_undefined: If False, an exception is raised
                              when a PDB residue is encountered for
                              which no molecule name is supplied
                              in names. If True, an AtomCluster
                              object is constructed for each unknown
                              molecule.
     :returns: a collection of :class:~MMTK.ChemicalObjects.Molecule objects,
               one for each molecule in the PDB file. Each PDB residue not 
               describing an amino acid or nucleotide residue is considered a
               molecule.
     :rtype: :class:~MMTK.Collections.Collection
     """
     collection = Collections.Collection()
     mol_dicts = [molecule_names]
     if type(names) == type({}):
         mol_dicts.append(names)
         names = None
     for name in self.molecules.keys():
         full_name = None
         for dict in mol_dicts:
             full_name = dict.get(name, None)
         if names is None or name in names or full_name in names:
             if full_name is None and not permit_undefined:
                 raise ValueError("no definition for molecule " + name)
             for molecule in self.molecules[name]:
                 if full_name:
                     m = ChemicalObjects.Molecule(full_name)
                     setConfiguration(m, [molecule])
                 else:
                     pdbdict = {}
                     atoms = []
                     i = 0
                     for atom in molecule:
                         aname = atom.name
                         while aname[0] in string.digits:
                             aname = aname[1:] + aname[0]
                         try:
                             element = atom['element'].strip()
                             a = ChemicalObjects.Atom(element, name = aname)
                         except KeyError:
                             try:
                                 a = ChemicalObjects.Atom(aname[:2].strip(),
                                                          name = aname)
                             except IOError:
                                 a = ChemicalObjects.Atom(aname[:1],
                                                          name = aname)
                         a.setPosition(atom.position)
                         atoms.append(a)
                         pdbdict[atom.name] = Database.AtomReference(i)
                         i += 1
                     m = ChemicalObjects.AtomCluster(atoms, name = name)
                     if len(pdbdict) == len(molecule):
                         # pdbmap is correct only if the AtomCluster has
                         # unique atom names
                         m.pdbmap = [(name, pdbdict)]
                     setConfiguration(m, [molecule])
                 collection.addObject(m)
     return collection
Example #12
0
 def getReference(self, atom):
     if atom.__class__ is Database.AtomReference:
         return atom
     return Database.AtomReference(self.atoms.index(atom))
Example #13
0
        if toplevel:
            return ['<molecule ref="%s"/>' % name]
        else:
            return None

    def getXMLAtomOrder(self):
        if self.type is None:
            atoms = []
            for molecule in self.molecules:
                atoms.extend(molecule.getXMLAtomOrder())
            return atoms
        else:
            return ChemicalObject.getXMLAtomOrder(self)


Database.registerInstanceClass(Atom.blueprintclass, Atom)
Database.registerInstanceClass(Group.blueprintclass, Group)
Database.registerInstanceClass(Molecule.blueprintclass, Molecule)
Database.registerInstanceClass(Crystal.blueprintclass, Crystal)
Database.registerInstanceClass(Complex.blueprintclass, Complex)


class AtomCluster(CompositeChemicalObject, ChemicalObject):
    """
    An agglomeration of atoms

    An atom cluster acts like a molecule without any bonds or atom
    properties. It can be used to represent a group of atoms that
    are known to form a chemical unit but whose chemical properties
    are not sufficiently known to define a molecule.
    """
Example #14
0
            ChemicalObject.writeXML(self, file, memo, toplevel)
        if toplevel:
            return ['<molecule ref="%s"/>' % name]
        else:
            return None

    def getXMLAtomOrder(self):
        if self.type is None:
            atoms = []
            for molecule in self.molecules:
                atoms.extend(molecule.getXMLAtomOrder())
            return atoms
        else:
            return ChemicalObject.getXMLAtomOrder(self)

Database.registerInstanceClass(Atom.blueprintclass, Atom)
Database.registerInstanceClass(Group.blueprintclass, Group)
Database.registerInstanceClass(Molecule.blueprintclass, Molecule)
Database.registerInstanceClass(Crystal.blueprintclass, Crystal)
Database.registerInstanceClass(Complex.blueprintclass, Complex)


class AtomCluster(CompositeChemicalObject, ChemicalObject):

    """
    An agglomeration of atoms

    An atom cluster acts like a molecule without any bonds or atom
    properties. It can be used to represent a group of atoms that
    are known to form a chemical unit but whose chemical properties
    are not sufficiently known to define a molecule.
Example #15
0
    def __init__(self, *items, **properties):
        """
        :param items: either a sequence of peptide chain objects, or
                      a string, which is interpreted as the name of a
                      database definition for a protein.
                      If that definition does not exist, the string
                      is taken to be the name of a PDB file, from which
                      all peptide chains are constructed and
                      assembled into a protein.
        :keyword model: one of "all" (all-atom), "no_hydrogens" or "none"
                        (no hydrogens),"polar_hydrogens" or "polar"
                        (united-atom with only polar hydrogens),
                        "polar_charmm" (like "polar", but defining
                        polar hydrogens like in the CHARMM force field),
                        "polar_opls" (like "polar", but defining
                        polar hydrogens like in the latest OPLS force field),
                        "calpha" (only the |C_alpha| atom of each residue).
                        Default is "all".
        :type model: str
        :keyword position: the center-of-mass position of the protein
        :type position: Scientific.Geometry.Vector
        :keyword name: a name for the protein
        :type name: str
        """
        if items == (None,):
            return
        self.name = ''
        if len(items) == 1 and type(items[0]) == type(''):
            try:
                filename = Database.databasePath(items[0], 'Proteins')
                found = 1
            except IOError:
                found = 0
            if found:
                blueprint = Database.BlueprintProtein(items[0])
                items = blueprint.chains
                for attr, value in vars(blueprint).items():
                    if attr not in ['type', 'chains']:
                        setattr(self, attr, value)
            else:
                import PDB
                conf = PDB.PDBConfiguration(items[0])
                model = properties.get('model', 'all')
                items = conf.createPeptideChains(model)
        molecules = []
        for i in items:
            if ChemicalObjects.isChemicalObject(i):
                molecules.append(i)
            else:
                molecules = molecules + list(i)
        for m, i in zip(molecules, range(len(molecules))):
            m._numbers = [i]
            if not m.name:
                m.name = 'chain'+`i`
        ss = self._findSSBridges(molecules)
        new_mol = {}
        for m in molecules:
            new_mol[m] = ([m],[])
        for bond in ss:
            m1 = new_mol[bond[0].topLevelChemicalObject()]
            m2 = new_mol[bond[1].topLevelChemicalObject()]
            if m1 == m2:
                m1[1].append(bond)
            else:
                combined = (m1[0] + m2[0], m1[1] + m2[1] + [bond])
                for m in combined[0]:
                    new_mol[m] = combined
        self.molecules = []
        while new_mol:
            m = new_mol.values()[0]
            for i in m[0]:
                del new_mol[i]
            bonds = m[1]
            if len(m[0]) == 1:
                m = m[0][0]
                m._addSSBridges(bonds)
            else:
                numbers = sum((i._numbers for i in m[0]), [])
                m = ConnectedChains(m[0])
                m._numbers = numbers
                m._addSSBridges(bonds)
                m._finalize()
                for c in m:
                    c.parent = self
            m.parent = self
            self.molecules.append(m)

        self.atoms = []
        self.chains = []
        for m in self.molecules:
            self.atoms.extend(m.atoms)
            if hasattr(m, 'is_connected_chains'):
                for c, name, i in zip(range(len(m)),
                                   m.chain_names, m._numbers):
                    self.chains.append((m, c, name, i))
            else:
                try: name = m.name
                except AttributeError: name = ''
                self.chains.append((m, None, name, m._numbers[0]))
        self.chains.sort(lambda c1, c2: cmp(c1[3], c2[3]))
        self.chains = map(lambda c: c[:3], self.chains)

        self.parent = None
        self.type = None
        self.configurations = {}
        try:
            self.name = properties['name']
            del properties['name']
        except KeyError: pass
        if properties.has_key('position'):
            self.translateTo(properties['position'])
            del properties['position']
        self.addProperties(properties)

        undefined = 0
        for a in self.atoms:
            if a.position() is None:
                undefined += 1
        if undefined > 0 and undefined != len(self.atoms):
            Utility.warning('Some atoms in a protein ' +
                            'have undefined positions.')
Example #16
0
                    objects.append(module.Cylinder(p1, p2, radius,
                                                   material = material1))
            else:
                if radius is None:
                    objects.append(module.Line(p1, p1+bond_vector,
                                               material = material1))
                    objects.append(module.Line(p2, p2-bond_vector,
                                               material = material2))
                else:
                    objects.append(module.Cylinder(p1, p1+bond_vector, radius,
                                                   material = material1))
                    objects.append(module.Cylinder(p2, p2-bond_vector, radius,
                                                   material = material2))
        return objects

Database.registerInstanceClass(Bond.blueprintclass, Bond)

#
# Bond angles
#
class BondAngle(object):

    """
    Bond angle
    
    A bond angle is the angle between two bonds that share a common atom.
    It is defined by two bond objects (attributes b1 and b2) and an atom
    object (the common atom, attribute ca).
    """

    def __init__(self, b1, b2, ca):