Example #1
0
def unbond_close_hydrogen_bonds(selection='all'):
    """
    DESCRIPTION

        Removes spurious chemical bonds between an amide hydrogen and an amide
        oxygen in a peptide/protein

    USAGE

        unbond_close_hydrogen_bonds [selection]

    ARGUMENTS

        selection: the selection to operate on, containing the acceptors and
        the hydrogens (defaults to 'all')

    NOTES

        Some molecular formats do not save bond information. In this case Pymol
        tries to guess bonds based on inter-atomic distances, which sometimes
        results in spurious bonds between atoms which lie too close. This
        function removes these bonds between a hydrogen bond acceptor and a
        hydrogen of a peptide bond.
    """

    for oxygen in iterate_indices(
            '({}) and (e. O) and name O'.format(selection)):
        for hydrogen in iterate_indices(
                '({}) and (neighbor idx {}) and name HN and e. H'.format(
                    selection, oxygen)):
            cmd.unbond('({}) and idx {}'.format(selection, oxygen),
                       '({}) and idx {}'.format(selection, hydrogen))
Example #2
0
def bond_zns(sel):
    cmd.unbond(sel + " and resn ZNS", sel + " and not resn ZNS")
    # for c,i in getres("resn ZNS"):
    #    cmd.bond(sel+" and chain %s and resi %i and name ZN1"%(c,i),
    #             sel+" and chain %s and resi %i and name S*"%(c,i))
    for c, i in getres("name ZN1"):
        cmd.bond(sel + " and chain %s and resi %i and name ZN1" % (c, i),
                 sel + " and chain %s and resi %i and name S*,N2,N4" % (c, i))
    allsg = cmd.get_model(sel + " and (resn CYS and (name CB))").atom
    allsf = cmd.get_model(sel + " and (resn ZHC and (name S*,C1,C4))").atom
    while allsg:
        closest = [9e9, None, None]
        for sga in allsg:
            for sfa in allsf:
                sg = Vec(sga.coord)
                sf = Vec(sfa.coord)
                if (sg - sf).length() < closest[0]:
                    closest = [(sg - sf).length(), sga, sfa]
        sga, sfa = closest[1:]
        allsg.remove(sga)
        allsf.remove(sfa)
        if closest[0] > 10.0: break
        cmd.bond(
            sel + " and resi %s and chain %s and name %s" %
            (sga.resi, sga.chain, sga.name),
            sel + " and resi %s and chain %s and name %s" %
            (sfa.resi, sfa.chain, sfa.name))
Example #3
0
def bond_zns(sel):
    cmd.unbond(sel + " and resn ZNS", sel + " and not resn ZNS")
    # for c, i in getres("resn ZNS"):
    #    cmd.bond(sel+" and chain %s and resi %i and name ZN1"%(c, i),
    #             sel+" and chain %s and resi %i and name S*"%(c, i))
    for c, i in getres("name ZN1"):
        cmd.bond(
            sel + " and chain %s and resi %i and name ZN1" % (c, i),
            sel + " and chain %s and resi %i and name S*, N2, N4" % (c, i),
        )
    allsg = cmd.get_model(sel + " and (resn CYS and (name CB))").atom
    allsf = cmd.get_model(sel + " and (resn ZHC and (name S*, C1, C4))").atom
    while allsg:
        closest = [9e9, None, None]
        for sga in allsg:
            for sfa in allsf:
                sg = Vec(sga.coord)
                sf = Vec(sfa.coord)
                if (sg - sf).length() < closest[0]:
                    closest = [(sg - sf).length(), sga, sfa]
        sga, sfa = closest[1:]
        allsg.remove(sga)
        allsf.remove(sfa)
        if closest[0] > 10.0:
            break
        cmd.bond(
            sel + " and resi %s and chain %s and name %s" % (sga.resi, sga.chain, sga.name),
            sel + " and resi %s and chain %s and name %s" % (sfa.resi, sfa.chain, sfa.name),
        )
Example #4
0
    def testRepsExist(self):
        cmd.viewport(200, 150)
        cmd.load(self.datafile('1oky-frag.pdb'), 'm1')

        # make some nonbonded
        cmd.unbond('resi 115-', 'resi 115-')

        # labels
        cmd.label('all', 'name')

        # measurements
        cmd.distance('measure1', 'index 1', 'index 10')
        cmd.angle('measure1', 'index 1', 'index 10', 'index 20')
        cmd.dihedral('measure1', 'index 1', 'index 10', 'index 20', 'index 30')

        # color test setup
        cmd.color('white', '*')
        cmd.set('ambient', 1)
        cmd.set('depth_cue', 0)
        cmd.set('antialias', 0)
        cmd.set('line_smooth', 0)
        cmd.orient()

        # test most reps
        for rep in REPS:
            cmd.show_as(rep)
            self.assertImageHasColor('white', msg='rep missing: ' + rep)

        # test cartoon
        cmd.show_as('cartoon')
        for cart in CARTOONS:
            cmd.cartoon(cart)
            self.assertImageHasColor('white', msg='cartoon missing: ' + cart)
Example #5
0
    def testRepsExist(self):
        cmd.viewport(200, 150)
        cmd.load(self.datafile('1oky-frag.pdb'), 'm1')

        # make some nonbonded
        cmd.unbond('resi 115-', 'resi 115-')

        # labels
        cmd.label('all', 'name')

        # measurements
        cmd.distance('measure1', 'index 1', 'index 10')
        cmd.angle('measure1', 'index 1', 'index 10', 'index 20')
        cmd.dihedral('measure1', 'index 1', 'index 10', 'index 20', 'index 30')

        # color test setup
        cmd.color('white', '*')
        cmd.set('ambient', 1)
        cmd.set('depth_cue', 0)
        cmd.set('antialias', 0)
        cmd.set('line_smooth', 0)
        cmd.orient()

        # test most reps
        for rep in REPS:
            cmd.show_as(rep)
            self.assertImageHasColor('white', msg='rep missing: ' + rep)

        # test cartoon
        cmd.show_as('cartoon')
        for cart in CARTOONS:
            cmd.cartoon(cart)
            self.assertImageHasColor('white', msg='cartoon missing: ' + cart)
Example #6
0
def untangle_sidechains(sele):
    for c, i in getres(sele):
        if c != "":
            cmd.unbond(
                "%s and resi %i and chain %s and not name N+C" % (sele, i, c),
                "not (%s and resi %i and chain %s)" % (sele, i, c),
            )
        else:
            cmd.unbond(
                "%s and resi %i and              not name N+C" % (sele, i),
                "not (%s and resi %i             )" % (sele, i),
            )
Example #7
0
    def test_bond(self):
        cmd.pseudoatom('m1', pos=(0, 0, 0))
        cmd.pseudoatom('m1', pos=(1, 0, 0))
        cmd.pseudoatom('m1', pos=(1, 1, 0))

        cmd.bond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 2)

        cmd.unbond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 1)
Example #8
0
    def test_bond(self):
        cmd.pseudoatom('m1', pos=(0,0,0))
        cmd.pseudoatom('m1', pos=(1,0,0))
        cmd.pseudoatom('m1', pos=(1,1,0))

        cmd.bond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 2)

        cmd.unbond('m1`1', 'm1`2')
        count = cmd.count_atoms('(m1`1) extend 1')
        self.assertEqual(count, 1)
Example #9
0
    def test(self):
        cmd.set('cartoon_gap_cutoff', 0)  # default varies by version

        self.ambientOnly()

        cmd.viewport(150, 150)
        cmd.load(self.datafile('1oky-frag.pdb'))
        cmd.cartoon('dash')
        cmd.show_as('cartoon')
        cmd.orient()

        # no gaps
        img_nogaps = self.get_imagearray()

        # gap of length 0
        cmd.unbond('96/C', '97/N')
        img_gap = self.get_imagearray()
        self.assertFalse((img_gap == img_nogaps).all())

        # close gap with setting, should match first image (special case)
        cmd.set('cartoon_gap_cutoff', 1)  # exact cutoff
        img_gap = self.get_imagearray()
        self.assertTrue((img_gap == img_nogaps).all())

        # gap of length 1
        cmd.remove('92/')
        img_gap = self.get_imagearray()
        cmd.set('cartoon_gap_cutoff', 2)  # exact cutoff
        img_nogaps = self.get_imagearray()
        self.assertFalse((img_gap == img_nogaps).all())

        # gap of length 3
        cmd.remove('102-104/')
        cmd.cartoon('auto')  # default
        img_gap = self.get_imagearray()
        cmd.set('cartoon_gap_cutoff', 10)  # arbitrary larger cutoff
        img_nogaps = self.get_imagearray()
        self.assertFalse((img_gap == img_nogaps).all())
Example #10
0
    def test(self):
        cmd.set('cartoon_gap_cutoff', 0) # default varies by version

        self.ambientOnly()

        cmd.viewport(150, 150)
        cmd.load(self.datafile('1oky-frag.pdb'))
        cmd.cartoon('dash')
        cmd.show_as('cartoon')
        cmd.orient()

        # no gaps
        img_nogaps = self.get_imagearray()

        # gap of length 0
        cmd.unbond('96/C', '97/N')
        img_gap = self.get_imagearray()
        self.assertFalse((img_gap == img_nogaps).all())

        # close gap with setting, should match first image (special case)
        cmd.set('cartoon_gap_cutoff', 1) # exact cutoff
        img_gap = self.get_imagearray()
        self.assertTrue((img_gap == img_nogaps).all())

        # gap of length 1
        cmd.remove('92/')
        img_gap = self.get_imagearray()
        cmd.set('cartoon_gap_cutoff', 2) # exact cutoff
        img_nogaps = self.get_imagearray()
        self.assertFalse((img_gap == img_nogaps).all())

        # gap of length 3
        cmd.remove('102-104/')
        cmd.cartoon('auto') # default
        img_gap = self.get_imagearray()
        cmd.set('cartoon_gap_cutoff', 10) # arbitrary larger cutoff
        img_nogaps = self.get_imagearray()
        self.assertFalse((img_gap == img_nogaps).all())
Example #11
0
def create_object_with_flipkin_coords(mpobj, which_flips='NQ'):
    '''Duplicate the mpobj molecule and apply the flipNQ/H group coordinates.

    PARAMETERS

        mpobj           An MPObject instance

        which_flips     Either 'NQ' or 'H' to specify which flipkin to use

    '''
    flipkin_name = 'flipkin{}'.format(which_flips)
    flipkin = mpobj.kin[flipkin_name]
    flip_group = 'flip{}'.format(which_flips)

    reduced_obj = mpobj.pdb['reduce']
    flipped_obj = mpobj.pdb[flipkin_name]
    cmd.create(flipped_obj, reduced_obj)

    for vl in flipkin.vectorlists():
        # Skip if not coordinates
        if vl[0].vectorlist_name == 'x':
            msg = 'skipping non-coords vectorlist {}'
            logger.debug(msg.format(vl[0].vectorlist_name))
            continue

        # Skip everything except the'flipNQ' (or 'flipH') group
        if vl[0].group[0] != flip_group:
            msg = 'skipping non-{} vectorlist'.format(flip_group)
            logger.debug(msg)
            continue

        logger.debug('begin flipping vectorlist')
        for v in vl:
            if not (v.atom[0] and v.atom[1]):
                msg = 'vector {} was missing atoms: {}'.format(v, v.atom)
                logger.warning(msg)
                continue
            macro = v.macro(1)
            sel = v.sel(1)
            logger.debug('atom to be flipped: {}\n  sel: {}'.format(macro, sel))
            source_coords = v.coords[1]

            target_sel = '{} and {}'.format(flipped_obj, sel)
            msg = 'flipping atom {} to {}'.format(target_sel, source_coords)
            logger.debug(msg)


            ret = cmd.load_coords([source_coords], target_sel)
            if ret == -1:
                success = 0
                a = v.atom[1]

                if a['resn'] == 'HIS':
                    his_h = {
                            'HD1': {
                                'old_h': 'HE2',
                                'old_n': 'NE2',
                                'new_h': 'HD1',
                                'new_n': 'ND1',
                                },
                            'HE2': {
                                'old_h': 'HD1',
                                'old_n': 'ND1',
                                'new_h': 'HE2',
                                'new_n': 'NE2',
                                }
                            }
                    if a['name'] in his_h.keys():
                        # Reduce has switched which N is protonated. Let's move
                        # the old H atom and rename it.
                        resi_sel = '{} and chain {} and resi {}'.format(
                            flipped_obj, a['chain'], a['resi'])
                        h = his_h[a['name']]
                        old_h = '{} and name {}'.format(resi_sel, h['old_h'])
                        old_n = '{} and name {}'.format(resi_sel, h['old_n'])
                        new_h = '{} and name {}'.format(resi_sel, h['new_h'])
                        new_n = '{} and name {}'.format(resi_sel, h['new_n'])

                        # Break the old bond
                        cmd.unbond(old_h, old_n)

                        # Rename the atom
                        cmd.alter(old_h, 'name="{}"'.format(a['name']))

                        # Make the new bond
                        cmd.bond(new_h, new_n)

                        # Retry loading coordinates
                        ret = cmd.load_coords([source_coords], target_sel)
                        if not ret == -1:
                            success = 1

                if not success:
                    msg = 'failed to load coords for {}!'.format(macro)
                    logger.warning(msg)

        logger.debug('end flipping vectorlist')
Example #12
0
def fix_bonds(selection):

    stored.residues = []
    cmd.iterate(selection + ' and n. ca',
                'stored.residues.append((resi,resn))')
    last_residue = stored.residues[-1][0]
    print(last_residue)
    for r1 in range(len(stored.residues)):
        residue1 = selection + " and r. " + stored.residues[r1][
            1] + " and i. " + stored.residues[r1][0]
        sele1 = residue1 + " and n. ca+c+c+o+n"
        sele2 = residue1 + " and !n. ca+c+c+o+n+cb"
        print("unbond ", sele1, ",", sele2)
        cmd.unbond(sele1, sele2)
        for r2 in range(r1 + 1, len(stored.residues)):
            residue2 = selection + " and r. " + stored.residues[r2][
                1] + " and i. " + stored.residues[r2][0]
            if int(stored.residues[r1][0]) != int(stored.residues[r2][0]):
                sele1 = residue1
                sele2 = residue2
                print("unbond ", sele1, ",", sele2)
                cmd.unbond(sele1, sele2)
            if int(stored.residues[r2][0]) == (int(stored.residues[r1][0]) +
                                               1):
                sele1 = residue1 + " and n. c"
                sele2 = residue2 + " and n. n"
                print("bond ", sele1, ",", sele2)
                cmd.bond(sele1, sele2)

        # FIX RESIDUE SIDE CHAIN
        if stored.residues[r1][1] == "PRO":
            sele1 = residue1 + " and n. n"
            sele2 = residue1 + " and n. cd"
            print("bond ", sele1, ",", sele2)
            cmd.bond(sele1, sele2)
        elif stored.residues[r1][1] == "THR":
            sele1 = residue1 + " and !n. ca+og1+cg2+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)
        elif stored.residues[r1][1] == "ILE" or stored.residues[r1][1] == "VAL":
            for resitype in ["ILE", "VAL"]:
                sele1 = residue1 + " and !n. ca+cg1+cg2+cb"
                sele2 = residue1 + " and n. cb"
                print("unbond ", sele1, ",", sele2)
                cmd.unbond(sele1, sele2)
        elif stored.residues[r1][1] == "SER":
            sele1 = residue1 + " and !n. ca+og+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)
        elif stored.residues[r1][1] == "CYS":
            sele1 = residue1 + " and !n. ca+sg+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)
        else:
            sele1 = residue1 + " and !n. ca+cg+cb"
            sele2 = residue1 + " and n. cb"
            print("unbond ", sele1, ",", sele2)
            cmd.unbond(sele1, sele2)

        # FIX CENTROID LEVEL
        sele1 = residue1 + " and n. cen"
        sele2 = residue1 + " and n. cb"
        print("bond ", sele1, ",", sele2)
        cmd.bond(sele1, sele2)

        # FIX C-TERMINAL
        if stored.residues[r1][0] == last_residue:
            sele1 = residue1 + " and n. c"
            sele2 = residue1 + " and n. oxt"
            print("bond ", sele1, ",", sele2)
            cmd.bond(sele1, sele2)

    stored.cys = []
    cmd.iterate(selection + ' and r. CYS and n. cb',
                'stored.cys.append((resi,resn))')
    if len(stored.cys) >= 2:
        for r1 in range(len(stored.cys)):
            for r2 in range(r1 + 1, len(stored.cys)):
                if stored.cys[r1][0] != stored.cys[r2][0]:
                    sele1 = selection + " and i. " + stored.cys[r1][
                        0] + " and n. cb"
                    sele2 = selection + " and i. " + stored.cys[r2][
                        0] + " and n. cb"
                    dist = cmd.distance("tmpdist", sele1, sele2)
                    if dist < 4.0:
                        print(dist, sele1, ",", sele2)
                        sele1 = selection + " and i. " + stored.cys[r1][
                            0] + " and n. sg"
                        sele2 = selection + " and i. " + stored.cys[r2][
                            0] + " and n. sg"
                        print("bond ", sele1, ",", sele2)
                        cmd.bond(sele1, sele2)
    cmd.delete("tmpdist")
Example #13
0
def create_object_with_flipkin_coords(mpobj, which_flips='NQ'):
    '''Duplicate the mpobj molecule and apply the flipNQ/H group coordinates.

    PARAMETERS

        mpobj           An MPObject instance

        which_flips     Either 'NQ' or 'H' to specify which flipkin to use

    '''
    flipkin_name = 'flipkin{}'.format(which_flips)
    flipkin = mpobj.kin[flipkin_name]
    flip_group = 'flip{}'.format(which_flips)

    reduced_obj = mpobj.pdb['reduce']
    flipped_obj = mpobj.pdb[flipkin_name]
    cmd.create(flipped_obj, reduced_obj)

    for vl in flipkin.vectorlists():
        # Skip if not coordinates
        if vl[0].vectorlist_name == 'x':
            msg = 'skipping non-coords vectorlist {}'
            logger.debug(msg.format(vl[0].vectorlist_name))
            continue

        # Skip everything except the'flipNQ' (or 'flipH') group
        if vl[0].group[0] != flip_group:
            msg = 'skipping non-{} vectorlist'.format(flip_group)
            logger.debug(msg)
            continue

        logger.debug('begin flipping vectorlist')
        for v in vl:
            if not (v.atom[0] and v.atom[1]):
                msg = 'vector {} was missing atoms: {}'.format(v, v.atom)
                logger.warning(msg)
                continue
            macro = v.macro(1)
            sel = v.sel(1)
            logger.debug('atom to be flipped: {}\n  sel: {}'.format(
                macro, sel))
            source_coords = v.coords[1]

            target_sel = '{} and {}'.format(flipped_obj, sel)
            msg = 'flipping atom {} to {}'.format(target_sel, source_coords)
            logger.debug(msg)

            ret = cmd.load_coords([source_coords], target_sel)
            if ret == -1:
                success = 0
                a = v.atom[1]

                if a['resn'] == 'HIS':
                    his_h = {
                        'HD1': {
                            'old_h': 'HE2',
                            'old_n': 'NE2',
                            'new_h': 'HD1',
                            'new_n': 'ND1',
                        },
                        'HE2': {
                            'old_h': 'HD1',
                            'old_n': 'ND1',
                            'new_h': 'HE2',
                            'new_n': 'NE2',
                        }
                    }
                    if a['name'] in his_h.keys():
                        # Reduce has switched which N is protonated. Let's move
                        # the old H atom and rename it.
                        resi_sel = '{} and chain {} and resi {}'.format(
                            flipped_obj, a['chain'], a['resi'])
                        h = his_h[a['name']]
                        old_h = '{} and name {}'.format(resi_sel, h['old_h'])
                        old_n = '{} and name {}'.format(resi_sel, h['old_n'])
                        new_h = '{} and name {}'.format(resi_sel, h['new_h'])
                        new_n = '{} and name {}'.format(resi_sel, h['new_n'])

                        # Break the old bond
                        cmd.unbond(old_h, old_n)

                        # Rename the atom
                        cmd.alter(old_h, 'name="{}"'.format(a['name']))

                        # Make the new bond
                        cmd.bond(new_h, new_n)

                        # Retry loading coordinates
                        ret = cmd.load_coords([source_coords], target_sel)
                        if not ret == -1:
                            success = 1

                if not success:
                    msg = 'failed to load coords for {}!'.format(macro)
                    logger.warning(msg)

        logger.debug('end flipping vectorlist')
Example #14
0
    def do_library(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name C"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name O"%src_sele)==1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable","selector","everythin")
        cmd.feedback("disable","editor","actions")
        self.prompt = [ 'Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight",src_sele)
        
        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom',"0",quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele,animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode=="current":
            pymol.stored.resn=""
            cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn)
            if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'):
                self.lib_mode = rot_type # force fragment-based load
            else:
                cmd.create(frag_name,src_sele,1,1)
                if self.c_cap=='open':
                    cmd.remove("%s and name OXT"%frag_name)
                    
        if self.lib_mode!='current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'):
                if not ( cmd.count_atoms(
                    "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"%
                                     (src_sele,src_sele))):
                    # use N-terminal fragment
                    frag_type ="NT_"+frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'):
                if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                     (src_sele,src_sele))):
                    # use C-terminal fragment
                    frag_type ="CT_"+frag_type
            if rot_type[0:3] in [ 'NT_', 'CT_' ]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("("+frag_name+" and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("("+src_sele+") and hydro")==0:
                    cmd.remove("("+frag_name+" and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space)
            cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and
                 (cmd.count_atoms("(%s & name CB)"%src_sele)==1)):
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name CB)"%frag_name,
                             "(%s & name CB)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)
            else:
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]")
            cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)"%src_sele):
                cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]")
                cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)"%frag_name,
                                         "(%s & name CA)"%frag_name,
                                         "(%s & name C)"%frag_name,
                                         "(%s & name O)"%frag_name)
                cmd.protect("(%s & name O)"%frag_name)
                cmd.set_dihedral("(%s & name N)"%frag_name,
                                 "(%s & name CA)"%frag_name,
                                 "(%s & name C)"%frag_name,
                                 "(%s & name OXT)"%frag_name,180.0+angle)
                cmd.deprotect(frag_name)

                
            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1:
                    cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele,
                                      "stored.list=[x,y,z]")
                    cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name,
                                    "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)"%frag_name,
                                             "(%s & name CA)"%frag_name,
                                             "(%s & name N)"%frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)"%frag_name,
                                     "(%s & name CA)"%frag_name,
                                     "(%s & name N)"%frag_name,
                                     "(%s & name H)"%frag_name,180.0+angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in [ 'amin', 'nmet' ]:
                if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name C & (%s)"%(frag_name))==1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh')
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
                         
            # add n-cap (if appropriate)
            if self.n_cap in [ 'acet' ]:
                if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name N & (%s)"%(frag_name))==1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & (%s)"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
 

                    

        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0)
            
        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s"%src_sele)
                if len(result)==1:
                    (phi,psi) = list(result.values())[0]
                    (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10))))
                    key = (rot_type,phi,psi)
                    if key not in self.dep_library:
                        (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20))))
                        key = (rot_type,phi,psi)                    
                        if key not in self.dep_library:
                            (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60))))
                            key = (rot_type,phi,psi)
                    lib = self.dep_library.get(key,None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key,None)
            if (lib!= None) and self.dep == 'dep':
                print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.')
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name,frag_name,1,state)
                if state == 1:
                    cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele)) 
                if rot_type=='PRO':
                    cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                for b in a.keys():
                    if b!='FREQ':
                        cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]),
                                         "(%s & n;%s)"%(mut_sele,b[1]),
                                         "(%s & n;%s)"%(mut_sele,b[2]),
                                         "(%s & n;%s)"%(mut_sele,b[3]),
                                         a[b],state=state)
                    else:
                        cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100))
                if rot_type=='PRO':
                    cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)                
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded."%len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(bump_name,
                "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"%
                           (src_sele,mut_sele,src_sele,mut_sele),singletons=1)
                cmd.color("gray50",bump_name+" and elem C")
                cmd.set("seq_view",0,bump_name,quiet=1)
                cmd.hide("everything",bump_name)
                if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2, "(name C & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2,"(name N & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)
                
                cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"%
                            (bump_name,bump_name,mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo",bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode",1,bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name,frag_name,1,1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view",0,obj_name,quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("("+obj_name+")")
        cmd.show(self.rep,obj_name)
        cmd.show('lines',obj_name) #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon",obj_name)
        if sticks:
            cmd.show("sticks",obj_name)
        cmd.set('auto_zoom',auto_zoom,quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)
        cmd.unpick()
        cmd.feedback("pop")
Example #15
0
def load_ff(filename):
    """
        Load a fDynamo force field file (.ff)

        Re-bond ligands accordingly
        Alter properties of all atoms:
         - 'text_type' : atomtypes
         - 'partial_charges' : charges

        Parameters
        ----------
        filename : str
            file path
    """

    print(f" pyDYNAMON: reading \"{filename}\"")

    # residue names excluded from re-bonding
    rebond_excluded = []
    rebond_excluded.extend(aa_dict.keys())
    rebond_excluded.extend(["SOL", "NA", "CL"])

    # read file as list of strings
    with open(filename, "rt") as f:
        ff_file = f.readlines()
        # remove comment lines and blank lines
        ff_file = [
            line.strip() for line in ff_file
            if line.strip() and not line.startswith("!")
        ]

    # read residue atoms and bonds
    topology = dict()
    current_sect = None
    for line in ff_file:
        line = line.split("!")
        keyword = line[0].split()[0].lower()
        content = line[0].split()
        if keyword == 'end':
            current_sect = None
        elif keyword == 'residues':
            current_sect = keyword
        elif current_sect == 'residues' or keyword == 'residue':
            if keyword == 'residue':  # new residue
                current_sect = 'residues'
                resname = content[1]
                topology[resname] = dict()
                continue
            top = topology[resname]
            if not topology[resname]:  # first line (numbers)
                top['natoms'] = int(content[0])
                top['nbonds'] = int(content[1])
                top['nimpropers'] = int(content[2])
                top['atoms'] = dict()
                top['bonds'] = []
                top['impropers'] = []
            elif len(top['atoms']) < top['natoms']:
                param = {
                    'atomtype': str(content[1]).upper(),
                    'charge': float(content[2])
                }
                top['atoms'][str(content[0]).upper()] = param
            elif len(top['bonds']) < top['nbonds']:
                bonds = [(b.split()[0].upper(), b.split()[1].upper())
                         for b in " ".join(content).split(";") if b.strip()]
                top['bonds'].extend(bonds)
            elif len(top['impropers']) < top['nimpropers']:
                impropers = [(i.split()[0].upper(), i.split()[1].upper(),
                              i.split()[2].upper(), i.split()[3].upper())
                             for i in " ".join(content).split(";")
                             if i.strip()]
                top['impropers'].extend(impropers)

    for resname, top in topology.items():
        # atomtypes and partial charges
        for name, param in top['atoms'].items():
            cmd.alter(f"resn {resname} & name {name}",
                      f"partial_charge={param['charge']}")
            cmd.alter(f"resn {resname} & name {name}",
                      f"text_type=\'{param['atomtype']}\'")
        # unbond all and re-bond
        if resname in rebond_excluded: continue
        cmd.unbond(f"resn {resname}", f"resn {resname}")
        for bond in top['bonds']:
            cmd.bond(f"resn {resname} & name {bond[0]}",
                     f"resn {resname} & name {bond[1]}")
        CTERM_tuple: [CTERM_bonds_all, CTERM_bonds_double],
        ARG_tuple: [ARG_bonds_all, ARG_bonds_double]
    }

    if bonds != 2:
        lines = 4
        print "Formating as delocalized bonds"
    else:
        lines = 1
        print "Formating as double bonds"

    # for all tuples (i.e format_dict.keys())
    for p in format_dict.keys():
        # go through list except ID at pos 1
        for q in p[1:]:
            # format bonds
            for r in format_dict[p][0]:
                cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), lines)
            if lines == 1:
                # add double bonds
                for r in format_dict[p][1]:
                    cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                    cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), 2)

    return bonds
cmd.extend("format_bonds", format_bonds)
cmd.auto_arg[0]['format_bonds'] = [lambda: cmd.Shortcut(['all', 'resn PHE+TYR+PTR+NIY+PNIY+TRP+NIW+HIS', 'resn GLU+ASP', 'resn ARG', 'last all']), 'selection=', ', ']
cmd.auto_arg[1]['format_bonds'] = [lambda: cmd.Shortcut(['4', '2', '1']), 'bonds=', '']
################################################################################
    def do_library(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name C"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name O"%src_sele)==1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable","selector","everythin")
        cmd.feedback("disable","editor","actions")
        self.prompt = [ 'Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight",src_sele)

        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom',"0",quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele,animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode=="current":
            pymol.stored.resn=""
            cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn)
            if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'):
                self.lib_mode = rot_type # force fragment-based load
            else:
                cmd.create(frag_name,src_sele,1,1)
                if self.c_cap=='open':
                    cmd.remove("%s and name OXT"%frag_name)

        if self.lib_mode!='current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'):
                if not ( cmd.count_atoms(
                    "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"%
                                     (src_sele,src_sele))):
                    # use N-terminal fragment
                    frag_type ="NT_"+frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'):
                if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                     (src_sele,src_sele))):
                    # use C-terminal fragment
                    frag_type ="CT_"+frag_type
            if rot_type[0:3] in [ 'NT_', 'CT_' ]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("("+frag_name+" and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("("+src_sele+") and hydro")==0:
                    cmd.remove("("+frag_name+" and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space)
            cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and
                 (cmd.count_atoms("(%s & name CB)"%src_sele)==1)):
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name CB)"%frag_name,
                             "(%s & name CB)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)
            else:
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]")
            cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)"%src_sele):
                cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]")
                cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)"%frag_name,
                                         "(%s & name CA)"%frag_name,
                                         "(%s & name C)"%frag_name,
                                         "(%s & name O)"%frag_name)
                cmd.protect("(%s & name O)"%frag_name)
                cmd.set_dihedral("(%s & name N)"%frag_name,
                                 "(%s & name CA)"%frag_name,
                                 "(%s & name C)"%frag_name,
                                 "(%s & name OXT)"%frag_name,180.0+angle)
                cmd.deprotect(frag_name)


            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1:
                    cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele,
                                      "stored.list=[x,y,z]")
                    cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name,
                                    "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)"%frag_name,
                                             "(%s & name CA)"%frag_name,
                                             "(%s & name N)"%frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)"%frag_name,
                                     "(%s & name CA)"%frag_name,
                                     "(%s & name N)"%frag_name,
                                     "(%s & name H)"%frag_name,180.0+angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in [ 'amin', 'nmet' ]:
                if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name C & (%s)"%(frag_name))==1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh')
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in [ 'acet' ]:
                if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name N & (%s)"%(frag_name))==1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & (%s)"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")




        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0)

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s"%src_sele)
                if len(result)==1:
                    (phi,psi) = list(result.values())[0]
                    (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10))))
                    key = (rot_type,phi,psi)
                    if key not in self.dep_library:
                        (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20))))
                        key = (rot_type,phi,psi)
                        if key not in self.dep_library:
                            (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60))))
                            key = (rot_type,phi,psi)
                    lib = self.dep_library.get(key,None)
            except:
                pass
        if lib is None:
            key = rot_type
            lib = self.ind_library.get(key,None)
            if (lib is not None) and self.dep == 'dep':
                print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.')
        if lib is not None:
            state = 1
            for a in lib:
                cmd.create(obj_name,frag_name,1,state)
                if state == 1:
                    cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele))
                if rot_type=='PRO':
                    cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                for b in a.keys():
                    if b!='FREQ':
                        cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]),
                                         "(%s & n;%s)"%(mut_sele,b[1]),
                                         "(%s & n;%s)"%(mut_sele,b[2]),
                                         "(%s & n;%s)"%(mut_sele,b[3]),
                                         a[b],state=state)
                    else:
                        cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100))
                if rot_type=='PRO':
                    cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded."%len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(bump_name,
                "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"%
                           (src_sele,mut_sele,src_sele,mut_sele),singletons=1)
                cmd.color("gray50",bump_name+" and elem C")
                cmd.set("seq_view",0,bump_name,quiet=1)
                cmd.hide("everything",bump_name)
                if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2, "(name C & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2,"(name N & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"%
                            (bump_name,bump_name,mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo",bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode",1,bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name,frag_name,1,1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view",0,obj_name,quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("("+obj_name+")")
        cmd.show(self.rep,obj_name)
        cmd.show('lines',obj_name) #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon",obj_name)
        if sticks:
            cmd.show("sticks",obj_name)
        cmd.set('auto_zoom',auto_zoom,quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)
        cmd.unpick()
        cmd.feedback("pop")
Example #18
0
def format_bonds(
    selection='all',
    bonds=4,
):
    '''
DESCRIPTION
    Formats bonds in aromatic or charged residues
EXAMPLE
    frag PHE
    format_bonds
USAGE
    format_bonds [ selection [, bonds ]]
ARGUMENTS
    selection: <str> input selection {default: 'all'}
    bonds:     <int> toogles format of bonds
               1: single bonds (deactivates valence display)
               2: regular double bonds (activates valence display)
             >=3: delocalized (activates valence display)
    '''
    # Selection
    try:
        # group selection with bracketing and select complete residues
        selection = '(byres (' + str(selection) + '))'
        # checks functional selection
        cmd.count_atoms(selection)
    except:
        print "invalid selection"
        return False

    # PARAMETERS
    try:
        bonds = int(bonds)
    except:
        pass
    if (not (bonds in [1, 2])):
        bonds = 4

    if bonds == 1:
        cmd.set('valence', 0)
        print "Valence display disabled!"
        return bonds
    else:
        cmd.set('valence', 1)
        print "Valence display enabled!"
    # proceed

    ##### SELECTION BY OBJECT AND CHAIN #####
    # variable for the selections
    # get the names of the proteins in the selection
    objects = cmd.get_object_list(selection)
    # include chains

    # subselect chains
    names = []
    for p in objects:
        for chain in cmd.get_chains('model ' + p) or ['']:
            names.append("(model %s and chain '%s')" % (p, chain))

    ##### SELECTION LISTS #####
    # get TRP
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn TRP+NIW) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    # the integer is to ensure unique keys
    TRP_tuple = (1,) + tuple(stored.temp)

    # get PHETYR
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn PHE+TYR+PTR+NIY+PNIY) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    PHETYR_tuple = (2,) + tuple(stored.temp)

    # get HIS
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn HIS) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    HIS_tuple = (3,) + tuple(stored.temp)

    # get NITRO
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn NIY+PNIY+NIW) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    NITRO_tuple = (4,) + tuple(stored.temp)

    # get GLU
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn GLU) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    GLU_tuple = (5,) + tuple(stored.temp)

    # get ASP
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn ASP) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    ASP_tuple = (6,) + tuple(stored.temp)

    # get CTERM
    stored.temp = []
    for p in names:
        cmd.iterate(
            '(byres (last %s)) and (not (hetatm)) '
            'and (name OXT)' % (p),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    CTERM_tuple = (7,) + tuple(stored.temp)

    # get ARG
    stored.temp = []
    for p in names:
        cmd.iterate((
            '(%s) and (resn ARG) '
            'and (name CA)' % (p)),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p
        )
    ARG_tuple = (8,) + tuple(stored.temp)

    ##### SELECTION TUPLES DONE #####

    ##### ATOM LISTS #####

    TRP_bonds_all = [
        ['CG', 'CD1'],
        ['CD1', 'NE1'],
        ['NE1', 'CE2'],
        ['CE2', 'CD2'],
        ['CD2', 'CG'],
        ['CD2', 'CE3'],
        ['CE3', 'CZ3'],
        ['CZ3', 'CH2'],
        ['CH2', 'CZ2'],
        ['CZ2', 'CE2']
    ]

    TRP_bonds_double = [
        ['CG', 'CD1'],
        ['CE2', 'CD2'],
        ['CE3', 'CZ3'],
        ['CH2', 'CZ2']
    ]

    PHETYR_bonds_all = [
        ['CG', 'CD1'],
        ['CD1', 'CE1'],
        ['CE1', 'CZ'],
        ['CZ', 'CE2'],
        ['CE2', 'CD2'],
        ['CD2', 'CG']
    ]

    PHETYR_bonds_double = [
        ['CG', 'CD1'],
        ['CE1', 'CZ'],
        ['CE2', 'CD2']
    ]

    HIS_bonds_all = [
        ['CG', 'CD2'],
        ['CD2', 'NE2'],
        ['NE2', 'CE1'],
        ['CE1', 'ND1'],
        ['ND1', 'CG'],
    ]

    HIS_bonds_double = [
        ['CG', 'CD2'],
        ['CE1', 'ND1']
    ]

    NITRO_bonds_all = [
        ['NN', 'O1'],
        ['NN', 'O2']
    ]
    NITRO_bonds_double = [
        ['NN', 'O1']
    ]

    GLU_bonds_all = [
        ['CD', 'OE1'],
        ['CD', 'OE2']
    ]
    GLU_bonds_double = [
        ['CD', 'OE1']
    ]

    ASP_bonds_all = [
        ['CG', 'OD1'],
        ['CG', 'OD2']
    ]
    ASP_bonds_double = [
        ['CG', 'OD1']
    ]

    CTERM_bonds_all = [
        ['C', 'O'],
        ['C', 'OXT']
    ]
    CTERM_bonds_double = [
        ['C', 'O']
    ]

    ARG_bonds_all = [
        ['CZ', 'NH1'],
        ['CZ', 'NH2']
    ]

    ARG_bonds_double=[
    ['CZ','NH1']
    ]

    ##### FORMATING #####

    # dictionary: entries:atoms
    format_dict = {
        TRP_tuple: [TRP_bonds_all, TRP_bonds_double],
        PHETYR_tuple: [PHETYR_bonds_all, PHETYR_bonds_double],
        HIS_tuple: [HIS_bonds_all, HIS_bonds_double],
        NITRO_tuple: [NITRO_bonds_all, NITRO_bonds_double],
        GLU_tuple: [GLU_bonds_all, GLU_bonds_double],
        ASP_tuple: [ASP_bonds_all, ASP_bonds_double],
        CTERM_tuple: [CTERM_bonds_all, CTERM_bonds_double],
        ARG_tuple: [ARG_bonds_all, ARG_bonds_double]
    }

    if bonds != 2:
        lines = 4
        print "Formating as delocalized bonds"
    else:
        lines = 1
        print "Formating as double bonds"

    # for all tuples (i.e format_dict.keys())
    for p in format_dict.keys():
        # go through list except ID at pos 1
        for q in p[1:]:
            # format bonds
            for r in format_dict[p][0]:
                cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), lines)
            if lines == 1:
                # add double bonds
                for r in format_dict[p][1]:
                    cmd.unbond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]))
                    cmd.bond('%s and name %s' % (q, r[0]), '%s and name %s' % (q, r[1]), 2)

    return bonds
Example #19
0
    def do_library(self):
        cmd = self.cmd
        pymol = cmd._pymol
        if not (
            (cmd.count_atoms("(%s) and name n" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name c" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name o" % src_sele) == 1)
        ):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable", "selector", "everythin")
        cmd.feedback("disable", "editor", "actions")
        self.prompt = ["Loading rotamers..."]

        pymol.stored.name = "residue"
        cmd.iterate("first (%s)" % src_sele, 'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight", src_sele)

        auto_zoom = cmd.get_setting_text("auto_zoom")
        cmd.set("auto_zoom", "0", quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele, animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode == "current":
            pymol.stored.resn = ""
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn)
            if (self.c_cap != "none") or (self.n_cap != "none") or (self.hyd != "auto"):
                self.lib_mode = rot_type  # force fragment-based load
            else:
                cmd.create(frag_name, src_sele, 1, 1)
                if self.c_cap == "open":
                    cmd.remove("%s and name OXT" % frag_name)

        if self.lib_mode != "current":
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == "posi") and (frag_type[0:3] != "NT_"):
                if not (cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) &! r. ace" % (src_sele, src_sele))):
                    # use N-terminal fragment
                    frag_type = "NT_" + frag_type
            if (self.c_cap == "nega") and (frag_type[0:3] != "CT_"):
                if not (cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele))):
                    # use C-terminal fragment
                    frag_type = "CT_" + frag_type
            if rot_type[0:3] in ["NT_", "CT_"]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(string.lower(frag_type), frag_name)
            # trim off hydrogens
            if self.hyd == "none":
                cmd.remove("(" + frag_name + " and hydro)")
            elif self.hyd == "auto":
                if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                    cmd.remove("(" + frag_name + " and hydro)")
            # copy identifying information
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.chain=chain")
            cmd.alter("(%s)" % frag_name, "chain=stored.chain")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resi=resi")
            cmd.alter("(%s)" % frag_name, "resi=stored.resi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.segi=segi")
            cmd.alter("(%s)" % frag_name, "segi=stored.segi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.ss=ss")
            cmd.alter("(%s)" % frag_name, "ss=stored.ss")
            # move the fragment
            if (cmd.count_atoms("(%s and n;cb)" % frag_name) == 1) and (
                cmd.count_atoms("(%s and n;cb)" % src_sele) == 1
            ):
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;cb)" % frag_name,
                    "(%s and n;cb)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )
            else:
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )

            # fix the carbonyl position...
            cmd.iterate_state(1, "(%s and n;o)" % src_sele, "stored.list=[x,y,z]")
            cmd.alter_state(1, "(%s and n;o)" % frag_name, "(x,y,z)=stored.list")
            if cmd.count_atoms("(%s and n;oxt)" % src_sele):
                cmd.iterate_state(1, "(%s and n;oxt)" % src_sele, "stored.list=[x,y,z]")
                cmd.alter_state(1, "(%s and n;oxt)" % frag_name, "(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s and n;oxt)" % frag_name):  # place OXT if no template exists
                angle = cmd.get_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;o)" % frag_name,
                )
                cmd.protect("(%s and n;o)" % frag_name)
                cmd.set_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;oxt)" % frag_name,
                    180.0 + angle,
                )
                cmd.deprotect(frag_name)

            # fix the hydrogen position (if any)
            if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % frag_name) == 1:
                if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % src_sele) == 1:
                    cmd.iterate_state(1, "(elem h and bound_to (n;n and (%s)))" % src_sele, "stored.list=[x,y,z]")
                    cmd.alter_state(1, "(elem h and bound_to (n;n and (%s)))" % frag_name, "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1, "(n;c and bound_to (%s and e;n))" % src_sele) == 1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral(
                        "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, tmp_sele1
                    )
                    cmd.set_dihedral(
                        "(%s and n;c)" % frag_name,
                        "(%s and n;ca)" % frag_name,
                        "(%s and n;n)" % frag_name,
                        "(%s and n;h)" % frag_name,
                        180.0 + angle,
                    )
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in ["amin", "nmet"]:
                if not cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele)):
                    if cmd.count_atoms("n;c & (%s)" % (frag_name)) == 1:
                        if self.c_cap == "amin":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nhh")
                        elif self.c_cap == "nmet":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nme")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & bound_to (n;c & (%s))" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in ["acet"]:
                if not cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) & !r. ace " % (src_sele, src_sele)):
                    if cmd.count_atoms("n;n & (%s)" % (frag_name)) == 1:
                        if self.n_cap == "acet":
                            editor.attach_amino_acid("n;n & (%s)" % (frag_name), "ace")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & (%s)" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

        cartoon = cmd.count_atoms("(%s and n;ca and rep cartoon)" % src_sele) > 0
        sticks = cmd.count_atoms("(%s and n;ca and rep sticks)" % src_sele) > 0

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == "dep":
            try:
                result = cmd.phi_psi("%s" % src_sele)
                if len(result) == 1:
                    (phi, psi) = result[result.keys()[0]]
                    (phi, psi) = (int(10 * round(phi / 10)), int(10 * (round(psi / 10))))
                    key = (rot_type, phi, psi)
                    if not self.dep_library.has_key(key):
                        (phi, psi) = (int(20 * round(phi / 20)), int(20 * (round(psi / 20))))
                        key = (rot_type, phi, psi)
                        if not self.dep_library.has_key(key):
                            (phi, psi) = (int(60 * round(phi / 60)), int(60 * (round(psi / 60))))
                            key = (rot_type, phi, psi)
                    lib = self.dep_library.get(key, None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key, None)
            if (lib != None) and self.dep == "dep":
                print " Mutagenesis: no phi/psi, using backbone-independent rotamers."
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name, frag_name, 1, state)
                if state == 1:
                    cmd.select(mut_sele, "(byres (%s like %s))" % (obj_name, src_sele))
                if rot_type == "PRO":
                    cmd.unbond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                for b in a.keys():
                    if b != "FREQ":
                        cmd.set_dihedral(
                            "(%s & n;%s)" % (mut_sele, b[0]),
                            "(%s & n;%s)" % (mut_sele, b[1]),
                            "(%s & n;%s)" % (mut_sele, b[2]),
                            "(%s & n;%s)" % (mut_sele, b[3]),
                            a[b],
                            state=state,
                        )
                    else:
                        cmd.set_title(obj_name, state, "%1.1f%%" % (a[b] * 100))
                if rot_type == "PRO":
                    cmd.bond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print " Mutagenesis: %d rotamers loaded." % len(lib)
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(
                    bump_name,
                    "(((byobj %s) within 6 of (%s and not name n+c+ca+o+h+ha)) and (not (%s)))|(%s)"
                    % (src_sele, mut_sele, src_sele, mut_sele),
                    singletons=1,
                )
                cmd.color("gray50", bump_name + " and elem c")
                cmd.set("seq_view", 0, bump_name, quiet=1)
                cmd.hide("everything", bump_name)
                if (cmd.select(tmp_sele1, "(n;N and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;C and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                if (cmd.select(tmp_sele1, "(n;C and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;N and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect("%s and not (%s in (%s and not name n+c+ca+o+h+ha))" % (bump_name, bump_name, mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo", bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode", 1, bump_name)
                state = 1
                for a in lib:
                    cmd.sculpt_iterate(bump_name, state=state)
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name, frag_name, 1, 1)
            print " Mutagenesis: no rotamers found in library."
        cmd.set("seq_view", 0, obj_name, quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("(" + obj_name + ")")
        cmd.show(self.rep, obj_name)
        cmd.show("lines", obj_name)  # neighbor  always show lines
        if cartoon:
            cmd.show("cartoon", obj_name)
        if sticks:
            cmd.show("sticks", obj_name)
        cmd.set("auto_zoom", auto_zoom, quiet=1)
        cmd.delete(frag_name)
        cmd.frame(0)
        cmd.unpick()
        cmd.feedback("pop")
Example #20
0
def format_bonds(
    selection='all',
    bonds=4,
):
    '''
DESCRIPTION
    Formats bonds in aromatic or charged residues
EXAMPLE
    frag PHE
    format_bonds
USAGE
    format_bonds [ selection [, bonds ]]
ARGUMENTS
    selection: <str> input selection {default: 'all'}
    bonds:     <int> toogles format of bonds
               1: single bonds (deactivates valence display)
               2: regular double bonds (activates valence display)
             >=3: delocalized (activates valence display)
    '''
    # Selection
    try:
        # group selection with bracketing and select complete residues
        selection = '(byres (' + str(selection) + '))'
        # checks functional selection
        cmd.count_atoms(selection)
    except:
        print("invalid selection")
        return False

    # PARAMETERS
    try:
        bonds = int(bonds)
    except:
        pass
    if (not (bonds in [1, 2])):
        bonds = 4

    if bonds == 1:
        cmd.set('valence', 0)
        print("Valence display disabled!")
        return bonds
    else:
        cmd.set('valence', 1)
        print("Valence display enabled!")
    # proceed

    ##### SELECTION BY OBJECT AND CHAIN #####
    # variable for the selections
    # get the names of the proteins in the selection
    objects = cmd.get_object_list(selection)
    # include chains

    # subselect chains
    names = []
    for p in objects:
        for chain in cmd.get_chains('model ' + p) or ['']:
            names.append("(model %s and chain '%s')" % (p, chain))

    ##### SELECTION LISTS #####
    # get TRP
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn TRP+NIW) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    # the integer is to ensure unique keys
    TRP_tuple = (1, ) + tuple(stored.temp)

    # get PHETYR
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn PHE+TYR+PTR+NIY+PNIY) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    PHETYR_tuple = (2, ) + tuple(stored.temp)

    # get HIS
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn HIS) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    HIS_tuple = (3, ) + tuple(stored.temp)

    # get NITRO
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn NIY+PNIY+NIW) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    NITRO_tuple = (4, ) + tuple(stored.temp)

    # get GLU
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn GLU) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    GLU_tuple = (5, ) + tuple(stored.temp)

    # get ASP
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn ASP) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    ASP_tuple = (6, ) + tuple(stored.temp)

    # get CTERM
    stored.temp = []
    for p in names:
        cmd.iterate(
            '(byres (last %s)) and (not (hetatm)) '
            'and (name OXT)' % (p),
            'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    CTERM_tuple = (7, ) + tuple(stored.temp)

    # get ARG
    stored.temp = []
    for p in names:
        cmd.iterate(('(%s) and (resn ARG) '
                     'and (name CA)' % (p)),
                    'stored.temp.append("(%s and resi "+str(resi)+")")' % p)
    ARG_tuple = (8, ) + tuple(stored.temp)

    ##### SELECTION TUPLES DONE #####

    ##### ATOM LISTS #####

    TRP_bonds_all = [['CG', 'CD1'], ['CD1', 'NE1'], ['NE1', 'CE2'],
                     ['CE2', 'CD2'], ['CD2', 'CG'], ['CD2', 'CE3'],
                     ['CE3', 'CZ3'], ['CZ3', 'CH2'], ['CH2', 'CZ2'],
                     ['CZ2', 'CE2']]

    TRP_bonds_double = [['CG', 'CD1'], ['CE2', 'CD2'], ['CE3', 'CZ3'],
                        ['CH2', 'CZ2']]

    PHETYR_bonds_all = [['CG', 'CD1'], ['CD1', 'CE1'], ['CE1', 'CZ'],
                        ['CZ', 'CE2'], ['CE2', 'CD2'], ['CD2', 'CG']]

    PHETYR_bonds_double = [['CG', 'CD1'], ['CE1', 'CZ'], ['CE2', 'CD2']]

    HIS_bonds_all = [
        ['CG', 'CD2'],
        ['CD2', 'NE2'],
        ['NE2', 'CE1'],
        ['CE1', 'ND1'],
        ['ND1', 'CG'],
    ]

    HIS_bonds_double = [['CG', 'CD2'], ['CE1', 'ND1']]

    NITRO_bonds_all = [['NN', 'O1'], ['NN', 'O2']]
    NITRO_bonds_double = [['NN', 'O1']]

    GLU_bonds_all = [['CD', 'OE1'], ['CD', 'OE2']]
    GLU_bonds_double = [['CD', 'OE1']]

    ASP_bonds_all = [['CG', 'OD1'], ['CG', 'OD2']]
    ASP_bonds_double = [['CG', 'OD1']]

    CTERM_bonds_all = [['C', 'O'], ['C', 'OXT']]
    CTERM_bonds_double = [['C', 'O']]

    ARG_bonds_all = [['CZ', 'NH1'], ['CZ', 'NH2']]

    ARG_bonds_double = [['CZ', 'NH1']]

    ##### FORMATING #####

    # dictionary: entries:atoms
    format_dict = {
        TRP_tuple: [TRP_bonds_all, TRP_bonds_double],
        PHETYR_tuple: [PHETYR_bonds_all, PHETYR_bonds_double],
        HIS_tuple: [HIS_bonds_all, HIS_bonds_double],
        NITRO_tuple: [NITRO_bonds_all, NITRO_bonds_double],
        GLU_tuple: [GLU_bonds_all, GLU_bonds_double],
        ASP_tuple: [ASP_bonds_all, ASP_bonds_double],
        CTERM_tuple: [CTERM_bonds_all, CTERM_bonds_double],
        ARG_tuple: [ARG_bonds_all, ARG_bonds_double]
    }

    if bonds != 2:
        lines = 4
        print("Formating as delocalized bonds")
    else:
        lines = 1
        print("Formating as double bonds")

    # for all tuples (i.e format_dict.keys())
    for p in list(format_dict.keys()):
        # go through list except ID at pos 1
        for q in p[1:]:
            # format bonds
            for r in format_dict[p][0]:
                cmd.unbond('%s and name %s' % (q, r[0]),
                           '%s and name %s' % (q, r[1]))
                cmd.bond('%s and name %s' % (q, r[0]),
                         '%s and name %s' % (q, r[1]), lines)
            if lines == 1:
                # add double bonds
                for r in format_dict[p][1]:
                    cmd.unbond('%s and name %s' % (q, r[0]),
                               '%s and name %s' % (q, r[1]))
                    cmd.bond('%s and name %s' % (q, r[0]),
                             '%s and name %s' % (q, r[1]), 2)

    return bonds