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 testSaveRef(self, format): # for rms_cur (not all formats save all identifiers) m = -1 cmd.set('retain_order') cmd.fragment('ala', 'm1') cmd.copy('m2', 'm1') cmd.copy('m3', 'm1') cmd.rotate('y', 90, 'm2') cmd.align('m3', 'm2') # with ref=m3 with testing.mktemp('.' + format) as filename: cmd.save(filename, 'm2', ref='m3') cmd.load(filename, 'm4') self.assertAlmostEqual(cmd.rms_cur('m4', 'm1', matchmaker=m), 0.00, delta=1e-2) self.assertAlmostEqual(cmd.rms_cur('m4', 'm2', matchmaker=m), 1.87, delta=1e-2) # without ref with testing.mktemp('.' + format) as filename: cmd.save(filename, 'm2') cmd.load(filename, 'm5') self.assertAlmostEqual(cmd.rms_cur('m5', 'm2', matchmaker=m), 0.00, delta=1e-2) self.assertAlmostEqual(cmd.rms_cur('m5', 'm1', matchmaker=m), 1.87, delta=1e-2)
def draw_bonds(self, selection): warn = False selection_objects = cmd.get_object_list(selection) for obj in selection_objects: elastics_obj = obj+"_elastics" # Create dummy object to draw elastic bonds in cmd.copy(elastics_obj, obj) for a, b, data in self.graph.edges(data=True): # draw non-elastic bonds if data['type'] in ['bonds', 'constr']: try: a += 1 b += 1 try: cmd.add_bond(obj, a, b) except AttributeError: cmd.bond(f"({obj} and ID {a})", f"({obj} and ID {b})") except KeyError: warn = True # Draw elastic network if data['type'] == 'harmonic': try: a += 1 b += 1 try: cmd.add_bond(elastics_obj, a, b) except AttributeError: cmd.bond(f"({elastics_obj} and ID {a})", f"({elastics_obj} and ID {b})") except KeyError: warn = True cmd.color("orange", elastics_obj) # warn about missing atoms if needed. if warn: print('WARNING: some atoms present in the tpr file were not found in the loaded ' 'structure.\n Bonds containing those atoms were not drawn.')
def builderMicelle(detergent, r, numberOfDetergents): i = 0 numberOfDetergents = (int)(numberOfDetergents) #FIXME: if number of detergents > 360, molecules may clash in space if numberOfDetergents > 360: x1 = range(-180, 180) x2 = range(0, 360) theta = ([random.choice(x1) for _ in range(numberOfDetergents)]) phi = ([random.choice(x2) for _ in range(numberOfDetergents)]) else: theta = random.sample(range(-180, 180), numberOfDetergents) phi = random.sample(range(0, 360), numberOfDetergents) for t, p in zip(theta, phi): i += 1 cmd.copy(f"seg{i}", detergent) # randomly sample on a sphere cmd.translate(f"[0,{r},0]", f"seg{i}") cmd.rotate("x", f"{t}", f"seg{i}") cmd.rotate("z", f"{p}", f"seg{i}") s = f"micelle_{detergent}_{(int)(r)}_{(int)(numberOfDetergents)}" cmd.create(f"{s}", "seg*") cmd.delete("seg*") #center(f"{s}") #cmd.show_as("sticks","org") # could be streched if necessary # affineStretch(s, 10) return s
def prepare(model, resi1, resi2, resi3, segis_for_save, segis_for_del): resi1,resi2,resi3 = sorted((resi1,resi2,resi3)) cmd.fetch(model, async=0) cmd.remove('not alt a+""') # delete additional protein segis if segis_for_del != '': cmd.remove('segi {}'.format(segis_for_del.replace(' ', '+'))) # all_segis contains segis which are included to that protein part (symmetric) we need all_segis = [] for resi in (resi1, resi2, resi3): all_segis.append([]) cmd.iterate('/{}///{}/CA'.format(model, resi), \ 'all_segis[-1].append(segi)', \ space={'all_segis': all_segis}) all_segis = [set(x) for x in all_segis] all_segis = all_segis[0] | all_segis[1] | all_segis[2] cmd.remove('not segi {}'.format(str_riffle(list(all_segis), '+'))) if type(segis_for_save) == list: segis_for_save_fact = set(segis_for_save) absent_segis_names = sorted(all_segis - segis_for_save_fact) else: segis_for_save_fact = absent_segis_names = sorted(all_segis) model_save = '{}_save'.format(model) cmd.copy(model_save, model) cmd.remove('{} and not segi {}'.format(model, str_riffle(list(segis_for_save_fact), '+'))) return sorted(all_segis)
def object_tfm_interpolate(object_properties, number_of_frames, frameno): tmpnames = [] for objnm, properties in object_properties.items(): [source_tfm, target_tfm, reverse, color, small_molecule] = properties[:5] transparency_range = properties[5] if len(properties) > 5 else None frame = frameno if reverse: frame = number_of_frames - frame tfm = intermediate_tfm(source_tfm, target_tfm, number_of_frames, frame) if objnm == "lipid": lipid_decimate(number_of_frames, frameno) tmpnm = objnm + str(frameno) cmd.copy(tmpnm, objnm, zoom=0) cmd.transform_selection(tmpnm, tfm) transparency = -1 if transparency_range: transparency = transparency_range[0] \ + float(frameno)/number_of_frames*(transparency_range[1]-transparency_range[0]) if small_molecule: if objnm == "lipid": style_lipid(tmpnm) else: style_substrate(tmpnm, mol_color[objnm], transparency) else: clump_representation([tmpnm], color, tmpnm, small_molecule=small_molecule, transparency=transparency) tmpnames.append(tmpnm) return tmpnames
def sewalign(first,second): #hide waters cmd.hide("(solvent and (all))") #hide hydrogens cmd.hide( 'sticks', 'elem H' ) cmd.hide( 'lines', 'elem H' ) #show cartoon cmd.show("cartoon" ,"all") #create duplicate of first first_copy = first + "_copy" cmd.copy(first_copy, first) #select first 14 residues cmd.select('node_9_selection', '(obj *_9_* and resi 1-14)') cmd.select('node_12_selection', '(obj *_12_* and resi 1-14)') cmd.select('node_15_selection', '(obj *_15_* and resi 1-14)') alignment_1 = cmd.align(first, 'node_9_selection') print alignment_1[0] alignment_2 = cmd.align(second, 'node_12_selection') print alignment_2[0] alignment_3 = cmd.align(first_copy, 'node_15_selection') print alignment_3[0]
def testIgnoreCase(self): # check defaults self.assertEqual(cmd.get_setting_int('ignore_case'), 1) self.assertEqual(cmd.get_setting_int('ignore_case_chain'), 0) # data natoms = 10 cmd.fragment('ala', 'm1') cmd.copy('m2', 'm1') cmd.alter('m1', 'chain, segi = "C", "S"') cmd.alter('m2', 'chain, segi = "c", "s"') cmd.alter('m2', 'resn, name = resn.lower(), name.lower()') self.assertEqual(cmd.count_atoms('chain C'), natoms) self.assertEqual(cmd.count_atoms('segi S'), natoms) self.assertEqual(cmd.count_atoms('chain c'), natoms) self.assertEqual(cmd.count_atoms('segi s'), natoms) self.assertEqual(cmd.count_atoms('resn ALA'), natoms * 2) self.assertEqual(cmd.count_atoms('resn ala'), natoms * 2) self.assertEqual(cmd.count_atoms('name CA'), 2) self.assertEqual(cmd.count_atoms('name ca'), 2) cmd.set('ignore_case_chain') self.assertEqual(cmd.count_atoms('chain C'), natoms * 2) self.assertEqual(cmd.count_atoms('segi S'), natoms * 2) self.assertEqual(cmd.count_atoms('chain c'), natoms * 2) self.assertEqual(cmd.count_atoms('segi s'), natoms * 2) cmd.set('ignore_case', 0) self.assertEqual(cmd.count_atoms('resn ALA'), natoms) self.assertEqual(cmd.count_atoms('resn ala'), natoms) self.assertEqual(cmd.count_atoms('name CA'), 1) self.assertEqual(cmd.count_atoms('name ca'), 1)
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 apply_symmetry(R, t, inchain, outchain): cmd.copy('symm', f'inpdb') coords = cmd.get_coords('symm') cmd.remove(f'symm and not chain {inchain}') coords_symm = (R.dot(coords.T)).T + t cmd.load_coords(coords_symm, 'symm') myspace = {'outchain': outchain} cmd.alter('symm', 'chain=f"{outchain}"', space=myspace)
def growShape(self, lastNode, idList, newNode): rel = self.xDB['pairsData'][lastNode][newNode] self.transformPymolShape(idList, [0, 0, 0], rel['rot'], rel['tran']) copyNodeName = newNode + '#' + str(len(idList)) cmd.copy(copyNodeName, newNode) idList = np.append(idList, copyNodeName) return idList, rel['rot'], rel['tran'], copyNodeName
def builder(residues, bonds, mol_name): """Using the list generated by read_input connects monosacharides in a single oligosaccharide""" cmd.set('suspend_updates', 'on') cmd.feedback('disable', 'executive', 'actions') every_object = cmd.get_object_list('all') if mol_name in every_object: cmd.delete(mol_name) every_object.remove(mol_name) if every_object: sel = 'not (' + ' or '.join(every_object) + ') and' else: sel = '' for i in range(0, len(residues)): res_name = residues[i] cmd.load(os.path.join(path, 'db_glycans', '%s.pdb' % res_name)) cmd.set_name(res_name, i) #rename object (necessary to avoid repeating names) cmd.alter(i, 'resi = %s' % i) #name residues for further referencing cmd.sort(i) for i in range(0, len(bonds)): resi_i, resi_j, atom_i, atom_j = bonds[i][0], bonds[i][2], bonds[i][ 4], bonds[i][5] if atom_i > atom_j: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_j, atom_j, atom_j)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_i, atom_i)) cmd.fuse('%s (resi %s and name O%s)' % (sel, resi_i, atom_i), '%s (resi %s and name C%s)' % (sel, resi_j, atom_j), mode=2) else: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_i, atom_i, atom_i)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_j, atom_j)) cmd.fuse('%s (resi %s and name C%s)' % (sel, resi_i, atom_i), '%s (resi %s and name O%s)' % (sel, resi_j, atom_j), mode=2) cmd.delete('%s' % i) cmd.copy(mol_name, '%s' % resi_j) cmd.delete('%s' % resi_j) for i in range(0, len(bonds)): set_phi(mol_name, bonds[i], -60) set_psi(mol_name, bonds[i], 120) cmd.delete('pk1') cmd.delete('pk2') cmd.delete('pkbond') cmd.delete('pkmol') if babel: fast_min(mol_name, 5000) minimize(mol_name) else: fast_min(mol_name, 5000) cmd.feedback('enable', 'executive', 'actions') cmd.set('suspend_updates', 'off')
def refinements(self): """Refinements for the visualization""" # Show sticks for all residues interacing with the ligand cmd.select( 'AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or ' 'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)') cmd.show('sticks', 'AllBSRes') # Show spheres for the ring centroids cmd.hide('everything', 'centroids*') cmd.show('nb_spheres', 'centroids*') # Show spheres for centers of charge if self.object_exists('Chargecenter-P') or self.object_exists( 'Chargecenter-L'): cmd.hide('nonbonded', 'chargecenter*') cmd.show('spheres', 'chargecenter*') cmd.set('sphere_scale', 0.4, 'chargecenter*') cmd.color('yellow', 'chargecenter*') cmd.set('valence', 1) # Show bond valency (e.g. double bonds) # Optional cartoon representation of the protein cmd.copy('%sCartoon' % self.protname, self.protname) cmd.show('cartoon', '%sCartoon' % self.protname) cmd.show('sticks', '%sCartoon' % self.protname) cmd.set('stick_transparency', 1, '%sCartoon' % self.protname) # Resize water molecules. Sometimes they are not heteroatoms HOH, but part of the protein cmd.set('sphere_scale', 0.2, 'resn HOH or Water' ) # Needs to be done here because of the copy made cmd.set('sphere_transparency', 0.4, '!(resn HOH or Water)') if 'Centroids*' in cmd.get_names("selections"): cmd.color('grey80', 'Centroids*') cmd.hide('spheres', '%sCartoon' % self.protname) cmd.hide('cartoon', '%sCartoon and resn DA+DG+DC+DU+DT+A+G+C+U+T' % self.protname) # Hide DNA/RNA Cartoon if self.ligname == 'SF4': # Special case for iron-sulfur clusters, can't be visualized with sticks cmd.show('spheres', '%s' % self.ligname) cmd.hide( 'everything', 'resn HOH &!Water') # Hide all non-interacting water molecules cmd.hide( 'sticks', '%s and !%s and !AllBSRes' % (self.protname, self.ligname)) # Hide all non-interacting residues if self.ligandtype in ['PEPTIDE', 'INTRA']: self.adapt_for_peptides() if self.ligandtype == 'INTRA': self.adapt_for_intra()
def series_resfile(color="orange"): # Main PDB File Name object = cmd.get_names()[0] counter = 0 # Read Rosetta Resfile for fname in glob.glob('*.resfile'): counter += 1 if counter == 1: fname_rem = fname cmd.copy(fname, object) for line in open(fname): # Split Resfile Line by Tab data = line.split('\t') # Only Consider Lines that Start with Residue Numbers if data[0].isdigit(): # Get Revalent Data pos = data[0] chain = data[1] mut = data[3] # Generate Mutation Label label = mut label_list = list(label) label_list.insert(1, "%s" % (pos)) label = ''.join(label_list) # PyMOL Color and Label cmd.color(color, "resi %s and chain %s and %s" % (pos, chain, fname)) cmd.label( "resi %s and chain %s and name ca and %s" % (pos, chain, fname), "\'%s\'" % (label)) # Output Comments to the Console elif line[:1] == "#": # Remove newline feeds line.rstrip("\n") print "\n%s" % (line) cmd.disable('all') cmd.enable(fname_rem) cmd.orient cmd.set_key('pgup', move_up) cmd.set_key('pgdn', move_down)
def sample_uniform(pose, con_matrix, angles_prob): random_angle = np.random.choice(['phi', 'psi', 'chi'], p=angles_prob) random_res = np.random.random_integers(0, len(con_matrix) - 1) bond = con_matrix[random_res] cmd.copy('tmp', pose) if random_angle == "phi": phi = get_phi('tmp', bond) angle_value = np.random.normal(phi, 30) set_phi('tmp', bond, angle_value) elif random_angle == "psi": psi = get_psi('tmp', bond) angle_value = np.random.normal(psi, 30) set_psi('tmp', bond, angle_value) else: set_chi('tmp', bond) set_chi('tmp', bond)
def sample_uniform(pose, con_matrix, angles_prob): random_angle = np.random.choice(['phi', 'psi', 'chi'], p=angles_prob) random_res = np.random.random_integers(0, len(con_matrix)-1) bond = con_matrix[random_res] cmd.copy('tmp', pose) if random_angle == "phi": phi = get_phi('tmp', bond) angle_value = np.random.normal(phi, 30) set_phi('tmp', bond, angle_value) elif random_angle == "psi": psi = get_psi('tmp', bond) angle_value = np.random.normal(psi, 30) set_psi('tmp', bond, angle_value) else: set_chi('tmp', bond) set_chi('tmp', bond)
def _check_optimzer_results_pairwise_5(self, exit_test_mode=False): '''Creates groups for all pairs which are connected. And show them all in grid mode :warning: only designed for pairwise restraints ''' self.check_results_mode = 5 # 1) Check which molecule pairs have connections pair_exists = {} for i_m1 in range(len(self.pymol_molecule_objects)): for i_m2 in range(len(self.pymol_molecule_objects)): pair_exists.update({str(i_m1 + 1) + str(i_m2 + 1): False}) for r in self.logic_handler.selected_restraints: pair_exists.update({str(r.atoms[0].resi) + str(r.atoms[1].resi): True}) mol_pairs = [(str(i_m1 + 1), str(i_m2 + 1)) for i_m1 in range(len(self.pymol_molecule_objects) - 1) for i_m2 in range(i_m1, len(self.pymol_molecule_objects)) if pair_exists[str(i_m1 + 1) + str(i_m2 + 1)] or pair_exists[str(i_m2 + 1) + str(i_m1 + 1)]] print(mol_pairs, mv=1) cmd.disable('all') for p in mol_pairs: m1, m2 = p[0], p[1] m1_name = m1 + '-' + m2 + 'mol_' + m1 m2_name = m1 + '-' + m2 + 'mol_' + m2 cmd.copy(m1 + '-' + m2 + 'mol_' + m1, 'mol_' + m1) cmd.copy(m1 + '-' + m2 + 'mol_' + m2, 'mol_' + m2) group_expression = m1_name + ' ' + m2_name cmd.group('pair_' + m1 + '_' + m2, group_expression) cmd.enable(group_expression) cmd.set('grid_mode', 1) cmd.reset() if (exit_test_mode): self.check_results_mode = 0 for p in mol_pairs: m1_name = m1 + '-' + m2 + 'mol_' + m1 m2_name = m1 + '-' + m2 + 'mol_' + m2 group_expression = m1_name + ' ' + m2_name cmd.delete(m1_name) cmd.delete(m2_name) cmd.ungroup('group_expression') cmd.set('grid_mode', 0) cmd.enable('all')
def builderCorona(theta, fi, detergent, r, detR): # Build symmates with desired rotations thetaSteps = len(theta) angleVer = np.linspace(-90, 90, thetaSteps) i = 0 for t, a in zip(theta, angleVer): for f in fi: i += 1 cmd.copy(f"seg{i}", detergent) # corona cmd.rotate("x", f"{a}", f"seg{i}") cmd.translate(f"[0,{r + 0.5*detR*np.cos(np.deg2rad(a))},0]", f"seg{i}") cmd.translate(f"[0,0,{(r+detR)*np.sin(np.deg2rad(t))}]", f"seg{i}") cmd.rotate("z", f"{f}", f"seg{i}") cmd.create("corona", "seg*") cmd.delete("seg*")
def builder(residues, bonds, mol_name): """Using the list generated by read_input connects monosacharides in a single oligosaccharide""" cmd.set('suspend_updates', 'on') cmd.feedback('disable', 'executive', 'actions') every_object = cmd.get_object_list('all') if mol_name in every_object: cmd.delete(mol_name) every_object.remove(mol_name) if every_object: sel = 'not (' + ' or '.join(every_object) + ') and' else: sel = '' for i in range(0, len(residues)): res_name = residues[i] cmd.load(os.path.join(path, 'db_glycans', '%s.pdb' % res_name)) cmd.set_name(res_name, i) #rename object (necessary to avoid repeating names) cmd.alter(i, 'resi = %s' % i) #name residues for further referencing cmd.sort(i) for i in range(0, len(bonds)): resi_i, resi_j, atom_i, atom_j = bonds[i][0], bonds[i][2], bonds[i][4], bonds[i][5] if atom_i > atom_j: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_j, atom_j, atom_j)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_i, atom_i)) cmd.fuse('%s (resi %s and name O%s)' % (sel, resi_i, atom_i), '%s (resi %s and name C%s)' % (sel, resi_j, atom_j), mode=2) else: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_i, atom_i, atom_i)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_j, atom_j)) cmd.fuse('%s (resi %s and name C%s)' % (sel, resi_i, atom_i), '%s (resi %s and name O%s)' % (sel, resi_j, atom_j), mode=2) cmd.delete('%s' % i) cmd.copy(mol_name, '%s' % resi_j) cmd.delete('%s' % resi_j) for i in range(0, len(bonds)): set_phi(mol_name, bonds[i], -60) set_psi(mol_name, bonds[i], 120) cmd.delete('pk1') cmd.delete('pk2') cmd.delete('pkbond') cmd.delete('pkmol') if babel: fast_min(mol_name, 5000) minimize(mol_name) else: fast_min(mol_name, 5000) cmd.feedback('enable', 'executive', 'actions') cmd.set('suspend_updates', 'off')
def builderMicelle(detergent, r, numberOfDetergents): refresh() i = 0 numberOfDetergents = int(numberOfDetergents) # FIXME: if number of detergents > 360, molecules may clash in space points = fibonacci_sphere(numberOfDetergents) print("Rotating detergent molecule for build protocol...") for x,y,z in points: i += 1 t = np.degrees(np.arccos(z)) p = np.degrees(np.arctan(y/x)) cmd.copy("seg{}".format(i), detergent) cmd.alter("seg{}".format(i), "resi={}".format(i)) # assign residue numbers # put to to knot of fibonacci grid center("seg{}".format(i)) cmd.translate("[0,{},0]".format(r), "seg{}".format(i)) if x < 0: cmd.rotate("z", 180, "seg{}".format(i)) cmd.rotate("z", str(t), "seg{}".format(i)) cmd.rotate("y", str(p), "seg{}".format(i)) #cmd.translate("[{},{},{}]".format(r * x, r * y, r * z), "seg{}".format(i)) # if numberOfDetergents > 360: # x1 = range(-180, 180) # x2 = range(0, 360) # theta = ([random.choice(x1) for _ in range(numberOfDetergents)]) # phi = ([random.choice(x2) for _ in range(numberOfDetergents)]) # else: # theta = random.sample(range(-180, 180), numberOfDetergents) # phi = random.sample(range(0, 360), numberOfDetergents) # for t, p in zip(theta, phi): # i += 1 # cmd.copy("seg{}".format(i), detergent) # cmd.alter("seg{}".format(i), "resi={}".format(i)) # assign residue numbers # # randomly sample on a sphere # cmd.translate("[0,{},0]".format(r), "seg{}".format(i)) # cmd.rotate("x", str(t), "seg{}".format(i)) # cmd.rotate("z", str(p), "seg{}".format(i)) s = "micelle_{}_{}_{}".format(detergent, int(r), int(numberOfDetergents)) cmd.create(s, "seg*") cmd.delete("seg*") # center(f"{s}") # cmd.show_as("sticks","org") # could be streched if necessary # affineStretch(s, 10) return s
def show_result(tmpdir, ligname): n = 10 # number of positions of ligand ft_file = tmpdir + "/ft.000.0.0" rm_file = tmpdir + "/rm.000.0.0" ft_data = np.loadtxt(ft_file) rm_data = np.loadtxt(rm_file) for i in range(n): num_state = i + 1 name_copy = "copy_ligand_" + str(i) cmd.copy(name_copy, ligname) tv = ft_data[i, 1:4] rm = rm_data[i].reshape((3, 3)) en = ft_data[i, 4] cmd.translate(list(tv), name_copy) cmd.rotate(list(get_axis(rm)), get_angle(rm), name_copy) cmd.create("result", name_copy, 0, num_state) cmd.delete(name_copy) result = tmpdir + "/result_dock.pdb" cmd.save(result, "result") cmd.mplay()
def builderNanodisc(protein, membrane, scaffold, prefixName, runNumber, x=0, y=0, refine=False): """ builds a MP-nanodisc systems scaffold in this case is a double belt of MSP """ # Checking time of builder function execution if protein != None: print('protein is: ' + protein) print('scaffold is: ' + scaffold) print('membrane is: ' + membrane) empty = False if protein is None: empty = True if not empty: tmp_prot = "tmp_prot" + str(runNumber) cmd.copy(tmp_prot, protein) # store initial cmd.translate("[{},{},0]".format(x, y), tmp_prot) print("State of empty/not-empty: {}".format(empty)) # copies to delete later tmp_scaffold = "tmp_scaffold" + str(runNumber) tmp_memb = "tmp_memb" + str(runNumber) tmp_origin = "origin" + str(runNumber) cmd.copy(tmp_scaffold, scaffold) # store initial cmd.copy(tmp_memb, membrane) # store initial center(tmp_memb) center(tmp_scaffold) cmd.pseudoatom(tmp_origin, pos=[0, 0, 0]) cmd.origin(tmp_origin) #outRadius = findAverDist(tmp_scaffold) #doubles time for each run outRadius = TMdistCheck(tmp_scaffold, 0.2) print("Max distance from origin to scaffold in xy plane: {}".format(outRadius)) # remove lipids beyond border encased by MSP cmd.remove("br. org and {} beyond {} of {}".format(tmp_memb, outRadius, tmp_origin)) # remove lipids clashing with tmp_protein core if not empty: avXY = TMdistCheck(tmp_prot, 0.2) if avXY == -1: return "bad model" minXY = avXY / 2.0 # remove lipids inside pore cmd.remove("br. org and {} within {} of {}".format(tmp_memb, minXY, tmp_origin)) print("Mean distance if TM cross-section in xy plane: {}".format(avXY)) if empty: cmd.remove("br. org and {} within 0.4 of {} and not hydro".format(tmp_memb, tmp_scaffold)) s = "empty_{}_{}".format(membrane, scaffold) else: cmd.remove("br. org and {} within 0.3 of pol. and not hydro".format(tmp_memb)) s = "{}_{}_{}".format(protein, membrane, scaffold) if refine: s += "{}_{}".format(int(x), int(y)) if prefixName: s = "{}{}".format(prefixName, s) cmd.create(s, "({},{}, {})".format(protein, tmp_scaffold, tmp_memb)) cmd.save(s + ".pdb", s) cmd.delete(tmp_memb) cmd.delete(tmp_scaffold) cmd.delete(tmp_prot) cmd.delete(tmp_origin) return s
def test_update(self): # 3 states cmd.fragment('gly', 'm1') cmd.create('m1', 'm1', 1, 2) cmd.create('m1', 'm1', 1, 3) # second object, 90 degree rotates cmd.copy('m2', 'm1') cmd.rotate('x', 90, '(m2)', state=0) # reference coordsets cs = cmd.get_coordset cs1 = cs('m1', 1) cs2 = cs('m2', 1) # m2/3 will change (pre-check) self.assertArrayEqual(cs2, cs('m2', 3)) self.assertArrayNotEqual(cs1, cs('m2', 3)) # update explicit state cmd.update('m2', 'm1', 3, 2) # m2/3 has changed self.assertArrayEqual(cs1, cs('m2', 3)) self.assertArrayNotEqual(cs2, cs('m2', 3)) # these haven't changed self.assertArrayEqual(cs2, cs('m2', 1)) self.assertArrayEqual(cs2, cs('m2', 2)) # reset m2/3 cmd.load_coordset(cs2, 'm2', 3) self.assertArrayEqual(cs2, cs('m2', 3)) # update all states cmd.update('m2', 'm1', 0, 0) self.assertArrayEqual(cs1, cs('m2', 1)) self.assertArrayEqual(cs1, cs('m2', 2)) self.assertArrayEqual(cs1, cs('m2', 3))
def Add_VDW(object, radii=""): cmd.copy(object + "_vdw", object) cmd.alter(object + "_vdw and elem H", "vdw=1.09") radii = radii.lower() if radii == "cpk" or radii == "bondi": # retrieve the data (coords and atomtypes) ATOMTYPES = [] CARTESIANS = [] atomslist = cmd.get_model(object + "_vdw") for i in range(0, len(atomslist.atom)): ATOMTYPES.append(atomslist.atom[i].symbol) CARTESIANS.append(atomslist.atom[i].coord) for i in range(0, len(ATOMTYPES)): atomid = i + 1 # careful, pymol numbering starts at 1, but list starts at 0 cmd.alter( "%s_vdw & id %s" % (object, atomid), "vdw=%.2f" % atomicModelRadius(ATOMTYPES, CARTESIANS, radii, i)) cmd.rebuild() cmd.set("sphere_scale", 1, object + "_vdw") cmd.hide("nonbonded", object + "_vdw") cmd.hide("lines", object + "_vdw") cmd.hide("sticks", object + "_vdw") cmd.set("sphere_transparency", 0.7, object + "_vdw")
def builderMembrane(lipid, runNumber): """ build membrane bilayer from single lipid PDB file """ refresh() cmd.load(lipid + ".pdb", "start_lipid") cmd.alter("start_lipid", "chain = 'X'") cmd.alter("start_lipid", "segi = 'mema'") # cmd.rotate('x', 90, "start_lipid") dmax = findMaxDist("start_lipid") # create lipid copies and translate them to new position nlip = 20 # number of lipids forming edge of bilayer s0 = range(1, nlip, 1) s1 = range(1, nlip + 1, 1) # excludes first lipid step_x = 0 # translation in x (TODO: automatic determination of spacing without clashes) step_y = 7 step_z = 0 step_x2 = 7 step_y2 = 0 step_z2 = 0 for i in s1: # first column cmd.copy("lip{}".format(i), "start_lipid") # row of lipids cmd.alter("lip{}".format(i), "resi={}".format(i)) # change residue numbers y = i * step_y cmd.translate("[{},{},{}]".format(step_x, y, step_z), "lip{}".format(i)) # generate remaining rows/columns in same leaflet for j in s0: k = int(nlip) * i + j # TODO: general counter to write correct lipid number cmd.copy("lip{}".format(k), "lip{}".format(i)) # adjacent row of lipids cmd.alter("lip{}".format(k), "resi={}".format(k)) # change residue numbers x2 = j * step_x2 cmd.translate("[{},{},{}]".format(x2, step_y2, step_z2), "lip{}".format(k)) cmd.sort() # sort atom order # create second leaflet # simple method by creating a single leaflet object: cmd.create("mema", "(lip*)") cmd.delete("lip*") cmd.copy("memb", "mema") cmd.alter("memb", "segi = 'memb'") cmd.rotate("x", 180, "memb") cmd.translate("[0,0,{}]".format((-1.0 * (dmax + 0.5))), "memb") # cmd.color("yellow", "segi = 'mema'") # cmd.color("blue", "segi = 'memb'") cmd.translate("[3.5,3.5,0]", "memb") # optional shift of single leaflet to avoid aliphatic clashes s = "{}_bilayer".format(lipid) cmd.create(s, "(mema,memb)") cmd.delete("mema ,memb, start_lipid") center(s) cmd.save(s + ".pdb", s) cmd.reset() return s
def extract_state_to_object(morph, state, new_object): number_of_states = cmd.count_states(morph) if number_of_states < state: print("in extract_state_to_object() requested state " + "{} > number of states ({}) available in {}".format( state, number_of_states, morph)) exit() if morph == new_object: print("in extract_state_to_object() please picked different " + "name for extraction (currently bouth '{}') ".format(morph)) exit() # after this I will have each state available as its own object, called "{morphname}_000x" (padded to length of 4) # x starts with 1 --> not clear - that might depend on the numbering in the input file cmd.split_states(morph) state_name = morph + "_" + str(state).zfill(4) cmd.copy(new_object, state_name) for statenum in range(1, number_of_states + 1): state_name = morph + "_" + str(statenum).zfill(4) cmd.delete(state_name) cmd.delete(morph) return
def builderNanodisc(protein, membrane, scaffold, prefixName, offset=0, refine=False): """ builds a MP-nanodisc systems scaffold in this case is a double belt of MSP """ # Checking time of builder function execution print(f'protein is: {protein}') print(f'scaffold is: {scaffold}') print(f'membrane is: {membrane}') empty = False if protein == None: empty = True # copies to delete later cmd.copy("tmp_scaffold", scaffold) # store initial cmd.copy("tmp_memb", membrane) # store initial cmd.copy("tmp_prot", protein) # store initial center("tmp_memb") center("tmp_scaffold") cmd.pseudoatom("origin0", pos=[0, 0, 0]) cmd.origin("origin0") outRadius = findAverDist("tmp_scaffold") cmd.translate(f"[0,0,{offset}]", f"tmp_scaffold") print(f"Max distance from origin to scaffold in xy plane: {outRadius}") # remove lipids beyond border encased by MSP cmd.remove(f"org and tmp_memb beyond {outRadius} of origin0") print(f"State of empty/not-empty: {empty}") # remove lipids clashing with tmp_protein core if not empty: avXY = TMdistCheck("tmp_prot", 0.2) minXY = avXY / 2.0 # remove lipids inside pore cmd.remove(f"org and tmp_memb within {minXY} of origin0") print(f"Mean distance if TM cross-section in xy plane: {avXY}") if empty: cmd.remove("org and tmp_memb within 0.4 of tmp_scaffold and not hydro") s = f"{prefixName}empty_{membrane}_{scaffold}" else: cmd.remove("org and tmp_memb within 0.3 of pol. and not hydro") s = f"{prefixName}{protein}_{membrane}_{scaffold}" if refine: s += str(int(offset)) cmd.create(s, f"({protein},tmp_scaffold, tmp_memb)") cmd.save(s + ".pdb", s) cmd.delete("tmp_memb") cmd.delete("tmp_scaffold") cmd.delete("tmp_prot") cmd.delete("origin0") return s
def my_mutate(rec_name, lig_name, dist): # select residues in rec_name within dist of lig_name # and show them as lines, the rest as cartoon rec_pocket = f'byres {rec_name} within {dist} of {lig_name}' # get the names and indices of the pocket residues space = dict(residues=set()) cmd.iterate(rec_pocket, 'residues.add((resv, resn))', space=space) residues = sorted(space['residues']) res_idxs = [str(i) for i, n in residues] res_idxs = '(resi ' + '+'.join(res_idxs) + ')' # create a mapping from charged residues to # oppositely charged residues of similar size charge_map = { 'ARG': 'GLU', 'HIS': 'ASP', 'LYS': 'GLU', 'ASP': 'LYS', 'GLU': 'LYS', } # mutate each pocket residue individually for res_idx, res_name in residues: # make a mutant with the residue as alanine mut_name = f'{rec_name}_mut_{res_idx}_{res_name}_ALA' cmd.copy(mut_name, rec_name) mutate(mut_name, res_idx, 'ALA') cmd.save(mut_name + '.pdb', mut_name) if res_name in charge_map: # make another mutant with the charge flipped inv_name = charge_map[res_name] mut_name = f'{rec_name}_mut_{res_idx}_{res_name}_{inv_name}' cmd.copy(mut_name, rec_name) mutate(mut_name, res_idx, inv_name) cmd.save(mut_name + '.pdb', mut_name) # create one final mutant with ALL charges flipped mut_name = f'{rec_name}_mut_all_charges' cmd.copy(mut_name, rec_name) for res_idx, res_name in residues: if res_name in charge_map: inv_name = charge_map[res_name] mutate(mut_name, res_idx, inv_name) cmd.save(mut_name + '.pdb', mut_name) cmd.zoom(rec_pocket) print(res_idxs)
def testCopy(self): cmd.fragment('ala', 'm1') cmd.copy('m2', 'm1') self.assertEqual( cmd.count_atoms('m1'), cmd.count_atoms('m2'))
def phenotype_scene(gnao_cartoon=True): # shared between movie and xlsx all_structures = ["AC", "RGS", "GPCR", "substrate", "gnao"] load_structures(structure_home, structure_filename, all_structures) cmd.bg_color("white") #style_substrate("substrate", mol_color["substrate"]) if gnao_cartoon: cmd.copy("gnao-cartoon", "gnao") cmd.show("cartoon", "gnao-cartoon") cmd.color("white", "gnao-cartoon") cmd.set("ray_shadows", "off") if gnao_cartoon: cmd.remove("gnao-cartoon and resi 58-170") cmd.remove("gnao-cartoon and resi 347-350") # see below cmd.remove("gnao and resi 58-170") cmd.remove("gnao and resi 347-350" ) # the isosurface at the GPCR interface won't close otherwise # substrate interface_clump("substrate", "gnao", mol_color["substrate"], depth=5, transparency=0.5) #clump_representation(["substrate"], mol_color["substrate"], "substrate", transparency=0.2) cmd.set("stick_radius", 0.5, "substrate") cmd.show_as("sticks", "substrate") cmd.show_as("spheres", "substrate and name MG") cmd.color(mol_color["substrate"], "substrate") cmd.remove("AC and (resi 1-1065 or resi 1175-1500)") interface_clump("AC", "gnao", mol_color["AC"], depth=5, transparency=0.6) if gnao_cartoon: interface_clump("GPCR", "gnao", mol_color["GPCR"], depth=5, transparency=0.6) else: # I get a hole in the mesh here interface_clump("GPCR", "gnao", mol_color["GPCR"], depth=5, transparency=0.6, grid_spacing=0.8) interface_clump("RGS", "gnao", mol_color["RGS"], depth=5, transparency=0.6, grid_spacing=0.7) residue_cluster_clump("gnao", conserved, "gnao-conserved", "aquamarine", transparency=0.6) ############################# residue_cluster_clump("gnao", conserved, "gnao-conserved", "aquamarine", transparency=0.6) pheno_residues() return
def testAlignto(self): cmd.fragment("gly", "m1") cmd.copy("m2", "m1") cmd.alignto(method="fit", mobile_state=1, target_state=1)
def make_GDP(in_name, new_name): cmd.copy(new_name, in_name, zoom=0) cmd.remove("{} and not resn GDP".format(new_name)) return
def mcm(pose, mc_steps, SASA, randomize): ################################# MCM Parameters ########################## T = 300. # Temperature k = 0.0019872041 # Boltzmann constant kT = k * T # probability to sample phi, psi or chi angles_prob = [1 / 3, 1 / 3, 1 / 3] accepted = 0 ########################################################################## # first, last = pose_from_pdb(pose) if first or last: print('Starting MCM') from energy import minimize, set_sasa, get_sasa sus_updates = cmd.get('suspend_updates') cmd.set('suspend_updates', 'on') # uncomment for debugging cmd.feedback('disable', 'executive', 'everything') pdb_conect = cmd.get('pdb_conect_all') cmd.set('pdb_conect_all', 1) glyco_bonds = get_glyco_bonds(first, last) con_matrix = writer(glyco_bonds) # Remove previous pdb files prev_files = glob.glob('mcm_*.pdb') for prev_file in prev_files: os.remove(prev_file) # set all paramenters for sasa-energy computation if SASA: params, points, const = set_sasa(n=1000) # randomize initial conformation if randomize: for i in range(len(con_matrix) - 1): bond = con_matrix[i] angle_values = np.random.uniform(-180, 180, size=2) set_psi(pose, bond, angle_values[0]) set_phi(pose, bond, angle_values[1]) for i in range(6): set_chi(pose, bond) # minimize energy of starting conformation and save it NRG_old = minimize(pose, nsteps=5000, rigid_geometry=False) NRG_min = NRG_old cmd.save('mcm_%08d.pdb' % accepted) # start MCM routine fd = open("mcm_log.txt", "w") print('# iterations remaining = %s' % (mc_steps)) for i in range(1, mc_steps + 1): if i % (mc_steps // 10) == 0: print('#remaining iterations = %s' % (mc_steps - i)) if True: sample_uniform(pose, con_matrix, angles_prob) NRG_new = minimize('tmp', nsteps=100, rigid_geometry=False) if SASA: solvatation_nrg = get_sasa(params, points, const, selection='all', probe=0)[0] NRG_new = NRG_new + solvatation_nrg if NRG_new < NRG_old: NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 else: delta = np.exp(-(NRG_new - NRG_old) / (kT)) if delta > np.random.uniform(0, 1): NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 cmd.delete('tmp') if NRG_new < NRG_min: NRG_min = NRG_new cmd.save('mcm_min.pdb') fd.close() cmd.delete('all') print('Savings all accepted conformations on a single file') de_builds = cmd.get('defer_builds_mode') cmd.set('defer_builds_mode', 5) for i in range(0, accepted): cmd.load('mcm_%08d.pdb' % i, 'mcm_trace') cmd.save('mcm_trace.pdb', 'all', state=0) cmd.delete('all') cmd.load('mcm_trace.pdb') cmd.intra_fit('mcm_trace') print('MCM completed') # restore settings cmd.set('suspend_updates', sus_updates) cmd.set('pdb_conect_all', pdb_conect) cmd.set('defer_builds_mode', de_builds)
def symset(prefix="sym", object=-1, x=0, y=0, z=0, opList=[]): if object == -1: object = cmd.get_names()[0] cell = [float(x), float(y), float(z)] view = cmd.get_view() cmd.show("lines", object) sgInfo = cmd.get_symmetry(object) raw_ops = [] for s in sgtbx.space_group_info(sgInfo[6]).group(): raw_ops.append(str(s)) if len(opList) == 0: for i in range(len(raw_ops)): opList.append(i) opMatrices = [] vars = ["x", "y", "z"] #CREATE 4X4 MATRICES FOR SYMMETRY OPERATORS for i, raw_op in enumerate(raw_ops): ops = raw_op.split(",") matrix = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]] for j in range(len(ops)): for k in range(len(vars)): index = ops[j].find(vars[k]) if index != -1: if index == 0: matrix[k][j] = 1 elif ops[j][index - 1] == "-": matrix[k][j] = -1 else: matrix[k][j] = 1 index = ops[j].find("/") if index != -1: matrix[3][j] = float(ops[j][index - 1]) / float( ops[j][index + 1]) opMatrices.append(matrix) a, b, c, alpha, beta, gamma = sgInfo[0:6] ca = math.cos(math.radians(alpha)) cb = math.cos(math.radians(beta)) cg = math.cos(math.radians(gamma)) sb = math.sin(math.radians(beta)) sg = math.sin(math.radians(gamma)) fracToOrt = N.array([[a, b * cg, c * cb, 0.0], [0.0, b * sg, c * (ca - cb * cg) / sg, 0.0], [ 0.0, 0.0, c * sb * math.sqrt(1.0 - ((cb * cg - ca) / (sb * sg))**2), 0.0 ], [0.0, 0.0, 0.0, 1.0]]) fracToOrt = fracToOrt.transpose() ortToFrac = inv(fracToOrt) stored.atoms = [] cmd.iterate_state(1, object, "stored.atoms.append([x,y,z,1])") stored.atoms = N.array(stored.atoms) fracCoords = N.dot(stored.atoms, ortToFrac) for i in opList: try: op = opMatrices[i] except: print("Bad symmetry partner numbers. Try again.") quit() copy = "%s%02d_%d_%d_%d" % (prefix, i, x, y, z) cmd.copy(copy, object) newCoordsFrac = N.dot(fracCoords, op) stored.newCoords = N.dot(newCoordsFrac, fracToOrt) stored.j = 0 cmd.alter_state( 1, copy, "x,y,z = stored.newCoords[stored.j][0], stored.newCoords[stored.j][1], stored.newCoords[stored.j][2]; stored.j = stored.j + 1" ) xSum = ySum = zSum = 0.0 for a, b, c in newCoordsFrac: xSum += a ySum += b zSum += c center = N.array([xSum, ySum, zSum]) center = center / len(stored.newCoords) shift = [ cell[0] - math.floor(center[0]), cell[1] - math.floor(center[1]), cell[2] - math.floor(center[2]) ] cell_shift(copy, shift[0], shift[1], shift[2], 0) ''' #COPIES COORDINATES OF EACH ATOM TO CORRESPONDING ONE IN GIVEN SYMMETRY PARTNER #cmd.alter_state(1, copy, "x,y,z = cmd.sym_partner([x,y,z], stored.tmpOp)") #MOVES SYMMETRY PARTNER TO PROPER LATTICE COORDINATES AND CORRECTS FOR NATIVE LATTICE POSITION ERROR #stored.xSum,stored.ySum,stored.zSum = 0.0,0.0,0.0 #atoms = cmd.count_atoms(copy) #cmd.iterate_state(1, copy, "stored.xSum = stored.xSum + x; stored.ySum = stored.ySum + y; stored.zSum = stored.zSum + z") #xMean = stored.xSum / atoms #yMean = stored.ySum / atoms #zMean = stored.zSum / atoms #xError, yError, zError = N.dot(N.array([xMean,yMean,zMean]), stored.ortToFrac) #dX,dY,dZ = cell[0]-math.floor(xError), cell[1]-math.floor(yError), cell[2]-math.floor(zError) #cell_shift(copy,dX,dY,dZ, 0) ''' cmd.hide("everything", object) cmd.set_view(view)
def testCopyMap(self): cmd.load(self.datafile('emd_1155.ccp4'), 'map1') cmd.copy('map2', 'map1') self.assertEqual(cmd.get_symmetry('map1'), cmd.get_symmetry('map2')) self.assertArrayEqual(cmd.get_volume_field('map1'), cmd.get_volume_field('map2'))
def mcm(pose, mc_steps, SASA, randomize): ################################# MCM Parameters ########################## T = 300. # Temperature k = 0.0019872041 # Boltzmann constant angles_prob = [1/3, 1/3, 1/3] # probability to sample phi, psi or chi accepted = 0 ############################################################################ # first, last = pose_from_pdb(pose) if first or last: print('Starting MCM') from energy import minimize, set_sasa, get_sasa cmd.set('suspend_updates', 'on') cmd.feedback('disable', 'executive', 'everything') ##uncomment for debugging cmd.set('pdb_conect_all', 1) glyco_bonds = get_glyco_bonds(first, last) con_matrix = writer(glyco_bonds) # Remove previous pdb files prev_files = glob.glob('mcm_*.pdb') for prev_file in prev_files: os.remove(prev_file) # set all paramenters for sasa-energy computation if SASA: params, points, const = set_sasa(n=1000) ## randomize initial conformation if randomize: for i in range(len(con_matrix)-1): bond = con_matrix[i] angle_values = np.random.uniform(-180, 180, size=2) set_psi(pose, bond, angle_values[0]) set_phi(pose, bond, angle_values[1]) for i in range(6): set_chi(pose, bond) # minimize energy of starting conformation and save it NRG_old = minimize(pose, nsteps=5000, rigid_geometry=False) NRG_min = NRG_old cmd.save('mcm_%08d.pdb' % accepted) ## start MCM routine fd = open("mcm_log.txt", "w") print('# iterations remaining = %s' % (mc_steps)) for i in range(1, mc_steps+1): if i % (mc_steps//10) == 0: print('#remaining iterations = %s' % (mc_steps-i)) if True: sample_uniform(pose, con_matrix, angles_prob) NRG_new = minimize('tmp', nsteps=100, rigid_geometry=False) if SASA: solvatation_nrg = get_sasa(params, points, const, selection='all', probe=0)[0] NRG_new = NRG_new + solvatation_nrg if NRG_new < NRG_old: NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 else: delta = np.exp(-(NRG_new-NRG_old)/(T*k)) if delta > np.random.uniform(0, 1): NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 cmd.delete('tmp') if NRG_new < NRG_min: NRG_min = NRG_new cmd.save('mcm_min.pdb') fd.close() cmd.delete('all') print('Savings all accepted conformations on a single file') cmd.set('defer_builds_mode', 5) for i in range(0, accepted): cmd.load('mcm_%08d.pdb' % i, 'mcm_trace') cmd.save('mcm_trace.pdb', 'all', state=0) cmd.delete('all') cmd.load('mcm_trace.pdb') cmd.intra_fit('mcm_trace') print(' MCM completed') cmd.set('suspend_updates', 'off')
def symset(prefix = "sym", object = -1, x=0,y=0,z=0, opList = []): if object == -1: object = cmd.get_names()[0] cell = [float(x),float(y),float(z)] view = cmd.get_view() cmd.show("lines", object) sgInfo = cmd.get_symmetry(object) raw_ops = [] for s in sgtbx.space_group_info(sgInfo[6]).group(): raw_ops.append(str(s)) if (len(opList) == 0): for i in range(len(raw_ops)): opList.append(i) opMatrices = [] vars = ["x","y","z"] i = 0 j = 0 k = 0 #CREATE 4X4 MATRICES FOR SYMMETRY OPERATORS for raw_op in raw_ops: ops = raw_op.split(",") matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] for j in range(len(ops)): for k in range(len(vars)): index = ops[j].find(vars[k]) if index != -1: if index == 0: matrix[k][j] = 1 elif ops[j][index - 1] == "-": matrix[k][j] = -1 else: matrix[k][j] = 1 index = ops[j].find("/") if index != -1: matrix[3][j] = float(ops[j][index - 1]) / float(ops[j][index + 1]) opMatrices.append(matrix) i=i+1 a,b,c,alpha,beta,gamma = sgInfo[0:6] ca = math.cos(math.radians(alpha)) cb = math.cos(math.radians(beta)) cg = math.cos(math.radians(gamma)) sb = math.sin(math.radians(beta)) sg = math.sin(math.radians(gamma)) fracToOrt = N.array([[a, b * cg, c * cb, 0.0], [0.0, b * sg, c * (ca - cb * cg) / sg, 0.0], [0.0, 0.0, c * sb * math.sqrt(1.0 - ((cb * cg - ca) / (sb * sg))**2), 0.0], [0.0,0.0,0.0,1.0]]) fracToOrt = fracToOrt.transpose() ortToFrac = inv(fracToOrt) stored.atoms = [] cmd.iterate_state(1,object,"stored.atoms.append([x,y,z,1])") stored.atoms = N.array(stored.atoms) fracCoords = N.dot(stored.atoms,ortToFrac) for i in opList: try: op = opMatrices[i] except: print "Bad symmetry partner numbers. Try again." quit() if i > 9: copy = prefix + str(i) + "_" + str(x) + "_" + str(y) + "_" + str(z) else: copy = prefix + "0" + str(i) + "_" + str(x) + "_" + str(y) + "_" + str(z) cmd.copy(copy, object) newCoordsFrac = N.dot(fracCoords, op) stored.newCoords = N.dot(newCoordsFrac, fracToOrt) stored.j = 0 cmd.alter_state(1,copy,"x,y,z = stored.newCoords[stored.j][0], stored.newCoords[stored.j][1], stored.newCoords[stored.j][2]; stored.j = stored.j + 1") xSum=ySum=zSum=0.0 for k in range(len(newCoordsFrac)): xSum = newCoordsFrac[k][0] + xSum ySum = newCoordsFrac[k][1] + ySum zSum = newCoordsFrac[k][2] + zSum center = N.array([xSum,ySum,zSum]) center = center/len(stored.newCoords) shift = [-math.floor(center[0]) + cell[0], -math.floor(center[1]) + cell[1], -math.floor(center[2]) + cell[2]] cell_shift(copy,shift[0],shift[1],shift[2],0) ''' #COPIES COORDINATES OF EACH ATOM TO CORRESPONDING ONE IN GIVEN SYMMETRY PARTNER #cmd.alter_state(1, copy, "x,y,z = cmd.sym_partner([x,y,z], stored.tmpOp)") #MOVES SYMMETRY PARTNER TO PROPER LATTICE COORDINATES AND CORRECTS FOR NATIVE LATTICE POSITION ERROR #stored.xSum,stored.ySum,stored.zSum = 0.0,0.0,0.0 #atoms = cmd.count_atoms(copy) #cmd.iterate_state(1, copy, "stored.xSum = stored.xSum + x; stored.ySum = stored.ySum + y; stored.zSum = stored.zSum + z") #xMean = (stored.xSum / atoms) #yMean = (stored.ySum / atoms) #zMean = (stored.zSum / atoms) #xError, yError, zError = N.dot(N.array([xMean,yMean,zMean]), stored.ortToFrac) #dX,dY,dZ = -math.floor(xError) + cell[0], -math.floor(yError) + cell[1], -math.floor(zError) + cell[2] #cell_shift(copy,dX,dY,dZ, 0) ''' cmd.hide("everything", object) cmd.set_view(view)