Example #1
0
def addNewOs(new_res, psi, **kw):

    new_N = new_res.atomsMap['N'][0]
    new_CA = new_res.atomsMap['CA'][0]
    new_C = new_res.atomsMap['C'][0]

    new_OXT = addDihedralAtom('OXT',
                              chimera.Element(8),
                              new_C,
                              new_CA,
                              new_N,
                              DIST_C_O,
                              114,
                              psi,
                              residue=new_res)
    new_OXT.drawMode = kw['atomDrawMode']
    new_OXT.bfactor = kw['bFactor']

    addBond(new_OXT, new_C, drawMode=kw['bondDrawMode'])

    avail_bond_pos = bondPositions(bondee=new_C.coord(),
                                   geom=chimera.Atom.Planar,
                                   bondLen=DIST_C_O,
                                   bonded=[a.coord() for a in new_C.neighbors])

    use_point = avail_bond_pos[0]

    new_O = addAtom('O', chimera.Element(8), new_res, use_point)
    new_O.drawMode = kw['atomDrawMode']
    new_O.bfactor = kw['bFactor']

    addBond(new_O, new_C, drawMode=kw['bondDrawMode'])

    return new_O, new_OXT
    def _processMolecules(self, topFile):
        molInfo = {
            'SOL': [
                # atoms
                [('OW', chimera.Element('O'), 1),
                 ('HW1', chimera.Element('H'), 1),
                 ('HW2', chimera.Element('H'), 1)],

                # atom map
                {
                    0: 0,
                    1: 1,
                    2: 2
                },

                # res names
                ['SOL'],

                # res map
                {
                    1: 0
                },

                # bonds
                [[0, 1], [0, 2]]
            ]
        }
        molInfo.update(self.molInfo)
        curRes = None
        line = self._readLine(topFile)
        while line:
            molType, num = line.split()
            num = int(num)
            try:
                atoms, atomMap, resNames, resMap, bonds = \
                   molInfo[molType]
            except KeyError:
                raise ValueError("Unknown molecule type: %s" % molType)
            for i in range(num):
                resBase = len(self.resNames)
                atomBase = len(self.atomNames)
                self.resNames.extend(resNames)
                for atomName, element, resLookup in atoms:
                    self.atomNames.append(atomName)
                    resIndex = resBase + resMap[resLookup]
                    if resIndex != curRes:
                        self.resIndices.append(len(self.atomNames))
                        curRes = resIndex
                    self.elements.append(element)
                for a1, a2 in bonds:
                    i1, i2 = atomMap[a1], atomMap[a2]
                    self.bonds.append((atomBase + i1, atomBase + i2))
            line = self._readLine(topFile)
        return False
Example #3
0
def _methylate(na, n, atomNames):
    added = []
    aname = _getAName("C", atomNames)
    from chimera.molEdit import addAtom
    nn = addAtom(aname, chimera.Element('C'), na.residue, n.coord())
    added.append(nn)
    na.molecule.newBond(na, nn)
    from chimera.bondGeom import bondPositions
    for pos in bondPositions(nn.coord(), 4, 1.1, [na.coord()]):
        hname = _getAName("H", atomNames)
        nh = addAtom(hname, chimera.Element('H'), na.residue, pos)
        added.append(nh)
        na.molecule.newBond(nn, nh)
    return added
Example #4
0
def _phosphorylate(mols, status, deletes):
    replyobj.info("Deleting 5' phosphates from: %s\n" %
                  ", ".join([str(r) for r in deletes]))
    from chimera.molEdit import addAtom
    for r in deletes:
        r.amberName += "5"
        for p in r.atomsMap['P']:
            o = None
            for nb in p.neighbors:
                for nnb in nb.neighbors:
                    if nnb == p:
                        continue
                    if nnb.element.number > 1:
                        o = nb
                        continue
                    r.molecule.deleteAtom(nnb)
                if nb != o:
                    r.molecule.deleteAtom(nb)
            v = p.coord() - o.coord()
            sn = getattr(p, "serialNumber", None)
            r.molecule.deleteAtom(p)
            v.length = 0.96
            addAtom("H5T",
                    chimera.Element('H'),
                    r,
                    o.coord() + v,
                    serialNumber=sn,
                    bondedTo=o)
Example #5
0
    def add_dummy_atom(self,
                       where,
                       name='dum',
                       element=None,
                       residue=None,
                       bonded_to=None,
                       serial=None):
        """
        Adds a placeholder atom at the coordinates specified by `where`

        Parameters
        ----------
        where : chimera.Atom or 3-tuple of float
            Coordinates of target location. A chimera.Atom can be supplied,
            in which case its coordinates will be used (via `.coord()`)
        name : str, optional
            Name for the new atom
        element : chimera.Element, optional
            Element of the new atom
        residue : chimera.Residue, optional
            Residue that will incorporate the new atom
        bonded_to : chimera.Atom, optional
            Atom that will form a bond with new atom
        serial : int
            Serial number that will be assigned to atom

        """
        if isinstance(where, chimera.Atom):
            element = where.element if not element else element
            where = where.coord()
        else:
            element = chimera.Element('C')

        residue = self.mol.residues[-1] if not residue else residue
        return addAtom(name, element, residue, where, serial, bonded_to)
Example #6
0
def addNewCA(last_bbone_ats, new_res, **kw):
    last_CA = last_bbone_ats['CA']
    last_C = last_bbone_ats['C']
    last_O = last_bbone_ats['O']

    new_N = new_res.atomsMap['N'][0]

    ## add the CA atom (not dihedral!)
    ## first, find the location for the new CA atom
    new_CA_bond_pos = bondPositions(
        bondee=new_N.coord(),
        geom=chimera.Atom.Planar,
        bondLen=DIST_CA_N,
        bonded=[a.coord() for a in new_N.neighbors],
        coPlanar=[last_CA.coord(), last_O.coord()])

    shortest_point = getShortestPoint(last_O.coord(), new_CA_bond_pos)

    new_CA = addAtom('CA', chimera.Element(6), new_res, shortest_point)
    new_CA.drawMode = kw['atomDrawMode']
    new_CA.bfactor = kw['bFactor']

    addBond(new_N, new_CA, drawMode=kw['bondDrawMode'])

    return new_CA
Example #7
0
 def computeElements(self):
     self.elements = []
     for i, atom_type in enumerate(self.prmtop['AtomSym']):
         try:
             elementName = atom_type_to_elements[atom_type.upper()]
         except KeyError:
             # use mass
             from Trajectory import determineElementFromMass
             el = determineElementFromMass(self.prmtop['Masses'][i])
         else:
             el = chimera.Element(elements.name.index(elementName))
         self.elements.append(el)
Example #8
0
def patch_mol2_reader(*args, **kwargs):
    """
    Force UCSF Chimera to read UFF atom types in Mol2
    """
    def parse_uff(atom_line):
        atom_type = getattr(atom_line, 'mol2type',
                            None) or atom_line.split().fields[5]
        matches = re.search(r'([A-Za-z]{1,3})[^A-Za-z\s]{0,6}', atom_type)
        element = matches.group(0).title() if matches else atom_type
        return element

    molecules = chimera._openMol2Model_original(*args, **kwargs)
    for molecule in molecules:
        for atom in molecule.atoms:
            atom.element = chimera.Element(parse_uff(atom))
def normalizeMSE(r):
    S = chimera.Element("S")
    from BuildStructure import setBondLength
    for a in r.atoms:
        if a.element.name != "Se":
            continue
        a.element = S
        a.name = "SD"
        a.idatmType = "S3"
        for n, b in a.bondsMap.items():
            if n.name == "CE":
                setBondLength(b, 1.78)
            elif n.name == "CG":
                setBondLength(b, 1.81)
    r.type = "MET"
    replyobj.info("MSE residue %s changed to MET\n" % str(r))
def completeTerminalCarboxylate(cter):
    from chimera.bondGeom import bondPositions
    from chimera.molEdit import addAtom
    if "OXT" in cter.atomsMap:
        return
    try:
        cs = cter.atomsMap["C"]
    except KeyError:
        return
    for c in cs:  # alt locs are possible
        if len(c.primaryBonds()) != 2:
            return
        loc = bondPositions(c.coord(), 3, 1.229,
                            [n.coord() for n in c.primaryNeighbors()])[0]
        oxt = addAtom("OXT", chimera.Element("O"), cter, loc, bondedTo=c)
    replyobj.info("Missing OXT added to C-terminal residue %s\n" % str(cter))
Example #11
0
class FakeHydrogen:
	def __init__(self, atm):
		self.bonded = atm
	element = chimera.Element(1)
	def primaryNeighbors(self):
		return [self.bonded]
	def oslIdent(self):
		return 'FakeHydrogen'
	idatmType = 'HC'
	def xformCoord(self):
		primary = self.primaryNeighbors()[0]
		pos = bondPositions(primary.xformCoord(), 4, 1.0, bonds)
		class FakeCoord:
			pass	
		crd = FakeCoord()
		crd = pos[0]
		return crd
Example #12
0
def convert_gaussian_molecule_to_chimera(path_or_parser):
    if isinstance(path_or_parser, basestring):
        parsed = Gaussian(path_or_parser).parse()
    else:
        parsed = path_or_parser

    elements = parsed.atomnos
    coords = parsed.atomcoords[-1]
    m = chimera.Molecule()
    r = m.newResidue("UNK", " ", 1, " ")
    for i, (element, xyz) in enumerate(zip(elements, coords)):
        element = chimera.Element(element)
        a = m.newAtom('{}{}'.format(element, i), element)
        r.addAtom(a)
        a.setCoord(chimera.Point(*xyz))
        a.serialNumber = i
    chimera.connectMolecule(m)
    return m
Example #13
0
def addNewN(last_bbone_ats, new_res, **kw):

    ## add the N atom of new residue's backbone to the last residue
    last_C = last_bbone_ats['C']

    new_N_bond_pos = bondPositions(
        bondee=last_C.coord(),
        geom=chimera.Atom.Planar,
        bondLen=DIST_N_C,
        bonded=[a.coord() for a in last_C.neighbors])

    use_point = new_N_bond_pos[0]
    new_N = addAtom('N', chimera.Element(7), new_res, use_point)
    new_N.drawMode = kw['atomDrawMode']
    new_N.bfactor = kw['bFactor']

    addBond(last_C, new_N, drawMode=kw['bondDrawMode'])

    return new_N
def _mutateSugarSe(r):
    for a in r.atoms:
        if a.name == "CA'":
            for nb in a.neighbors:
                if nb.element.number == 1:
                    r.molecule.deleteAtom(nb)
            r.molecule.deleteAtom(a)
            break
    O = chimera.Element("O")
    from BuildStructure import setBondLength
    for a in r.atoms:
        if a.element.name != "Se":
            continue
        a.element = O
        a.name = "O2'"
        a.idatmType = "O3"
        for n, b in a.bondsMap.items():
            if n.name == "C2'":
                setBondLength(b, 1.43)
Example #15
0
def reposLastO(last_res, last_bbone_ats, atom_drawMode, bond_drawMode):
    ## reposition the last residue's 'O' atom
    last_O = getBboneAtom(last_res, 'O')
    last_res.molecule.deleteAtom(last_O)

    last_C = last_bbone_ats['C']
    last_CA = last_bbone_ats['CA']

    old_O_bond_pos = bondPositions(
        bondee=last_C.coord(),
        geom=chimera.Atom.Planar,
        bondLen=1.229,
        bonded=[a.coord() for a in last_C.neighbors])

    ## should only be one spot left
    old_O_bond_pos = old_O_bond_pos[0]
    new_O = addAtom('O', chimera.Element(8), last_res, old_O_bond_pos)
    new_O.drawMode = atom_drawMode
    addBond(new_O, last_C, drawMode=bond_drawMode)

    return new_O
Example #16
0
def addNewC(last_bbone_ats, new_res, phi, **kw):

    last_C = last_bbone_ats['C']

    new_CA = new_res.atomsMap['CA'][0]
    new_N = new_res.atomsMap['N'][0]

    new_C = addDihedralAtom('C',
                            chimera.Element(6),
                            new_CA,
                            new_N,
                            last_C,
                            DIST_C_CA,
                            109.5,
                            phi,
                            residue=new_res)
    new_C.drawMode = kw['atomDrawMode']
    new_C.bfactor = kw['bFactor']

    addBond(new_CA, new_C, drawMode=kw['bondDrawMode'])

    return new_C
Example #17
0
def restoreMolecules(molInfo, resInfo, atomInfo, bondInfo, crdInfo):
    from SimpleSession import registerAttribute
    items = []
    sm = globals.sessionMap

    res2mol = []
    atom2mol = []
    for ids, name, cid, display, lineWidth, pointSize, stickScale, \
    pdbHeaders, surfaceOpacity, ballScale, vdwDensity, autochain, \
    ribbonHidesMainchain, riCID, aromaticCID, aromaticDisplay, \
    aromaticLineType, aromaticMode, hidden in zip(
       expandSummary(molInfo['ids']),
       expandSummary(molInfo['name']),
       expandSummary(molInfo['color']),
       expandSummary(molInfo['display']),
       expandSummary(molInfo['lineWidth']),
       expandSummary(molInfo['pointSize']),
       expandSummary(molInfo['stickScale']),
       molInfo['pdbHeaders'],
       expandSummary(molInfo['surfaceOpacity']),
       expandSummary(molInfo['ballScale']),
       expandSummary(molInfo['vdwDensity']),
       expandSummary(molInfo['autochain']),
       expandSummary(molInfo['ribbonHidesMainchain']),
       expandSummary(molInfo['ribbonInsideColor']),
       expandSummary(molInfo['aromaticColor']),
       expandSummary(molInfo['aromaticDisplay']),
       expandSummary(molInfo['aromaticLineType']),
       expandSummary(molInfo['aromaticMode']),
       expandSummary(molInfo['hidden'])
       ):
        m = chimera.Molecule()
        sm[len(items)] = m
        items.append(m)
        m.name = name
        from SimpleSession import modelMap, modelOffset
        chimera.openModels.add([m],
                               baseId=ids[0] + modelOffset,
                               subid=ids[1],
                               hidden=hidden)
        modelMap.setdefault(ids, []).append(m)
        m.color = getColor(cid)
        m.display = display
        m.lineWidth = lineWidth
        m.pointSize = pointSize
        m.stickScale = stickScale
        m.setAllPDBHeaders(pdbHeaders)
        m.surfaceOpacity = surfaceOpacity
        m.ballScale = ballScale
        m.vdwDensity = vdwDensity
        m.autochain = autochain
        m.ribbonHidesMainchain = ribbonHidesMainchain
        m.ribbonInsideColor = getColor(riCID)
        m.aromaticColor = getColor(aromaticCID)
        m.aromaticDisplay = aromaticDisplay
        m.aromaticLineType = aromaticLineType
        m.aromaticMode = aromaticMode
    if molInfo['optional']:
        for attrName, info in molInfo['optional'].items():
            hashable, sv = info
            registerAttribute(chimera.Molecule, attrName, hashable=hashable)
            vals = expandSummary(sv, hashable=hashable)
            for m, val in zip(items, vals):
                if val is not None:
                    setattr(m, attrName, val)

    resStart = len(items)
    for mid, name, chain, pos, insert, rcid, lcid, ss, ssId, ribbonDrawMode, \
    ribbonDisplay, label, labelOffset, isHet, fillDisplay, fillMode in zip(
       expandSummary(resInfo['molecule']),
       expandSummary(resInfo['name']),
       expandSummary(resInfo['chain']),
       expandSequentialSummary(resInfo['position']),
       expandSummary(resInfo['insert']),
       expandSummary(resInfo['ribbonColor']),
       expandSummary(resInfo['labelColor']),
       expandSummary(resInfo['ss']),
       expandSummary(resInfo['ssId']),
       expandSummary(resInfo['ribbonDrawMode']),
       expandSummary(resInfo['ribbonDisplay']),
       expandSummary(resInfo['label']),
       expandSummary(resInfo['labelOffset']),
       expandSummary(resInfo['isHet']),
       expandSummary(resInfo['fillDisplay']),
       expandSummary(resInfo['fillMode']),
       ):
        m = idLookup(mid)
        r = m.newResidue(name, chain, pos, insert)
        sm[len(items)] = r
        items.append(r)
        r.ribbonColor = getColor(rcid)
        r.labelColor = getColor(lcid)
        r.isHelix, r.isStrand, r.isTurn = ss
        r.ssId = ssId
        r.ribbonDrawMode = ribbonDrawMode
        r.ribbonDisplay = ribbonDisplay
        r.label = label
        if labelOffset is not None:
            r.labelOffset = labelOffset
        r.isHet = isHet
        r.fillDisplay = fillDisplay
        r.fillMode = fillMode
    if resInfo['optional']:
        residues = items[resStart:]
        for attrName, info in resInfo['optional'].items():
            hashable, sv = info
            registerAttribute(chimera.Residue, attrName, hashable=hashable)
            vals = expandSummary(sv, hashable=hashable)
            for r, val in zip(residues, vals):
                if val is not None:
                    setattr(r, attrName, val)

    atomStart = len(items)
    for rid, name, element, cid, vcid, lcid, scid, drawMode, display, \
    label, labelOffet, surfaceDisplay, surfaceCategory, surfaceOpacity, \
    radius, vdw, idatmType, altLoc in zip(
       expandSummary(atomInfo['residue']),
       expandSummary(atomInfo['name']),
       expandSummary(atomInfo['element']),
       expandSummary(atomInfo['color']),
       expandSummary(atomInfo['vdwColor']),
       expandSummary(atomInfo['labelColor']),
       expandSummary(atomInfo['surfaceColor']),
       expandSummary(atomInfo['drawMode']),
       expandSummary(atomInfo['display']),
       expandSummary(atomInfo['label']),
       expandSummary(atomInfo['labelOffset']),
       expandSummary(atomInfo['surfaceDisplay']),
       expandSummary(atomInfo['surfaceCategory']),
       expandSummary(atomInfo['surfaceOpacity']),
       expandSummary(atomInfo['radius']),
       expandSummary(atomInfo['vdw']),
       expandSummary(atomInfo['idatmType']),
       expandSummary(atomInfo['altLoc'])
       ):
        r = idLookup(rid)
        a = r.molecule.newAtom(name, chimera.Element(element))
        sm[len(items)] = a
        items.append(a)
        r.addAtom(a)
        a.color = getColor(cid)
        a.vdwColor = getColor(vcid)
        a.labelColor = getColor(lcid)
        a.surfaceColor = getColor(scid)
        a.drawMode = drawMode
        a.display = display
        a.label = label
        if labelOffset is not None:
            a.labelOffset = labelOffset
        a.surfaceDisplay = surfaceDisplay
        a.surfaceCategory = surfaceCategory
        a.surfaceOpacity = surfaceOpacity
        a.radius = radius
        a.vdw = vdw
        if idatmType:
            a.idatmType = idatmType
        a.altLoc = altLoc
    if atomInfo['optional']:
        atoms = items[atomStart:]
        for attrName, info in atomInfo['optional'].items():
            hashable, sv = info
            registerAttribute(chimera.Atom, attrName, hashable=hashable)
            vals = expandSummary(sv, hashable=hashable)
            for a, val in zip(atoms, vals):
                if val is not None:
                    setattr(a, attrName, val)

    bondStart = len(items)
    for atoms, drawMode, display, label, labelOffset, radius in zip(
            bondInfo['atoms'], expandSummary(bondInfo['drawMode']),
            expandSummary(bondInfo['display']),
            expandSummary(bondInfo['label']),
            expandSummary(bondInfo['labelOffset']),
            expandSummary(bondInfo['radius'])):
        a1, a2 = [idLookup(a) for a in atoms]
        b = a1.molecule.newBond(a1, a2)
        sm[len(items)] = b
        items.append(b)
        b.drawMode = drawMode
        b.display = display
        b.label = label
        if labelOffset is not None:
            b.labelOffset = labelOffset
        b.radius = radius
    if bondInfo.get('optional', {}):
        bonds = items[bondStart:]
        for attrName, info in bondInfo['optional'].items():
            hashable, sv = info
            registerAttribute(chimera.Bond, attrName, hashable=hashable)
            vals = expandSummary(sv, hashable=hashable)
            for b, val in zip(bonds, vals):
                if val is not None:
                    setattr(b, attrName, val)

    from chimera import Point
    for mid, crdSets in crdInfo.items():
        m = idLookup(mid)
        active = crdSets.pop('active')
        for key, crds in crdSets.items():
            coordSet = m.newCoordSet(key, len(crds))
            for aid, crdString in crds:
                idLookup(aid).setCoord(
                    Point(*tuple([float(c) for c in crdString.split()])),
                    coordSet)
            if key == active:
                m.activeCoordSet = coordSet
Example #18
0
            if test == "model" and a.molecule != nb.molecule:
                continue
            clash = a.radius + nb.radius - a.xformCoord().distance(
                nb.xformCoord())
            if hbondAllowance:
                if (_donor(a) and _acceptor(nb)) or (_donor(nb)
                                                     and _acceptor(a)):
                    clash -= hbondAllowance
            if clash < clashThreshold:
                continue
            clashes.setdefault(a, {})[nb] = clash
            clashes.setdefault(nb, {})[a] = clash
    return clashes


hyd = chimera.Element(1)
negative = set([chimera.Element(sym) for sym in ["N", "O", "S"]])
from chimera.idatm import typeInfo


def _donor(a):
    if a.element == hyd:
        if a.neighbors and a.neighbors[0].element in negative:
            return True
    elif a.element in negative:
        try:
            if len(a.bonds) < typeInfo[a.idatmType].substituents:
                # implicit hydrogen
                return True
        except KeyError:
            pass
Example #19
0
File: mmcif.py Project: gregdp/mapq
def ReadMol ( fpath, log=False ) :

    from random import random

    cif, loops = ReadCif ( fpath, log )

    # descriptions by chain id:
    descrByEntityId = GetEntityDescr ( cif, loops )

    try :
        atoms = loops['_atom_site']['data']
        print " - %d atom records" % len(atoms)
    except :
        print " - no atoms in cif?"
        return None

    labels = loops['_atom_site']['labels']
    if 0 :
        print "Labels:"
        for l in labels :
            print " : ", l

    import time
    start = time.time()

    rmap = {}

    nmol = chimera.Molecule()
    from os import path
    #nmol.name = path.splitext ( path.split (fpath)[1] )[0]
    nmol.name = path.split (fpath) [1]
    nmol.openedAs = [ fpath, [] ]
    nmol.cif = cif
    nmol.cifLoops = loops

    nmol.chainColors = {}
    nmol.chainDescr = {}

    numQ = 0
    first = True
    for at in atoms :
        mp = at['asMap']

        if log and first :
            #for label, val in mp.iteritems () :
            for li, label in enumerate ( labels ) :
                print "   %d : %s : %s" % (li+1, label, mp[label])

        first = False

        atType = mp['type_symbol']
        atName = mp['label_atom_id']
        rtype = mp['label_comp_id']
        chainId = mp['label_asym_id']
        chainEId = mp['label_entity_id']
        px = mp['Cartn_x']
        py = mp['Cartn_y']
        pz = mp['Cartn_z']
        occ = mp['occupancy']
        bfactor = mp['B_iso_or_equiv']
        altLoc = mp['label_alt_id']
        if altLoc == "." : altLoc = ''

        if chainEId in descrByEntityId :
            nmol.chainDescr [chainId] = descrByEntityId [chainEId]

        resId = ResId ( mp )
        if resId == None :
            continue

        ris = "%s%d" % (chainId, resId)
        res = None
        if not ris in rmap :
            res = nmol.newResidue ( rtype, chimera.MolResId(chainId, resId) )
            rmap[ris] = res
        else :
            res = rmap[ris]

        clr = None
        if not chainId in nmol.chainColors :
            clr = chimera.MaterialColor ( random(), random(), random(), 1.0 )
            nmol.chainColors[chainId] = clr
            if 0 and log :
                print " - chain %s" % chainId
        else :
            clr = nmol.chainColors [chainId]

        nat = nmol.newAtom ( atName, chimera.Element(atType) )

        drawRib = rtype in protein3to1 or rtype in nucleic3to1

        #aMap[at] = nat
        res.addAtom( nat )
        nat.setCoord ( chimera.Point( float(px), float(py), float(pz) ) )
        nat.altLoc = altLoc
        nat.occupancy = float(occ)
        nat.bfactor = float(bfactor)

        if 'Q-score' in mp :
            try :
                Q = float ( mp['Q-score'] )
                nat.Q = Q
                numQ += 1
            except :
                #print " - q score is",  mp['Q-score']
                pass

    end = time.time()
    print " - created %d atoms, %.1fs, %d q-scores" % ( len(nmol.atoms), end-start, numQ )

    return nmol
 def append_node(molecule, list, residue):
     at = molecule.newAtom("Tunnel", chimera.Element("Tunn"))
     at.setCoord(chimera.Coord(list[0], list[1], list[2]))
     at.radius = list[3]
     residue.addAtom(at)
def restoreMolecules(molInfo, resInfo, atomInfo, bondInfo, crdInfo):
    items = []
    sm = globals.sessionMap

    res2mol = []
    atom2mol = []
    openModelsArgs = {}
    for ids, name, cid, display, lineWidth, pointSize, stickScale, \
    pdbHeaders, surfaceOpacity, ballScale, vdwDensity, autochain, \
    ribbonHidesMainchain in zip(
       expandSummary(molInfo['ids']),
       expandSummary(molInfo['name']),
       expandSummary(molInfo['color']),
       expandSummary(molInfo['display']),
       expandSummary(molInfo['lineWidth']),
       expandSummary(molInfo['pointSize']),
       expandSummary(molInfo['stickScale']),
       molInfo['pdbHeaders'],
       expandSummary(molInfo['surfaceOpacity']),
       expandSummary(molInfo['ballScale']),
       expandSummary(molInfo['vdwDensity']),
       expandSummary(molInfo['autochain']),
       expandSummary(molInfo['ribbonHidesMainchain'])
       ):
        m = chimera.Molecule()
        sm[len(items)] = m
        items.append(m)
        m.name = name
        from SimpleSession import modelMap, modelOffset
        chimera.openModels.add([m], baseId=ids[0] + modelOffset, subid=ids[1])
        modelMap.setdefault(ids, []).append(m)
        m.color = getColor(cid)
        m.display = display
        m.lineWidth = lineWidth
        m.pointSize = pointSize
        m.stickScale = stickScale
        m.setAllPDBHeaders(pdbHeaders)
        m.surfaceOpacity = surfaceOpacity
        m.ballScale = ballScale
        m.vdwDensity = vdwDensity
        m.autochain = autochain
        m.ribbonHidesMainchain = ribbonHidesMainchain

    for mid, name, chain, pos, insert, rcid, lcid, ss, ribbonDrawMode, \
    ribbonDisplay, label in zip(
       expandSummary(resInfo['molecule']),
       expandSummary(resInfo['name']),
       expandSummary(resInfo['chain']),
       resInfo['position'],
       expandSummary(resInfo['insert']),
       expandSummary(resInfo['ribbonColor']),
       expandSummary(resInfo['labelColor']),
       expandSummary(resInfo['ss']),
       expandSummary(resInfo['ribbonDrawMode']),
       expandSummary(resInfo['ribbonDisplay']),
       expandSummary(resInfo['label'])
       ):
        m = idLookup(mid)
        r = m.newResidue(name, chain, pos, insert)
        sm[len(items)] = r
        items.append(r)
        r.ribbonColor = getColor(rcid)
        r.labelColor = getColor(lcid)
        r.isHelix, r.isStrand, r.isTurn = ss
        r.ribbonDrawMode = ribbonDrawMode
        r.ribbonDisplay = ribbonDisplay
        r.label = label

    for rid, name, element, cid, vcid, lcid, scid, drawMode, display, \
    label, surfaceDisplay, surfaceCategory, surfaceOpacity, radius, vdw, \
    bfactor, occupancy, charge, idatmType in zip(
       expandSummary(atomInfo['residue']),
       expandSummary(atomInfo['name']),
       expandSummary(atomInfo['element']),
       expandSummary(atomInfo['color']),
       expandSummary(atomInfo['vdwColor']),
       expandSummary(atomInfo['labelColor']),
       expandSummary(atomInfo['surfaceColor']),
       expandSummary(atomInfo['drawMode']),
       expandSummary(atomInfo['display']),
       expandSummary(atomInfo['label']),
       expandSummary(atomInfo['surfaceDisplay']),
       expandSummary(atomInfo['surfaceCategory']),
       expandSummary(atomInfo['surfaceOpacity']),
       expandSummary(atomInfo['radius']),
       expandSummary(atomInfo['vdw']),
       expandSummary(atomInfo['bfactor']),
       expandSummary(atomInfo['occupancy']),
       expandSummary(atomInfo['charge']),
       expandSummary(atomInfo['idatmType'])
       ):
        r = idLookup(rid)
        a = r.molecule.newAtom(name, chimera.Element(element))
        sm[len(items)] = a
        items.append(a)
        r.addAtom(a)
        a.color = getColor(cid)
        a.vdwColor = getColor(vcid)
        a.labelColor = getColor(lcid)
        a.surfaceColor = getColor(scid)
        a.drawMode = drawMode
        a.display = display
        a.label = label
        a.surfaceDisplay = surfaceDisplay
        a.surfaceCategory = surfaceCategory
        a.surfaceOpacity = surfaceOpacity
        a.radius = radius
        a.vdw = vdw
        if bfactor is not None:
            a.bfactor = bfactor
        if occupancy is not None:
            a.occupancy = occupancy
        if charge is not None:
            a.charge = charge
        if idatmType:
            a.idatmType = idatmType

    for atoms, drawMode, display in zip(bondInfo['atoms'],
                                        expandSummary(bondInfo['drawMode']),
                                        expandSummary(bondInfo['display'])):
        a1, a2 = [idLookup(a) for a in atoms]
        b = a1.molecule.newBond(a1, a2)
        sm[len(items)] = b
        items.append(b)
        b.drawMode = drawMode
        b.display = display

    from chimera import Point
    for mid, crdSets in crdInfo.items():
        m = idLookup(mid)
        active = crdSets.pop('active')
        for key, crds in crdSets.items():
            coordSet = m.newCoordSet(key, len(crds))
            for aid, crdString in crds:
                idLookup(aid).setCoord(
                    Point(*tuple([float(c) for c in crdString.split()])),
                    coordSet)
            if key == active:
                m.activeCoordSet = coordSet