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 draw_csv(spec_file=None, scale=1.0, width=2.0, centered=False, shift=None): """Draws points specified by a csv. Args: - spec_file - string path - scale - float - width - float - centered - boolean - shift - 3-value list or tuple """ if spec_file is None: print(draw_csv.__doc__) else: with open(spec_file, 'r') as file: pts = np.asarray([[float(n) for n in re.split(', *| *', l.strip())] for l in file.read().split('\n') if len(l) > 0]) if centered: pts = pts - pts[-1] dists = [np.linalg.norm(p-[0,0,0]) for p in pts] if shift is not None: pts += np.asarray(shift) * np.mean(dists) draw_points(pts, scale=scale, width=width) cmd.reset() cmd.set("depth_cue", 0)
def tview(pdbid: str): species = str(int(log.get_struct(pdbid)['taxid'].values[0])) l22chain = log.get_struct(pdbid).uL22.values[0] l4chain = log.get_struct(pdbid).uL4.values[0] l22_res = int(log.get_struct(pdbid).constrictionResidueL22_id.values[0]) l4_res = int(log.get_struct(pdbid).constrictionResidueL4_id.values[0]) # cmd.delete('all') pdbid = pdbid.upper() TUNNELS = os.getenv("TUNNELS") SCOOP_RADIUS = os.getenv("SCOOP_RADIUS") TUNNEL_SCRIPT = os.path.join(TUNNELS, species, pdbid, 'pymol', 'complex.py') inputstructpath = os.path.join( TUNNELS, species, pdbid, '{}_{}Ascoop.pdb'.format(pdbid, SCOOP_RADIUS)) csvpaths = os.path.join( TUNNELS, species, pdbid, 'csv', ) cmd.load(inputstructpath) cmd.color('gray', 'all') if not os.path.exists(TUNNEL_SCRIPT): print("TUNNEL SCRIPT NOT FOUND.") return cmd.run(TUNNEL_SCRIPT) cmd.hide('everything', 'Tunnels') cmd.show('mesh', 'Tunnels') # tunnels = os.listdir(csvpaths) # tunnumbers = map(lambda x: re.findall(r'\d+',x)[0], tunnels) # [cmd.delete(f'Tunnel{tunN}') if tunN not in choices else None for tunN in tunnumbers] # paint_tunnel(pdbid) sele_ptc(9606) # cmd.select('PTC', 'resi 2055 or resi 2056 or resi 2451 or resi 2452 or resi 2507 or resi 2506') # cmd.create('PTC',"PTC") # cmd.color('blue', 'PTC') cmd.select( 'ConstrictionSite', 'c. {} and resi {} or c. {} and resi {}'.format( l22chain, l22_res, l4chain, l4_res)) cmd.create('ConstrictionSite', "ConstrictionSite") cmd.show('everything', 'ConstrictionSite') cmd.color('magenta', 'ConstrictionSite') cmd.reset()
def check_file(self): while (self.watch): if (os.path.exists(self.file_name)): print "checking..." mtime = os.path.getmtime(self.file_name) if (mtime > self.mtime): self.mtime = mtime print "Re-loading %s" % self.file_name time.sleep(2) cmd.load(self.file_name, state=1) cmd.reset() cmd.hide(representation="lines", selection="all") cmd.show(representation="cartoon", selection="all") view = cmd.get_view() camera = list(view) camera[0] = -1 camera[1] = 0 camera[2] = 0 camera[3] = 0 camera[4] = 0 camera[5] = 1 camera[6] = 0 camera[7] = 1 camera[8] = 0 cmd.set_view(camera) time.sleep(self.time_wait)
def render_to_file(fname, top=True, side=True, vesicle=False, zoom_obj="pbcbox", zoom_distance=10): fname = os.path.splitext(fname)[0] cmd.reset() cmd.zoom(zoom_obj, zoom_distance) if vesicle: cmd.turn("z", -90) cmd.move("y", -50) if top: cmd.ray("2048") cmd.png("%s_top.png" % fname) if side: cmd.turn("x", -90) if vesicle: cmd.move("y", 150) cmd.ray("2048") cmd.png("%s_side.png" % fname) cmd.reset() cmd.zoom(zoom_obj, zoom_distance) if vesicle: cmd.turn("z", -90) cmd.move("y", -50)
def compare_sol(specFile, solCSV): if specFile.rfind('.csv') != -1: specPts = utils.readCSVPoints(specFile) elif specFile.rfind('.json') != -1: with open(specFile, 'r') as file: specPts = np.asarray(json.load(file)['coms']) else: print 'Unknown spec file format' solPts = utils.readCSVPoints(solCSV) # Centre both pts centredSpec = specPts - np.mean(specPts, axis=0) centredSol = solPts - np.mean(solPts, axis=0) # Draw specification draw_pts(centredSpec, color=[0.7,0,0]) # Equalise sample points specUpPts = utils.upsample(centredSpec, centredSol) draw_pts(specUpPts, color=[0.5,0.5,0]) # Find Kabsch rotation for solution -> spec R = Kabsch.kabsch(centredSpec, specUpPts) centredSpecR = np.dot(centredSpec, R) draw_pts(centredSpecR, color=[0,0.5,0.7]) cmd.reset() cmd.set("depth_cue", 0)
def draw_axes(length=500, width=2, font_size=20): """Draws the XYZ axes.""" draw_line( starting_point=(-length,0,0), line_vector=(length,0,0), color=(1,0,0), width=width, label='X', font_size=font_size); draw_line( starting_point=(0,-length,0), line_vector=(0,length,0), color=(0,1,0), width=width, label='Y', font_size=font_size); draw_line( starting_point=(0,0,-length), line_vector=(0,0,length), color=(0,0,1), width=width, label='Z', font_size=font_size); cmd.reset() cmd.set("depth_cue", 0)
def draw_axis(l=350, w=1): draw(-l, 0, 0, l, 0, 0, 1, 0, 0, w, label='X') draw(0, -l, 0, 0, l, 0, 0, 1, 0, w, label='Y') draw(0, 0, -l, 0, 0, l, 0, 0, 1, w, label='Z') cmd.reset() cmd.set("depth_cue", 0)
def draw_json(spec_file, scale=1.0, width=2.0, centered=False, shift=None): """Draws points specified by a json. Args: - spec_file - string path - scale - float - width - float - centered - boolean - shift - 3-value list or tuple """ if spec_file is None: print(draw_csv.__doc__) else: with open(spec_file, 'r') as file: pts = np.asarray(json.load(file)['coms']) if centered: pts = pts - pts[-1] dists = [np.linalg.norm(p-[0,0,0]) for p in pts] if shift is not None: pts += np.asarray(shift) * np.mean(dists) draw_points(pts, scale=scale, width=width) cmd.reset() cmd.set("depth_cue", 0)
def reset(options): cmd.reset() cmd.delete('all') cmd.set('bg_rgb', options['background color']) if options['light-colored background']: cmd.set('depth_cue', 0) cmd.set('ray_trace_fog', 0)
def run_build(self): # callback for the "Build" button cmd.cache("clear") cmd.reset() seconds_init = time.time() self.runNumber += 1 # get form data prefixName = self.form.output_filename_prefix.text() assemblyType = self.form.input_type.currentText() print('Assembly is: {}'.format(assemblyType)) print('Building model...') # center protein if needed self.preOriProt() # delete old model cmd.delete(self.modelName) # executions depends on the assembly type if assemblyType == "detergent": # execute detergent builder self.modelName = builderDetergent(self.protName, self.membName, prefixName, self.runNumber) elif assemblyType == "salipro": # execute salipro builder rotAng = self.form.input_rotAng.value() numScaffoldCopies = self.form.input_copies.value() print('Number of scaffold copies: {}'.format(numScaffoldCopies)) if self.buildMemb: self.membName = builderMembrane(self.membName) self.form.input_filename_lip.setText(self.membName) self.modelName = builderSalipro(self.protName, self.scafName, self.membName, prefixName, self.runNumber, numScaffoldCopies, rotAng) elif assemblyType == "nanodisc": # execute nanodisc builder # build bilayer if check box is activated if self.buildMemb: self.membName = builderMembrane(self.membName) self.form.input_filename_lip.setText(self.membName) # execute builder self.modelName = builderNanodisc(self.protName, self.membName, self.scafName, prefixName, self.runNumber) elif assemblyType == "bilayer": # execute detergent builder self.membName = builderMembrane(self.membName, self.runNumber) self.form.input_filename_lip.setText(self.membName) elif assemblyType == "bicelle": # execute bicelle builder # build bilayer if check box is activated if self.buildMemb: self.membName = builderMembrane(self.membName, self.runNumber) self.form.input_filename_lip.setText(self.membName) # execute builder self.modelName = builderBicelle(self.protName, self.membName, self.scafName, prefixName, self.runNumber) refresh() print("Model name is {}".format(self.modelName)) seconds_tmp = time.time() t = int((seconds_tmp - seconds_init)) print("{:d} seconds consumed.".format(t))
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 colour_by_heatmap(colour_data, structure_path, molecule_name="protein", output_path="colour_by_heatmap", view=None): ''' DESCRIPTION Colours PDB structure by colour map data. output_filepath >>> colour_by_heatmap(df, structure_filepath="xxxx.pdb", mol_name="protein", out_dir='.') ''' # if not (isinstance(colour_data, pd.core.series.Series) or isinstance(colour_data, dict)): # print(''' # Passed data must be either dictionary or Pandas Series object. # Key = residue number # Value = PyMOL hex code # ''') # return None cmd.load(structure_path, object=molecule_name) # Set view if view == None: cmd.reset() cmd.orient() else: cmd.set_view(view) cmd.viewport(width=1200, height=1200) cmd.zoom(complete=1) cmd.set('cartoon_discrete_colors', 1) cmd.set('sphere_scale', 1) cmd.show_as('cartoon', molecule_name) cmd.color('white', molecule_name) # Iterate over the alpha-carbons # residue_numbers = [] # cmd.iterate('{} and name CA'.format(molecule_name) , 'residue_numbers.append(resi)') # Colour the structure for residue_number in colour_data.columns: # print(colour_data[residue_number].item()) cmd.color(colour_data[residue_number].item(), '{0} and resi {1}'.format(molecule_name, residue_number)) png_out_path = output_path + ".png" pse_out_path = output_path + ".pse" cmd.save(pse_out_path) cmd.set('ray_opaque_background', 0) cmd.png(png_out_path, width=1200, height=1200, ray=1, quiet=0)
def loadSinglePdbsIntoPymol(self, singlesDir): # Load all singles utils.die( singlesDir is None, 'Must provide singles directory when attempting to display in PyMol!' ) for singlePdb in glob.glob(singlesDir + '/*.pdb'): cmd.load(singlePdb) cmd.hide('everything', 'all') cmd.reset()
def orient_origin(selection): shift_to_center(selection) cmd.orient(selection) cv = list(cmd.get_view(quiet=1)) #cmd.origin(selection, position=origin1) cmd.transform_selection(selection, cv[0:3] + [0.0] + cv[3:6] + [0.0] + cv[6:9] + [0.0] + cv[12:15] + [1.0], transpose=1) cmd.reset()
def sele_ptc(spec: int): # cmd.color('gray','all') if spec in [83333, 562]: cmd.select( 'PTC', 'resi 2055 or resi 2056 or resi 2451 or resi 2452 or resi 2507 or resi 2506' ) if spec in [9606]: cmd.select('PTC', 'resi 4452') cmd.create('PTC', "PTC") cmd.color('blue', 'PTC') cmd.reset()
def chain_align_save(*args, **kwargs): args = [ast.literal_eval(kvpair) for kvpair in args] for pair in args: cmd.fetch(str.lower(pair[0])) create_subchain_object(pair[0], pair[1]) cmd.delete(str.lower(pair[0])) for mobile in [ '{}.{}'.format(model, chain) for (model, chain) in args ][1:]: cmd.super(mobile, "{}.{}".format(args[0][0], args[0][1]),reset=1,transform=1,quiet=0) cmd.reset() cmd.save('alignment.cif')
def draw_json(specFile, scale=1.0, width=2.0, centred=False, shift=None): with open(specFile, 'r') as file: pts = np.asarray(json.load(file)['coms']) if centred: pts = pts - pts[-1] dists = [np.linalg.norm(p - [0, 0, 0]) for p in pts] if shift is not None: pts += np.asarray(shift) * np.mean(dists) draw_pts(pts, scale=scale, width=width) cmd.reset() cmd.set("depth_cue", 0)
def draw_csv(specFile, scale=1.0, width=2.0, centred=False, shift=None): with open(specFile, 'r') as file: pts = np.asarray([[float(n) for n in re.split(', *| *', l.strip())] for l in file.read().split('\n') if len(l) > 0]) if centred: pts = pts - pts[-1] dists = [np.linalg.norm(p - [0, 0, 0]) for p in pts] if shift is not None: pts += np.asarray(shift) * np.mean(dists) draw_pts(pts, scale=scale, width=width) cmd.reset() cmd.set("depth_cue", 0)
def testReset(self): # view v = cmd.get_view() cmd.turn('x', 10) cmd.move('y', 10) self.assertNotEqual(v, cmd.get_view()) cmd.reset() self.assertEqual(v, cmd.get_view()) # object cmd.pseudoatom("m1") x = cmd.get_object_matrix("m1") cmd.translate([1, 2, 3], object="m1") self.assertNotEqual(x, cmd.get_object_matrix("m1")) cmd.reset("m1") self.assertEqual(x, cmd.get_object_matrix("m1"))
def testReset(self): # view v = cmd.get_view() cmd.turn('x', 10) cmd.move('y', 10) self.assertNotEqual(v, cmd.get_view()) cmd.reset() self.assertEqual(v, cmd.get_view()) # object cmd.pseudoatom("m1") x = cmd.get_object_matrix("m1") cmd.translate([1,2,3], object="m1") self.assertNotEqual(x, cmd.get_object_matrix("m1")) cmd.reset("m1") self.assertEqual(x, cmd.get_object_matrix("m1"))
def display_graphkernel(pdb_id, pdb_path): ''' ''' # Load PDB cmd.bg_color('white') cmd.load(pdb_path + pdb_id[:-2] + '.pdb') cmd.split_chains(pdb_id[:-2]) for name in cmd.get_names('objects', 0, '(all)'): if not name.endswith(pdb_id[-1].upper()) and name.startswith( pdb_id[:4]): cmd.delete(name) else: zero_residues(name) cmd.reset() pdb_id2 = pdb_id + 'copy' cmd.create(pdb_id2, pdb_id) cmd.hide('everything', pdb_id) cmd.show_as('lines', pdb_id + ' and (name ca or name c or name n)') cmd.set('line_width', 5) cmd.set_bond('line_width', 5, pdb_id + ' and (name ca or name c or name n)') cmd.show('spheres', pdb_id + ' and name ca') cmd.set('sphere_transparency', 0.0, pdb_id + ' and name ca') cmd.set('sphere_scale', 0.5, pdb_id + ' and name ca') cmd.hide('everything', pdb_id2) cmd.show('spheres', pdb_id2 + ' and name ca') cmd.set('sphere_transparency', 0.8, pdb_id2 + ' and name ca') cmd.set('sphere_scale', code2[elem], elem + '&' + selection) #cmd.set('sphere_scale', 2, pdb_id2 + ' and name ca') data = cmd.get_coords(selection=pdb_id + ' and name ca', state=1) j = 55 cmd.set('dash_width', 1.0) cmd.set('dash_color', 'marine') for i in range(len(data)): cmd.distance('d' + str(i) + str(j), pdb_id2 + ' and name ca and res ' + str(i), pdb_id2 + ' and name ca and res ' + str(j)) cmd.hide('labels', 'd' + str(i) + str(j)) resicolor(pdb_id) resicolor(pdb_id) resicolor(pdb_id2, True)
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 stucture_attribution(pdb_id, attributions_path, pdb_path, flag=False): ''' ''' data = np.load(attributions_path) attributions = data['data'] kernels = data['kernels'] labels = data['labels'] offsets = data['offsets'] ind = np.where(labels == pdb_id) #attribution = attributions[ind][0][:,-1] if flag: a_ = data["all_"][0] a_[a_ <= 0] = 0.0 attribution = data['all_'][0] + data['all_'][1] attribution[attribution <= 0] = 0.0 attribution = a_ * attribution else: a_ = data["all_"][1] a_[a_ <= 0] = 0.0 attribution = data['all_'][0] + data['all_'][1] attribution[attribution <= 0] = 0.0 attribution = a_ * attribution # Load PDB cmd.load(pdb_path + pdb_id[:-2] + '.pdb') cmd.split_chains(pdb_id[:-2]) for name in cmd.get_names('objects', 0, '(all)'): if not name.endswith(pdb_id[-1].upper()) and name.startswith( pdb_id[:4]): cmd.delete(name) else: zero_residues(name) cmd.reset() cmd.color('white', pdb_id) for i, _ in enumerate(attribution): #if flag: _ = _ *-1 cmd.select('toBecolored', pdb_id + ' and res ' + str(i + offsets[ind][0])) cmd.set_color('saliency' + str(i) + pdb_id, list(cmap(norm(_)))[:3]) #else: cmd.set_color('saliency'+str(i)+pdb_id, list(cmap2(norm(_)))[:3]) cmd.color('saliency' + str(i) + pdb_id, 'toBecolored') cmd.select('selected', pdb_id) #cmd.show('mesh', 'selected') #cmd.show('sticks', 'selected') cmd.deselect()
def gen(self, chainLen): nodes = [] # Step 1: Pick starting single from non-terminal nodes nNonTerms = len(self.nonTerms) nodes.append(self.nonTerms[random.randint(0, nNonTerms - 1)]) # Shape (array of CoMs) starts from origin coms = numpy.zeros(shape=(1, 3), dtype='float64') # Main structure generation loop # Keep adding a next node from any node until either # specified length is reached for i in xrange(0, chainLen - 1): lastNode = nodes[i] newNode = self.chooseNextNode(nodes, coms) nodes.append(newNode) rel = self.pairsData[lastNode][newNode] coms = numpy.append(coms, [rel['comB']], axis=0) coms = numpy.dot(coms, numpy.asarray(rel['rot'])) + rel['tran'] # Move display/print/postprocess to after construction succeeded # Makes generation faster motherPdb, _ = ElfinUtils.makePdbFromNodes(self.xDB, nodes, elfinDir + self.doublesDir, elfinDir + self.singlesDir) if haveCmd: tmpFile = './elfin.tmp' ElfinUtils.savePdb(motherPdb, tmpFile) cmd.load(tmpFile, str(i) + '-' + pairName) cmd.hide('everything', 'all') cmd.show('cartoon', 'all') cmd.reset() cmd.util.cbc() self.bmarks.append({ 'pdb': motherPdb, 'data': OrderedDict([('nodes', nodes), ('coms', coms.tolist())]) })
def kernels(pdb_id, data_path, pdb_path, flag=False): ''' ''' data = np.load(data_path) kernels = data['kernels'] labels = data['labels'] offsets = data['offsets'] ind = np.where(labels == pdb_id) kernels = kernels[ind][0][0] # Load PDB cmd.load(pdb_path + pdb_id[:-2] + '.pdb') cmd.split_chains(pdb_id[:-2]) for name in cmd.get_names('objects', 0, '(all)'): if not name.endswith(pdb_id[-1].upper()) and name.startswith( pdb_id[:4]): cmd.delete(name) else: zero_residues(name) cmd.reset() pdb_id2 = pdb_id + 'kernel' cmd.create(pdb_id2, pdb_id) cmd.delete(pdb_id) ''' cmd.hide('everything',pdb_id) cmd.show_as('lines', pdb_id + ' and (name ca or name c or name n)') cmd.set('line_width', 5) cmd.set_bond('line_width', 5, pdb_id + ' and (name ca or name c or name n)') cmd.show('spheres', pdb_id + ' and name ca') cmd.set('sphere_transparency', 0.0, pdb_id + ' and name ca') cmd.set('sphere_scale', 0.5, pdb_id + ' and name ca') ''' cmd.hide('everything', pdb_id2) cmd.show('spheres', pdb_id2 + ' and name ca') cmd.set('sphere_transparency', 0.9, pdb_id2 + ' and name ca') for i, _ in enumerate(kernels): print(_) cmd.set( 'sphere_scale', _ / (1.7 * 2), pdb_id2 + ' and res ' + str(i + offsets[ind][0]) + ' and name ca') cmd.deselect()
def compare_solutions(spec_file=None, sol_csv_file=None): """ Compares solution center-of-mass points again the specification. Args: - spec_file - a csv or json file string path - sol_csv_file - a csv file string path """ if spec_file is None or sol_csv_file is None: print(compare_solutions.__doc__) else: if spec_file.rfind('.csv') != -1: spec_pts = elfinpy.read_csv_points(spec_file) elif spec_file.rfind('.json') != -1: with open(spec_file, 'r') as file: spec_pts = np.asarray(json.load(file)['coms']) else: print 'Unknown spec file format' sol_pts = elfinpy.read_csv_points(sol_csv_file) # Centre both pts centred_spec = spec_pts - np.mean(spec_pts, axis=0) centred_sol = sol_pts - np.mean(sol_pts, axis=0) # Draw specification draw_pts(centred_spec, color=[0.7, 0, 0]) # Equalise sample points specUpPts = elfinpy.upsample(centred_spec, centred_sol) draw_pts(specUpPts, color=[0.5, 0.5, 0]) # Find Kabsch rotation for solution -> spec R = kabsch.run_kabsch(centred_spec, specUpPts) centredSpecR = np.dot(centred_spec, R) draw_pts(centredSpecR, color=[0, 0.5, 0.7]) cmd.reset() cmd.set("depth_cue", 0)
def structure_attribution(self, pdb_id, flag=False): # Load Attribution data = np.load(self.attribution_path, allow_pickle=True) attributions = data['data'] offsets = data['offsets'] labels = data['labels'] ind = np.where(labels == pdb_id) attribution = attributions[ind][0][:, -1] cmd.bg_color('white') cmd.load(self.data_path + pdb_id[:-2] + '.pdb') cmd.split_chains() for name in cmd.get_names('objects', 0, '(all)'): if not name.endswith(pdb_id[-1].upper()): cmd.delete(name) else: zero_residues(name) cmd.reset() cmd.color('white', pdb_id) for i, _ in enumerate(attribution): cmd.select('toBecolored', 'res ' + str(i + offsets[ind][0])) cmd.set_color('saliency' + str(i), list(cmap(norm(_)))[:3]) cmd.color('saliency' + str(i), 'toBecolored') cmd.select('selected', 'chain ' + pdb_id[-1].upper()) #cmd.show('mesh', 'selected') cmd.deselect() cmd.save(self.output_path + pdb_id + '.pse') return self.output_path + pdb_id + '.pse' ############################################################# # pdb_id = '4q9z_a' # attributions_path = 'Output/Kinases/seed1/attributions.npz' # data_path = 'pdb_extractor/Kinases/PDB/' # cmd.reinitialize() # cmd.bg_color('black') # sA = StructureAttribution(attributions_path,data_path) # sA.structure_attribution(pdb_id)
def matrix_to_ttt(names, reverse=0, state=-1, quiet=1): ''' DESCRIPTION Objects can have state matrices and view (frames) matrices. This function takes the total matrix and stores it either as view matrix or as state matrix (reverse=1). For movie frames, movie_auto_store must be set. ''' from . import querying reverse, state, quiet = int(reverse), int(state), int(quiet) ostate = state for object in cmd.get_object_list('(' + names + ')'): if ostate < 1: state = querying.get_object_state(object) matrix = cmd.get_object_matrix(object, state) cmd.matrix_reset(object) if reverse: cmd.reset(object) cmd.transform_object(object, matrix, homogenous=1) else: cmd.set_object_ttt(object, matrix)
def matrix_to_ttt(names, reverse=0, state=-1, quiet=1): ''' DESCRIPTION Objects can have state matrices and view (frames) matrices. This function takes the total matrix and stores it either as view matrix or as state matrix (reverse=1). For movie frames, movie_auto_store must be set. ''' from . import querying reverse, state, quiet = int(reverse), int(state), int(quiet) ostate = state for object in cmd.get_object_list('(' + names + ')'): if ostate < 1: state = querying.get_object_state(object) matrix = cmd.get_object_matrix(object, state) for i in range(cmd.count_states(object)): cmd.matrix_reset(object, i + 1) if reverse: cmd.reset(object) cmd.transform_object(object, matrix, homogenous=1) else: cmd.set_object_ttt(object, matrix)
#__main__.pymol_argv = [ 'pymol', '-qc'] #import pymol #pymol.finish_launching() # DEBUG: ANALYSIS PATH IS HARD-CODED FOR NOW source_directory = 'experiments' reference_pdbfile = 'setup/systems/Abl-STI/complex.pdb' phase = 'complex' replica = 0 # replica index to render #replica = 15 # replica index to render # Load PDB file. cmd.rewind() cmd.delete('all') cmd.reset() cmd.load(reference_pdbfile, 'complex') cmd.remove('resn WAT') # remove waters cmd.select('receptor', '(not resn MOL) and (not resn WAT) and (not hydrogen)') cmd.select('ligand', 'resn MOL and not hydrogen') cmd.select('ions', 'resn Na\+ or resn Cl\-') cmd.deselect() cmd.hide('all') cmd.show('cartoon', 'receptor') cmd.show('spheres', 'ligand') cmd.show('spheres', 'ions') util.cbay('ligand') cmd.color('green', 'receptor') # speed up builds cmd.set('defer_builds_mode', 3)
__main__.pymol_argv = [ 'pymol', '-qc'] import pymol pymol.finish_launching() # DEBUG: ANALYSIS PATH IS HARD-CODED FOR NOW source_directory = 'output' reference_pdbfile = 'setup/complex-implicit-initial.pdb' phase = 'complex-implicit' replica = 0 # replica index to render #replica = 15 # replica index to render # Load PDB file. cmd.rewind() cmd.delete('all') cmd.reset() cmd.load(reference_pdbfile, 'complex') cmd.select('receptor', 'not chain C and not hydrogen') cmd.select('ligand', 'chain C and not hydrogen') cmd.deselect() cmd.hide('all') cmd.show('cartoon', 'receptor') cmd.show('sticks', 'ligand') util.cbay('ligand') cmd.color('green', 'receptor') # speed up builds cmd.set('defer_builds_mode', 3) cmd.set('cache_frames', 0) model = cmd.get_model('complex')
def growProtein(): cmd.mstop() cmd.mclear() cmd.mset() glb.update() objects = cmd.get_names('all') if 'protein' in objects: cmd.bg_color('black') # create the objects to be used in this movie cmd.create('helix', 'ss h and protein') cmd.create('sheets', 'ss s and protein') cmd.create('surface', objects[0]) cmd.mset('1', '1400') # dna and rna will be represented as sticks # to make them stand out from the protein if 'dna' in objects: glb.procolor('dna','sticks','cpk',None) if 'rna' in objects: glb.procolor('rna','sticks','cpk',None) # coloring the protein and secondary structures cmd.color('white', 'protein') cmd.color('purple', 'helix') cmd.color('teal', 'sheets') cmd.cartoon('loop', 'protein') cmd.cartoon('automatic', 'helix') cmd.cartoon('automatic', 'sheets') cmd.hide('all') cmd.show('cartoon', 'protein') #cmd.mdo(1,'hide cartoon, helix; hide cartoon, sheets;') cmd.util.mrock('2', '200', '90', '1', '1') cmd.mdo(201,'show cartoon, helix;') cmd.util.mrock('202', '400', '90', '1', '1') cmd.mdo(401,'show cartoon, sheets;') cmd.util.mrock('402', '600', '90', '1', '1') if 'ligands' in objects: cmd.color('hotpink', 'ligands') cmd.mdo(600, 'show spheres, ligands; show sticks, ligands;'+ ' set sphere_transparency = 0.5, ligands;') cmd.util.mroll('601', '800', '1', axis = "x") cmd.color('blue', 'surface') cmd.mview('store', '800') cmd.turn('z', 180) cmd.mview('store' , '1000') cmd.turn('z', 180) cmd.mdo(800, 'show surface, surface; '+ 'set transparency = 0.8, surface;') cmd.mdo(850,'set transparency = 0.7, surface;') cmd.mdo(900,'set transparency = 0.6, surface;') cmd.mdo(950,'set transparency = 0.5, surface;') cmd.mdo(1000,'set transparency = 0.4, surface;') cmd.mdo(1050,'set transparency = 0.3, surface;') cmd.mdo(1100,'set transparency = 0.2, surface;') cmd.mdo(1150,'set transparency = 0.1, surface;') cmd.mdo(1200,'set transparency = 0.0, surface;') cmd.mview('store', '1200') cmd.util.mrock('1201', '1399', '180', '1', '1') cmd.hide('everything', 'surface') cmd.hide('everything', 'helix') cmd.hide('everything', 'sheets') cmd.reset() cmd.orient() cmd.mdo(1400,'hide everything, all; show cartoon, protein;') cmd.mdo(1400,'mstop') cmd.mview('interpolate') cmd.rewind()
def display_graphconv(pdb_id, pdb_path): ''' ''' cmd.bg_color('white') cmd.load(pdb_path + pdb_id[:-2] + '.pdb') cmd.split_chains(pdb_id[:-2]) for name in cmd.get_names('objects', 0, '(all)'): if not name.endswith(pdb_id[-1].upper()) and name.startswith( pdb_id[:4]): cmd.delete(name) else: zero_residues(name) cmd.reset() pdb_id2 = pdb_id + 'copy' cmd.create(pdb_id2, pdb_id) cmd.color('white', pdb_id) cmd.hide('everything', pdb_id) cmd.show('spheres', pdb_id + ' and name ca') cmd.set('sphere_transparency', 0.0, pdb_id + ' and name ca') cmd.set('sphere_scale', 0.5, pdb_id + ' and name ca') data = cmd.get_coords(selection=pdb_id + ' and name ca', state=1) j = 55 cmd.set('dash_width', 1.0) cmd.set('dash_color', 'marine') data = np.random.uniform(0, 0.25, len(data)) for i in range(len(data)): cmd.distance('d' + str(i) + str(j), pdb_id + ' and name ca and res ' + str(i), pdb_id + ' and name ca and res ' + str(j)) cmd.hide('labels', 'd' + str(i) + str(j)) cmd.select('toBecolored', pdb_id + ' and name ca and res ' + str(i)) if i == j: cmd.set_color('saliency' + str(i) + pdb_id, list(cmap(norm(1)))[:3]) else: cmd.set_color('saliency' + str(i) + pdb_id, list(cmap(norm(data[i])))[:3]) cmd.color('saliency' + str(i) + pdb_id, 'toBecolored') cmd.color('white', pdb_id2) cmd.hide('everything', pdb_id2) cmd.show('spheres', pdb_id2 + ' and name ca') cmd.set('sphere_transparency', 0.0, pdb_id2 + ' and name ca') cmd.set('sphere_scale', 0.5, pdb_id2 + ' and name ca') j = 55 cmd.set('dash_width', 1.0) cmd.set('dash_color', 'marine') #data = np.random.uniform(0,0.25,len(data)) for i in range(len(data)): cmd.distance('d' + str(i) + str(j), pdb_id2 + ' and name ca and res ' + str(i), pdb_id2 + ' and name ca and res ' + str(j)) cmd.hide('labels', 'd' + str(i) + str(j)) cmd.select('toBecolored', pdb_id2 + ' and name ca and res ' + str(i)) if i == j: cmd.set_color('saliency' + str(i) + pdb_id2, list(cmap(norm(0)))[:3]) else: cmd.set_color('saliency' + str(i) + pdb_id2, list(cmap(norm(data[i])))[:3]) cmd.color('saliency' + str(i) + pdb_id2, 'toBecolored')
def optAlign( sel1, sel2 ): """ optAlign performs the Kabsch alignment algorithm upon the alpha-carbons of two selections. Example: optAlign MOL1 and i. 20-40, MOL2 and i. 102-122 Example 2: optAlign 1GGZ and i. 4-146 and n. CA, 1CLL and i. 4-146 and n. CA Two RMSDs are returned. One comes from the Kabsch algorithm and the other from PyMol based upon your selections. By default, this program will optimally align the ALPHA CARBONS of the selections provided. To turn off this feature remove the lines between the commented "REMOVE ALPHA CARBONS" below. @param sel1: First PyMol selection with N-atoms @param sel2: Second PyMol selection with N-atoms """ cmd.reset() # make the lists for holding coordinates # partial lists stored.sel1 = [] stored.sel2 = [] # full lists stored.mol1 = [] stored.mol2 = [] # now put the coordinates into a list # partials # -- REMOVE ALPHA CARBONS sel1 = sel1 + " and N. CA" sel2 = sel2 + " and N. CA" # -- REMOVE ALPHA CARBONS cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])") cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])") # full molecule mol1 = cmd.identify(sel1,1)[0][0] mol2 = cmd.identify(sel2,1)[0][0] cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])") cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])") K = kabsch() U, T1, T2, RMSD, c1, c2 = K.align(stored.sel1, stored.sel2, []) stored.mol2 = map(lambda v:[T2[0]+((v[0]*U[0][0])+(v[1]*U[1][0])+(v[2]*U[2][0])),T2[1]+((v[0]*U[0][1])+(v[1]*U[1][1])+(v[2]*U[2][1])),T2[2]+((v[0]*U[0][2])+(v[1]*U[1][2])+(v[2]*U[2][2]))],stored.mol2) #stored.mol1 = map(lambda v:[ v[0]+T1[0], v[1]+T1[1], v[2]+T1[2] ], stored.mol1) stored.mol1 = map(lambda v:[ v[0]+T1[0], v[1]+T1[1], v[2]+T1[2] ], stored.mol1) cmd.alter_state(1,mol1,"(x,y,z)=stored.mol1.pop(0)") cmd.alter_state(1,mol2,"(x,y,z)=stored.mol2.pop(0)") cmd.alter( 'all',"segi=''") cmd.alter('all', "chain=''") print "RMSD=%f" % cmd.rms_cur(sel1, sel2) print "MY RMSD=%f" % RMSD cmd.hide('everything') cmd.show('ribbon', sel1 + ' or ' + sel2) cmd.color('gray70', mol1 ) cmd.color('paleyellow', mol2 ) cmd.color('red', 'visible') cmd.show('ribbon', 'not visible') cmd.center('visible') cmd.orient() cmd.zoom('visible')
def reps(self,cleanup=0): rep_list = [ "lines","sticks","spheres","surface","mesh","dots","ribbon","cartoon" ] try: if not cleanup: cmd.disable() cmd.set("suspend_updates",1,quiet=1) cmd.load("$PYMOL_DATA/demo/pept.pdb","rep1") cmd.alter("rep1///1-5+8-13/","ss='S'") cmd.cartoon("auto") cmd.hide("everything","rep1") for a in range(2,9): cmd.create("rep%d"%a,"rep1") for x, y in enumerate(rep_list, 1): cmd.show(x, "rep%d" % y) cmd.reset() cmd.zoom("rep1",24) util.cbay("rep2") util.cbac("rep3") util.cbas("rep4") util.cbab("rep5") util.cbaw("rep6") util.cbay("rep8") cmd.set("suspend_updates",0,quiet=1) scale=0.5 for b in range(1,20): cmd.set("suspend_updates",0,quiet=1) cmd.refresh() cmd.set("suspend_updates",1,quiet=1) xt=-3.2 yt=1.6 for a in range(1,5): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 yt=-yt xt=-3.2 for a in range(5,9): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 for a in range(1,9): cmd.origin("rep%d"%a,object="rep%d"%a) cmd.mset("1") st = ' '.join(map(lambda x,y:"rotate angle=-3,object=rep%d,axis=%s;"%(x,y),list(range(1,9)), ['x','y','x','y','x','y','x','y'])) cmd.mdo(1,st) cmd.set("suspend_updates",0,quiet=1) cmd.mplay() cgo = [] axes = [[4.5,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]] c = 1 for a in rep_list: ext = cmd.get_extent("rep%d"%c) pos = [(ext[0][0]+ext[1][0])/2, (ext[0][1]+ext[1][1])/2+14, (ext[0][2]+ext[1][2])/2] c = c + 1 pos[0]=pos[0]-(measure_text(plain,a,axes)/2) wire_text(cgo,plain,pos,a,axes) cmd.set("cgo_line_width",1.5) cmd.set("auto_zoom",0) cmd.load_cgo(cgo,'reps') cmd.set("auto_zoom",1) else: cmd.delete("rep*") cmd.mset() cmd.mstop() except: traceback.print_exc()
def align_to_axis(obj, atom_sel=None, axis="y", axes_dict=AXES): """ DESCRIPTION Align protein to arbitrary axis with atom selection at origin. USAGE align_to_axis obj [, atom_sel [, axis ]] NOTES "atom_sel" must contain a single atom in "obj". If not specified, defaults to N-terminal nitrogen. "axis" must be either x, y, or z, or coordinates for an axis (e.g. [1, 2, 3]). EXAMPLES # align to y-axis with N-terminus at origin align_to_axis obj # align to x-axis align_to_axis obj, axis=x # align to y-axis with C-terminus at origin cmd.select("cterm", "index %d:%d" % cmd.get_model("obj and not het", 1).get_residues()[-1]) align_to_axis obj, cterm and n. c """ if atom_sel is None: stored.list = [] cmd.iterate("%s and not hetatm and n. n" % obj, "stored.list.append(resi)") atom_sel = "%s and resi %s and n. n" % (obj, stored.list[0]) if axis.lower() in axes_dict: target_vect = np.asarray(axes_dict[axis], dtype=np.float) else: try: target_vect = np.asarray(ast.literal_eval(axis), dtype=np.float) except (ValueError, TypeError): print ("AlignToAxisError: Provided axis is of unknown format: %s." % (repr(axis))) return False target_vect = as_unit(target_vect) cmd.reset() origin_coord_list = cmd.get_model(atom_sel, 1).get_coord_list() if len(origin_coord_list) != 1: print ( "AlignToAxisError: atom selection should contain exactly 1 atom. Selection contains %d atoms." % (len(origin_coord_list)) ) return False origin_coord = np.asarray(origin_coord_list[0], dtype=np.float) com_coord = np.asarray(get_com(obj), dtype=np.float) com_vect = com_coord - origin_coord pre_trans_vect = -com_coord post_trans_vect = target_vect * np.linalg.norm(com_vect) rot_matrix = create_rot_matrix(com_vect, target_vect) trans_matrix = create_trans_matrix(rot_matrix, pre_trans_vect, post_trans_vect) cmd.transform_selection(obj, trans_matrix.flatten().tolist(), homogenous=0) cmd.reset()
def optAlign( sel1, sel2 ): """ optAlign performs the Kabsch alignment algorithm upon the alpha-carbons of two selections. Example: optAlign MOL1 and i. 20-40, MOL2 and i. 102-122 Example 2: optAlign 1GGZ and i. 4-146 and n. CA, 1CLL and i. 4-146 and n. CA Two RMSDs are returned. One comes from the Kabsch algorithm and the other from PyMol based upon your selections. By default, this program will optimally align the ALPHA CARBONS of the selections provided. To turn off this feature remove the lines between the commented "REMOVE ALPHA CARBONS" below. @param sel1: First PyMol selection with N-atoms @param sel2: Second PyMol selection with N-atoms """ cmd.reset() # make the lists for holding coordinates # partial lists stored.sel1 = [] stored.sel2 = [] # full lists stored.mol1 = [] stored.mol2 = [] # -- CUT HERE sel1 += " and N. CA" sel2 += " and N. CA" # -- CUT HERE # Get the selected coordinates. We # align these coords. cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])") cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])") # get molecule name mol1 = cmd.identify(sel1,1)[0][0] mol2 = cmd.identify(sel2,1)[0][0] # Get all molecule coords. We do this because # we have to rotate the whole molcule, not just # the aligned selection cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])") cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])") # check for consistency assert len(stored.sel1) == len(stored.sel2) L = len(stored.sel1) assert L > 0 # must alway center the two proteins to avoid # affine transformations. Center the two proteins # to their selections. COM1 = numpy.sum(stored.sel1,axis=0) / float(L) COM2 = numpy.sum(stored.sel2,axis=0) / float(L) stored.sel1 -= COM1 stored.sel2 -= COM2 # Initial residual, see Kabsch. E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0) # # This beautiful step provides the answer. V and Wt are the orthonormal # bases that when multiplied by each other give us the rotation matrix, U. # S, (Sigma, from SVD) provides us with the error! Isn't SVD great! V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1)) # we already have our solution, in the results from SVD. # we just need to check for reflections and then produce # the rotation. V and Wt are orthonormal, so their det's # are +/-1. reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt)))) if reflect == -1.0: S[-1] = -S[-1] V[:,-1] = -V[:,-1] RMSD = E0 - (2.0 * sum(S)) RMSD = numpy.sqrt(abs(RMSD / L)) #U is simply V*Wt U = numpy.dot(V, Wt) # rotate and translate the molecule stored.sel2 = numpy.dot((stored.mol2 - COM2), U) stored.sel2 = stored.sel2.tolist() # center the molecule stored.sel1 = stored.mol1 - COM1 stored.sel1 = stored.sel1.tolist() # let PyMol know about the changes to the coordinates cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)") cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)") print "RMSD=%f" % RMSD # make the alignment OBVIOUS cmd.hide('everything') cmd.show('ribbon', sel1 + ' or ' + sel2) cmd.color('gray70', mol1 ) cmd.color('paleyellow', mol2 ) cmd.color('red', 'visible') cmd.show('ribbon', 'not visible') cmd.center('visible') cmd.orient() cmd.zoom('visible')