def mutate_atoms(desired_sequence): # Acquire the lock once you execute this program lock.acquire() cmd.reset() # Check the length of peptide sequence # If the sequence does not match the MHC structure, the program will terminate. try: if len(desired_sequence) != 9: raise AssertionError except AssertionError: sys.exit( "Please input a peptide sequence with exactly 9 residues (in short abbreviation, no space)!" ) # Execute the mutation command based on the PyMOL API. # For each round, we construct a new PyMOL object to avoid the problem of different mutation affecting each other. cmd.wizard("mutagenesis") cmd.load("structures/3pwn_clear_original.pdb") new_sequence = translate_sequence(desired_sequence) for i in range(len(new_sequence)): cmd.refresh_wizard() cmd.get_wizard().set_mode(new_sequence[i]) cmd.get_wizard().do_select("C/%d/" % (i + 1)) cmd.get_wizard().apply() cmd.save("structures/mutated_intermediate/mutated_pmhc_complex.pdb") cmd.quit() # Release the lock when the program ends lock.release()
def mutate_peptide(new_seq): ''' mutate peptide to new_seq starting at second residue in the peptide ''' cmd.copy(new_seq, "peptide_template") aa1 = list("ACDEFGHIKLMNPQRSTVWY") aa3 = "ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR".split( ) aa123 = dict(zip(aa1, aa3)) for ind, aa in enumerate(new_seq, 2): cmd.wizard("mutagenesis") cmd.do("refresh_wizard") print ind print aa # lets mutate residue 104 to GLN cmd.get_wizard().set_mode(aa123[aa]) cmd.get_wizard().do_select("/{0}//B/{1}".format(new_seq, ind)) # Select the rotamer #cmd.frame(1) # Apply the mutation cmd.get_wizard().apply()
def mutate_peptide( new_seq ): ''' mutate peptide to new_seq starting at second residue in the peptide ''' cmd.copy(new_seq, "peptide_template") aa1 = list("ACDEFGHIKLMNPQRSTVWY") aa3 = "ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR".split() aa123 = dict(zip(aa1,aa3)) for ind, aa in enumerate(new_seq,2): cmd.wizard("mutagenesis") cmd.do("refresh_wizard") print ind print aa # lets mutate residue 104 to GLN cmd.get_wizard().set_mode(aa123[aa]) cmd.get_wizard().do_select("/{0}//B/{1}".format(new_seq, ind)) # Select the rotamer #cmd.frame(1) # Apply the mutation cmd.get_wizard().apply()
def crysolRefinementNanodisc(z_min, z_max, z_step, \ protName, membName, scafName, dataName, prefixName): '''Refine the membrane protein detergent complex against experimental data''' zs = np.arange(z_min, z_max, z_step) res = {"angle": -9999, "number-of-scaffolds": -9999, "chi2": 9999} with tempdir.TemporaryDirectory() as tmpdir: # copy data file tmpdir.copy_in(dataName) best = "" fitBest = "" for counter1, z in enumerate(zs): cmd.refresh() modelName = builderNanodisc(protName, membName, scafName, prefixName, z, True) cmd.save(modelName + ".pdb", modelName) fit, fitResult = fitcrysol(modelName, dataName, "yes", False) cmd.wizard( "message", f"Refinement: {counter1 } out of {len(zs)} steps." f"Chi2: {fitResult['chi2']}") # if model fits better - store it if float(fitResult['chi2']) < float(res['chi2']): if best != "": cmd.delete(best) res['chi2'] = fitResult['chi2'] res['vertical-offset'] = z best = modelName fitBest = fit else: cmd.delete(modelName) tmpdir.move_out(best + ".pdb") tmpdir.move_out(fitBest) print(f"Best model: Vertical Offset : {res['vertical-offset']}") print(f"Chi^2 : {res['chi2']} Best model name : {best}") return best, fitBest
def pymol_mutate(file_name, chain, res_index): pymol.finish_launching() cmd.delete('all') selection = chain + '/' + res_index + '/' mutant = 'CYS' cmd.wizard("mutagenesis") pdb = file_name[:-4] cmd.load(file_name) cmd.remove('not (alt ''+A)') cmd.select('mut', 'resi ' + res_index + ' and chain ' + chain) if cmd.count_atoms('mut') == 0: return False cmd.refresh_wizard() cmd.get_wizard().set_mode(mutant) cmd.get_wizard().do_select(selection) nStates = cmd.count_states("mutation") for i in range(1, nStates + 1): cmd.get_wizard().do_select(selection) cmd.frame(i) cmd.get_wizard().apply() cmd.save("rec_" + str(res_index) + "_" + str(i) + ".pdb") cmd.set_wizard() cmd.remove(file_name[:-4]) return True
def test_CanMutateNonCanonicalNucleo(self): cmd.load(self.datafile("1k5e.cif")) cmd.wizard("nucmutagenesis") cmd.select("/1k5e/A/A/6") cmd.get_wizard().mode = "Adenine" cmd.get_wizard().do_select("sele") cmd.get_wizard().apply() seq = cmd.get_fastastr("/1k5e/A/A").splitlines()[1] self.assertEqual(seq, "CGGACAAGAAG")
def test_CanGetNewDNASequence(self): cmd.load(self.datafile("1bna.cif")) cmd.wizard("nucmutagenesis") cmd.select("/1bna/A/A/1") cmd.get_wizard().mode = "Adenine" cmd.get_wizard().do_select("sele") cmd.get_wizard().apply() seq = cmd.get_fastastr("/1bna/A/A").splitlines()[1] self.assertEqual(seq, "AGCGAATTCGCG")
def test_CanGetNewRNASequence(self): cmd.load(self.datafile("1rna.cif")) cmd.wizard("nucmutagenesis") cmd.select("/1rna/A/A/14") cmd.get_wizard().mode = "Guanine" cmd.get_wizard().do_select("sele") cmd.get_wizard().apply() seq = cmd.get_fastastr("/1rna/A/A").splitlines()[1] self.assertEqual(seq, "UUAUAUAUAUAUAG")
def mutate(selection, aa): aa = fix_aa(aa) cmd.set("retain_order", 0) cmd.wizard("mutagenesis") cmd.refresh_wizard() for single_res in iter_residues(selection): mutate_one(single_res, aa) cmd.set_wizard() cmd.sort()
def Mutagenesis(kinase1, model, template,peptide_instance): """superposition the model and template, remove template and leave peptide behind """ """replace peptide with instance peptide""" list_name = peptide_instance with open(input_data_folder+list_name,'r') as f: instances = f.readlines() instance = [x.strip() for x in instances] print "your peptide: ", instance for pep in instance: cmd.delete('all') cmd.fetch(model) # model_candidate, ex.chk1,chk2... cmd.remove("hetatm") #remove the nonstandard residues cmd.fetch(template) #mutagenesis template, ex.2phk peptide_template = cmd.get_fastastr( "/"+template+'//B') #get the peptide from the template and generate another one for mutagenesis peptide_template = peptide_template + 'G' #peptide of 2phk is 7 amino acid long, when our input peptide is 8 aa, we need to plus one character for aa in peptide_template[6:].lower(): #creat template_peptide for mutagenesis cmd._alt(aa) firstaa = AAcode_1_to_3(peptide_template[6]) #translate template_peptide to 3 letter low_firstaa = firstaa[0].lower() cmd.alter(low_firstaa, 'chain = "B"') #select this template_peptide cmd.show_as("cartoon") cmd.align(model, template) #superpostion of model and template cmd.align(low_firstaa,template) #superpostion of template_peptide and template remove_part = "("+template+" and not resn ATP"+")" cmd.select("remove_part",remove_part) cmd.remove("remove_part") #remove the template except for ATP, there are only model and template_peptide cmd.remove("resn hoh") #remove water cmd.wizard("mutagenesis") peptide_position = 0 for i in pep: #the peptide_position starting point depends the first position of mutagenesis peptide #pymol's peptide start from 1, not 0 mutagenesis_template = '/'+low_firstaa+ '///' + str(peptide_position + 2) # because of 2phk start at 2nd of peptide #mutagenesis_template = '/' + template + '//B/' + str(peptide_position + 2) cmd.get_wizard().do_select(mutagenesis_template) # select peptide position of mutation replace_aminoacid = AAcode_1_to_3(pep)[peptide_position] cmd.get_wizard().set_mode(replace_aminoacid) # select which residue want to mutate to cmd.get_wizard().apply() peptide_position += 1 filename = kinase1 + '_' + model + 'model_' + template + 'muta_' + pep + '.pdb' #build the canonical name cmd.save(filename) ATPchange(filename) #change ATP naming to the format of ATP.params cmd.wizard(None) return
def mutate(protein, resi, mode='ALA', chain='A'): cmd.wizard('mutagenesis') cmd.do("refresh_wizard") cmd.get_wizard().set_mode(mode.upper()) selection = f'/{protein}//{chain}/{resi}' cmd.get_wizard().do_select(selection) cmd.frame(str(1)) cmd.get_wizard().apply() cmd.set_wizard('done') cmd.refresh()
def mutate(molecule, chain, resi, target="CYS", mutframe="1"): target = target.upper() cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode("%s" % target) selection = "/%s//%s/%s" % (molecule, chain, resi) cmd.get_wizard().do_select(selection) cmd.frame(str(mutframe)) cmd.get_wizard().apply() # cmd.set_wizard("done") cmd.set_wizard()
def mutate(molecule,chain,resi,target="CYS",mutframe="1"): target = target.upper() cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode("%s"%target) selection="/%s//%s/%s"%(molecule,chain,resi) cmd.get_wizard().do_select(selection) cmd.frame(str(mutframe)) cmd.get_wizard().apply() #cmd.set_wizard("done") cmd.set_wizard()
def mutXYZposition(residues): cmd.hide("everything") cmd.show("sticks") for resi in residues: for caa in residues[resi]: print(resi, caa) filename = "residue" + str(resi) + "to" + caa + ".csv" outfile = open(filename, "w") row = ("rotamer" + "," + "X" + "," + "Y" + "," + "Z" + "\n") cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode(caa) sel = "/test//A/" + str(resi) cmd.get_wizard().do_select(sel) fram = cmd.count_states("mutation") stored.pos = [] cmd.iterate_state(0, 'mutation', 'stored.pos.append((x,y,z))', atomic=0) counter = 1 state = 1 natom = int(len(stored.pos) / fram) for po in stored.pos: if counter < natom: row = (str(state) + "," + str(po[0]) + "," + str(po[1]) + "," + str(po[2]) + "\n") outfile.write(row) counter += 1 elif counter == natom: row = (str(state) + "," + str(po[0]) + "," + str(po[1]) + "," + str(po[2]) + "\n") outfile.write(row) counter = 1 state += 1 outfile.close() cmd.frame(fram) cmd.get_wizard().apply() cmd.set_wizard("done") cmd.save("residue" + str(resi) + "to" + caa + "rotamer" + str(fram) + ".pdb") for f in range(1, fram): fra = fram - f cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().do_select(sel) cmd.frame(fra) cmd.get_wizard().apply() cmd.set_wizard("done") cmd.save("residue" + str(resi) + "to" + caa + "rotamer" + str(fra) + ".pdb")
def test_CorrectChiDihedral(self): cmd.load(self.datafile("1rna.cif")) src_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'", "/1rna/A/A/14 & name C1'", "/1rna/A/A/14 & name N9", "/1rna/A/A/14 & name C4'") cmd.wizard("nucmutagenesis") cmd.select("/1rna/A/A/14") cmd.get_wizard().mode = "Guanine" cmd.get_wizard().do_select("sele") cmd.get_wizard().apply() des_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'", "/1rna/A/A/14 & name C1'", "/1rna/A/A/14 & name N9", "/1rna/A/A/14 & name C4'") self.assertAlmostEqual(src_dihedral, des_dihedral, delta=2.0)
def test_CorrectChiDihedral(self): cmd.load(self.datafile("1rna.cif")) src_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'", "/1rna/A/A/14 & name C1'", "/1rna/A/A/14 & name N9", "/1rna/A/A/14 & name C4'") cmd.wizard("nucmutagenesis") cmd.select("/1rna/A/A/14") cmd.get_wizard().mode = "Guanine" cmd.get_wizard().do_select("sele") cmd.get_wizard().apply() des_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'", "/1rna/A/A/14 & name C1'", "/1rna/A/A/14 & name N9", "/1rna/A/A/14 & name C4'") self.assertAlmostEqual(src_dihedral, des_dihedral, delta = 2.0)
def mutate_to_cys(pdb, resnum_i): selection_i = "resi " + str(resnum_i) cmd.wizard("mutagenesis") cmd.get_wizard().set_mode("CYS") cmd.do("refresh_wizard") cmd.get_wizard().do_select(selection_i) cmd.get_wizard().do_select(selection_i) for frame_i in [1, 2, 3]: cmd.frame(frame_i) cmd.create("rotamer_" + str(resnum_i) + "_" + str(frame_i), "mutation", frame_i, 1) rotamer_i_pymol_prefix = "/" + "rotamer_" + str(resnum_i) + "_" + str(frame_i) + "///" + resnum_i + "/" cmd.set_wizard("done")
def crysolRefinementDetergent(rot_min_ang, rot_max_ang, rot_step_ang, dens_min_ang, dens_max_ang, dens_step_ang, protName, membName, dataName, prefixName, runNumber): """Refine the membrane protein detergent complex against experimental data""" angs = np.arange(rot_min_ang, rot_max_ang, rot_step_ang) dens = np.arange(dens_min_ang, dens_max_ang, dens_step_ang) res = {"angle": -9999, "number-of-scaffolds": -9999, "chi2": 9999} with tempdir.TemporaryDirectory() as tmpdir: # copy data file tmpdir.copy_in(dataName) best = "" fitBest = "" for counter1, ang in enumerate(angs): for counter2, densAng in enumerate(dens): cmd.refresh() modelName = builderDetergent(protName, membName, prefixName, runNumber, ang, densAng, True) runNumber += 1 if modelName == "bad model": print("Bad model parameters: ang: {} densAng: {}".format(ang, densAng)) continue cmd.save(modelName + ".pdb", modelName) fit, fitResult = fitcrysol(modelName, os.path.basename(dataName), "yes", False) cmd.wizard("message", "Refinement: {} ".format(1 + counter2 + counter1 * (len(dens))) + " out of {} steps. Chi2: {}".format(len(dens) * len(angs), fitResult['chi2'])) # if model fits better - store it if float(fitResult['chi2']) < float(res['chi2']): if best != "": cmd.delete(best) res['chi2'] = fitResult['chi2'] res['lipid density'] = densAng res['max-polar-angle'] = ang best = modelName fitBest = fit else: cmd.delete(modelName) if res['chi2'] < 9999: tmpdir.move_out(best + ".pdb") tmpdir.move_out(fitBest) else: return "Bad parameters", "No good fit found!" print("Best model: Lipid Density : {} Max Polar Angle = {})".format(res['lipid density'], res['max-polar-angle'])) print("Chi^2 : {} Best model name : {}".format(res['chi2'], best)) return best, fitBest, counter1*counter2
def doubleMut(original, positions, residues): cmd.hide("everything") cmd.show("sticks") posone = positions[0][0] chainone = positions[0][1] postwo = positions[1][0] chaintwo = positions[1][1] outfile = open("forheatmap.csv", "w") #generate the protein with one mutation for a in residues: cmd.create(a, original) cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode(a) sel = "/" + a + "//" + str(chainone) + "/" + str(posone) cmd.get_wizard().do_select(sel) cmd.get_wizard().apply() for m in residues: #for all the mutations generated for i in residues: #for each residue to which will be mutated name = m + "2" cmd.create(name, m) cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode(i) se = "/" + name + "//" + str(chaintwo) + "/" + str(postwo) cmd.get_wizard().do_select(se) mut_name = "mutation" if cmd.count_states(mut_name) != 1: bump_name = "_bump_check" cmd.sculpt_activate(bump_name) scores = [] for rotamer in range(1, 1 + cmd.count_states(bump_name)): score = cmd.sculpt_iterate(bump_name, rotamer, 1) scores.append(score) scores.sort(reverse=True) row = (i + "," + m + "," + str(scores[0]) + "\n") else: row = (i + "," + m + "," + "?" + "\n") outfile.write(row) outfile.close()
def crysolRefinementSalipro(rot_min_ang, rot_max_ang, rot_step_ang, \ scaffold_min, scaffold_max, scaffold_step, \ protName, membName, scafName, dataName, \ prefixName): '''Refine the membrane protein lipids scaffolding proteins complex against experimental data''' angs = np.arange(rot_min_ang, rot_max_ang, rot_step_ang) numScaffoldCopies = np.arange(scaffold_min, scaffold_max, scaffold_step) res = {"angle": -9999, "number-of-scaffolds": -9999, "chi2": 9999} with tempdir.TemporaryDirectory() as tmpdir: # copy data file tmpdir.copy_in(dataName) best = "" fitBest = "" for counter1, ang in enumerate(angs): for counter2, num in enumerate(numScaffoldCopies): cmd.refresh() modelName = builderSalipro(protName, scafName, membName, prefixName, num, ang, True) cmd.save(modelName + ".pdb", modelName) fit, fitResult = fitcrysol(modelName, dataName, "yes", False) cmd.wizard( "message", f"Refinement: {counter2 + counter1 * (len(numScaffoldCopies))} " f"out of {len(numScaffoldCopies) * len(angs)} steps. Chi2: {fitResult['chi2']}" ) if float(fitResult['chi2']) < float(res['chi2']): if best != "": cmd.delete(best) res['chi2'] = fitResult['chi2'] res['number-of-scaffolds'] = num res['angle'] = ang best = modelName fitBest = fit else: cmd.delete(modelName) tmpdir.move_out(best + ".pdb") tmpdir.move_out(fitBest) cmd.wizard() print( f"Best model: Number of Scaffolds = {res['number-of-scaffolds']}; Angle = {res['angle']}" ) print(f"Chi^2 : {res['chi2']} Best model name : {best}") return best, fitBest
def pymol_mutate(file_name, chain, res_index, number, mutant): pymol.finish_launching() cmd.delete(file_name[:-4]) selection = chain + '/' + res_index + '/' cmd.wizard("mutagenesis") pdb = file_name[:-4] cmd.load(file_name) cmd.refresh_wizard() cmd.get_wizard().set_mode(mutant) cmd.get_wizard().do_select(selection) nStates = cmd.count_states("mutation") for i in range(1, nStates + 1): cmd.get_wizard().do_select(selection) cmd.frame(i) cmd.get_wizard().apply() cmd.save("rec_" + str(res_index) + "_" + str(i) + ".pdb") cmd.set_wizard() cmd.remove(file_name[:-4])
def crysolRefinementSalipro(rot_min_ang, rot_max_ang, rot_step_ang, scaffold_min, scaffold_max, scaffold_step, protName, membName, scafName, dataName, prefixName, runNumber): """Refine the membrane protein lipids scaffolding proteins complex against experimental data""" angs = np.arange(rot_min_ang, rot_max_ang, rot_step_ang) numScaffoldCopies = np.arange(scaffold_min, scaffold_max, scaffold_step) res = {"angle": -9999, "number-of-scaffolds": -9999, "chi2": 9999} with tempdir.TemporaryDirectory() as tmpdir: # copy data file tmpdir.copy_in(dataName) best = "" fitBest = "" for counter1, ang in enumerate(angs): for counter2, num in enumerate(numScaffoldCopies): cmd.refresh() modelName = builderSalipro(protName, scafName, membName, prefixName, runNumber, num, ang, True) runNumber += 1 if modelName == "bad model": print("Bad model parameters: ang: {} num: {}".format(ang, num)) continue cmd.save(modelName + ".pdb", modelName) fit, fitResult = fitcrysol(modelName, os.path.basename(dataName), "yes", False) cmd.wizard("message", "Refinement: {} ".format(1 + counter2 + counter1 * (len(numScaffoldCopies))) + " out of {} steps. Chi2: {}".format(len(numScaffoldCopies) * len(angs), fitResult['chi2'])) if float(fitResult['chi2']) < float(res['chi2']): if best != "": cmd.delete(best) res['chi2'] = fitResult['chi2'] res['number-of-scaffolds'] = num res['angle'] = ang best = modelName fitBest = fit else: cmd.delete(modelName) tmpdir.move_out(best + ".pdb") tmpdir.move_out(fitBest) cmd.wizard() print("Best model: Number of Scaffolds = {}; Angle = {}".format(res['number-of-scaffolds'], res['angle'])) print("Chi^2 : {} Best model name : {}".format(res['chi2'], best)) return best, fitBest, counter1*counter2
def crysolRefinementDetergent(rot_min_ang, rot_max_ang, rot_step_ang, \ dens_min_ang, dens_max_ang, dens_step_ang, \ protName, membName, dataName, prefixName): '''Refine the membrane protein detergent complex against experimental data''' angs = np.arange(rot_min_ang, rot_max_ang, rot_step_ang) dens = np.arange(dens_min_ang, dens_max_ang, dens_step_ang) res = {"angle": -9999, "number-of-scaffolds": -9999, "chi2": 9999} with tempdir.TemporaryDirectory() as tmpdir: # copy data file tmpdir.copy_in(dataName) best = "" fitBest = "" for counter1, ang in enumerate(angs): for counter2, densAng in enumerate(dens): cmd.refresh() modelName = builderDetergent(protName, membName, prefixName, ang, densAng, True) cmd.save(modelName + ".pdb", modelName) fit, fitResult = fitcrysol(modelName, dataName, "yes", False) cmd.wizard( "message", f"Refinement: {counter2 + counter1 * (len(dens))} out of {len(dens) * len(angs)} steps." f"Chi2: {fitResult['chi2']}") # if model fits better - store it if float(fitResult['chi2']) < float(res['chi2']): if best != "": cmd.delete(best) res['chi2'] = fitResult['chi2'] res['lipid density'] = densAng res['max-polar-angle'] = ang best = modelName fitBest = fit else: cmd.delete(modelName) tmpdir.move_out(best + ".pdb") tmpdir.move_out(fitBest) print( f"Best model: Lipid Density : {res['lipid density']} Max Polar Angle = {res['max-polar-angle']})" ) print(f"Chi^2 : {res['chi2']} Best model name : {best}") return best, fitBest
def pymol_mutate(file_name, chain, res_index, number): pymol.finish_launching() cmd.delete(file_name[:-4]) selection = chain + '/' + res_index + '/' mutant = 'CYS' cmd.wizard("mutagenesis") pdb = file_name[:-4] cmd.load(file_name) cmd.refresh_wizard() cmd.get_wizard().set_mode(mutant) cmd.get_wizard().do_select(selection) nStates = cmd.count_states("mutation") for i in range(1, nStates + 1): cmd.get_wizard().do_select(selection) cmd.frame(i) cmd.get_wizard().apply() cmd.save("rec_" + str(res_index) + "_" + str(i) + ".pdb") cmd.set_wizard() cmd.remove(file_name[:-4])
def crysolRefinementNanodisc(x_min, x_max, x_step, y_min, y_max, y_step, protName, membName, scafName, dataName, prefixName, runNumber): """Refine the membrane protein detergent complex against experimental data""" xs = np.arange(x_min, x_max, x_step) ys = np.arange(y_min, y_max, y_step) res = {"x-offset": -9999, "y-offset": -9999, "chi2": 9999} with tempdir.TemporaryDirectory() as tmpdir: # copy data file tmpdir.copy_in(dataName) best = "" fitBest = "" for counter1, x in enumerate(xs): for counter2, y in enumerate(ys): cmd.refresh() modelName = builderNanodisc(protName, membName, scafName, prefixName, runNumber, x, y, True) runNumber += 1 if modelName == "bad model": # print("Bad model parameters: " + str(z)) continue cmd.save(modelName + ".pdb", modelName) fit, fitResult = fitcrysol(modelName, os.path.basename(dataName), "yes", False) cmd.wizard("message", "Refinement: {} ".format(1 + counter2 + counter1 * (len(ys))) + " out of {} steps. Chi2: {}".format(len(xs) * len(ys), fitResult['chi2'])) # if model fits better - store it if float(fitResult['chi2']) < float(res['chi2']): if best != "": cmd.delete(best) res['chi2'] = fitResult['chi2'] res['x-offset'] = x res['y-offset'] = y best = modelName fitBest = fit else: cmd.delete(modelName) tmpdir.move_out(best + ".pdb") tmpdir.move_out(fitBest) print("Best model: Offset coordinates in XY plane : ({},{})".format(res['x-offset'], res['y-offset'])) print("Chi^2 : {} Best model name : {}".format(res['chi2'], best)) return best, fitBest, counter1*counter2
def extractStrain(residues): cmd.hide("everything") cmd.show("sticks") for resi in residues: for caa in residues[resi]: filename = "residue" + str(resi) + "to" + caa + ".csv" outfile = open(filename, "w") print(resi, caa) cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode(caa) sel = "/test//A/" + str(resi) cmd.get_wizard().do_select(sel) bump_name = "_bump_check" cmd.sculpt_activate(bump_name) cmd.set("sculpt_vdw_vis_mode", 1, bump_name) for rotamer in range(1, 1 + cmd.count_states(bump_name)): score = cmd.sculpt_iterate(bump_name, rotamer, 1) row = (str(rotamer) + "," + str(score) + "\n") outfile.write(row) outfile.close() cmd.get_wizard().clear()
def thread_onto_backbone(backbone_object, backbone_selection, aaString): # # # # create a new temporary dictionary stored.tmp_res_dict = {} # store residue indices(=key) and chain(=value) cmd.iterate(backbone_selection, "stored.tmp_res_dict[resi] = chain") # create a sorted list of all indices as integers sorted_keys_list = [] for index_string in stored.tmp_res_dict.keys(): sorted_keys_list.append(int(index_string)) sorted_keys_list.sort() # set up the mutagenesis wizard cmd.wizard("mutagenesis") cmd.refresh_wizard() count = 0 for residue_index in range(sorted_keys_list[0], sorted_keys_list[0] + len(sorted_keys_list) ): # get a selection string representation of our current residue # e.g. /HPG-3//A/12 index_string = "%d" %(residue_index) selection_str = "/" + backbone_object + "//"+ stored.tmp_res_dict[index_string] + "/%d/" %(residue_index) # perform the desired mutagenesis cmd.get_wizard().do_select(selection_str) cmd.get_wizard().set_mode(aaName(aaString[count])) cmd.get_wizard().apply() count = count + 1 # close up the mutagenesis wizard cmd.set_wizard()
def test_CanInit(self): cmd.wizard("nucmutagenesis") self.assertTrue(cmd.get_wizard() != None)
def test1232(self): with testing.mktemp('.pse') as filename: cmd.save(filename) cmd.wizard('message', 'foo') cmd.load(filename)
def _create_model_from_template_pymol(self, savepath, mhcseq, pepseq, pdb, add_polar_h=False): """ This doesn't work properly """ raise NotImplementedError() table = self.pdb_table row = table[table.pdb == pdb].iloc[0, :] resi_list = row['resi_orig'].split(',') tplseq = row['seq_orig'] pepseq_orig = row['peptide'] aln = Bio.pairwise2.align.globalds(mhcseq, tplseq, matlist.blosum62, -14.0, -4.0)[0] aln1 = aln[0] aln2 = aln[1] logger.info('Alignment:') logger.info('new sequence: ' + aln1) logger.info('old sequence: ' + aln2) logger.info('') logger.info('new peptide: ' + pepseq) logger.info('old peptide: ' + pepseq_orig) mhc_mutations = [] for anew, aold, resi in zip(list(aln1), list(aln2), resi_list): if anew != aold: if anew != '-' and anew != 'X' and aold != '-' and aold != 'X': mhc_mutations.append((seq3(anew), seq3(aold), resi)) logger.info('Found %i mutations in MHC' % len(mhc_mutations)) pep_mutations = [] pep_resi = map(str, range(1, len(pepseq_orig) + 1)) for anew, aold, resi in zip(list(pepseq), list(pepseq_orig), pep_resi): if anew != aold: if anew != '-' and anew != 'X' and aold != '-' and aold != 'X': pep_mutations.append((anew, aold, resi)) logger.info('Found %i mutations in peptide' % len(pep_mutations)) cmd.delete('all') cmd.load(self._get_mhc_path(pdb), 'mhc') cmd.load(self._get_pep_path(pdb), 'pep') cmd.wizard('mutagenesis') cmd.refresh_wizard() cmd.remove("not alt ''+A") cmd.alter('all', "alt=''") for new, old, resi in mhc_mutations: logger.info(resi, old, new) cmd.get_wizard().do_select("A/" + resi + "/") cmd.get_wizard().set_mode(seq3(new).upper()) cmd.get_wizard().apply() for new, old, resi in pep_mutations: logger.info(resi, old, new) cmd.get_wizard().do_select("B/" + resi + "/") cmd.get_wizard().set_mode(seq3(new).upper()) cmd.get_wizard().apply() cmd.set_wizard() if add_polar_h: cmd.h_add('donors or acceptors') cmd.save(savepath, "all") cmd.delete("all")
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
def run(self): my_view = cmd.get_view() #mark Search if self.mode == 'Search': #show message cmd.wizard("message", "Searching conformers...") cmd.refresh() if self.currentLabel.uid != "Rx": self.search() print "Creating Rotamers in PyMOL...", for aRotamer in self.currentLabel.ensembles["mW"].rotamers: self.createRotamerInPymol(aRotamer, "mW") # if self.thoroughness == "painstaking" and self.currentLabel.uid == "R1": # scoringWeights = {"totalContactWeight": 0.0, "typeOfContactWeight": 1.0} # for aRotamer in self.currentLabel.ensembles["mW"].rotamers: # aRotamer.score(scoringWeights) # self.currentLabel.ensembles["mW"].sortRotamers("chi2") # numberOfRotamers = len(self.currentLabel.ensembles["mW"].rotamers) # newEnsemble = ensemble.Ensemble() # newEnsemble.name = "contactFit" # newEnsemble.rotamers = self.currentLabel.ensembles["mW"].rotamers[0:20] # self.currentLabel.ensembles["contactFit"] = newEnsemble # for aRotamer in self.currentLabel.ensembles["contactFit"].rotamers: # self.createRotamerInPymol(aRotamer, "contactFit") print "done!" elif self.currentLabel.uid == "Rx": ca1 = numpy.array( cmd.get_model(self.residue1Name + " & name CA", 1).get_coord_list()[0]) ca2 = numpy.array( cmd.get_model(self.residue2Name + " & name CA", 1).get_coord_list()[0]) try: cb1 = numpy.array( cmd.get_model(self.residue1Name + " & name CB", 1).get_coord_list()[0]) except: cb1 = ca1 try: cb2 = numpy.array( cmd.get_model(self.residue2Name + " & name CB", 1).get_coord_list()[0]) except: cb2 = ca2 environmentatoms = numpy.array(cmd.get_model("(%s within 10 of %s or %s) and not (%s or %s)" \ %(self.pickedObject1, \ self.residue1Name, \ self.residue2Name, \ self.residue1Name, \ self.residue2Name), 1).get_coord_list()) anchor1rotamers = self.currentLabel.calculateCone( ca1, cb1, environmentatoms, numberOfAtoms=8000) anchor2rotamers = self.currentLabel.calculateCone( ca2, cb2, environmentatoms, numberOfAtoms=8000) solutions1 = [] solutions2 = [] for anchor1rotamer in anchor1rotamers: anAtom = anchor1rotamer.atoms["N1"] solutions1.append(anAtom.coordinate) for anchor2rotamer in anchor2rotamers: anAtom = anchor2rotamer.atoms["N1"] solutions2.append(anAtom.coordinate) #determine common accessible volume distances1 = self.currentLabel.quick_map(solutions1, cb2) distances2 = self.currentLabel.quick_map(solutions2, cb1) indices1 = numpy.where(numpy.any(distances1 > 6, axis=1)) indices2 = numpy.where(numpy.any(distances2 > 6, axis=1)) solutions1 = numpy.delete(solutions1, indices1, 0) solutions2 = numpy.delete(solutions2, indices2, 0) solutions = numpy.concatenate((solutions1, solutions2)) #create resulting ensemble newEnsemble = ensemble.Ensemble() newEnsemble.name = "mW" id = 0 newRotamers = [] if len(solutions) > 0: for solution in solutions: newRotamer = rotamer.Rotamer() thisAtom = atom.Atom() thisAtom.coordinate = solution thisAtom.name = "N1" thisAtom.element = "N" newRotamer.id = id newRotamer.atoms["N1"] = thisAtom id += 1 newRotamers.append(newRotamer) else: print "Did not find any possible N1 locations. Are the two anchorpoints too far apart?" newEnsemble.rotamers = newRotamers self.currentLabel.ensembles[newEnsemble.name] = newEnsemble cmd.load( "%s/labels/%s" % (self.path, self.currentLabel.pdbFile), "currentLabel") for aRotamer in self.currentLabel.ensembles["mW"].rotamers: self.createRotamerInPymol(aRotamer, "mW") self.numberOfLabel += 1 self.finalCosmetics() #dismiss message cmd.wizard() #mark Measure elif self.mode == "Measure": cmd.wizard("message", "Calculating distances...") cmd.refresh() print "\n\n\nDistance calculation:\n" print "The dashed lines are the c-beta distance (green),\nand the distance between the geometric averages\nof the two ensembles (yellow).\n" print "The following statistics refer to the distribution\nof the individual distances between all conformers (may take a while):\n" #find out what the selections are stored.label1 = [] stored.label2 = [] stored.label1Coordinates = [] stored.label2Coordinates = [] stored.atomNames1 = [] stored.atomNames2 = [] #extract label info cmd.iterate(self.residue1Name, 'stored.label1.append(segi)') cmd.iterate(self.residue2Name, 'stored.label2.append(segi)') cmd.iterate(self.residue1Name, 'stored.atomNames1.append(name)') cmd.iterate(self.residue2Name, 'stored.atomNames2.append(name)') try: label1 = label.Label.fromfile("labels/%s.txt" % stored.label1[0]) cmd.iterate_state( 0, "%s & name %s" % (self.residue1Name, label1.spinLocation), 'stored.label1Coordinates.append((x,y,z))') except: cmd.iterate_state(0, "%s" % (self.residue1Name), 'stored.label1Coordinates.append((x,y,z))') try: label2 = label.Label.fromfile("labels/%s.txt" % stored.label2[0]) cmd.iterate_state( 0, "%s & name %s" % (self.residue2Name, label2.spinLocation), 'stored.label2Coordinates.append((x,y,z))') except: cmd.iterate_state(0, "%s" % (self.residue2Name), 'stored.label2Coordinates.append((x,y,z))') #calculate distances distances = distanceDistribution.DistanceDistribution() dist = distances.calculateDistanceDistribution( stored.label1Coordinates, stored.label2Coordinates) #create pseudoatom at average coordinate of each ensemble and display the distance between them atoms1 = numpy.array(stored.label1Coordinates) atoms2 = numpy.array(stored.label2Coordinates) avgAtoms1 = numpy.average(atoms1, axis=0) avgAtoms2 = numpy.average(atoms2, axis=0) self.createPseudoatom(avgAtoms1, "tmp_average1", 1) self.createPseudoatom(avgAtoms2, "tmp_average2", 1) cmd.distance(self.object_prefix + "avg", "tmp_average1 & name PS1", "tmp_average2 & name PS1") cmd.delete("tmp_average1") cmd.delete("tmp_average2") #cbeta distance if cbeta is present in both selections #cBetaDistance = 0.0 if any("CB" in atom for atom in stored.atomNames1) and any( "CB" in atom for atom in stored.atomNames2): cmd.distance(self.object_prefix + "cBeta", self.residue1Name + " & name CB", self.residue2Name + " & name CB") #for some reason, cmd.distance does not return the correct distance. Although it is shown in the viewer... #get_distance gives the correct distance, but does not create the object in the viewer. cBetaDistance = cmd.get_distance( self.residue1Name + " & name CB", self.residue2Name + " & name CB") cmd.set("dash_color", "green", self.object_prefix + "cBeta") histogram = numpy.histogram(dist, numpy.arange(100)) envelopePlot = numpy.zeros((100, 2)) envelopePlot[0:99] = numpy.column_stack( (histogram[1][0:len(histogram[1]) - 1], histogram[0])) #put point in mid of bin envelopePlot[:, 0] += 0.5 normEnvelopePlot = numpy.copy(envelopePlot) normEnvelopePlot[:, 1] = normEnvelopePlot[:, 1] / numpy.amax( histogram[0]) #combine dist and histogram to single array before output output = numpy.column_stack((envelopePlot, normEnvelopePlot[:, 1])) averageDistance = numpy.average(dist) #make graph dictionary for mtsslPlotter graphtitle = "%s-%s" % (self.residue1Name, self.residue2Name) xlim = [0, 100] ylim = [0, 1] plotDictionary = self.makeGraphDataDictionary( graphtitle, "DistanceDistribution", "Distance (Angstrom)", "Relative Probability", output[:, 0], output[:, 2], 0, xlim, ylim) stored.plots.append(plotDictionary) print "Distribution plot added to memory. Inspect it with mtsslPlotter." #Copy to clipboard header = "Dist. Count Norm.Count\n" outputStr = header + numpy.array_str(output) outputStr = outputStr.replace("[", "") outputStr = outputStr.replace("]", "") self.copyStringToClipboard(outputStr) #Write to file if self.writeToFile: try: filename = "%s-%s" % (self.residue1Name, self.residue2Name) numpy.savetxt(filename + ".txt", output, delimiter='\t') print "Written to file:" print "%s/%s" % (os.getcwd(), filename) except: print "Writing to file failed!" print self.calculateStatistics2(dist) try: if cBetaDistance > 0.0: print "Cbeta distance: %3.1f" % cBetaDistance except: print "No Cbeta distance." cmd.wizard() #mark Distance Map elif self.mode == "Distance Map": #show message cmd.wizard("message", "Calculating distance maps. Please be patient...") cmd.refresh() dm = distanceMap.DistanceMap(self.writeToFile, self.currentLabel, self.homoOligomerMode) if self.pickedObject1 == self.pickedObject2: dm.intraDistanceMap(self.pickedObject1) else: dm.interDistanceMap(self.pickedObject1, self.pickedObject2) print "Done!" cmd.wizard() self.cleanupAfterRun() cmd.set_view(my_view)
def dis(event): cmd.wizard('Distance')
elif mutation_list[x][-1] == 'F': residue_list[x] = 'PHE' elif mutation_list[x][-1] == 'P': residue_list[x] = 'PRO' elif mutation_list[x][-1] == 'S': residue_list[x] = 'SER' elif mutation_list[x][-1] == 'T': residue_list[x] = 'THR' elif mutation_list[x][-1] == 'W': residue_list[x] = 'TRP' elif mutation_list[x][-1] == 'Y': residue_list[x] = 'TYR' elif mutation_list[x][-1] == 'V': residue_list[x] = 'VAL' cmd.load('D:/autodock_automation/tmafc.pdb') #Replace with your directory cmd.wizard('mutagenesis') for x in range(len(mutation_list)): cmd.get_wizard().do_select('/tmafc//A/%s' % (position_list[x])) cmd.get_wizard().set_mode("%s" % (residue_list[x])) cmd.get_wizard().apply() cmd.save('D:/autodock_automation/PDB_Files/mutant_%s.pdb' % (mutation)) cmd.reinitialize('everything') cmd.quit() for pdbFile in os.listdir('D:/autodock_automation/PDB_FILES'): subprocess.run( 'cmd /c "python D:/autodock_automation/prepare_receptor4.py -r D:/autodock_automation/PDB_Files/' + pdbFile + ' -o D:/autodock_automation/PDBQT_Files/' + pdbFile + 'qt -U waters"') for pdbqtFile in os.listdir('D:/autodock_automation/PDBQT_FILES'):
# pymol -qc mutate.py pdb selection new_residue # example: pymol -qc mutate.py 0.pdb C/1/ ALA 0_mutated.pdb # run for all the confs in the ensemble # append all to one using mdconvert 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") 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.save(output_name, "file")