def testIsosurface(self): cmd.viewport(100, 100) cmd.fragment('gly', 'm1') cmd.set('gaussian_b_floor', 30) cmd.set('mesh_width', 5) cmd.map_new('map') cmd.delete('m1') # make mesh cmd.isosurface('surface', 'map') cmd.isosurface('surface', 'map', source_state=1, state=-2) ## check mesh presence by color meshcolor = 'red' cmd.color(meshcolor, 'surface') self.ambientOnly() self.assertImageHasColor(meshcolor) cmd.frame(2) self.assertEqual(cmd.get_state(), 2) self.assertImageHasColor(meshcolor) with testing.mktemp('.pse') as filename: cmd.save(filename) cmd.delete('*') self.assertImageHasNotColor(meshcolor) cmd.load(filename) self.assertImageHasColor(meshcolor) cmd.frame(2) self.assertEqual(cmd.get_state(), 2) self.assertImageHasColor(meshcolor)
def addSele2Host(self): try: stateNo = cmd.get_state() cmd.create("host", "%host or sele", stateNo) except: stateNo = cmd.get_state() cmd.create("host", "sele", stateNo)
def addSele2Guest(self): try: stateNo = cmd.get_state() cmd.create("guest", "%guest or sele", stateNo) except: stateNo = cmd.get_state() cmd.create("guest", "sele", stateNo)
def testScene(self): cmd.fragment('ala', 'm1') cmd.fragment('gly', 'm2') cmd.create('m2', 'm2', 1, 2) cmd.create('m2', 'm2', 1, 3) cmd.create('m2', 'm2', 1, 4) # store cmd.show_as('sticks', 'm1') cmd.show_as('spheres', 'm2') cmd.color('blue', 'm1') cmd.color('yellow', 'm2') view_001 = cmd.get_view() cmd.scene('new', 'store', 'hello world') # store cmd.frame(3) cmd.show_as('lines') cmd.color('red') cmd.turn('x', 45) view_002 = cmd.get_view() cmd.scene('new', 'store') # we actually don't know the auto naming counter # self.assertEqual(cmd.get_scene_list(), ['001', '002']) names = cmd.get_scene_list() # recall cmd.scene(names[0], 'recall', animate=0) self.assertArrayEqual(view_001, cmd.get_view(), delta=1e-3) self.assertEqual(cmd.count_atoms('m1'), cmd.count_atoms('color blue')) self.assertEqual(cmd.count_atoms('m1'), cmd.count_atoms('rep sticks')) self.assertEqual(cmd.count_atoms('m2'), cmd.count_atoms('color yellow')) self.assertEqual(cmd.count_atoms('m2'), cmd.count_atoms('rep spheres')) self.assertNotEqual(cmd.get_wizard(), None) self.assertEqual(cmd.get_state(), 1) # recall cmd.scene(names[1], 'recall', animate=0) self.assertArrayEqual(view_002, cmd.get_view(), delta=1e-3) self.assertEqual(0, cmd.count_atoms('color blue')) self.assertEqual(0, cmd.count_atoms('rep sticks')) self.assertEqual(cmd.count_atoms(), cmd.count_atoms('color red')) self.assertEqual(cmd.count_atoms(), cmd.count_atoms('rep lines')) self.assertEqual(cmd.get_wizard(), None) self.assertEqual(cmd.get_state(), 3) # with movie (not playing) it must not recall the state cmd.mset('1-4') cmd.frame(1) cmd.scene(names[1], 'recall', animate=0) self.assertEqual(cmd.get_state(), 1) # rename and delete cmd.scene('F2', 'store') cmd.scene(names[0], 'rename', new_key='F1') cmd.scene(names[1], 'delete') self.assertEqual(cmd.get_scene_list(), ['F1', 'F2'])
def Create_NewSphere(self): Center = General_cmd.Get_CenterOfMass2(self.TargetName, cmd.get_state()) Width = General_cmd.Get_MaxWidth(self.TargetName, cmd.get_state()) if len(Center) > 0 and Width != -1: self.Vars.BindingSite.Sphere = SphereObj.SphereObj(Width/4.0,Width/2.0,Center) self.sclResizeSphere.config(from_=0.5,to=self.Vars.BindingSite.Sphere.MaxRadius) self.SphereSize.set(self.Vars.BindingSite.Sphere.Radius) else: self.DisplayMessage(" ERROR: Could not display the default sphere", 1) self.RngOpt.set('')
def __init__(self, top, queue): #print "New instance of FlexSC Wizard" Wizard.__init__(self) self.top = top self.queue = queue self.FlexAID = self.top.top self.FlexAID.WizardError = False self.TargetName = self.FlexAID.IOFile.Target self.TargetFlex = self.top.Vars.TargetFlex self.ResidueName = '...' self.PanelResidue = ' Residue: ' # Initial view self.View = cmd.get_view() self.State = cmd.get_state() self.auto_zoom = cmd.get("auto_zoom") # for Quit_Wizard self.ErrorCode = 1 self.ErrorStatus = [ "Side-chains shown in white are already set as flexible.", "Side-chains shown in orange are 'active' and are ready to be added." ]
def __init__(self, top, queue, UseOldTypes): #print "New instance of Wizard SetAtomType" Wizard.__init__(self) self.top = top self.FlexAID = self.top.top self.queue = queue # Save view self.View = cmd.get_view() self.State = cmd.get_state() #self.pdbPath = self.FlexAID.SimPath + 'tmp.pdb' self.pdbPath = self.FlexAID.IOFile.ProcessedLigandPath.get() self.ErrorCode = 1 self.SelAtomName = '...' self.SelAtomType = '...' self.Set_DDL_Colors(UseOldTypes) smm = [] smm.append([ 2, 'Type Selection', '' ]) for a in self.types: smm.append([ 1, self.type_name[a], 'cmd.get_wizard().set_AtomType("' + a + '")']) self.menu['type']=smm self.atom = list() self.ID = ''
def displaySphere(self): try: cmd.delete(self.SphereDisplay) cmd.refresh() except: pass if self.Sphere != None: # Only display sphere in current state cmd.pseudoatom(self.SphereDisplay, pos=self.Sphere.Center, vdw=self.Sphere.Radius, color='purpleblue', state=cmd.get_state()) cmd.refresh() cmd.hide('nonbonded', self.SphereDisplay) cmd.refresh() cmd.show('spheres', self.SphereDisplay) cmd.refresh() cmd.set('sphere_transparency', 0.7, self.SphereDisplay) cmd.rebuild(self.SphereDisplay)
def Btn_ExtractLigand_Clicked(self): state = cmd.get_state() # Get the Drop Down List Selection Name ddlSelection = self.defaultOption.get() if ddlSelection == '' or self.Validate_ObjectSelection( ddlSelection, 'Ligand', state): return LigandPath = tkFileDialog.asksaveasfilename( filetypes=[('PDB File', '*.pdb')], initialdir=self.top.FlexAIDLigandProject_Dir, title='Save the PDB File', initialfile=ddlSelection, defaultextension='.pdb') if len(LigandPath) > 0: LigandPath = os.path.normpath(LigandPath) if General.validate_String(LigandPath, '.pdb', True, False, True): self.DisplayMessage( " ERROR: Could not save the file because you entered an invalid name.", 2) return if self.top.ValidateSaveProject(LigandPath, 'Ligand'): self.DisplayMessage( " ERROR: The file can only be saved at its default location", 2) return try: cmd.save(LigandPath, ddlSelection, state) LigandName = os.path.basename(os.path.splitext(LigandPath)[0]) cmd.extract(self.ExtractObject, ddlSelection) cmd.set_name(self.ExtractObject, LigandName) if ddlSelection != LigandName: # as if the object was renamed, delete the object cmd.delete(ddlSelection) except: self.DisplayMessage( " ERROR: An error occured while extracting the ligand object.", 1) return self.LigandPath.set(os.path.normpath(LigandPath)) self.LigandName.set(LigandName) #self.LigandMD5.set(General.hashfile(self.LigandPath.get())) self.Reset_Ligand() self.DisplayMessage( ' Successfully extracted the ligand: ' + self.LigandName.get() + "'", 0)
def testIsolevel(self): cmd.viewport(100, 100) cmd.fragment('gly', 'm1') cmd.set('gaussian_b_floor', 30) cmd.set('mesh_width', 5) cmd.map_new('map') cmd.delete('m1') # make mesh cmd.isodot('dot', 'map') cmd.isodot('dot', 'map', source_state=1, state=-2) ## check mesh presence by color meshcolor = 'red' cmd.color(meshcolor, 'dot') self.ambientOnly() self.assertImageHasColor(meshcolor) cmd.frame(2) self.assertEqual(cmd.get_state(), 2) self.assertImageHasColor(meshcolor) for contourlvl in range(7): cmd.isolevel('dot', contourlvl) self.assertImageHasColor(meshcolor) cmd.isolevel('dot', 10) self.assertImageHasNotColor(meshcolor)
def gyradius(selection='(all)', state=-1, quiet=1): ''' DESCRIPTION Radius of gyration Based on: http://pymolwiki.org/index.php/Radius_of_gyration SEE ALSO centerofmass ''' from chempy import cpv state, quiet = int(state), int(quiet) if state < 0: states = [cmd.get_state()] elif state == 0: states = list(range(1, cmd.count_states(selection)+1)) else: states = [state] rg_sq_list = [] for state in states: model = cmd.get_model(selection, state) x = [i.coord for i in model.atom] mass = [i.get_mass() * i.q for i in model.atom if i.q > 0] xm = [cpv.scale(v,m) for v,m in zip(x,mass)] tmass = sum(mass) rr = sum(cpv.dot_product(v,vm) for v,vm in zip(x,xm)) mm = sum((sum(i)/tmass)**2 for i in zip(*xm)) rg_sq_list.append(rr/tmass - mm) rg = (sum(rg_sq_list)/len(rg_sq_list))**0.5 if not quiet: print(' Radius of gyration: %.2f' % (rg)) return rg
def readGuest(self): try: stateNo = cmd.get_state() cmd.create("guest", "sele", stateNo) cmd.select("guestFrozen", "none") except: print("lo kurla")
def Start(self): # self.queue.put(lambda: self.top.top.root.withdraw()) cmd.window('hide') cmd.refresh_wizard() cmd.orient() cmd.window('show') # self.queue.put(lambda: cmd.window('show')) self.ErrorCode = 1 try: self.State = cmd.get_state() self.config_mouse = General_cmd.get_config_mouse() cmd.config_mouse('three_button_editing') self.exc = [ self.SphereDisplay ] General_cmd.mask_Objects(self.exc) # success self.ErrorCode = 0 except: self.queue.put(lambda: self.App.DisplayMessage(" ERROR: Could not start the Sphere wizard", 1)) self.queue.put(lambda: self.App.DisplayMessage(" The wizard will abort prematurely", 1)) self.Quit_Wizard() return if self.DisplaySphere(): self.queue.put(lambda: self.App.DisplayMessage(" ERROR: Could not display the Sphere", 1)) self.queue.put(lambda: self.App.DisplayMessage(" The wizard will abort prematurely", 1)) self.Quit_Wizard() return
def readHostFromSeleAround(self): try: stateNo = cmd.get_state() radius = self.seleRadius.get() cmd.create("host", "byres ( sele around " + radius + ")", stateNo) except: print("lo kurla")
def __init__(self, top, queue, ResSeq, LigandPath): #print "New instance of flexbond Class.\n" Wizard.__init__(self) self.top = top self.queue = queue self.FlexAID = self.top.top self.FlexAID.WizardError = False self.ResSeq = ResSeq self.dictFlexBonds = self.FlexAID.IOFile.Vars.dictFlexBonds self.dictNeighbours = self.FlexAID.IOFile.Vars.dictNeighbours self.RefLigand = LigandPath self.View = cmd.get_view() self.State = cmd.get_state() self.auto_zoom = cmd.get("auto_zoom") self.pick_count = 0 self.panelForceBond = 'Adv.: Force bond OFF' self.Force = False self.point1 = list() self.point2 = list() self.atom1 = list() self.atom2 = list() self.ErrorStatus = [ "Flexible bonds of the ligand are shown in orange.", "Selected flexible bonds of the ligand are shown in white." ]
def chop(self, sele): try: model = cmd.get_model(sele) except: return chain2resId2atomNames = {} for atom in model.atom: resnum = int(atom.resi) pdbname = atom.name chain = atom.chain if not chain in chain2resId2atomNames: chain2resId2atomNames[chain] = {resnum: set([pdbname])} else: if resnum in chain2resId2atomNames[chain]: chain2resId2atomNames[chain][resnum].add(pdbname) else: chain2resId2atomNames[chain][resnum] = set([pdbname]) for chain in chain2resId2atomNames: resId2atomNames = chain2resId2atomNames[chain] resIds2addN = set([]) resIds2addC = set([]) for resnum in resId2atomNames: if resId2atomNames[resnum] != set([ "CA", "C", "O" ]) and resId2atomNames[resnum] != set(["CA", "N"]): resIds2addC.add(resnum + 1) resIds2addN.add(resnum - 1) resIds2addN -= set(resId2atomNames.keys()) resIds2addC -= set(resId2atomNames.keys()) stateNo = cmd.get_state() for resnum in resIds2addC: cmd.create( sele, " %" + sele + " or ( ( resi " + str(resnum) + " and chain " + chain + " ) and ( name CA or name N) ) ", stateNo) cmd.bond( "%" + sele + " and name N and resi " + str(resnum), "%" + sele + " and name C and resi " + str(resnum - 1), 1) for resnum in resIds2addN: cmd.create( sele, " %" + sele + " or ( ( resi " + str(resnum) + " and chain " + chain + " ) and ( name CA or name C or name O) ) ", stateNo) cmd.bond( "%" + sele + " and name C and resi " + str(resnum), "%" + sele + " and name N and resi " + str(resnum + 1), 1) cmd.show("sticks", sele)
def do_state(self,state): cmd=self.cmd if cmd.get("sculpting")=="on": names = cmd.get_names("all_objects") if (bump_name in names) and (obj_name in names): cmd.update(bump_name,obj_name) if self.bump_scores: state = cmd.get_state() print(' Rotamer %d/%d, strain=%.2f' % (state, cmd.count_states(obj_name), self.bump_scores[state - 1]))
def accept(self): # accept compound and advance if self.object == None: print " Filter-Error: Please choose an object first" else: state = cmd.get_state() ident = cmd.get_title(self.object, state) print " Filter: Accepting '%s'" % ident self.count(ident, accept_str) cmd.forward() cmd.refresh_wizard()
def accept(self): # accept compound and advance if self.object==None: print " Filter-Error: Please choose an object first" else: state = cmd.get_state() ident = self.get_ident(self.object,state) print " Filter: Accepting '%s'"%ident self.count(ident,accept_str) cmd.forward() cmd.refresh_wizard()
def CenterSphere(self, sel): if not self.top.WizardRunning(): return Center = General_cmd.Get_CenterOfMass2(sel, cmd.get_state()) if len(Center) > 0: self.top.ActiveWizard.SphereView.Set_Center(Center) self.top.ActiveWizard.DisplaySphere() self.defOptSphere.set(sel)
def reject(self): # reject compound and advance if self.object == None: print(" Filter-Error: Please choose an object first") else: state = cmd.get_state() ident = self.get_ident(self.object, state) print(" Filter: Rejecting '%s'" % ident) self.check_object_dict() self.count(ident, reject_str) cmd.forward() cmd.refresh_wizard()
def Btn_SaveObject_Clicked(self, objtype): # Get the Drop Down List Selection Name ddlSelection = self.defaultOption.get() state = cmd.get_state() self.Set_Object_Variables(objtype) if ddlSelection == '' or self.Validate_ObjectSelection(ddlSelection, objtype, state): return Path = tkFileDialog.asksaveasfilename(filetypes=[('PDB File','*.pdb')], initialdir=self.savepath, title='Save the PDB File', initialfile=ddlSelection, defaultextension='.pdb') if len(Path) > 0: Path = os.path.normpath(Path) if General.validate_String(Path, '.pdb', True, False, True): self.DisplayMessage(" ERROR: Could not save the file because you entered an invalid name.", 2) return if self.top.ValidateSaveProject(Path, objtype): self.DisplayMessage(" ERROR: The file can only be saved at its default location", 2) return try: cmd.save(Path, ddlSelection, state) Name = os.path.basename(os.path.splitext(Path)[0]) cmd.load(Path, Name, state=1) cmd.refresh() if ddlSelection != Name: # as if the object was renamed, delete the object cmd.delete(ddlSelection) except: self.DisplayMessage(" ERROR: An error occured while saving the object.", 1) return self.VarPath.set(os.path.normpath(Path)) self.VarName.set(Name) self.VarProc.set('') self.top.SaveSessionFile = '' #self.VarMD5.set(General.hashfile(self.VarPath.get())) if objtype == 'Ligand': self.Reset_Ligand() self.DisplayMessage(' Successfully saved and loaded the object: ' + self.VarName.get() + "'", 0)
def defer(self): # defer compound and advance if self.object==None: print " Filter-Error: Please choose an object first" else: state = cmd.get_state() ident = self.get_ident(self.object,state) print " Filter: Deferring '%s'"%ident self.check_object_dict() self.count(ident,defer_str) cmd.forward() cmd.refresh_wizard()
def defer(self): # defer compound and advance if self.object == None: print " Filter-Error: Please choose an object first" else: state = cmd.get_state() ident = cmd.get_title(self.object, state) print " Filter: Deferring '%s'" % ident self.check_object_dict() self.count(ident, defer_str) cmd.forward() cmd.refresh_wizard()
def deepshifts_infer(selection, host='localhost', port=7000): model = cmd.get_model(selection, cmd.get_state()) data = { 'species': [atom.symbol for atom in model.atom], 'coords': [atom.coord for atom in model.atom] } req = requests.post('http://{}:{}/infer'.format(host, port), json=data) shifts = req.json() for n, (s, y) in enumerate(zip(data['species'], shifts)): print(n, s, y) cmd.iterate(selection, 'p["deepshifts"]=l.pop(0)', space={'l': shifts})
def do_pick(self, picked_bond): self.reset() cmd.iterate("pk1", "setattr(cmd.get_wizard(),'pk1_st'," "'%s/%s/%s/%s/%s'%(model,segi,chain,resi,name))") if picked_bond: cmd.iterate("pk1", "setattr(cmd.get_wizard(),'pk2_st'," "'%s/%s/%s/%s/%s'%(model,segi,chain,resi,name))") else: # for single atom, also get 3D coordinates (EXAMPLE) cmd.iterate_state(cmd.get_state(), "pk1", "setattr(cmd.get_wizard(),'pk1_xyz',(x,y,z))") cmd.unpick() cmd.refresh_wizard()
def Btn_ExtractLigand_Clicked(self): state = cmd.get_state() # Get the Drop Down List Selection Name ddlSelection = self.defaultOption.get() if ddlSelection == '' or self.Validate_ObjectSelection(ddlSelection, 'Ligand', state): return LigandPath = tkFileDialog.asksaveasfilename(filetypes=[('PDB File','*.pdb')], initialdir=self.top.FlexAIDLigandProject_Dir, title='Save the PDB File', initialfile=ddlSelection, defaultextension='.pdb') if len(LigandPath) > 0: LigandPath = os.path.normpath(LigandPath) if General.validate_String(LigandPath, '.pdb', True, False, True): self.DisplayMessage(" ERROR: Could not save the file because you entered an invalid name.", 2) return if self.top.ValidateSaveProject(LigandPath, 'Ligand'): self.DisplayMessage(" ERROR: The file can only be saved at its default location", 2) return try: cmd.save(LigandPath, ddlSelection, state) LigandName = os.path.basename(os.path.splitext(LigandPath)[0]) cmd.extract(self.ExtractObject, ddlSelection) cmd.set_name(self.ExtractObject, LigandName) if ddlSelection != LigandName: # as if the object was renamed, delete the object cmd.delete(ddlSelection) except: self.DisplayMessage(" ERROR: An error occured while extracting the ligand object.", 1) return self.LigandPath.set(os.path.normpath(LigandPath)) self.LigandName.set(LigandName) #self.LigandMD5.set(General.hashfile(self.LigandPath.get())) self.Reset_Ligand() self.DisplayMessage(' Successfully extracted the ligand: ' + self.LigandName.get() + "'", 0)
def centerofmass(selection='(all)', state=-1, quiet=1): ''' DESCRIPTION Calculates the center of mass. Considers atom mass and occupancy. ARGUMENTS selection = string: atom selection {default: all} state = integer: object state, -1 for current state, 0 for all states {default: -1} EXAMPLE from psico.querying import * x = centerofmass('chain A') r = gyradius('chain A') cmd.pseudoatom('com', pos=x, vdw=r) SEE ALSO gyradius ''' from chempy import cpv state, quiet = int(state), int(quiet) if state < 0: states = [cmd.get_state()] elif state == 0: states = list(range(1, cmd.count_states(selection)+1)) else: states = [state] com = cpv.get_null() totmass = 0.0 for state in states: model = cmd.get_model(selection, state) for a in model.atom: if a.q == 0.0: continue m = a.get_mass() * a.q com = cpv.add(com, cpv.scale(a.coord, m)) totmass += m com = cpv.scale(com, 1./totmass) if not quiet: print(' Center of Mass: [%8.3f,%8.3f,%8.3f]' % tuple(com)) return com
def get_prompt(self): # returns text prompt self.prompt = None if self.object == None: self.prompt = [ 'Please select a multi-state object...' ] else: self.prompt = [ '%s: %d accepted, %d rejected, %d deferred, %d remaining'%( self.object,self.acce,self.reje,self.defe,self.togo) ] state = cmd.get_state() ident = self.get_ident(self.object,state) sdo=self.dict[self.object] if sdo.has_key(ident): self.prompt.append('%s: %s'%(ident,sdo[ident])) else: self.prompt.append('%s?'%(ident)) return self.prompt
def get_prompt(self): # returns text prompt self.prompt = None if self.object == None: self.prompt = ['Please select a multi-state object...'] else: self.prompt = [ '%s: %d accepted, %d rejected, %d deferred, %d remaining' % (self.object, self.acce, self.reje, self.defe, self.togo) ] state = cmd.get_state() ident = self.get_ident(self.object, state) sdo = self.dict[self.object] if ident in sdo: self.prompt.append('%s: %s' % (ident, sdo[ident])) else: self.prompt.append('%s?' % (ident)) return self.prompt
def do_pick(self, picked_bond): self.reset() cmd.iterate( "pk1", "setattr(cmd.get_wizard(),'pk1_st'," "'%s/%s/%s/%s/%s'%(model,segi,chain,resi,name))") if picked_bond: cmd.iterate( "pk1", "setattr(cmd.get_wizard(),'pk2_st'," "'%s/%s/%s/%s/%s'%(model,segi,chain,resi,name))") else: # for single atom, also get 3D coordinates (EXAMPLE) cmd.iterate_state(cmd.get_state(), "pk1", "setattr(cmd.get_wizard(),'pk1_xyz',(x,y,z))") cmd.unpick() cmd.refresh_wizard()
def __init__(self, top, queue, LigandPath, AnchorAtom): #print("New instance of anchor Class.\n") Wizard.__init__(self) self.top = top self.queue = queue self.FlexAID = self.top.top self.FlexAID.WizardError = False self.LigandPath = LigandPath self.PrevAnchorAtom = AnchorAtom self.AnchorAtom = self.PrevAnchorAtom self.View = cmd.get_view() self.State = cmd.get_state() self.auto_zoom = cmd.get("auto_zoom") self.ErrorStatus = []
def get_prompt(self): # returns text prompt self.prompt = None if self.object == None: self.prompt = ["Please select a multi-state object..."] else: cnt = cmd.count_states(self.object) self.prompt = [ "%s: %d total, %d accepted, %d rejected, %d deferred, %d remaining" % (self.object, self.tota, self.acce, self.reje, self.defe, self.togo) ] state = cmd.get_state() ident = cmd.get_title(self.object, state) sdo = self.dict[self.object] if sdo.has_key(ident): self.prompt.append("%s: %s" % (ident, sdo[ident])) else: self.prompt.append("%s?" % (ident)) return self.prompt
def save_pdb_ordered(filename, selection='all', state=-1): """ DESCRIPTION Save a PDB file while preserving the atom order. USAGE save_pdb_ordered filename [, selection [, state]] ARGUMENTS filename: the file name to save to selection: selected atoms to save to. Defaults to 'all' state: the state from where the coordinates are taken. Special values are: 0 : saves all states in a multi-model PDB file -1 : saves the current state (this is the default) """ state = int(state) with open(filename, 'wt') as f: if state == -1: states = [cmd.get_state()] elif state == 0: states = list(range(cmd.count_states(selection))) else: states = [state] for i, s in enumerate(states): if len(states) > 1: f.write('MODEL{:>9d}\n'.format(i + 1)) for a in sorted(cmd.get_model(selection, s).atom, key=lambda a: a.id): f.write( 'ATOM {:5d} {:>4s} {:3s} {}{:4d} {:8.3f}{:8.3f}{:8.3f} 1.00 0.00 {:s}\n' .format(a.index, a.name, a.resn, a.chain, int(a.resi), a.coord[0], a.coord[1], a.coord[2], a.symbol)) if len(states) > 1: f.write('ENDMDL\n')
def get_sasa(selection, state=-1, dot_density=5, quiet=1): ''' DESCRIPTION Get solvent accesible surface area SEE ALSO get_area pymol.util.get_sasa (considered broken!) ''' state, dot_density, quiet = int(state), int(dot_density), int(quiet) if state < 1: state = cmd.get_state() n = cmd.get_unused_name('_') cmd.create(n, selection, state, 1, zoom=0, quiet=1) cmd.set('dot_solvent', 1, n) if dot_density > -1: cmd.set('dot_density', dot_density, n) r = cmd.get_area(n, quiet=int(quiet)) cmd.delete(n) return r
def get_prompt(self): # returns text prompt self.prompt = None if self.object == None: self.prompt = ['Please select a multi-state object...'] else: cnt = cmd.count_states(self.object) self.prompt = [ '%s: %d total, %d accepted, %d rejected, %d deferred, %d remaining' % (self.object, self.tota, self.acce, self.reje, self.defe, self.togo) ] state = cmd.get_state() ident = cmd.get_title(self.object, state) sdo = self.dict[self.object] if sdo.has_key(ident): self.prompt.append('%s: %s' % (ident, sdo[ident])) else: self.prompt.append('%s?' % (ident)) return self.prompt
def get_Coords(self, atom_number, point): found = False try: atom_number = int(atom_number) atoms = cmd.get_model(self.LigDisplay, state=cmd.get_state()) for at in atoms.atom: if General_cmd.get_ID(at.index, self.LigDisplay) == atom_number: point.extend([at.coord[0],at.coord[1],at.coord[2]]) found = True break if not found: return 1 except: return 1 return 0
def displaySphere(self): try: cmd.delete(self.SphereDisplay) cmd.refresh() except: pass if self.Sphere != None: # Only display sphere in current state cmd.pseudoatom(self.SphereDisplay, pos=self.Sphere.Center, vdw=self.Sphere.Radius, color='purpleblue', state=cmd.get_state()) cmd.refresh() cmd.hide('nonbonded',self.SphereDisplay) cmd.refresh() cmd.show('spheres', self.SphereDisplay) cmd.refresh() cmd.set('sphere_transparency', 0.7, self.SphereDisplay) cmd.rebuild(self.SphereDisplay)
def get_Atom(self, name): info = [] try: list = cmd.index(name + " & " + self.LigDisplay) if len(list) > 0: atoms = cmd.get_model(name, state=cmd.get_state()) for at in atoms.atom: info.extend([ at.index, at.resn, at.resi, at.chain, at.name, at.coord[0], at.coord[1], at.coord[2] ]) else: self.ErrorStatus = [ "You can only select atoms from the object " + self.LigDisplay + ". Try again." ] return info cmd.deselect() except: self.ErrorStatus = [ "An error occured while retrieving atom info. Try again." ] self.Quit_Wizard() return info
def get_Atom(self, name): info = [] try: list = cmd.index(name + " & " + self.LigDisplay) if len(list) > 0: atoms = cmd.get_model(name, state=cmd.get_state()) for at in atoms.atom: info.extend([ at.index, at.resn, at.resi, at.chain, at.name, at.coord[0], at.coord[1], at.coord[2] ]) else: self.FlexAID.DisplayMessage("You must click in the object " + self.LigDisplay, 1) return info cmd.deselect() except: self.FlexAID.DisplayMessage("Error while retrieving atom info", 1) self.Quit_Wizard(self.ErrorCode) return info
def get_raw_distances(names='', state=1, selection='all', quiet=1): ''' DESCRIPTION Get the list of pair items from distance objects. Each list item is a tuple of (index1, index2, distance). Based on a script from Takanori Nakane, posted on pymol-users mailing list. http://www.mail-archive.com/[email protected]/msg10143.html ARGUMENTS names = string: names of distance objects (no wildcards!) {default: all measurement objects} state = integer: object state {default: 1} selection = string: atom selection {default: all} SEE ALSO select_distances, cmd.find_pairs, cmd.get_raw_alignment ''' from chempy import cpv state, quiet = int(state), int(quiet) if state < 1: state = cmd.get_state() valid_names = cmd.get_names_of_type('object:measurement') if names == '': names = ' '.join(valid_names) else: for name in names.split(): if name not in valid_names: print(' Error: no such distance object: ' + name) raise CmdException raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names'] xyz2idx = {} cmd.iterate_state(state, selection, 'xyz2idx[x,y,z] = (model,index)', space=locals()) r = [] for obj in raw_objects: try: points = obj[5][2][state-1][1] if points is None: raise ValueError except (KeyError, ValueError): continue for i in range(0, len(points), 6): xyz1 = tuple(points[i:i+3]) xyz2 = tuple(points[i+3:i+6]) try: r.append((xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2))) if not quiet: print(' get_raw_distances: ' + str(r[-1])) except KeyError: if quiet < 0: print(' Debug: no index for %s %s' % (xyz1, xyz2)) return r
def delaunay(selection='enabled', name=None, cutoff=10.0, as_cgo=0, qdelaunay_exe='qdelaunay', state=-1, quiet=1): ''' DESCRIPTION Full-atom Delaunay Tessalator Creates either a molecular object with delaunay edges as bonds, or a CGO object with edge colors according to edge length. USAGE delaunay [ selection [, name [, cutoff=10.0 [, as_cgo=0 ]]]] SEE ALSO PyDeT plugin: http://pymolwiki.org/index.php/PyDet ''' from chempy import cpv, Bond if name is None: name = cmd.get_unused_name('delaunay') cutoff = float(cutoff) as_cgo = int(as_cgo) state, quiet = int(state), int(quiet) if state < 1: state = cmd.get_state() model = cmd.get_model(selection, state) regions_iter = qdelaunay((a.coord for a in model.atom), 3, len(model.atom), qdelaunay_exe=qdelaunay_exe) edges = set(tuple(sorted([region[i-1], region[i]])) for region in regions_iter for i in range(len(region))) edgelist=[] r = [] minco = 9999 maxco = 0 for edge in edges: ii, jj = edge a = model.atom[ii] b = model.atom[jj] co = cpv.distance(a.coord, b.coord) if cutoff > 0.0 and co > cutoff: continue if as_cgo: minco=min(co,minco) maxco=max(co,maxco) edgelist.append(a.coord + b.coord + [co]) else: bnd = Bond() bnd.index = [ii, jj] model.add_bond(bnd) r.append((a,b,co)) if not as_cgo: cmd.load_model(model, name, 1) return r from pymol.cgo import CYLINDER difco = maxco-minco obj = [] mm = lambda x: max(min(x, 1.0), 0.0) for e in edgelist: co = ((e[6]-minco)/difco)**(0.75) color = [mm(1-2*co), mm(1-abs(2*co-1)), mm(2*co-1)] obj.extend([CYLINDER] + e[0:6] + [0.05] + color + color) cmd.load_cgo(obj, name) return r
def int_to_state(s): if s == -1: return cmd.get_state() return s
def bbPlane(selection='(all)', color='gray', transp=0.3, state=-1, name=None, quiet=1): """ DESCRIPTION Draws a plane across the backbone for a selection ARGUMENTS selection = string: protein object or selection {default: (all)} color = string: color name or number {default: white} transp = float: transparency component (0.0--1.0) {default: 0.0} state = integer: object state, 0 for all states {default: 1} NOTES You need to pass in an object or selection with at least two amino acids. The plane spans CA_i, O_i, N-H_(i+1), and CA_(i+1) """ from pymol.cgo import BEGIN, TRIANGLES, COLOR, VERTEX, END from pymol import cgo from chempy import cpv # format input transp = float(transp) state, quiet = int(state), int(quiet) if name is None: name = cmd.get_unused_name("backbonePlane") if state < 0: state = cmd.get_state() elif state == 0: for state in range(1, cmd.count_states(selection) + 1): bbPlane(selection, color, transp, state, name, quiet) return AAs = [] coords = dict() # need hydrogens on peptide nitrogen cmd.h_add('(%s) and n. N' % selection) # get the list of residue ids for obj in cmd.get_object_list(selection): sel = obj + " and (" + selection + ")" for a in cmd.get_model(sel + " and n. CA", state).atom: key = '/%s/%s/%s/%s' % (obj, a.segi, a.chain, a.resi) AAs.append(key) coords[key] = [a.coord, None, None] for a in cmd.get_model(sel + " and n. O", state).atom: key = '/%s/%s/%s/%s' % (obj, a.segi, a.chain, a.resi) if key in coords: coords[key][1] = a.coord for a in cmd.get_model(sel + " and ((n. N extend 1 and e. H) or (r. PRO and n. CD))", state).atom: key = '/%s/%s/%s/%s' % (obj, a.segi, a.chain, a.resi) if key in coords: coords[key][2] = a.coord # need at least two amino acids if len(AAs) <= 1: print("ERROR: Please provide at least two amino acids, the alpha-carbon on the 2nd is needed.") return # prepare the cgo obj = [ BEGIN, TRIANGLES, COLOR, ] obj.extend(cmd.get_color_tuple(color)) for res in range(0, len(AAs) - 1): curIdx, nextIdx = str(AAs[res]), str(AAs[res + 1]) # populate the position array pos = [coords[curIdx][0], coords[curIdx][1], coords[nextIdx][2], coords[nextIdx][0]] # if the data are incomplete for any residues, ignore if None in pos: if not quiet: print(' bbPlane: peptide bond %s -> %s incomplete' % (curIdx, nextIdx)) continue if cpv.distance(pos[0], pos[3]) > 4.0: if not quiet: print(' bbPlane: %s and %s not adjacent' % (curIdx, nextIdx)) continue normal = cpv.normalize(cpv.cross_product( cpv.sub(pos[1], pos[0]), cpv.sub(pos[2], pos[0]))) obj.append(cgo.NORMAL) obj.extend(normal) # need to order vertices to generate correct triangles for plane if cpv.dot_product(cpv.sub(pos[0], pos[1]), cpv.sub(pos[2], pos[3])) < 0: vorder = [0, 1, 2, 2, 3, 0] else: vorder = [0, 1, 2, 3, 2, 1] # fill in the vertex data for the triangles; for i in vorder: obj.append(VERTEX) obj.extend(pos[i]) # finish the CGO obj.append(END) # update the UI cmd.load_cgo(obj, name, state, zoom=0) cmd.set("cgo_transparency", transp, name)
def distancetoatom( origin='pk1', cutoff=10, filename=None, selection='all', state=0, property_name='p.dist', coordinates=0, decimals=3, sort=1, quiet=1 ): ''' DESCRIPTION distancetoatom.py Described at: http://www.pymolwiki.org/Distancetoatom Prints all distanced between the specified atom/coordinate/center and all atoms within cutoff distance that are part of the selection. All coordinates and distances can be saved in a csv-style text file report and can be appended to a (custom) atom property, if defined. USAGE distancetoatom [ origin [, cutoff [, filename [, selection [, state [, property_name [, coordinates [, decimals [, sort [, quiet ]]]]]]]]]] ARGUMENTS NAME TYPE FUNCTION origin: <list> defines the coordinates for the origin and can be: <str> 1. a list with coordinates [x,y,z] 2. a single atom selection string {default='pk1'} 3. a multi-atom selection string (center will be used) cutoff <float> sets the maximum distance {default: 10} filename <str> filename for optional output report. {default=None} set to e.g. 'report.txt' to create a report (omit or set to '', None, 0 or False to disable) selection <str> can be used to define/limit the measurment to specific sub-selections {default='all'} state <int> object state, {default=0} # = current property_name <str> the distance will be stored in this property {p.dist} set "" to disable coordinates <int> toggle whether atom coordinated will be reported {0} decimals <int> decimals for coordinates and distance: default = 3 # = max. PDB resolution sort <int> Sorting by distance? 1: ascending (default) 0: no sorting (by names) -1: descending quiet <bool> toggle verbosity ''' # keyword check try: selection = '(%s)'%selection ori=get_coord(origin) if not ori: print "distancetoatom: aborting - check input for 'origin'!" return False cutoff = abs(float(cutoff)) filename = str(filename) state = abs(int(state)) if (not int(state)): state=cmd.get_state() cmd.set('state', state) # distance by state property_name = str(property_name) decimals = abs(int(decimals)) sort = int(sort) coordinates=bool(int(coordinates)) quiet=bool(int(quiet)) except: print 'distancetoatom: aborting - input error!' return False # round origin ori = [round(x,decimals) for x in ori] # report? if filename in ['', '0', 'False', 'None']: filename=False else: try: report=open(filename,'w') # file for writing except: print 'distancetoatom: Unable to open report file! - Aborting!' return False # temporary name for pseudoatom tempname = cmd.get_unused_name('temp_name') tempsel = cmd.get_unused_name('temp_sel') #origin cmd.pseudoatom(object=tempname, resi=1, pos=ori) # select atoms within cutoff cmd.select(tempsel, '(%s around %f) and (%s) and state %d' %(tempname, cutoff, selection, state)) cmd.delete(tempname) # single atom ori and part of selection # avoid double reporting! single_atom_ori=False try: if cmd.count_atoms('(%s) and (%s) and (%s)'%(selection, tempsel, origin))==1: single_atom_ori=True except: pass # pass= coordinates or multi-atom or single, not selected --> report ori # atom list stored.temp=[] cmd.iterate(tempsel, 'stored.temp.append([model, segi, chain, resn, resi, name, alt])') # custom properties? # conditional disabling if (property_name==''): property_name=False if ((cmd.get_version()[1]<1.7) and (property_name not in ['b','q'])): property_name=False # calculate the distances, creating list distance_list=[] if (not single_atom_ori): distance_list.append(['ORIGIN: '+str(origin), ori[0], ori[1], ori[2], 0.0]) for atom in stored.temp: atom_name = ('/%s/%s/%s/%s`%s/%s`%s'%(atom[0], atom[1], atom[2], atom[3], atom[4], atom[5], atom[6])) atom_xyz = [round(x, decimals) for x in cmd.get_atom_coords(atom_name)] atom_dist = round(cpv.distance(ori, atom_xyz), decimals) distance_list.append([atom_name,atom_xyz[0],atom_xyz[1],atom_xyz[2], atom_dist]) # create property with distance (can be used for coloring, labeling etc) if property_name: try: cmd.alter(atom_name, '%s=%f'%(property_name, atom_dist)) except: # I'm not sure alter raises exceptions if the property is illegal property_name=False # sort list, if selected if sort>0: distance_list.sort(key=lambda dist: dist[4]) elif sort<0: distance_list.sort(key=lambda dist: dist[4], reverse=True) # add header distance_list=[['Atom Macro ID', 'x-coord', 'y-coord', 'z-coord', 'distance_to_origin'] ]+distance_list if ((not quiet) and (filename)): # Hijack stdout to print to file and console class logboth(object): def __init__(self, *files): self.files = files def write(self, obj): for f in self.files: f.write(obj) originalstdout = sys.stdout sys.stdout = logboth(sys.stdout, report) for entry in distance_list: if coordinates: output= '%s, %s, %s, %s, %s' %(entry[0],entry[1],entry[2],entry[3],entry[4]) #csv style else: output= '%s, %s' %(entry[0],entry[4]) #csv style if (not quiet): print output elif filename: report.write(output+'\n') # restore regular stdout if ((not quiet) and (filename)): sys.stdout = originalstdout # close file if filename: report.close() if (not quiet): if property_name: print 'Distances saved to property: %s' %str(property_name) else: print 'Distances NOT saved to property (illegal custom property)'
def apply(self): cmd=self.cmd if self.status==1: # find the name of the object which contains the selection src_frame = cmd.get_state() try: new_name = cmd.get_object_list(src_sele)[0] except IndexError: print(" Mutagenesis: object not found.") return if True: auto_zoom = cmd.get_setting_text('auto_zoom') cmd.set('auto_zoom',"0",quiet=1) if self.lib_mode!="current": # create copy with mutant in correct frame state = cmd.get_object_state(new_name) cmd.create(tmp_obj2, obj_name, src_frame, state) cmd.set_title(tmp_obj2, state, '') cmd.color(self.stored.identifiers[4], "?%s & elem C" % tmp_obj2) cmd.alter(tmp_obj2, 'ID = -1') # select backbone connection atoms cmd.select(tmp_sele1, 'neighbor ?%s' % (src_sele), 0) # remove residue and neighboring c-cap/n-cap (if any) cmd.remove("?%s | byres (?%s & " "(name N & resn NME+NHH | name C & resn ACE))" % (src_sele, tmp_sele1)) # create the merged molecule cmd.create(new_name, "?%s | ?%s" % (new_name, tmp_obj2), state, state) # now connect them cmd.select(tmp_sele2, '/%s/%s/%s/%s' % ((new_name,) + self.stored.identifiers[:3])) cmd.bond('?%s & name C' % (tmp_sele1), '?%s & name N' % (tmp_sele2), quiet=1) cmd.bond('?%s & name N' % (tmp_sele1), '?%s & name C' % (tmp_sele2), quiet=1) cmd.set_geometry('(?%s | ?%s) & name C+N' % (tmp_sele1, tmp_sele2), 3, 3) # make amide planer # fix N-H hydrogen position (if any exists) cmd.h_fix('?%s & name N' % (tmp_sele2)) # delete temporary objects/selections cmd.delete(tmp_sele1) cmd.delete(tmp_sele2) cmd.delete(tmp_obj2) self.clear() # and return to frame 1 cmd.frame(1) cmd.refresh_wizard() else: # create copy with conformation in correct state cmd.create(tmp_obj2,obj_name,src_frame,1) # remove existing c-cap in copy (if any) cmd.remove("byres (name N and (%s in (neighbor %s)) and resn NME+NHH)"% (new_name,src_sele)) cmd.remove("(%s) and name OXT"%src_sele) # remove existing n-cap in copy (if any) cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ACE)"% (new_name,src_sele)) # save existing conformation on undo stack # cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele)) cmd.push_undo("("+src_sele+")") # modify the conformation cmd.update(new_name,tmp_obj2) # cmd.unpick() cmd.delete(tmp_obj2) self.clear() # and return to frame 1 cmd.frame(1) cmd.refresh_wizard() cmd.set('auto_zoom',auto_zoom,quiet=1)
def apply(self): cmd = self.cmd pymol = cmd._pymol if self.status == 1: # find the name of the object which contains the selection new_name = None obj_list = cmd.get_names("objects") for a in obj_list: if cmd.get_type(a) == "object:molecule": if cmd.count_atoms("(%s and %s)" % (a, src_sele)): new_name = a break src_frame = cmd.get_state() if new_name == None: print " Mutagenesis: object not found." else: auto_zoom = cmd.get_setting_text("auto_zoom") cmd.set("auto_zoom", "0", quiet=1) if self.lib_mode != "current": # create copy w/o residue cmd.create(tmp_obj1, "(%s and not %s)" % (new_name, src_sele)) # remove existing c-cap in copy (if any) cmd.remove("byres (name N and (%s in (neighbor %s)) and resn nme,nhh)" % (tmp_obj1, src_sele)) # remove existing n-cap in copy (if any) cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ace)" % (tmp_obj1, src_sele)) # save copy for bonded atom reference cmd.create(tmp_obj3, new_name) # transfer the selection to copy cmd.select(src_sele, "(%s in %s)" % (tmp_obj3, src_sele)) # create copy with mutant in correct frame cmd.create(tmp_obj2, obj_name, src_frame, 1) cmd.set_title(tmp_obj2, 1, "") cmd.delete(new_name) # create the merged molecule cmd.create(new_name, "(%s or %s)" % (tmp_obj1, tmp_obj2), 1) # only one state in merged object... # now connect them cmd.select(mut_sele, "(byres (%s like %s))" % (new_name, src_sele)) # bond N+0 to C-1 if (cmd.select(tmp_sele1, "(name C and (%s in (neighbor %s)))" % (new_name, src_sele)) == 1) and ( cmd.select(tmp_sele2, "((%s in %s) and n;N)" % (mut_sele, tmp_obj2)) == 1 ): cmd.bond(tmp_sele1, tmp_sele2) cmd.set_geometry(tmp_sele1, 3, 3) # make amide planer cmd.set_geometry(tmp_sele2, 3, 3) # make amide planer # bond C+0 to N+1 if (cmd.select(tmp_sele1, "(name N and (%s in (neighbor %s)))" % (new_name, src_sele)) == 1) and ( cmd.select(tmp_sele2, "((%s in %s) and n;C)" % (mut_sele, tmp_obj2)) == 1 ): cmd.bond(tmp_sele1, tmp_sele2) cmd.set_geometry(tmp_sele1, 3, 3) # make amide planer cmd.set_geometry(tmp_sele2, 3, 3) # make amide planer cmd.delete(tmp_sele1) cmd.delete(tmp_sele2) # fix N-H hydrogen position (if any exists) cmd.h_fix("(name N and bound_to (%s in %s and n;H))" % (new_name, tmp_obj2)) # now transfer selection back to the modified object cmd.delete(tmp_obj1) cmd.delete(tmp_obj2) cmd.delete(tmp_obj3) self.clear() # and return to frame 1 cmd.frame(1) cmd.refresh_wizard() else: # create copy with conformation in correct state cmd.create(tmp_obj2, obj_name, src_frame, 1) # remove existing c-cap in copy (if any) cmd.remove("byres (name N and (%s in (neighbor %s)) and resn nme,nhh)" % (new_name, src_sele)) cmd.remove("(%s) and name OXT" % src_sele) # remove existing n-cap in copy (if any) cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ace)" % (new_name, src_sele)) # save existing conformation on undo stack # cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele)) cmd.push_undo("(" + src_sele + ")") # modify the conformation cmd.update(new_name, tmp_obj2) # cmd.unpick() cmd.delete(tmp_obj2) self.clear() # and return to frame 1 cmd.frame(1) cmd.refresh_wizard() cmd.set("auto_zoom", auto_zoom, quiet=1)
def pca_plot( aln_object, ref="all", state=0, maxlabels=20, size=20, invert="", which=(0, 1), alpha=0.75, filename=None, quiet=1, load_b=0, ): """ DESCRIPTION Principal Component Analysis on a set of superposed conformations, given by an alignment object. By default all states in all objects are considered. Generates a 2d-plot of the first two principal components. USAGE pca_plot aln_object [, ref [, state [, maxlabels ]]] ARGUMENTS aln_object = string: name of alignment object, defines the selection and the atom mapping between objects ref = string: object names for which to calculate PCA for {default: all} state = integer: if state=0 use all states {default: 0} maxlabels = integer: label dots in plot if maxlabels<0 or number of models not more than maxlabels {default: 20} size = float: size of plot points in px^2 {default: 20} invert = string: invert plotting axes x, y or xy {default: ''} which = (int,int): indices of principal components to plot {default: (0,1)} alpha = float: opacity of plotting points filename = string: if given, plot to file {default: None} EXAMPLE fetch 1ake 4ake 1dvr 1ak2, async=0 split_chains extra_fit (*_*) and name CA, reference=1ake_A, cycles=0, object=aln pca_plot aln, 1ake_* 4ake_* fetch 1ubq 2k39, async=0 align 2k39, 1ubq and guide, cycles=0, object=aln2 color blue, 1ubq color orange, 2k39 pca_plot aln2, filename=pca-ubq.pdf """ from numpy import array, dot from numpy.linalg import svd, LinAlgError from . import matplotlib_fix from matplotlib.pyplot import figure state, quiet = int(state), int(quiet) maxlabels = int(maxlabels) if cmd.is_string(which): which = cmd.safe_list_eval(which) if aln_object not in cmd.get_names_of_type("object:"): print(" Warning: first argument should be an alignment object") from .fitting import extra_fit selection = aln_object aln_object = cmd.get_unused_name("aln") extra_fit(selection, cycles=0, transform=0, object=aln_object) if state == 0: states = list(range(1, cmd.count_states() + 1)) elif state < 0: states = [cmd.get_state()] else: states = [state] models = cmd.get_object_list(aln_object) references = set(cmd.get_object_list("(" + ref + ")")).intersection(models) others = set(models).difference(references) aln = cmd.get_raw_alignment(aln_object) if not quiet: print(" PCA References:", ", ".join(references)) print(" PCA Others:", ", ".join(others)) if len(references) == 0: print(" PCA Error: No reference objects") raise CmdException model_count = len(models) coords = dict((model, []) for model in models) aln = [pos for pos in aln if len(pos) == model_count] for state in states: idx2xyz = dict() cmd.iterate_state(state, aln_object, "idx2xyz[model,index] = (x,y,z)", space={"idx2xyz": idx2xyz}) for pos in aln: for idx in pos: if idx not in idx2xyz: continue c = coords[idx[0]] if len(c) < state: c.append([]) c[-1].extend(idx2xyz[idx]) c_iter = lambda models: ((c, model, i + 1) for model in models for (i, c) in enumerate(coords[model])) X = array([i[0] for i in c_iter(references)]) Y = array([i[0] for i in c_iter(others)]) center = X.mean(0) X = X - center try: U, L, V = svd(X) except LinAlgError as e: print(" PCA Error: ", e) raise CmdException if int(load_b): cmd.alter("byobj " + aln_object, "b=-0.01") b_dict = {} i = which[0] b_array = (V[i].reshape((-1, 3)) ** 2).sum(1) ** 0.5 for pos, b in zip(aln, b_array): for idx in pos: b_dict[idx] = b cmd.alter(aln_object, "b=b_dict.get((model,index), -0.01)", space=locals()) cmd.color("yellow", "byobj " + aln_object) cmd.spectrum("b", "blue_red", aln_object + " and b > -0.01") X_labels = [i[1:3] for i in c_iter(references)] Y_labels = [i[1:3] for i in c_iter(others)] x_list = [] y_list = [] colors = [] text_list = [] def plot_pc_2d(X, labels): pca_12 = dot(X, V.T)[:, which] for (x, y), (model, state) in zip(pca_12, labels): x_list.append(x) y_list.append(y) colors.append(get_model_color(model)) if maxlabels < 0 or len(pca_12) <= maxlabels: text_list.append("%s(%d)" % (model, state)) else: text_list.append(None) plot_pc_2d(X, X_labels) if len(Y) > 0: Y = Y - center plot_pc_2d(Y, Y_labels) if "x" in invert: x_list = [-x for x in x_list] if "y" in invert: y_list = [-y for y in y_list] fig = figure() plt = fig.add_subplot(111, xlabel="PC %d" % (which[0] + 1), ylabel="PC %d" % (which[1] + 1)) plt.scatter(x_list, y_list, float(size), colors, linewidths=0, alpha=float(alpha)) for (x, y, text) in zip(x_list, y_list, text_list): if text is not None: plt.text(x, y, text, horizontalalignment="left") _showfigure(fig, filename, quiet)