Ejemplo n.º 1
0
def torsion_drive(atom1, atom2, atom3, atom4, interval, selection, path, mol_name,):
    """
    This function generates input pdbs of dihedral angles selected of intervals specified with interval
    :param atom1: name of atom 1 of dihedral
    :param atom2: name of atom 2 of dihedral
    :param atom3: name of atom 3 of dihedral
    :param atom4: name of atom 4 of dihedral
    :param interval: int or float (in degrees) of intervals to generate torsion scan for
    :param selection: name of selection for molecule
    :param path: path to where pdb files should be saved
    :param mole_name: name of molecule to append to filenamen
    """

    atom1 = selection + " and name " + atom1
    atom2 = selection + " and name " + atom2
    atom3 = selection + " and name " + atom3
    atom4 = selection + " and name " + atom4
    for angle in range(0, 360 + int(interval), int(interval)):
        try:
            os.makedirs('%s/%i' % (path, angle))
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise

        cmd.set_dihedral(atom1, atom2, atom3, atom4, angle)
        filename = '%s/%i/%s_%i.pdb' % (path, angle, mol_name, angle)
        cmd.save(filename, selection, 1)
Ejemplo n.º 2
0
 def test_set_dihedral(self):
     cmd.fragment('ala')
     angle = 45.0
     atoms = ('ID 7', 'ID 2', 'ID 1', 'ID 9')
     cmd.set_dihedral(*atoms, angle=angle)
     v = cmd.get_dihedral(*atoms)
     self.assertAlmostEqual(v, angle, 4)
Ejemplo n.º 3
0
 def test_set_dihedral(self):
     cmd.fragment('ala')
     angle = 45.0
     atoms = ('ID 7', 'ID 2', 'ID 1', 'ID 9')
     cmd.set_dihedral(*atoms, angle=angle)
     v = cmd.get_dihedral(*atoms)
     self.assertAlmostEqual(v, angle, 4)
Ejemplo n.º 4
0
def set_psi_angle(pymol_object, chainID, aa_number, new_angle):
    """Set Psi dihedral angle of a given residue.

    Parameters
    ----------
    pymol_object : String
        Name of Pymol object in the session.
    chainID : String
        ChainID of residue.
    aa_number : Integer
        Residue number.
    new_angle : Float
        New psi angle to be set.

    Returns
    -------
    None.

    """
    # Atom selection for each atom that participates in the angle
    # Ni+1
    atom1 = pymol_object + '//' + chainID + '/' + str(aa_number+1) + '/N'
    # Ci
    atom2 = pymol_object + '//' + chainID + '/' + str(aa_number) + '/C'
    # CAi
    atom3 = pymol_object + '//' + chainID + '/' + str(aa_number) + '/CA'
    # Ni
    atom4 = pymol_object + '//' + chainID + '/' + str(aa_number) + '/N'

    cmd.set_dihedral(atom1, atom2, atom3, atom4, new_angle)
Ejemplo n.º 5
0
def set_phipsi(selection, phi=None, psi=None):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    set_phi, set_psi, set_dihedral, phi_psi, cmd.get_phipsi, DynoPlot
    '''
    for model, index in cmd.index('byca (' + selection + ')'):
        atsele = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),  # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3],
                                 phi)
            if psi is not None:
                cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4],
                                 psi)
        except:
            print ' Error: cmd.set_dihedral failed'
Ejemplo n.º 6
0
def set_phipsi(selection, phi=None, psi=None):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    set_phi, set_psi, set_dihedral, phi_psi, cmd.get_phipsi, DynoPlot
    '''
    for model, index in cmd.index('byca (' + selection + ')'):
        atsele = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),                             # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3], phi)
            if psi is not None:
                cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4], psi)
        except:
            print ' Error: cmd.set_dihedral failed'
 def setDihVal(sele, atomNames, dih, val):
     cmd.set_dihedral(sele + " and name " + atomNames[0],
                      sele + " and name " + atomNames[1],
                      sele + " and name " + atomNames[2],
                      sele + " and name " + atomNames[3],
                      val,
                      quiet=1)
Ejemplo n.º 8
0
def modify_dihedral(atom1, atom2, atom3, atom4, value):
    try:
        cmd.set_dihedral(atom1, atom2, atom3, atom4, value)
    except:
        print "Error in pymol trying modified this dihedral %s %s %s %s %f" % (
            atom1, atom2, atom3, atom4, value)
        cmd.save("problem.pdb", "all", 0)
        exit()
def _set_dihedral(atoms, angle, mode="index"):
    if mode == "name":
        for i in range(4):
            cmd.select('a%d' % i, 'name %s' % atomnames[i])
    elif mode == "index":
        for i in range(4):
            cmd.select('a%d' % i, 'index %d' % atoms[i])
    cmd.set_dihedral('a0', 'a1', 'a2', 'a3', angle)
Ejemplo n.º 10
0
def helicize_beta_peptide(helixtype, selection='all'):
    """
    DESCRIPTION

    Adjust the torsion angles of a beta-peptide to different helical conformations

    USAGE

    helicize_beta_peptide helixtype [, selection]
    
    ARGUMENTS
    
    helixtype = the type of the helix (either short or IUPAC name),
        or a tuple of 3 floats, representing three torsional angles, or
        a list of tuples / short names / IUPAC names.
    
    selection = the selection to operate on. Must be a single peptide chain with 
        unique residue IDs (default: all)
    
    NOTES"""

    if isinstance(helixtype, str):
        for perczelname, iupacname, angles, theorylevel in helixtypes:
            helixtype = helixtype.replace(iupacname, perczelname).replace(
                perczelname, '({}, {}, {})'.format(*angles))
        helixtype = helixtype.strip()
        if not all([h in '0123456789.,()[] -+efg' for h in helixtype]):
            raise ValueError(
                'Helixtype parameter contains an invalid character (only numbers, parentheses, brackets, space and commas are accepted)'
            )
        helixtype = eval(helixtype, {}, {})
    assert isinstance(helixtype, collections.Iterable)
    if all([isinstance(x, numbers.Real)
            for x in helixtype]) and len(helixtype) == 3:
        helixtype = [helixtype]
    print('Helixtypes: {}'.format(helixtype))
    space = {'lis': []}
    cmd.iterate(selection, 'lis.append(resv)', space=space)
    residues = sorted(set(space['lis']))
    for r, ht in zip(sorted(residues), itertools.cycle(helixtype)):
        if len(ht) != 3 and not all([isinstance(x, numbers.Real) for x in ht]):
            raise ValueError('Invalid helixtype: {}'.format(ht))
        calpha = '({}) and (name CA) and (resi {})'.format(selection, r)
        cbeta = '({}) and (name CB+CB1) and (resi {})'.format(selection, r)
        c = '({}) and (name C) and (resi {})'.format(selection, r)
        n = '({}) and (name N) and (resi {})'.format(selection, r)
        prevc = '(neighbor ({})) and (name C)'.format(n)
        nextn = '(neighbor ({})) and (name N)'.format(c)
        prevo = '(neighbor ({})) and (name O)'.format(prevc)
        hn = '(neighbor ({})) and (name H+HN)'.format(n)
        o = '(neighbor ({})) and (name O)'.format(c)
        nexthn = '(neighbor ({})) and (name H+HN)'.format(nextn)
        set_beta_helix(prevc, n, cbeta, calpha, c, nextn, ht, selection)
        for n_, h_, c_, o_ in [(n, hn, prevc, prevo), (nextn, nexthn, c, o)]:
            if cmd.count_atoms(n_) + cmd.count_atoms(h_) + cmd.count_atoms(
                    c_) + cmd.count_atoms(o_) == 4:
                cmd.set_dihedral(h_, n_, c_, o_, 180.)
    cmd.orient(selection)
Ejemplo n.º 11
0
def set_omega(obj, bond, angle, state=1): 
    """
    Get the dihedral angle omega (O6-C6-C5-C4)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    atom1 = '%s and resi %s and name O6' % (obj, resi_j)
    atom2 = '%s and resi %s and name C6' % (obj, resi_j)
    atom3 = '%s and resi %s and name C5' % (obj, resi_j)
    atom4 = '%s and resi %s and name C4' % (obj, resi_j)
    cmd.set_dihedral(atom1, atom2, atom3, atom4, angle, state=state)
Ejemplo n.º 12
0
def set_omega(obj, bond, angle, state=1):
    """
    Get the dihedral angle omega (O6-C6-C5-C4)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    atom1 = '%s and resi %s and name O6' % (obj, resi_j)
    atom2 = '%s and resi %s and name C6' % (obj, resi_j)
    atom3 = '%s and resi %s and name C5' % (obj, resi_j)
    atom4 = '%s and resi %s and name C4' % (obj, resi_j)
    cmd.set_dihedral(atom1, atom2, atom3, atom4, angle, state=state)
Ejemplo n.º 13
0
def set_dihedral(modelname, nameandresi1, nameandresi2, nameandresi3,
                 nameandresi4, value):
    """A safer version of cmd.set_dihedral(): doesn't choke on non-singleton selections"""
    selections = [
        '({}) and name {} and resi {}'.format(modelname, *nr)
        for nr in [nameandresi1, nameandresi2, nameandresi3, nameandresi4]
    ]
    if not all([cmd.count_atoms(s) == 1 for s in selections]):
        return False
    cmd.set_dihedral(*(selections + [value]))
    cmd.unpick()
    return True
Ejemplo n.º 14
0
def set_phipsi(sel, phi, psi):
    # Get atoms from selection
    atoms = cmd.get_model("byres (" + sel + ")")

    # Loop through atoms in selection
    for at in atoms.atom:  # pylint: disable=E1103
        if at.name == "N":
            # Check for a null chain id (some PDBs contain this)
            unit_select = ""
            if not at.chain == "":
                unit_select = "chain " + str(at.chain) + " and "
            # end if

            try:
                # Define residue selections
                rdef_prev = unit_select + 'resi ' + str(int(at.resi) - 1)
                rdef = unit_select + 'resi ' + str(at.resi)
                #                print "rdef_prev: [%s]" % rdef_prev
                #                print "rdef     : [%s]" % rdef
                if at.resn == "PRO":
                    print "Skipping setting phi for PRO"
                else:
                    old_phi = cmd.get_dihedral(rdef_prev + ' and name C',
                                               rdef + ' and name N',
                                               rdef + ' and name CA',
                                               rdef + ' and name C')
                    cmd.set_dihedral(rdef_prev + ' and name C',
                                     rdef + ' and name N',
                                     rdef + ' and name CA',
                                     rdef + ' and name C', phi)
                    print "Changed residue %4s %4s phi: from %6.1f to %6.1f" % (
                        at.resn, at.resi, old_phi, float(phi))
            except:

                print "Note skipping set of phi because of error; this is normal for a N-terminal residue"
            try:
                rdef = unit_select + 'resi ' + str(at.resi)
                residue_def_next = unit_select + 'resi ' + str(
                    int(at.resi) + 1)
                #                print "rdef     : [%s]" % rdef
                #                print "residue_def_next: [%s]" % residue_def_next
                old_psi = cmd.get_dihedral(rdef + ' and name N',
                                           rdef + ' and name CA',
                                           rdef + ' and name C',
                                           residue_def_next + ' and name N')
                cmd.set_dihedral(rdef + ' and name N', rdef + ' and name CA',
                                 rdef + ' and name C',
                                 residue_def_next + ' and name N', psi)  # pylint: disable=C0301
                print "Changed residue %4s %4s psi: from %6.1f to %6.1f" % (
                    at.resn, at.resi, old_psi, float(psi))
            except:
                print "Note skipping set of psi; this is normal for a C terminal residue"
Ejemplo n.º 15
0
def set_psi(obj, bond, angle, state=1): 
    """
    Set the dihedral angle psi (C1-O'x-C'x-C'x-1)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    if atom_i > atom_j:
        atom_j = atom_i
        resi_i, resi_j = resi_j, resi_i
    atom1 = '%s and resi %s and name C1' % (obj, resi_i)
    atom2 = '%s and resi %s and name O%s' % (obj, resi_j, atom_j)
    atom3 = '%s and resi %s and name C%s' % (obj, resi_j, atom_j)
    atom4 = '%s and resi %s and name C%s' % (obj, resi_j, (atom_j-1))
    cmd.set_dihedral(atom1, atom2, atom3, atom4, angle, state=state)
Ejemplo n.º 16
0
def set_psi(obj, bond, angle, state=1):
    """
    Set the dihedral angle psi (C1-O'x-C'x-C'x-1)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    if atom_i > atom_j:
        atom_j = atom_i
        resi_i, resi_j = resi_j, resi_i
    atom1 = '%s and resi %s and name C1' % (obj, resi_i)
    atom2 = '%s and resi %s and name O%s' % (obj, resi_j, atom_j)
    atom3 = '%s and resi %s and name C%s' % (obj, resi_j, atom_j)
    atom4 = '%s and resi %s and name C%s' % (obj, resi_j, (atom_j - 1))
    cmd.set_dihedral(atom1, atom2, atom3, atom4, angle, state=state)
Ejemplo n.º 17
0
def set_phipsi(model, index, phi, psi):
    atsele = [
        'first ((%s`%d) extend 2 and name C)' % (model, index), # prev C
        'first ((%s`%d) extend 1 and name N)' % (model, index), # this N
        '(%s`%d)' % (model, index),                             # this CA
        'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
        'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
    ]
    try:
        cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3], phi)
        cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4], psi)
    except:
        print ' DynoPlot Error: cmd.set_dihedral failed'
Ejemplo n.º 18
0
def set_phipsi(model, index, phi, psi, state=-1):
    atsele = [
        'first ((%s`%d) extend 2 and name C)' % (model, index), # prev C
        'first ((%s`%d) extend 1 and name N)' % (model, index), # this N
        '(%s`%d)' % (model, index),                             # this CA
        'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
        'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
    ]
    try:
        cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3], phi, state)
        cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4], psi, state)
    except:
        print ' DynoPlot Error: cmd.set_dihedral failed'
Ejemplo n.º 19
0
def set_beta_helix(prevC, N, CB, CA, C, nextN, helixtype, selection='all'):
    """Set torsion angles of a beta peptide backbone

    Inputs:
       prevC: selection of the amide carbon in the previous amino acid
       N: selection of the amide Nitrogen in this amino acid
       CB: selection of the beta carbon
       CA: selection of the alpha carbon
       C: selection of the amide carbon
       nextN: selection of the amide nitrogen of the next amino acid
       helixtype: the type of the helix or a tuple of 3 floats: the 3 angles
       selection: the main selection in which we operate. Defaults to "*"
"""
    try:
        helixparam = [
            h for h in helixtypes if h[0] == helixtype or h[1] == helixtype
        ][0]
        angles = helixparam[2]
    except IndexError:
        if isinstance(helixtype, str):
            # try to interpret helixtype as a tuple or a list
            helixtype = helixtype.strip()
            try:
                if (helixtype.startswith('(') and helixtype.endswith(')')) or (
                        helixtype.startswith('[') and helixtype.endswith(']')):
                    helixtype = helixtype[1:-1]
                    angles = [float(x.strip()) for x in helixtype.split(',')]
            except:
                raise ValueError('Unknown helix type: {}'.format(helixtype))
        elif (isinstance(helixtype, collections.Sequence)
              and all([isinstance(x, numbers.Real) for x in helixtype])):
            angles = helixtype
        else:
            raise ValueError('Unknown helix type: {}'.format(helixtype))

    print('Helixtype in set_beta_helix: {} (type: {})'.format(
        helixtype, type(helixtype)))
    atoms = [
        '({}) and ({})'.format(selection, atomidx)
        for atomidx in [prevC, N, CB, CA, C, nextN]
    ]
    for i, angle in enumerate(angles):
        if any([cmd.count_atoms(atoms[i + j]) != 1 for j in range(4)]):
            # if any of the selections contains zero or more than one atoms, do not set the dihedral.
            continue
        cmd.set_dihedral(*(atoms[i:i + 4] + [angle]))
    cmd.delete('pk1')
    cmd.delete('pk2')
    cmd.delete('pkbond')
    cmd.delete('pkmol')
Ejemplo n.º 20
0
    def flip_by_atoms(self, atmA, atmB, atmC, atmD):
        from pymol import CmdException, cmd
        sele = self.selector()

        a, b, c, d = map(lambda a: '{}/{}'.format(sele, a),
                [atmA, atmB, atmC, atmD])

        try:
            dh = cmd.get_dihedral(a, b, c, d)
        except CmdException:
            print "Error on '{}'.".format(self.selector())
            pass
        else:
            cmd.set_dihedral(a, b, c, d, dh + 180)
            cmd.unpick()
Ejemplo n.º 21
0
        def __call__(self):

            # Loop through each item on plot to see if updated
            for key,value in canvas.shapes.items():
                dihedrals = value[5]

                # Look for update flag...
                if value[2]:

                    # Set residue's phi,psi to new values
                    print "Re-setting Phi,Psi: %s,%s" % (value[3],value[4])
                    cmd.set_dihedral(dihedrals[0],dihedrals[1],dihedrals[2],dihedrals[3],value[3])
                    cmd.set_dihedral(dihedrals[4],dihedrals[5],dihedrals[6],dihedrals[7],value[4])

                    value[2] = 0
Ejemplo n.º 22
0
def unfold_index(name, index):
    selection_string_array = [
        f'first (({name}`{index}) extend 2 and name C)',  # prev C
        f'first (({name}`{index}) extend 1 and name N)',  # this N
        f'({name}`{index})',  # this CA
        f'last (({name}`{index}) extend 1 and name C)',  # this C
        f'last (({name}`{index}) extend 2 and name N)'
    ]  # next N
    try:
        cmd.set_dihedral(selection_string_array[0], selection_string_array[1],
                         selection_string_array[2], selection_string_array[3],
                         random.randint(0, 360))
        cmd.set_dihedral(selection_string_array[1], selection_string_array[2],
                         selection_string_array[3], selection_string_array[4],
                         random.randint(0, 360))
    except Exception as e:
        pass
Ejemplo n.º 23
0
def set_phipsi(selection, phi=None, psi=None):
    for model, index in cmd.index('byca (' + selection + ')'):
        angles = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),  # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(angles[0], angles[1], angles[2], angles[3],
                                 phi)
            if psi is not None:
                cmd.set_dihedral(angles[1], angles[2], angles[3], angles[4],
                                 psi)
        except:
            print 'Error: cmd.set_dihedral failed'
Ejemplo n.º 24
0
def set_phipsi(selection, phi=None, psi=None, state=1, quiet=1):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    phi_psi, cmd.get_phipsi, set_dihedral, DynoPlot
    '''
    for idx in cmd.index('byca (' + selection + ')'):
        x = cmd.index('((%s`%d) extend 2 and name C+N+CA)' % idx)
        if len(x) != 5 or x[2] != idx:
            print(' Warning: set_phipsi: missing atoms (%s`%d)' % idx)
            continue
        if phi is not None:
            cmd.set_dihedral(x[0], x[1], x[2], x[3], phi, state, quiet)
        if psi is not None:
            cmd.set_dihedral(x[1], x[2], x[3], x[4], psi, state, quiet)
Ejemplo n.º 25
0
def set_phipsi(selection, phi=None, psi=None, state=1, quiet=1):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    phi_psi, cmd.get_phipsi, set_dihedral, DynoPlot
    '''
    for idx in cmd.index('byca (' + selection + ')'):
        x = cmd.index('((%s`%d) extend 2 and name C+N+CA)' % idx)
        if len(x) != 5 or x[2] != idx:
            print(' Warning: set_phipsi: missing atoms (%s`%d)' % idx)
            continue
        if phi is not None:
            cmd.set_dihedral(x[0], x[1], x[2], x[3], phi, state, quiet)
        if psi is not None:
            cmd.set_dihedral(x[1], x[2], x[3], x[4], psi, state, quiet)
Ejemplo n.º 26
0
def set_chi(obj, bond, state=1):
    """
    Set the dihedral angles chi (Cx-1-Cx-O'x-H'x) to one of tree predefinied 
    angles (-60, 60, 180). The perturbed chi angle is selected at random.
    This function considers the omega angle as a chi angle.
    """
    resi_i, resi_j = bond[0], bond[2]
    chises = [1, 2, 3, 4, 5, 6]
    np.random.shuffle(chises)
    angle = np.random.choice([-60, 60, 180])
    resi_i = np.random.choice([resi_i, resi_j])
    for chi in chises:
        if chi == 1:
            try:
                cmd.set_dihedral(
                    '%s and resi %s and name OR' % (obj, resi_i),
                    '%s and resi %s and name C%S' % (obj, resi_i, chi),
                    '%s and resi %s and name O%s' % (obj, resi_i, chi),
                    '%s and resi %s and name H%so' % (obj, resi_i, chi),
                    angle,
                    state=state)
                break
            except:
                pass
        elif chi <= 5:
            try:
                cmd.set_dihedral(
                    '%s and resi %s and name C%s' % (obj, resi_i, chi - 1),
                    '%s and resi %s and name C%S' % (obj, resi_i, chi),
                    '%s and resi %s and name O%s' % (obj, resi_i, chi),
                    '%s and resi %s and name H%so' % (obj, resi_i, chi),
                    angle,
                    state=state)
                break
            except:
                pass
        else:
            try:
                set_omega(obj, bond, angle)
                break
            except:
                pass
Ejemplo n.º 27
0
def set_phipsi(selection, phi=None, psi=None):
    for model, index in cmd.index(
            'byca (' + selection +
            ')'):  # 'byca' limits selection to one atom per residue
        atsele = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),  # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3],
                                 phi)  #sets value for all phi in selection
            if psi is not None:
                cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4],
                                 psi)  #sets value for all psi
        except:
            print ' Error: cmd.set_dihedral failed'
Ejemplo n.º 28
0
def set_phipsi(sel,phi,psi):
    # Get atoms from selection
    atoms = cmd.get_model("byres ("+sel+")")

    # Loop through atoms in selection
    for at in atoms.atom: # pylint: disable=E1103
        if at.name == "N":
            # Check for a null chain id (some PDBs contain this)
            unit_select = ""
            if not at.chain == "":
                unit_select = "chain "+str(at.chain)+" and "
            # end if
            
            try:
                # Define residue selections
                rdef_prev = unit_select+'resi '+str(int(at.resi)-1)
                rdef      = unit_select+'resi '+str(at.resi)
#                print "rdef_prev: [%s]" % rdef_prev
#                print "rdef     : [%s]" % rdef
                if at.resn == "PRO":
                    print "Skipping setting phi for PRO"
                else:
                    old_phi = cmd.get_dihedral(rdef_prev+' and name C',rdef+' and name N', rdef+' and name CA',rdef+' and name C')
                    cmd.set_dihedral(          rdef_prev+' and name C',rdef+' and name N', rdef+' and name CA',rdef+' and name C',phi)
                    print "Changed residue %4s %4s phi: from %6.1f to %6.1f" % (at.resn, at.resi, old_phi, float(phi))
            except:

                print "Note skipping set of phi because of error; this is normal for a N-terminal residue"
            try:
                rdef      = unit_select+'resi '+str(at.resi)
                residue_def_next = unit_select+'resi '+str(int(at.resi)+1)
#                print "rdef     : [%s]" % rdef
#                print "residue_def_next: [%s]" % residue_def_next
                old_psi = cmd.get_dihedral(rdef     +' and name N',rdef+' and name CA',rdef+' and name C', residue_def_next+' and name N')
                cmd.set_dihedral(          rdef     +' and name N',rdef+' and name CA',rdef+' and name C', residue_def_next+' and name N',psi) # pylint: disable=C0301
                print "Changed residue %4s %4s psi: from %6.1f to %6.1f" % (at.resn, at.resi, old_psi, float(psi))
            except:
                print "Note skipping set of psi; this is normal for a C terminal residue"
Ejemplo n.º 29
0
def torsion_drive(
    atom1,
    atom2,
    atom3,
    atom4,
    interval,
    selection,
    path,
    mol_name,
):
    """
    This function generates input pdbs of dihedral angles selected of intervals specified with interval
    :param atom1: name of atom 1 of dihedral
    :param atom2: name of atom 2 of dihedral
    :param atom3: name of atom 3 of dihedral
    :param atom4: name of atom 4 of dihedral
    :param interval: int or float (in degrees) of intervals to generate torsion scan for
    :param selection: name of selection for molecule
    :param path: path to where pdb files should be saved
    :param mole_name: name of molecule to append to filenamen
    """

    atom1 = selection + " and name " + atom1
    atom2 = selection + " and name " + atom2
    atom3 = selection + " and name " + atom3
    atom4 = selection + " and name " + atom4
    for angle in range(0, 360 + int(interval), int(interval)):
        try:
            os.makedirs('%s/%i' % (path, angle))
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise

        cmd.set_dihedral(atom1, atom2, atom3, atom4, angle)
        filename = '%s/%i/%s_%i.pdb' % (path, angle, mol_name, angle)
        cmd.save(filename, selection, 1)
Ejemplo n.º 30
0
def set_chi(obj, bond, state=1):
    """
    Set the dihedral angles chi (Cx-1-Cx-O'x-H'x) to one of tree predefinied 
    angles (-60, 60, 180). The perturbed chi angle is selected at random.
    This function considers the omega angle as a chi angle.
    """
    resi_i, resi_j = bond[0], bond[2]
    chises = [1,2,3,4,5,6]
    np.random.shuffle(chises)
    angle = np.random.choice([-60, 60, 180])
    resi_i = np.random.choice([resi_i, resi_j])
    for chi in chises:
        if chi == 1:
            try:
                cmd.set_dihedral('%s and resi %s and name OR' % (obj, resi_i), 
                                '%s and resi %s and name C%S' % (obj, resi_i, chi),
                                '%s and resi %s and name O%s' % (obj, resi_i, chi),  
                                '%s and resi %s and name H%so' % (obj, resi_i, chi), angle, state=state)        
                break
            except:
                pass   
        elif chi <= 5:
            try:
                cmd.set_dihedral('%s and resi %s and name C%s' % (obj, resi_i, chi-1), 
                                '%s and resi %s and name C%S' % (obj, resi_i, chi),
                                '%s and resi %s and name O%s' % (obj, resi_i, chi),  
                                '%s and resi %s and name H%so' % (obj, resi_i, chi), angle, state=state)
                break
            except:
                pass
        else:
            try:
                set_omega(obj, bond, angle)
                break
            except:
                pass
Ejemplo n.º 31
0
def calc_energyprofile(atom1, atom2, atom3, atom4, structurefilename,
                       forcefield, anglestep, mopacpath):
    energyprofilelist = []
    pymol.cmd.load(os.path.abspath(os.curdir) + "//" + structurefilename)
    for value in range(-180, 180, anglestep):
        cmd.set_dihedral("ID " + str(atom1), "ID " + str(atom2),
                         "ID " + str(atom3), "ID " + str(atom4), value)
        tmpstructurefilename = structurefilename.replace(".pdb", "_tmp.pdb")
        moptmpstructurefilename = structurefilename.replace(".pdb", "_tmp.mop")
        outtmpstructurefilename = structurefilename.replace(".pdb", "_tmp.out")
        cmd.save(tmpstructurefilename)

        #devnull = open('/dev/null', 'w') #para ocultar stdout
        command = "babel -ipdb " + tmpstructurefilename + " -omop " + moptmpstructurefilename + " -xk '" + forcefield + "' 2> /dev/null; " + mopacpath + " " + moptmpstructurefilename
        #process = subprocess.Popen(command , shell=True, bufsize=2048, stdout=devnull, stderr=devnull)
        os.system(command)
        #process.wait()
        #devnull.close()
        outtmpstructurefile = open(outtmpstructurefilename, "r")
        for line in outtmpstructurefile:
            if 'FINAL HEAT' in line:
                energyprofilelist.append([value, float(line.split()[5])])
        outtmpstructurefile.close()
    return energyprofilelist
Ejemplo n.º 32
0
    def UpdateSideChainConformations(self):
        
        try:
            # temporary sel. var
            strSelectSC  = ''

            # Loop through Flexible side-chains
            for residue in self.top.listSideChain:

                #print "Setting dihedrals for " + residue
                
                # Were any rotamers accepted for this side-chain
                if self.top.dictSideChainNRot.get(residue,''):

                    #print "List of possible rotamers:" + str(self.top.dictSideChainNRot[residue])

                    # Residu Name
                    Res = residue[0:3]
                    Num = residue[3:len(residue)-1]
                    Chn = residue[len(residue)-1:len(residue)]

                    strSelectSC += "(resn " + Res + " & resi " + Num
                    if Chn != '-':
                        strSelectSC += " & chain " + Chn
                    else:
                        strSelectSC += " & chain ''"                    
                    
                    strSelectSC += " & ! name C+O+N " + " & " + self.TargetObj + " & present) or "

                    # Get Integer value from GA.
                    IntVal = int(float(self.Line[self.colNo:(self.colNo+10)].strip()) + 0.5)
                    nFlex = Constants.nFlexBonds[Res]
                    
                    #print("IntVal", str(IntVal))
                    #print("nFlex", str(nFlex))
                    #print strSelectSC
                    
                    if IntVal > 0: # 0 is the default PDB side-chain conf.
        
                        # Get List of Dihedrals to rebuild
                        for k in range(0,nFlex):
                        
                            '''
                            print "for k=" + str(k) + " for residue=" + str(residue)
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+0])
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+1])
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+2])
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+3])
                            print self.top.dictSideChainRotamers[residue]
                            print self.top.dictSideChainRotamers[residue][(IntVal-1)*nFlex+k]
                            '''
                            
                            # Set dihedrals for side-chain
                            cmd.set_dihedral(self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+0]),
                                             self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+1]),
                                             self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+2]),
                                             self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+3]),
                                             self.top.dictSideChainRotamers[residue][(IntVal-1)*nFlex+k], self.State)
                            cmd.refresh()

                            
                    # Get next column starting index
                    self.colNo = self.colNo + 11


            # Side-chain selection string - remove last 4 chars
            if strSelectSC != '':
                strSelectSC = strSelectSC[:len(strSelectSC)-4]

            return strSelectSC

        except:

            self.CriticalError("Could not update side-chain conformations")
Ejemplo n.º 33
0
def _set_dihedral(index, angle):
    for i in range(4):
        cmd.select('a%d' % i, 'id %d' % index[i])
    cmd.set_dihedral('a0', 'a1', 'a2', 'a3', angle)
Ejemplo n.º 34
0
    def UpdateSideChainConformations(self):

        try:
            # temporary sel. var
            strSelectSC = ''

            # Loop through Flexible side-chains
            for residue in self.top.listSideChain:

                #print "Setting dihedrals for " + residue

                # Were any rotamers accepted for this side-chain
                if self.top.dictSideChainNRot.get(residue, ''):

                    #print "List of possible rotamers:" + str(self.top.dictSideChainNRot[residue])

                    # Residu Name
                    Res = residue[0:3]
                    Num = residue[3:len(residue) - 1]
                    Chn = residue[len(residue) - 1:len(residue)]

                    strSelectSC += "(resn " + Res + " & resi " + Num
                    if Chn != '-':
                        strSelectSC += " & chain " + Chn
                    else:
                        strSelectSC += " & chain ''"

                    strSelectSC += " & ! name C+O+N " + " & " + self.TargetObj + " & present) or "

                    # Get Integer value from GA.
                    IntVal = int(
                        float(self.Line[self.colNo:(self.colNo +
                                                    10)].strip()) + 0.5)
                    nFlex = Constants.nFlexBonds[Res]

                    #print("IntVal", str(IntVal))
                    #print("nFlex", str(nFlex))
                    #print strSelectSC

                    if IntVal > 0:  # 0 is the default PDB side-chain conf.

                        # Get List of Dihedrals to rebuild
                        for k in range(0, nFlex):
                            '''
                            print "for k=" + str(k) + " for residue=" + str(residue)
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+0])
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+1])
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+2])
                            print self.Get_AtomString(Res,Num,Chn,Constants.setDihedrals[Res][4*k+3])
                            print self.top.dictSideChainRotamers[residue]
                            print self.top.dictSideChainRotamers[residue][(IntVal-1)*nFlex+k]
                            '''

                            # Set dihedrals for side-chain
                            cmd.set_dihedral(
                                self.Get_AtomString(
                                    Res, Num, Chn,
                                    Constants.setDihedrals[Res][4 * k + 0]),
                                self.Get_AtomString(
                                    Res, Num, Chn,
                                    Constants.setDihedrals[Res][4 * k + 1]),
                                self.Get_AtomString(
                                    Res, Num, Chn,
                                    Constants.setDihedrals[Res][4 * k + 2]),
                                self.Get_AtomString(
                                    Res, Num, Chn,
                                    Constants.setDihedrals[Res][4 * k + 3]),
                                self.top.dictSideChainRotamers[residue][
                                    (IntVal - 1) * nFlex + k], self.State)
                            cmd.refresh()

                    # Get next column starting index
                    self.colNo = self.colNo + 11

            # Side-chain selection string - remove last 4 chars
            if strSelectSC != '':
                strSelectSC = strSelectSC[:len(strSelectSC) - 4]

            return strSelectSC

        except:

            self.CriticalError("Could not update side-chain conformations")
Ejemplo n.º 35
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 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")
Ejemplo n.º 36
0
# pymol -qc mutate.py pdb selection new_residue
# example: pymol -qc mutate.py 0.pdb C/1/ ALA 0_mutated.pdb

from pymol import cmd
import sys

pdb, selection, mutant, output_name = sys.argv[-4:]
print("file:", pdb)
print("selection:", selection)
print("mutating to:", mutant)
print("output name:", output_name)

cmd.load(pdb, "file")

resi_num = selection.split("/")[1]
#prefix = "chain B & resi " + resi_num + " & name "
prefix = "chain A & resi " + resi_num + " & name "
orig_dihedral = cmd.get_dihedral(prefix + "C", prefix + "CA", prefix + "CB", prefix + "CG")

cmd.wizard("mutagenesis")
cmd.refresh_wizard()
cmd.get_wizard().do_select(selection)
cmd.get_wizard().set_mode(mutant)
cmd.get_wizard().apply()
cmd.set_wizard()

cmd.set_dihedral(prefix + "C", prefix + "CA", prefix + "CB", prefix + "1HB", orig_dihedral)

cmd.save(output_name, "file")
Ejemplo n.º 37
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")
Ejemplo n.º 38
0
def attach_amino_acid(selection,amino_acid,phi,psi):
  if not selection in cmd.get_names("selections"):
    if amino_acid in cmd.get_names("objects"):
      print " Error: an object with than name already exists"
      raise QuietException
    cmd.fragment(amino_acid)
    if cmd.get_setting_legacy("auto_remove_hydrogens"):
      cmd.remove("(hydro and %s)"%amino_acid)
    if cmd.count_atoms("((%s) and name c)"%amino_acid,quiet=1):
      cmd.edit("((%s) and name c)"%amino_acid)
  else:
    cmd.fragment(amino_acid,tmp_editor)
    if cmd.count_atoms("((%s) and elem n)"%selection,quiet=1):
      cmd.select(tmp_ed_save,"(%s)"%selection)
      cmd.iterate("(%s)"%selection,"stored.resv=resv")
      stored.resi = str(stored.resv-1)
      cmd.alter(tmp_editor,"resi=stored.resi")
      cmd.fuse("(%s and name C)"%(tmp_editor),"(pk1)",2)
      if cmd.get_setting_legacy("auto_remove_hydrogens"):
        cmd.remove("(pkmol and hydro)")
      cmd.set_dihedral("(name ca and neighbor pk2)",
                            "(pk2)","(pk1)","(name ca,ch3 and neighbor pk1)",180.0)
      cmd.set_geometry("pk2",3,3) # make nitrogen planer
      cmd.select(tpk1,"pk2")
      cmd.select(tpk2,"pk1")
      if amino_acid[0:3]!='pro':
        cmd.set_dihedral( # PHI
            "(name c and neighbor (name ca and neighbor "+tpk1+"))", # C
            "(name ca and neighbor "+tpk1+")", # CA 
            tpk1, # N
            tpk2, # C
            phi)
      cmd.set_dihedral( # PSI (n-1)
          tpk1, # N
          tpk2, # C
          "(name ca and neighbor "+tpk2+")", # CA
          "(name n and neighbor (name ca and neighbor "+tpk2+"))", # C
          psi)
      cmd.delete(tpk1)
      cmd.delete(tpk2)
      sele = ("(name N and (byres neighbor %s) and not (byres %s))"%
                (tmp_ed_save,tmp_ed_save))
      if cmd.count_atoms(sele,quiet=1):
        cmd.edit(sele)
      cmd.delete(tmp_ed_save)
                
    elif cmd.count_atoms("((%s) and elem c)"%selection,quiet=1):
      cmd.select(tmp_ed_save,"(%s)"%selection)
      cmd.iterate("(%s)"%selection,"stored.resv=resv")
      stored.resi = str(stored.resv+1)
      cmd.alter(tmp_editor,"resi=stored.resi")
      cmd.fuse("(%s and name N)"%(tmp_editor),"(pk1)",2)
      if cmd.get_setting_legacy("auto_remove_hydrogens"):
        cmd.remove("(pkmol and hydro)")
      cmd.set_dihedral("(name ca and neighbor pk2)",
                            "(pk2)","(pk1)","(name ca,ch3 and neighbor pk1)",180.0)
      cmd.set_geometry("pk1",3,3) # make nitrogen planar
      cmd.select(tpk1,"pk1")
      cmd.select(tpk2,"pk2")
      if amino_acid[0:3]!='pro':
        cmd.set_dihedral( # PHI
            tpk2, # C
            tpk1, # N
            "(name ca and neighbor "+tpk1+")", # CA 
            "(name c and neighbor (name ca and neighbor "+tpk1+"))", # C
            phi)
      cmd.set_dihedral( # PSI (n-1)
          "(name n and neighbor (name ca and neighbor "+tpk2+"))", # C
          "(name ca and neighbor "+tpk2+")", # CA
          tpk2, # C
          tpk1, # N
          psi)
      cmd.delete(tpk1)
      cmd.delete(tpk2)
      sele = ("(name C and (byres neighbor %s) and not (byres %s))"%
                (tmp_ed_save,tmp_ed_save))
      if cmd.count_atoms(sele,quiet=1):
        cmd.edit(sele)
      cmd.delete(tmp_ed_save)
    elif cmd.count_atoms("((%s) and elem h)"%selection,quiet=1):
      print " Error: please pick a nitrogen or carbonyl carbon to grow from."
      cmd.delete(tmp_editor)
      raise QuietException
  
  cmd.delete(tmp_editor)
Ejemplo n.º 39
0
def mutate(selection, new_resn, inplace=0, sculpt=0, hydrogens='auto', mode=0, quiet=1):
    '''
DESCRIPTION

    Mutate a single residue. Does call the mutagenesis wizard non-interactively
    and tries to select the best rotamer. Can do some sculpting in the end to
    the best rotamer.

USAGE

    mutate selection, new_resn [, inplace [, sculpt [, hydrogens]]]

ARGUMENTS

    selection = string: atom selection of single residue

    new_resn = string: new residue name (3-letter or 1-letter)

    inplace = 0 or 1: work on copy of input object if 0 {default: 0}

    sculpt = 0: no sculpting {default}
    sculpt = 1: do sculpting on best rotamer
    sculpt = 2: do sculpting with neighbors

    hydrogens = string: keep, auto or none {default: auto}

    mode = 0: select rotamer with best clash score {default}
    mode = 1: take chi angles from original residue
    mode = 2: first rotamer

EXAMPLE

    fetch 2x19, async=0
    select x, A/CYS`122/
    zoom x
    mutate x, LYS
    '''
    from pymol.wizard import mutagenesis
    from . import three_letter

    inplace, sculpt = int(inplace), int(sculpt)
    mode = int(mode)
    quiet = int(quiet)
    org = cmd.get_object_list(selection)[0]
    tmp = cmd.get_unused_name()
    new_resn = new_resn.upper()
    new_resn = three_letter.get(new_resn, new_resn)

    if inplace:
        cpy = org
    else:
        cpy = cmd.get_unused_name(org + '_cpy')
        cmd.create(cpy, org, -1, 1, zoom=0)

    scr = []
    cmd.iterate('first (%s)' % selection, 'scr[:] = (segi,chain,resi,resn)', space={'scr': scr})
    res = '/%s/%s/%s/%s' % tuple([cpy] + scr[:3])

    if mode == 1:
        old_resn = scr[3]
        chi_atoms = {
            'ALA': [],
            'ARG': ['C','CA','CB','CG','CD','NE','CZ'],
            'ASN': ['C','CA','CB','CG','OD1'],
            'ASP': ['C','CA','CB','CG','OD1'],
            'CYS': ['C','CA','CB','SG'],
            'GLN': ['C','CA','CB','CG','CD','OE1'],
            'GLU': ['C','CA','CB','CG','CD','OE1'],
            'GLY': [],
            'HIS': ['C','CA','CB','CG','ND1'],
            'ILE': ['C','CA','CB','CG1','CD1'],
            'LEU': ['C','CA','CB','CG','CD1'],
            'LYS': ['C','CA','CB','CG','CD','CE','NZ'],
            'MET': ['C','CA','CB','CG','SD','CE'],
            'MSE': ['C','CA','CB','CG','SE','CE'],
            'PHE': ['C','CA','CB','CG','CD1'],
            'PRO': [],
            'SER': ['C','CA','CB','OG'],
            'THR': ['C','CA','CB','OG1'],
            'TRP': ['C','CA','CB','CG','CD2'],
            'TYR': ['C','CA','CB','CG','CD1'],
            'VAL': ['C','CA','CB','CG2'],
        }
        atoms = [res + '/' + name for name in chi_atoms.get(old_resn, [])]
        old_chi = []
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:]):
            try:
                old_chi.append(cmd.get_dihedral(*args))
            except:
                break

    cmd.remove('%s and not name CA+C+N+O+OXT' % (res))

    # start the wizard to count the number of rotamers for this residue
    cmd.wizard("mutagenesis")
    cmd.get_wizard().set_mode(new_resn)
    cmd.get_wizard().set_hyd(hydrogens)
    cmd.get_wizard().do_select("("+res+")")

    def get_best_state_bump():
        best_state = (1, 1e9)
        cmd.create(tmp, '%s and not name CA+C+N+O or (%s within 8.0 of (%s and name CB))' % \
                (mutagenesis.obj_name, cpy, mutagenesis.obj_name), zoom=0, singletons=1)
        cmd.bond('name CB and %s in %s' % (tmp, mutagenesis.obj_name),
                'name CA and %s in %s' % (tmp, res))
        cmd.sculpt_activate(tmp)
        for i in range(1, cmd.count_states(tmp)+1):
            score = cmd.sculpt_iterate(tmp, state=i)
            if not quiet:
                print('Frame %d Score %.2f' % (i, score))
            if score < best_state[1]:
                best_state = (i, score)
        cmd.delete(tmp)
        if not quiet:
            print(' Best: Frame %d Score %.2f' % best_state)
        return best_state

    if cmd.count_states(mutagenesis.obj_name) < 2 or mode > 0:
        best_state = (1, -1.0)
    else:
        best_state = get_best_state_bump()
    cmd.frame(best_state[0])
    cmd.get_wizard().apply()
    cmd.wizard()

    if mode == 1:
        atoms = [res + '/' + name for name in chi_atoms.get(new_resn, [])]
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:], old_chi):
            cmd.set_dihedral(*args)
        cmd.unpick()

    if sculpt > 0:
        sculpt_relax(res, 0, sculpt == 2, cpy)

    return cpy
Ejemplo n.º 40
0
def generate(dihedrals,
             directory="temp",
             setup_path="default",
             verbose="False"):
    # dihedrals = [[atom a, atom b, atom c, atom d]]
    # Log generation
    log = Log()
    log.write(
        "\n\n########################################\n########### G E N E R A T E ############\n########################################\n\n"
    )
    #verbose
    if verbose.lower() in ['true', '1', 't', 'y', 'yes']: verbose = True
    else: verbose = False
    # dihedrals: auto?
    if dihedrals.lower() in ['auto']:
        dihedrals = 'auto'  #To DO: generate dihedrals automatically
    # get setup.ini
    setup = Setup(log, setup_path)
    if setup.isLoaded() == True:
        angle_step = 360 / setup.angle_count
        dihedrals = dihedrals.strip(' []').split(',')
        for i in range(0, len(dihedrals)):
            dihedrals[i] = dihedrals[i].strip(' []')
        if len(dihedrals) % 4 != 0 and len(dihedrals) != 1:
            log.write(
                "Error: Problem in dihedral selection. 4 selections are needed for each dihedral. [%s] "
                % dihedrals)
            return False
        dihedral_count = int(len(dihedrals) / 4)
        combination_count = int(setup.angle_count**dihedral_count)
        log.write("Number of dihedrals: %s" % dihedral_count)
        log.write("For each dihedral: %s steps of %s degree" %
                  (setup.angle_count, angle_step))
        log.write("That represents %s combinations" % combination_count)
        result = backup_generate(directory)  # create backup
        if result: log.write("Making archives: %s" % result, verbose)
        else: log.write("Making directory: %s" % directory, verbose)
        if combination_count == 0:
            path = "%s/%s_0.pdb" % (directory, cmd.get_object_list()[0])
            try:
                cmd.set("retain_order", 1)
                cmd.save(path)
            except:
                log.write(
                    "Error: Can't save %s first conformer. One conformer will be missing!"
                    % path, verbose)
        else:
            # Generate all the combinations
            combination_list = [{} for k in range(0, combination_count)]
            for i in range(0, combination_count
                           ):  # iterate all the combinations of dihedrals
                dihedrals_curr_cbn = [{} for k in range(dihedral_count)]
                count = i
                for j in range(
                        0, dihedral_count
                ):  # modify the dihedral according to the combination
                    dihedrals_curr_cbn[j] = int(count % setup.angle_count)
                    count = int(count / setup.angle_count)
                log.write("Combination %s : %s " % (i, dihedrals_curr_cbn),
                          verbose)
                combination_list[i] = dihedrals_curr_cbn
            # Too many combinations?
            if combination_count > setup.combination_limit:
                todestroy_count = combination_count - setup.combination_limit
                log.write(
                    "The amount of possibility is %s. The limit is set at %s. %s combinations will be deleted to go down to the limit using %s algorithm."
                    % (combination_count, setup.combination_limit,
                       todestroy_count, setup.combination_remove_algorithm))
                if setup.combination_remove_algorithm == "random":
                    for i in range(
                            0, todestroy_count
                    ):  # loop as many time as the amount to randomly destroy
                        del combination_list[random.randint(
                            0, len(combination_list))]
                log.write(
                    "%s combinations. Limit is %s. Reduction of combinations done."
                    % (len(combination_list), setup.combination_limit),
                    verbose)
            # Generate the files
            for i in range(
                    len(combination_list)):  # going through each combination
                for j in range(
                        len(combination_list[i])
                ):  # going through each dihedral of the combination
                    try:
                        cmd.set_dihedral(dihedrals[j * 4],
                                         dihedrals[j * 4 + 1],
                                         dihedrals[j * 4 + 2],
                                         dihedrals[j * 4 + 3],
                                         combination_list[i][j] * angle_step)
                    except:
                        log.write(
                            "Error: Can't set the dihedrals. cmd.set_dihedrals failed."
                        )
                log.write(
                    "Writing Combination %s : %s " % (i, combination_list[i]),
                    verbose)
                path = "%s/%s_%s.pdb" % (directory, cmd.get_object_list()[0],
                                         str(i))
                try:
                    cmd.set("retain_order", 1)
                    cmd.save(path)
                except:
                    log.write(
                        "Error: Can't save %s. One conformer will be missing!"
                        % path)
                for j in range(0, dihedral_count):
                    cmd.undo()
        log.write(
            "----------------------------\n---- Normal Termination ----\n----------------------------\n"
        )
        log.finalize()
        return True
    else:
        log.write(
            "Error: Failed to load setup.ini in [%s]. Fix it to continue." %
            setup_path)
        return False
Ejemplo n.º 41
0
def _set_dihedral(atomnames,angle):
    for i in range(4):
        cmd.select('a%d'%i, 'name %s'%atomnames[i])
    cmd.set_dihedral('a0','a1','a2','a3',angle)
Ejemplo n.º 42
0
			for valor in paramod[npam]:
				matrizval[nsal].append(valor)
				nsal = nsal + 1
		matrizval.sort() #importante para el programa


	#3. Genera Archivos de Salidas
	infilenamediv=infilename.split(".")
	for nsal in range(0,nrosalidas):
		salida = [] #lista que contiene las lineas para un archivo de salida especifico
		npam = 0
		extname = infilenamediv[0]
		for line in atomIDs: 
			linediv=line.split(",")
			val = float(matrizval[int(nsal)][int(npam)])
			cmd.set_dihedral(linediv[0],linediv[1],linediv[2],linediv[3], val)
			#extname = extname + "_D" + linediv[0].strip("ID ")+"-"+linediv[1].strip("ID ")+"-"+linediv[2].strip("ID ")+"-"+linediv[3].strip("ID ") + "_" + str(int(val)) #nombre de salida con valores de parametros
			extname = extname + "_D" + str(npam) + "_" + str(int(val)) #nombre de salida con valores de parametros			
			npam = npam + 1
		cmd.save(extname+".pdb")
		print "Se creo el archivo " + extname+".pdb"
else:
	print "No se encuentran parametros para modificar"


# Get out!
pymol.cmd.quit()



Ejemplo n.º 43
0
def mutate(selection, new_resn, inplace=0, sculpt=0, hydrogens='auto', mode=0, quiet=1):
    '''
DESCRIPTION

    Mutate a single residue. Does call the mutagenesis wizard non-interactively
    and tries to select the best rotamer. Can do some sculpting in the end to
    the best rotamer.

USAGE

    mutate selection, new_resn [, inplace [, sculpt [, hydrogens]]]

ARGUMENTS

    selection = string: atom selection of single residue

    new_resn = string: new residue name (3-letter or 1-letter)

    inplace = 0 or 1: work on copy of input object if 0 {default: 0}

    sculpt = 0: no sculpting {default}
    sculpt = 1: do sculpting on best rotamer
    sculpt = 2: do sculpting with neighbors

    hydrogens = string: keep, auto or none {default: auto}

    mode = 0: select rotamer with best clash score {default}
    mode = 1: take chi angles from original residue
    mode = 2: first rotamer

EXAMPLE

    fetch 2x19, async=0
    select x, A/CYS`122/
    zoom x
    mutate x, LYS
    '''
    from pymol.wizard import mutagenesis
    from . import three_letter

    inplace, sculpt = int(inplace), int(sculpt)
    mode = int(mode)
    quiet = int(quiet)
    org = cmd.get_object_list(selection)[0]
    tmp = cmd.get_unused_name()
    new_resn = new_resn.upper()
    new_resn = three_letter.get(new_resn, new_resn)

    if inplace:
        cpy = org
    else:
        cpy = cmd.get_unused_name(org + '_cpy')
        cmd.create(cpy, org, -1, 1, zoom=0)

    scr = []
    cmd.iterate('first (%s)' % selection, 'scr[:] = (segi,chain,resi,resn)', space={'scr': scr})
    res = '/%s/%s/%s/%s' % tuple([cpy] + scr[:3])

    if mode == 1:
        old_resn = scr[3]
        chi_atoms = {
            'ALA': [],
            'ARG': ['C','CA','CB','CG','CD','NE','CZ'],
            'ASN': ['C','CA','CB','CG','OD1'],
            'ASP': ['C','CA','CB','CG','OD1'],
            'CYS': ['C','CA','CB','SG'],
            'GLN': ['C','CA','CB','CG','CD','OE1'],
            'GLU': ['C','CA','CB','CG','CD','OE1'],
            'GLY': [],
            'HIS': ['C','CA','CB','CG','ND1'],
            'ILE': ['C','CA','CB','CG1','CD1'],
            'LEU': ['C','CA','CB','CG','CD1'],
            'LYS': ['C','CA','CB','CG','CD','CE','NZ'],
            'MET': ['C','CA','CB','CG','SD','CE'],
            'MSE': ['C','CA','CB','CG','SE','CE'],
            'PHE': ['C','CA','CB','CG','CD1'],
            'PRO': [],
            'SER': ['C','CA','CB','OG'],
            'THR': ['C','CA','CB','OG1'],
            'TRP': ['C','CA','CB','CG','CD2'],
            'TYR': ['C','CA','CB','CG','CD1'],
            'VAL': ['C','CA','CB','CG2'],
        }
        atoms = [res + '/' + name for name in chi_atoms.get(old_resn, [])]
        old_chi = []
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:]):
            try:
                old_chi.append(cmd.get_dihedral(*args))
            except:
                break

    cmd.remove('%s and not name CA+C+N+O+OXT' % (res))

    # start the wizard to count the number of rotamers for this residue
    cmd.wizard("mutagenesis")
    cmd.get_wizard().set_mode(new_resn)
    cmd.get_wizard().set_hyd(hydrogens)
    cmd.get_wizard().do_select("("+res+")")

    def get_best_state_bump():
        best_state = (1, 1e9)
        cmd.create(tmp, '%s and not name CA+C+N+O or (%s within 8.0 of (%s and name CB))' % \
                (mutagenesis.obj_name, cpy, mutagenesis.obj_name), zoom=0, singletons=1)
        cmd.bond('name CB and %s in %s' % (tmp, mutagenesis.obj_name),
                'name CA and %s in %s' % (tmp, res))
        cmd.sculpt_activate(tmp)
        for i in range(1, cmd.count_states(tmp)+1):
            score = cmd.sculpt_iterate(tmp, state=i)
            if not quiet:
                print('Frame %d Score %.2f' % (i, score))
            if score < best_state[1]:
                best_state = (i, score)
        cmd.delete(tmp)
        if not quiet:
            print(' Best: Frame %d Score %.2f' % best_state)
        return best_state

    if cmd.count_states(mutagenesis.obj_name) < 2 or mode > 0:
        best_state = (1, -1.0)
    else:
        best_state = get_best_state_bump()
    cmd.frame(best_state[0])
    cmd.get_wizard().apply()
    cmd.wizard()

    if mode == 1:
        atoms = [res + '/' + name for name in chi_atoms.get(new_resn, [])]
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:], old_chi):
            cmd.set_dihedral(*args)
        cmd.unpick()

    if sculpt > 0:
        sculpt_relax(res, 0, sculpt == 2, cpy)

    return cpy
Ejemplo n.º 44
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")
Ejemplo n.º 45
0
cmd.load(in_protein, "MyProtein")

# Get original chain names
Chains = cmd.get_chains()

# Fix dihedral angles of residues near C-termini
for chn in Chains:
    # Fix Psi dihedral angle of LYS-31 to alpha-helix
    res0 = 31
    atom2 = "/MyProtein//" + chn + "/" + str(res0) + "/N"
    atom3 = "/MyProtein//" + chn + "/" + str(res0) + "/CA"
    atom4 = "/MyProtein//" + chn + "/" + str(res0) + "/C"
    atom5 = "/MyProtein//" + chn + "/" + str(res0 + 1) + "/N"

    cmd.set_dihedral(atom2, atom3, atom4, atom5, -45)

    # Set Phi dihedral angle of ARG-32 to alpha-helix
    res0 = 32
    atom1 = "/MyProtein//" + chn + "/" + str(res0 - 1) + "/C"
    atom2 = "/MyProtein//" + chn + "/" + str(res0) + "/N"
    atom3 = "/MyProtein//" + chn + "/" + str(res0) + "/CA"
    atom4 = "/MyProtein//" + chn + "/" + str(res0) + "/C"

    cmd.set_dihedral(atom1, atom2, atom3, atom4, -60)

    # Add missing residues to C-termini on ARG-376
    # NOTE: Amidate C-termini by default. For the last residue, we need a N to set Psi
    # So, this is why we cap peptides from the beginning

    cmd.select("MyAA", "/MyProtein//" + chn + "/THR`32/C")
Ejemplo n.º 46
0
def attach_amino_acid(selection,amino_acid,phi,psi):
  if not selection in cmd.get_names("selections"):
    if amino_acid in cmd.get_names("objects"):
      print " Error: an object with than name already exists"
      raise QuietException
    cmd.fragment(amino_acid)
    if cmd.get_setting_legacy("auto_remove_hydrogens"):
      cmd.remove("(hydro and %s)"%amino_acid)
    if cmd.count_atoms("((%s) and name c)"%amino_acid,quiet=1):
      cmd.edit("((%s) and name c)"%amino_acid)
  else:
    cmd.fragment(amino_acid,tmp_editor)
    if cmd.count_atoms("((%s) and elem n)"%selection,quiet=1):
      cmd.select(tmp_ed_save,"(%s)"%selection)
      cmd.iterate("(%s)"%selection,"stored.resv=resv")
      stored.resi = str(stored.resv-1)
      cmd.alter(tmp_editor,"resi=stored.resi")
      cmd.fuse("(%s and name C)"%(tmp_editor),"(pk1)",2)
      if cmd.get_setting_legacy("auto_remove_hydrogens"):
        cmd.remove("(pkmol and hydro)")
      cmd.set_dihedral("(name ca and neighbor pk2)",
                            "(pk2)","(pk1)","(name ca,ch3 and neighbor pk1)",180.0)
      cmd.set_geometry("pk2",3,3) # make nitrogen planer
#      if ss:
      cmd.select(tpk1,"pk2")
      cmd.select(tpk2,"pk1")
      if amino_acid[0:3]!='pro':
        cmd.set_dihedral( # PHI
            "(name c and neighbor (name ca and neighbor "+tpk1+"))", # C
            "(name ca and neighbor "+tpk1+")", # CA 
            tpk1, # N
            tpk2, # C
            phi)
      cmd.set_dihedral( # PSI (n-1)
          tpk1, # N
          tpk2, # C
          "(name ca and neighbor "+tpk2+")", # CA
          "(name n and neighbor (name ca and neighbor "+tpk2+"))", # C
          psi)
      cmd.delete(tpk1)
      cmd.delete(tpk2)
      sele = ("(name N and (byres neighbor %s) and not (byres %s))"%
                (tmp_ed_save,tmp_ed_save))
      if cmd.count_atoms(sele,quiet=1):
        cmd.edit(sele)
      cmd.delete(tmp_ed_save)

    elif cmd.count_atoms("((%s) and elem c)"%selection,quiet=1):
      cmd.select(tmp_ed_save,"(%s)"%selection)
      cmd.iterate("(%s)"%selection,"stored.resv=resv")
      stored.resi = str(stored.resv+1)
      cmd.alter(tmp_editor,"resi=stored.resi")
      cmd.fuse("(%s and name N)"%(tmp_editor),"(pk1)",2)
      if cmd.get_setting_legacy("auto_remove_hydrogens"):
        cmd.remove("(pkmol and hydro)")
      cmd.set_dihedral("(name ca and neighbor pk2)",
                            "(pk2)","(pk1)","(name ca,ch3 and neighbor pk1)",180.0)
      cmd.set_geometry("pk1",3,3) # make nitrogen planer
#      if ss:
      cmd.select(tpk1,"pk1")
      cmd.select(tpk2,"pk2")
      if amino_acid[0:3]!='pro':
        cmd.set_dihedral( # PHI
            tpk2, # C
            tpk1, # N
            "(name ca and neighbor "+tpk1+")", # CA 
            "(name c and neighbor (name ca and neighbor "+tpk1+"))", # C
            phi)
      cmd.set_dihedral( # PSI (n-1)
          "(name n and neighbor (name ca and neighbor "+tpk2+"))", # C
          "(name ca and neighbor "+tpk2+")", # CA
          tpk2, # C
          tpk1, # N
          psi)
      cmd.delete(tpk1)
      cmd.delete(tpk2)
      sele = ("(name C and (byres neighbor %s) and not (byres %s))"%
                (tmp_ed_save,tmp_ed_save))
      if cmd.count_atoms(sele,quiet=1):
        cmd.edit(sele)
      cmd.delete(tmp_ed_save)
    elif cmd.count_atoms("((%s) and elem h)"%selection,quiet=1):
      print " Error: please pick a nitrogen or carbonyl carbon to grow from."
      cmd.delete(tmp_editor)
      raise QuietException

  cmd.delete(tmp_editor)
Ejemplo n.º 47
0
        nsal = 0
        for p in range(0, nrosalidas / len(paramod[npam])):
            for valor in paramod[npam]:
                matrizval[nsal].append(valor)
                nsal = nsal + 1
        matrizval.sort()  #importante para el programa

    #3. Genera Archivos de Salidas
    infilenamediv = infilename.split(".")
    for nsal in range(0, nrosalidas):
        salida = [
        ]  #lista que contiene las lineas para un archivo de salida especifico
        npam = 0
        extname = infilenamediv[0]
        for line in atomIDs:
            linediv = line.split(",")
            val = float(matrizval[int(nsal)][int(npam)])
            cmd.set_dihedral(linediv[0], linediv[1], linediv[2], linediv[3],
                             val)
            extname = extname + "_D" + str(npam) + "_" + str(
                int(val))  #nombre de salida con valores de parametros
            npam = npam + 1
        cmd.set('pdb_conect_all')
        cmd.save(extname + ".pdb")
        print "Se creo el archivo " + extname + ".pdb"
else:
    print "No se encuentran parametros para modificar"

# Get out!
pymol.cmd.quit()