Example #1
0
def mini(total_steps=500,
            gradient=0.001,
            interval=100,
            object='rt',
            fix_flag=None,
            rest_flag=None,
            solvation=None,
            finish=None):

    global state
    if not state:
        print " realtime.mini: please run setup first..."
    else:
        model = state.model
        print " realtime.mini: %d atoms total\n" % model.nAtom
        try:
            while total_steps>0:
                total_steps = total_steps - interval
                state.minimize(max_iter=interval,
                                    fix_flag=fix_flag,
                                    rest_flag=rest_flag,
                                    solvation=solvation)
                cmd.delete(object)
                cmd.load_model(state.model,object,1)
                cmd.refresh()
                if finish!=None:
                    apply(finish[0],finish[1],finish[2])
        except:
            cmd.load_model(state.model,'ref')
            traceback.print_exc()
        print " realtime.mini: complete."
Example #2
0
def set_raw_alignment(name, aln, transform=0):
    '''
DESCRIPTION

    API only.
    Load an alignment object from a list like the one obtained with
    cmd.get_raw_alignment
    '''
    import itertools
    if not isinstance(aln[0], dict):
        aln = [dict(idx_pair) for idx_pair in aln]
    models = set(model for idx_pdict in aln for model in idx_pdict)
    sele1 = cmd.get_unused_name('_sele1')
    sele2 = cmd.get_unused_name('_sele2')
    fit = cmd.fit if transform else cmd.rms_cur
    for model1, model2 in itertools.combinations(models, 2):
        index_list1 = []
        index_list2 = []
        for idx_pdict in aln:
            if model1 in idx_pdict and model2 in idx_pdict:
                index_list1.append(idx_pdict[model1])
                index_list2.append(idx_pdict[model2])
        cmd.select_list(sele1, model1, index_list1, mode='index')
        cmd.select_list(sele2, model2, index_list2, mode='index')
        fit(sele1, sele2, cycles=0, matchmaker=4, object=name)
    cmd.delete(sele1)
    cmd.delete(sele2)
Example #3
0
 def testPseSupport(self):
     cmd.load_callback(callback.Callback(), 'c1')
     with testing.mktemp('tmp.pse') as session_filename:
         cmd.save(session_filename)
         cmd.delete('*')
         cmd.load(session_filename)
         self.assertTrue('c1' in cmd.get_names())
Example #4
0
def testFun(filePath):
    import networkx as nx
    cmd.delete("all")
    
    cmd.fetch("1C3W")
    cmd.hide("lines", "all")
    cmd.show("cartoon", "1C3W")
    cmd.color("green", "all")
    
    #------------------------------ cmd.color("yellow", "resi 194 and resn GLU")
    #------------------------------- cmd.show("sticks", "resi 194 and resn GLU")
    highlightRes("GLUA0194", color="yellow")
    highlightRes("GLUA0204", color="yellow")
    
        
    g = loadHbTxt(filePath)
    allNodes = nx.node_connected_component(g, "GLUA0194")
    #===========================================================================
    # print allNodes
    #===========================================================================
    
    accRes = {}
    for line in open("/Users/xzhu/sibyl/BR/1C3W/hydro/def/raw/acc.res"):
        fields = line.split()
        resString = fields[1] + fields[2]
        acc = float(fields[4])
        accRes[resString] = acc
    
    colorThreshold = 0.02
    for eachResidue in accRes.keys():
        if accRes[eachResidue] > colorThreshold:
            if eachResidue in allNodes:
                print eachResidue
                highlightRes(eachResidue)
Example #5
0
File: B06.py Project: Almad/pymol
def load():
   r = 0
   rep = [ "simple", "technical", "ligands", "ligand_sites","ligand_sites_trans","ligand_sites_mesh","pretty", "publication" ]
   list = glob("pdb/*/*")
#   while list[0]!="pdb/f8/pdb1f8u":
#      list.pop(0)
   for file in list:
      print file
      cmd.delete('pdb')
      cmd.load(file,'pdb')
      cmd.orient('pdb')
      cur_rep = rep.pop(0)
      rep = rep + [cur_rep]
      getattr(pymol.preset,cur_rep)('pdb')
      cmd.refresh()
# give PyMOL a chance
      time.sleep(0.02)
      time.sleep(0.02)
      time.sleep(0.02)
      time.sleep(0.02)
      cmd.refresh()
      time.sleep(0.02)
      time.sleep(0.02)
      time.sleep(0.02)
      time.sleep(0.02)

      while(pymol.run==0):
         time.sleep(0.1)
Example #6
0
File: T01.py Project: Almad/pymol
def load_save1():
   while 1:
      time.sleep(random.random())
      cmd.delete("obj1")
      cmd.load("dat/pept.pdb","obj1")
      time.sleep(random.random())
      cmd.save("tmp/T01a.pdb","obj1")
Example #7
0
File: T01.py Project: Almad/pymol
def load_save2():
   while 1:
      time.sleep(random.random())
      cmd.delete("obj2")
      cmd.load("dat/water.pdb","obj2")
      time.sleep(random.random())
      cmd.save("tmp/T01b.pdb","obj2")
Example #8
0
def load():
   cmd.set("valence")
   r = 0
   list = glob("pdb/*/*")
#   while list[0]!="pdb/f8/pdb1f8u":
#      list.pop(0)
   for file in list:
      try:
         cmd.delete('pdb')
         cmd.load(file,'pdb')
         cmd.set_title('pdb',1,os.path.split(file)[-1])
         cmd.rewind()
         cmd.orient('pdb')
         cmd.refresh()
         cmd.show_as("ribbon")
         cmd.refresh()
         cmd.show_as("sticks")
         cmd.refresh()
         sys.__stderr__.write(".")
         sys.__stderr__.flush()
         n = cmd.count_states()
         if n>1:
            cmd.rewind()
            sys.__stderr__.write(file+"\n")
            sys.__stderr__.flush()
            for a in range(1,n+1):
               cmd.forward()
               cmd.refresh()
      except:
         traceback.print_exc()
Example #9
0
def minimize(selection='all', forcefield='MMFF94s', method='conjugate gradients', nsteps=500, conv=0.0001, cutoff=False, cut_vdw=6.0, cut_elec=8.0):
    pdb_string = cmd.get_pdbstr(selection)
    name = cmd.get_legal_name(selection)
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    mol = ob.OBMol()
    obconversion.ReadString(mol, pdb_string)
    mol.AddHydrogens()
    ff = ob.OBForceField.FindForceField(forcefield)  # GAFF, MMFF94s, MMFF94, UFF, Ghemical
    ff.Setup(mol)
    if cutoff == True:
        ff.EnableCutOff(True)
        ff.SetVDWCutOff(cut_vdw)
        ff.SetElectrostaticCutOff(cut_elec)
    if method == 'conjugate gradients':
        ff.ConjugateGradients(nsteps, conv)
    else:
        ff.SteepestDescent(nsteps, conv)
    ff.GetCoordinates(mol)
    nrg = ff.Energy()
    pdb_string = obconversion.WriteString(mol)
    cmd.delete(name)
    if name == 'all':
        name = 'all_'
    cmd.read_pdbstr(pdb_string, name)
    print '#########################################'
    print 'The Energy of %s is %8.2f %s       ' % (name, nrg, ff.GetUnit())
    print '#########################################'
def colorize():
    cmd.hide('(not (name C+CA+N+O))')

    cmd.spectrum('b', 'red_yellow_green', minimum='-1.0', maximum='1.0')
    cmd.select('missing', 'b = -2.0')
    cmd.color('white', 'missing')
    cmd.delete('missing')
def com(selection,state=None,mass=None,object=None, quiet=1, **kwargs):
   """
DESCRIPTION
 
   Places a pseudoatom at the center of mass
 
   Author: Sean Law
   Michigan State University
   slaw (at) msu . edu
 
SEE ALSO
 
   pseudoatom, get_com
   """
   quiet = int(quiet)
   if (object == None):
      object = cmd.get_legal_name(selection)
      object = cmd.get_unused_name(object + "_COM", 0)
   cmd.delete(object)
 
   if (state != None):
      x, y, z=get_com(selection,mass=mass, quiet=quiet)
      if not quiet:
         print "%f %f %f" % (x, y, z)
      cmd.pseudoatom(object,pos=[x, y, z], **kwargs)
      cmd.show("spheres",object)
   else:
      for i in range(cmd.count_states()):
         x, y, z=get_com(selection,mass=mass,state=i+1, quiet=quiet)
         if not quiet:
            print "State %d:%f %f %f" % (i+1, x, y, z)
         cmd.pseudoatom(object,pos=[x, y, z],state=i+1, **kwargs)
         cmd.show("spheres", 'last ' + object)
Example #12
0
def slowpacking(pdb):
    "Derive mean packing density of pdb as pd.Series."
    cmd.delete('all')
    cmd.load(pdb)
    cmd.remove('solvent')
    # Only heavy atoms
    cmd.remove('hydro')
    # Compute SAS per atom
    cmd.set('dot_solvent')
    cmd.get_area('all', load_b=1)
    N = float(cmd.select('interior', 'b = 0'))

    internal_coords = [at.coord for at in cmd.get_model('interior').atom]#[1:50]
    all_coords = [at.coord for at in cmd.get_model('all').atom]#[1:50]

    # Count
    counts = pd.Series(0, index=RADS)
    for a, b in product(internal_coords, all_coords):
        es = euclid_step(a, b)
        if es is not None:
            counts.loc[es] += 1
    counts = counts.cumsum()
    # Mean per center atom
    meancounts = counts / N
    # Normalize to density
    volumina = pd.Series(4 / 3.0 * sp.pi * (RADS ** 3), index=RADS)
    density = meancounts / volumina
    # Correct for center
    density -= 1 / (4/3 * sp.pi * RADS ** 3)
    # Results
    counts.index = ["{}_correctcount".format(i) for i in counts.index]
    density.index = ["{}_density".format(i) for i in density.index]
    return pd.concat(([counts, density]))
Example #13
0
 def on_showaxes_clicked(self, event=None):
     if self.showaxesbtn['text'] == 'Show the axes':
         draw_axes()
         self.showaxesbtn['text'] = 'Hide the axes'
     else:
         cmd.delete('axes')
         self.showaxesbtn['text'] = 'Show the axes'
Example #14
0
def cartoonize(color, rep):
    """draw a cartoon representation of glycans"""
    stored.ResiduesNumber = []
    cmd.iterate('name c1', 'stored.ResiduesNumber.append((resi))')
    resn_list = [int(i) for i in stored.ResiduesNumber]
    bonds = get_glyco_bonds(resn_list[0], resn_list[-1]+1)
    con_matrix = writer(bonds)
    #con_matrix = writer2(bonds)
    rings = find_rings(resn_list)
    rings_coords = get_ring_coords(resn_list, rings)
    bonds_coords = get_bonds_coords(resn_list, con_matrix)
    colors = get_colors_c1(resn_list, color)
    bonds_colors = get_bonds_colors(resn_list, con_matrix, color)
    cmd.set('suspend_updates', 'on')
    for state, coords in enumerate(rings_coords):
        obj = []
        if rep == 'beads':
            radius_s = 1.8
            radius_b = 0.18
            obj = beads(obj, coords, colors[state], radius_s)
            obj = cylinder(obj, bonds_coords[state], bonds_colors[state], radius_b)
        else:
            if rep == 'cartoon':
                radius = 0.075
            else: 
                radius = 0.035
            obj = hexagon(obj, coords, colors[state], rep, radius)
            obj = cylinder(obj, bonds_coords[state], bonds_colors[state], radius)
        cmd.load_cgo(obj,'cgo01', state+1)

    cmd.select('glycan', 'byres name C1')
    cmd.delete('glycan')
    cmd.delete('tmp')
    cmd.set('two_sided_lighting', 1)
    cmd.set('suspend_updates', 'off')
Example #15
0
def packing(pdb):
    "Derive mean packing density of pdb as pd.Series."
    cmd.delete('all')
    cmd.load(pdb)
    cmd.remove('solvent')
    # Only heavy atoms
    cmd.remove('hydro')
    # Compute SAS per atom
    cmd.set('dot_solvent', 1)
    cmd.get_area('all', load_b=1)
    cmd.select('interior', 'b = 0')

    counts = pd.Series(0, index=RADS)
    vest = pd.Series(0, index=RADS)
    # from biggest to smallest radius
    for r in RADS[::-1]:
        # Counting
        counts.loc[r] = cmd.select('extended', 'interior extend {}'.format(r))
        cmd.remove('not extended')
        # moleculare area
        #cmd.set('dot_solvent', 0)
        vest[r] = cmd.get_area('all')
    # Results
    cvdens = counts / vest
    counts.index = ["{}_rawcount".format(i) for i in counts.index]
    vest.index = ["{}_volume estimate".format(i) for i in vest.index]
    cvdens.index = ["{}_cv density".format(i) for i in cvdens.index]
    return pd.concat(([counts, cvdens, vest]))
Example #16
0
def process_molecule_mae(file_header, mol, suspend_undo):
    global already_processed
    global undo_each_molecule
    tot = []
    tot.extend(file_header)
    tot.extend(mol)
    molstr = string.join(tot,'')

    nameorig, mdl = read_mae_model(molstr)
    name = nameorig.strip()
    if name in already_processed:
        return True
    already_processed = set(already_processed | set([name]))
    tmpname = "_temp_%s" % name
    cmd.delete(tmpname)

    try:
        cmd.load_model(mdl, tmpname)
        natoms = cmd.count_atoms(tmpname)
    except:
        return False
    if undo_each_molecule:
        cmd.push_undo( "( %s )" % name, just_coordinates=0)
        cmd.set("suspend_undo", 1, updates=0)
    cmd.remove(name)
    cmd.create(name, tmpname, copy_properties=True)
    cmd.set_title(name, -1, "")

    cmd.delete(tmpname)
    if undo_each_molecule:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return True
Example #17
0
def showHbBond(sele1, sele2, onlyShortest=True):
    '''Show hydrogen bond between two residues.
    '''
    
    atoms1 = getAllAtoms(sele1)
    atoms2 = getAllAtoms(sele2)
    
    smallestDist = 10000
    smallestDistObj = None
    
    for firstAtom in atoms1:
        if not hasHbond(firstAtom): continue
        firstSele = "name " + firstAtom + " and " + sele1 
        for secondAtom in atoms2:
            if not hasHbond(secondAtom): continue
            secondSele = "name " + secondAtom + " and " + sele2
#             print firstSele
#             print secondSele 
            distName = sele1+firstAtom+'-'+sele2+secondAtom
            tempDist = cmd.distance(distName, firstSele, secondSele)
            
            if tempDist < smallestDist:
                smallestDist = tempDist
                if smallestDistObj:
                    cmd.delete(smallestDistObj)
                smallestDistObj = distName
         
            else:
                cmd.delete(distName)
Example #18
0
    def DisplaySphere(self):
   
        try:
            # Display the Sphere
            cmd.delete(self.SphereDisplay)
            cmd.refresh()
        except:
            pass

        try:
            cmd.pseudoatom(self.SphereDisplay,
                           pos=self.SphereView.Center,
                           vdw=self.SphereView.Radius,
                           state=self.State)
            cmd.refresh()

            cmd.color('oxygen', self.SphereDisplay)
            cmd.refresh()

            cmd.hide('everything', self.SphereDisplay)
            cmd.refresh()

            cmd.show('spheres', self.SphereDisplay)
            cmd.refresh()
            
        except:
            self.ErrorCode = 1

        return self.ErrorCode
Example #19
0
def process_molecule_sdf(mol, suspend_undo):
    global already_processed
    global undo_each_molecule
    nameorig = mol[0]
    name = nameorig.strip()
    if name in already_processed:
        return True
    already_processed = set(already_processed | set([name]))
    tmpname = "_temp_%s" % name
    molstr = string.join(mol,'')
    cmd.delete(tmpname)
    try:
        importing.read_sdfstr(molstr, tmpname,object_props='*')
        natoms = cmd.count_atoms(tmpname)
    except:
        return False
    if undo_each_molecule:
        cmd.push_undo( "( %s )" % name, just_coordinates=0)
        cmd.set("suspend_undo", 1, updates=0)
    cmd.remove(name)

    print "before cmd.create(): using copy_properties=True"
    cmd.create(name, tmpname, copy_properties=True)
    cmd.set_title(name, -1, "")

    cmd.delete(tmpname)
    if undo_each_molecule:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return True
Example #20
0
def rc( selection = "all" ):
  """
  tube coloring for large RNA comparisons
  """
  cmd.bg_color( "white" )

  cmd.hide( 'everything',selection )

  cmd.color( 'red','resn rG+G+DG and '+selection )
  cmd.color( 'forest','resn rC+C+DC and '+selection)
  cmd.color( 'orange','resn rA+A+DA and '+selection)
  cmd.color( 'blue','resn rU+U+DT+BRU and '+selection)

  cmd.select( 'backbone', " (name o1p+o2p+o3p+p+op1+op2+'c1*'+'c2*'+'c3*'+'c5*'+'o2*'+'o3*'+'o4*'+'o5*'+'c1*'+'c2*'+'c3*'+'c4*'+'o2*'+'o4*'+c1'+c2'+c3'+c5'+o2'+o3'+o4'+o5'+c1'+c2'+c3'+c4'+o2'+o4') and (not name c1+c2+c3+c4+c5+o2+o3+o4+o5) ")

  #for x in AllObj:
  #print x
  cmd.show( "cartoon", selection )
  cmd.spectrum( "resi", "rainbow", selection+" and backbone" )

  cmd.cartoon( "tube", "backbone and "+selection )

  cmd.set( "cartoon_ring_mode", 0 )
  cmd.set( "cartoon_ring_transparency", 0.0 )
  cmd.set( "cartoon_tube_radius", 1.0 )

  cmd.color( 'red','resn rG+G and name n1+c6+o6+c5+c4+n7+c8+n9+n3+c2+n1+n2 and '+selection)
  cmd.color( 'forest','resn rC+C and name n1+c2+o2+n3+c4+n4+c5+c6 and '+selection)
  cmd.color( 'orange','resn rA+A and name n1+c6+n6+c5+n7+c8+n9+c4+n3+c2 and '+selection)
  cmd.color( 'blue','resn rU+U and name n3+c4+o4+c5+c6+n1+c2+o2 and '+selection)

  cmd.delete('backbone')
Example #21
0
    def Quit_Wizard(self):

        try:
            # Delete Sphere object
            General_cmd.unmask_Objects(self.exc)
            cmd.config_mouse(self.config_mouse)

            cmd.delete(self.SphereDisplay)
            cmd.refresh()
        except:
            pass

        # Catch error in App
        if self.ErrorCode > 0:
            self.App.WizardError = True

        # Re-enable controls
        
        self.App.ActiveWizard = None

        cmd.set_wizard()
        cmd.set_view(self.View)
        cmd.refresh()
                
        self.queue.put(lambda: self.top.SphereRunning(False))
        self.queue.put(lambda: self.top.top.root.deiconify())
        self.queue.put(lambda: self.top.top.root.update())
Example #22
0
def chain_contact():
    def chain_contact_loop(c,skip,chainPullList):
        d = 0
        l = c + 1
        while len(chainPullList) > l and (26-d) >= 0:
            cmd.select('chain_contact','%s w. 5 of %s'%(chainPullList[d],chainPullList[c+1]),enable=0,quiet=1,merge=1)
            cmd.select('chain_contact','%s w. 5 of %s'%(chainPullList[c+1],chainPullList[d]),enable=0,quiet=1,merge=1)
            d += 1
            l += 1
            while d == (c+1) or d in skip:
                d += 1
    glb.update()
    cmd.hide('everything')
    cmd.show('mesh', 'all')
    cmd.color('gray40', 'all')
    objects = cmd.get_names('all')
    chainPullList = []
    for i in cmd.get_chains(quiet=1):
        chainPullList.append('Chain-'+i)
    if len(chainPullList) < 2:
        showinfo('Notice','There needs to be two or more chains to run this functions.')
        return False
    c = 0
    skip = []
    while c < (len(chainPullList)-1) and c < 26:
        skip.append(c+1)
        chain_contact_loop(c,skip,chainPullList)
        c += 1
    glb.procolor('chain_contact','mesh','cpk',None)
    cmd.delete('chain_contact')
    return chainPullList
Example #23
0
File: B08.py Project: Almad/pymol
def load():
   cmd.set("valence")
   r = 0
   list = glob("pdb/*/*")
#   while list[0]!="pdb/f8/pdb1f8u":
#      list.pop(0)
   for file in list:
      try:
         cmd.delete('pdb')
         cmd.load(file,'pdb')
         cmd.set_title('pdb',1,os.path.split(file)[-1])
         cmd.rewind()
         cmd.orient('pdb')
         cmd.refresh()
         cmd.zoom('center',16)
         cmd.label("polymer and (name ca or elem P)","'//%s/%s/%s`%s/%s'%(segi,chain,resn,resi,name)")
         cmd.refresh()
         sys.__stderr__.write(".")
         sys.__stderr__.flush()
         n = cmd.count_states()
         if n>1:
            cmd.rewind()
            sys.__stderr__.write(file+"\n")
            sys.__stderr__.flush()
            for a in range(1,n+1):
               cmd.forward()
               cmd.refresh()
      except:
         traceback.print_exc()
Example #24
0
def test_conelineinter(sele):
    v = com(sele + " and name SG")
    a = (v - com(sele + " and name CB")).normalized()
    print v, a
    p = v + 5 * randvec()
    d = randvec().normalized()
    # v = Vec(0, 0, 0)
    # a = Vec(1, 0, 0)
    t = 45
    X = conelineinter(p, d, v, a, t)
    print "p", p
    print "d", d
    print "v", v
    print "a", a
    print "t", t
    print "X", X
    cmd.delete("lines")
    cmd.delete("X*")
    cmd.delete("L*")
    cmd.delete("A*")
    cmd.delete("B*")
    drawlines(p, d)
    for i, x in enumerate(X):
        createpoint(sele, x, "X" + str(i))
        o = projperp(a, x - v)
        L = o.length()
        o = o.normalized()
        ang = 90.0 - math.atan(1.0 / L) * 180.0 / math.pi
        print ang
        o1 = rotation_matrix(a, ang) * o
        o2 = rotation_matrix(a, -ang) * o
        createpoint(sele, v + o1, "A" + str(i))
        createpoint(sele, v + o2, "B" + str(i))
        drawlines(x, (x - (v + o1)).normalized(), "LA" + str(i))
        drawlines(x, (x - (v + o2)).normalized(), "LB" + str(i))
Example #25
0
def amber99(selection="(all)",quiet=0,_self=cmd):
    cmd=_self
    result = 1
    # first, set all parameters to zero

    cmd.alter(selection,"partial_charge=0")
    cmd.alter(selection,"elec_radius=0.0")
    cmd.alter(selection,"text_type=''")

    # next, flag all atoms so that we'll be able to detect what we miss
    
    cmd.flag(23,selection,'set')

    # get the amber99 dictionary
    
    if not hasattr(champ,'amber99_dict'):
        from chempy.champ.amber99 import amber99_dict
        champ.amber99_dict = amber99_dict

    # iterate through the residue dictionary matching each residue based on chemistry
    # and generating the expressions for reassigning formal charges
    
    alter_list = []
    for resn in champ.amber99_dict.keys():
        if cmd.select(tmp_sele1,"(%s) and resn %s"%(selection,resn))>0:
            entry = champ.amber99_dict[resn]
            for rule in entry:
                model = cmd.get_model(tmp_sele1)
                ch = Champ()
                model_pat = ch.insert_model(model)
                ch.pattern_detect_chirality(model_pat)
                assn_pat = ch.insert_pattern_string(rule[0])
                ch.pattern_clear_tags(model_pat)
                if ch.match_1v1_n(assn_pat,model_pat,10000,2)>0:
                    result = ch.pattern_get_ext_indices_with_tags(model_pat)
                    for atom_tag in result[0]: # just iterate over atom tags
                        if len(atom_tag[1])==1: # one and only one match
                            tag = atom_tag[1][0]
                            prop_list = rule[1][tag]
                            # the following expression both changes the formal charge and resets flag 23
                            alter_list.append([atom_tag[0],
            "name='''%s''';text_type='''%s''';partial_charge=%f;elec_radius=%f;flags=flags&-8388609"%prop_list])

    # now evaluate all of these expressions efficiently en-masse 
    cmd.alter_list(selection,alter_list)

    # see if we missed any atoms
    missed_count = cmd.count_atoms("("+selection+") and flag 23")

    if missed_count>0:
        if not quiet:
            # looks like we did, so alter the user
            print " WARNING: %d atoms did not have properties assigned"%missed_count
        result = 0

    # remove the temporary selection we used to select appropriate residues
    
    cmd.delete(tmp_sele1)

    return result
Example #26
0
def mkpntx(s1, s2):
    x = com(s1) - com(s2)
    if abs(x.x) > 0.1 or abs(x.y) > 0.1:
        print "DIE!", x
        return
    z = x.z
    c = Vec(0, z / 2 / math.tan(36.0 * math.pi / 180), z / 2)
    cmd.delete("p1")
    cmd.delete("p2")
    cmd.delete("p3")
    cmd.delete("p4")
    cmd.delete("p5")
    cmd.create("p1", s1)
    cmd.create("p2", s1)
    cmd.create("p3", s1)
    cmd.create("p4", s1)
    cmd.create("p5", s1)
    rot("p1", Vec(1, 0, 0), 0 * 72, c)
    rot("p2", Vec(1, 0, 0), 1 * 72, c)
    rot("p3", Vec(1, 0, 0), 2 * 72, c)
    rot("p4", Vec(1, 0, 0), 3 * 72, c)
    rot("p5", Vec(1, 0, 0), 4 * 72, c)
    cmd.color("green", "p1 and elem C")
    cmd.color("cyan", "p2 and elem C")
    cmd.color("yellow", "p3 and elem C")
    cmd.color("magenta", "p4 and elem C")
    cmd.color("orange", "p5 and elem C")
Example #27
0
def drawtestconeva(v, a):
    cmd.delete("cone hyperb")
    # v = com(sele+" and name SG")
    # a = (v - com(sele+" and name CB")).normalized()
    # print v, a
    ang = 5.0
    R = rotation_matrix(a, ang)
    perp = a.cross(randvec()).normalized()
    p = v + perp
    d = rotation_matrix(perp, 45) * a
    P, D = [], []
    for i in range(int(360 / ang)):
        P.append(p)
        D.append(d)
        p = R * (p - v) + v
        d = R * d
    drawlines(P, D, "hyperb", COL=(0, 0, 1))
    p = v
    d = rotation_matrix(a.cross(randvec()), 45) * a
    P, D = [], []
    for i in range(360 / ang):
        P.append(p)
        D.append(d)
        d = R * d
    drawlines(P, D, "cone", COL=(1, 0, 0))
Example #28
0
    def sculpt(self,cleanup=0):
        if not cleanup:
            cmd.set("suspend_updates",1,quiet=1)
            cmd.disable()
            cmd.delete("sculpt")
            cmd.set("sphere_scale","1.0")
            cmd.set("sphere_mode",5)
            cmd.load("$PYMOL_DATA/demo/pept.pdb","sculpt")
            cmd.hide("lines","sculpt")
#            cmd.show("sticks","sculpt")
            cmd.show("spheres","sculpt")
#            cmd.set("sphere_transparency","0.75","sculpt")
#            cmd.set("sphere_color","grey","sculpt")
            cmd.frame(1)
            cmd.set("auto_sculpt",1)
            cmd.set("sculpting",1)
            cmd.sculpt_activate("sculpt")
            cmd.set("sculpting_cycles","100")
            cmd.do("edit_mode")
            cmd.set("valence","0.05")
            cmd.set("suspend_updates",0,quiet=0)
            cmd.sculpt_iterate("sculpt")
            cmd.alter_state(1,"sculpt","x=x*1.5;y=y*0.1;z=z*1.5")
            cmd.zoom()

            cmd.unpick()
        else:
            cmd.set("valence","0")
            cmd.set("sculpting",0)
            cmd.set("auto_sculpt",0)
            cmd.delete("sculpt")
            cmd.mouse()
def findSurfaceAtoms(selection="all", cutoff=2.5, quiet=1):
    """
DESCRIPTION

    Finds those atoms on the surface of a protein
    that have at least 'cutoff' exposed A**2 surface area.

USAGE

    findSurfaceAtoms [ selection, [ cutoff ]]

SEE ALSO

    findSurfaceResidues
    """
    cutoff, quiet = float(cutoff), int(quiet)

    tmpObj = cmd.get_unused_name("_tmp")
    cmd.create(tmpObj, "(" + selection + ") and polymer", zoom=0)

    cmd.set("dot_solvent", 1, tmpObj)
    cmd.get_area(selection=tmpObj, load_b=1)

    # threshold on what one considers an "exposed" atom (in A**2):
    cmd.remove(tmpObj + " and b < " + str(cutoff))

    selName = cmd.get_unused_name("exposed_atm_")
    cmd.select(selName, "(" + selection + ") in " + tmpObj)

    cmd.delete(tmpObj)

    if not quiet:
        print("Exposed atoms are selected in: " + selName)

    return selName
Example #30
0
def hide_rep(tag):
    try:
        sel = glb.SELE
        if tag == 'Lines':
            cmd.hide('lines', sel)
        elif tag == 'Sticks':
            cmd.hide('sticks', sel)
        elif tag == 'Ribbons':
            cmd.hide('ribbon', sel)
        elif tag == 'Cartoon':
            cmd.hide('cartoon', sel)
        elif tag == 'Dots':
            cmd.hide('dots', sel)
        elif tag == 'Spheres':
            cmd.hide('spheres', sel)
        elif tag == 'Mesh':
            cmd.hide('mesh', sel)
        elif tag == 'Surface':
            cmd.hide('surface', sel)
        elif tag == 'Water':
            cmd.hide('(resn HOH)')
        elif tag == 'Everything':
            cmd.hide('everything', sel)
        elif tag == 'Ball and Stick':
            cmd.hide('spheres', sel)
            cmd.hide('sticks', sel)
        elif tag == 'Polar Contacts':
            cmd.delete(sel+"_polar_conts")
    except:
        showinfo('Error', 'Update Selection!')
def ColorByDisplacementAll(objSel1,
                           objSel2,
                           super1='all',
                           super2='all',
                           doColor="True",
                           doAlign="True",
                           AlignedWhite='yes'):
    ### First create backup copies; names starting with __ (underscores) are normally hidden by PyMOL
    tObj1, tObj2, aln = "__tempObj1", "__tempObj2", "__aln"

    if strTrue(doAlign):
        ### Create temp objects
        cmd.create(tObj1, objSel1)
        cmd.create(tObj2, objSel2)
        ### Align and make create an object aln which indicates which atoms were paired between the two structures
        ### Super is must faster than align http://www.pymolwiki.org/index.php/Super
        cmd.super(tObj1 + ' and ' + str(super1),
                  tObj2 + ' and ' + str(super2),
                  object=aln)
        ### Modify the original matrix of object1 from the alignment
        cmd.matrix_copy(tObj1, objSel1)
    else:
        ### Create temp objects
        cmd.create(tObj1, objSel1)
        cmd.create(tObj2, objSel2)
        ### Align and make create an object aln which indicates which atoms were paired between the two structures
        ### Super is must faster than align http://www.pymolwiki.org/index.php/Super
        cmd.super(tObj1 + ' and ' + str(super1),
                  tObj2 + ' and ' + str(super2),
                  object=aln)

    ### Modify the B-factor columns of the original objects,
    ### in order to identify the residues NOT used for alignment, later on
    cmd.alter(objSel1 + " or " + objSel2, "b=-0.2")
    cmd.alter(tObj1 + " or " + tObj2, "chain='A'")
    cmd.alter(tObj1 + " or " + tObj2, "segi='A'")

    ### Update pymol internal representations; one of these should do the trick
    cmd.refresh()
    cmd.rebuild()
    cmd.sort(tObj1)
    cmd.sort(tObj2)

    ###  Create lists for storage
    stored.alnAres, stored.alnBres = [], []

    ### Iterate over objects and get resi
    if AlignedWhite == 'yes':
        cmd.iterate(tObj1 + " and not " + aln,
                    "stored.alnAres.append((resi, name))")
        cmd.iterate(tObj2 + " and not " + aln,
                    "stored.alnBres.append((resi, name))")
    else:
        cmd.iterate(tObj1, "stored.alnAres.append((resi, name))")
        cmd.iterate(tObj2, "stored.alnBres.append((resi, name))")

    ### Change the B-factors for EACH object
    displacementUpdateBAll(tObj1, stored.alnAres, tObj2, stored.alnBres)

    ### Store the NEW B-factors
    stored.alnAnb, stored.alnBnb = [], []
    ### Iterate over objects and get b

    if AlignedWhite == 'yes':
        ### Iterate over objects which is not aligned
        cmd.iterate(tObj1 + " and not " + aln, "stored.alnAnb.append(b)")
        cmd.iterate(tObj2 + " and not " + aln, "stored.alnBnb.append(b)")
    else:
        ### Or Iterate over all objects with CA
        cmd.iterate(tObj1, "stored.alnAnb.append(b)")
        cmd.iterate(tObj2, "stored.alnBnb.append(b)")

    ### Get rid of all intermediate objects and clean up
    cmd.delete(tObj1)
    cmd.delete(tObj2)
    cmd.delete(aln)

    ### Assign the just stored NEW B-factors to the original objects
    print "Sooon ready. 1 more minute"
    for x in range(len(stored.alnAres)):
        cmd.alter(
            objSel1 + " and resi " + str(stored.alnAres[x][0]) + " and name " +
            str(stored.alnAres[x][1]), "b = " + str(stored.alnAnb[x]))
    for x in range(len(stored.alnBres)):
        cmd.alter(
            objSel2 + " and resi " + str(stored.alnBres[x][0]) + " and name " +
            str(stored.alnBres[x][1]), "b = " + str(stored.alnBnb[x]))
    cmd.rebuild()
    cmd.refresh()
    cmd.sort(objSel1)
    cmd.sort(objSel2)

    ### Provide some useful information
    stored.allRMSDval = []
    stored.allRMSDval = stored.alnAnb + stored.alnBnb
    print "\nColorByDisplacementAll completed successfully."
    print "The MAXIMUM Displacement is: " + str(max(
        stored.allRMSDval)) + " residue " + str(stored.alnAres[int(
            stored.allRMSDval.index(max(stored.allRMSDval)))])

    if strTrue(doColor):
        ### Showcase what we did
        #cmd.orient()
        #cmd.hide("all")
        cmd.show("sticks", objSel1 + " or " + objSel2)
        ### Select the residues not used for alignment; they still have their B-factors as "-0.2"
        cmd.select("notUsedForAln", "b = -0.2")
        ### White-wash the residues not used for alignment
        cmd.color("white", "notUsedForAln")
        ### Select the residues not in both pdb files; they have their B-factors as "-0.01"
        cmd.select("ResNotInBothPDB", "b = -0.01")
        ### White-wash the residues not used for alignment
        cmd.color("black", "ResNotInBothPDB")
        ### Color the residues used for alignment according to their B-factors (Displacement values)
        #cmd.spectrum("b", 'rainbow',  "((" + objSel1 + ") or (" + objSel2 +" )) and not notUsedForAln+ResNotInBothPDB")
        cmd.spectrum(
            "b", 'rainbow', "((" + objSel1 + ") or (" + objSel2 +
            " )) and not (notUsedForAln or ResNotInBothPDB)")
        ### Delete the selection of atoms not used for alignment
        ### If you would like to keep this selection intact,
        ### just comment "cmd.delete" line and
        ### uncomment the "cmd.disable" line abowe.
        cmd.disable("notUsedForAln")
        cmd.delete("notUsedForAln")
        cmd.disable("ResNotInBothPDB")
        cmd.delete("ResNotInBothPDB")
        print "\nObjects are now colored by C-alpha displacement deviation."
        print "Blue is minimum and red is maximum..."
        print "White is those residues used in the alignment algorithm. Can be turned off in top of algorithm."
        print "Black is residues that does not exist in both files..."
Example #32
0
import pandas as pd
from pymol import cmd
import os
from tqdm import tqdm
pdb_path = "./pdbs"

data = pd.read_csv("./csvs/less-than-256.csv")

num_atoms = []
print("Loading number of atoms.")
for pdb_file_name in tqdm(data.columns):
    cmd.delete("all")
    if len(pdb_file_name) != 4:
        pdb_file_name = pdb_file_name[1:]
    pdb_file_name = pdb_file_name.lower()
    pdb_path = "./pdbs/" + pdb_file_name + ".pdb"
    if not os.path.exists(pdb_path):
        print('fetching', pdb_file_name)
        cmd.fetch(pdb_file_name, path=os.path.join('.', 'pdbs'), type='pdb')
    else:
        cmd.load(pdb_path)
    num_atoms.append(cmd.count_atoms("all"))

data = data.transpose()
data['num_atoms'] = num_atoms
data = data.nsmallest(data.shape[0],
                      'num_atoms')  # use nlargest for to get the inverse
data.drop("num_atoms", axis=1, inplace=True)
data = data.transpose()
data.to_csv('./csvs/sorted-less-than-256.csv', index=False)
Example #33
0
    return pymol_module


ligands_dir = 'test/test_files/ligand_system/'
ligand_files = [
    '5_long_Ligands.pdb', '7_veryDifferent_Ligands.pdb',
    '9_similar_Ligands.pdb', '21_large_Ligands.pdb'
]  #['9_similar_Ligands.pdb','7_veryDifferent_Ligands.pdb',

ligands_path = [ligands_dir + lig_file for lig_file in ligand_files]
cmd = start_pymol()

all_results_dir = '/home/rhinerc/Desktop/ALL TEST RESULTS/all_optimizers/pca_criterion'

for lig in ligands_path:
    cmd.delete('all')
    pymol_module = load_ligands(lig)

    print('COMPARING ' + lig)
    print('len(all_atoms)', len(pymol_module.logic_handler.all_atoms))
    print('len(selected_atoms)',
          len(pymol_module.logic_handler.selected_atoms))
    print('len(selected_restraints)',
          len(pymol_module.logic_handler.selected_restraints))

    start_time = time.time()
    #Note; Changed criterion from convex_hull back to pca unscaled on Fr 24.05
    Optimizer.compare_pair_optimizers(criterion=Optimizer._calculate_value_unscaled_pca_2d, \
                                  atoms=pymol_module.logic_handler.all_atoms, \
                                  opt_types=[Optimizer.TreeHeuristicOptimizer, Optimizer.TreeHeuristicOptimizer,
                                              Optimizer.TreeHeuristicOptimizer, Optimizer.TreeHeuristicOptimizer,Optimizer.BestMoleculeRingOptimizer,Optimizer.BruteForceRingOptimzer,
Example #34
0
def color_by_mutation(obj1, obj2, waters=0, labels=0):
    '''
    DESCRIPTION

        Creates an alignment of two proteins and superimposes them.
        Aligned residues that are different in the two (i.e. mutations) are highlighted and
        colored according to their difference in the BLOSUM90 matrix.
        Is meant to be used for similar proteins, e.g. close homologs or point mutants,
        to visualize their differences.

    USAGE

        color_by_mutation selection1, selection2 [,waters [,labels ]]

    ARGUMENTS

        obj1: object or selection

        obj2: object or selection

        waters: bool (0 or 1). If 1, waters are included in the view, colored
                differently for the both input structures.
                default = 0

        labels: bool (0 or 1). If 1, the possibly mutated sidechains are
                labeled by their chain, name and id
                default = 0

    EXAMPLE

        color_by_mutation protein1, protein2

    SEE ALSO

        super
    '''
    from pymol import stored, CmdException

    if cmd.count_atoms(obj1) == 0:
        print('%s is empty' % obj1)
        return
    if cmd.count_atoms(obj2) == 0:
        print('%s is empty' % obj2)
        return
    waters = int(waters)
    labels = int(labels)

    # align the two proteins
    aln = '__aln'

    # first, an alignment with 0 cycles (no atoms are rejected, which maximized the number of aligned residues)
    # for some mutations in the same protein this works fine). This is essentially done to get a
    # sequence alignment
    cmd.super(obj1, obj2, object=aln, cycles=0)

    # superimpose the the object using the default parameters to get a slightly better superimposition,
    # i.e. get the best structural alignment
    cmd.super(obj1, obj2)

    stored.resn1, stored.resn2 = [], []
    stored.resi1, stored.resi2 = [], []
    stored.chain1, stored.chain2 = [], []

    # store residue ids, residue names and chains of aligned residues
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resn1.append(resn)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resn2.append(resn)')

    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resi1.append(resi)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resi2.append(resi)')

    cmd.iterate(obj1 + ' and name CA and ' + aln,
                'stored.chain1.append(chain)')
    cmd.iterate(obj2 + ' and name CA and ' + aln,
                'stored.chain2.append(chain)')

    mutant_selection = ''
    non_mutant_selection = 'none or '
    colors = []

    # loop over the aligned residues
    for n1, n2, i1, i2, c1, c2 in zip(stored.resn1, stored.resn2, stored.resi1,
                                      stored.resi2, stored.chain1,
                                      stored.chain2):
        # take care of 'empty' chain names
        if c1 == '':
            c1 = '""'
        if c2 == '':
            c2 = '""'
        if n1 == n2:
            non_mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or ' % (
                obj1, i1, c1, obj2, i2, c2)
        else:
            mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or ' % (
                obj1, i1, c1, obj2, i2, c2)
            # get the similarity (according to the blosum matrix) of the two residues and
            c = getBlosum90ColorName(n1, n2)
            colors.append(
                (c, '%s and resi %s and chain %s and elem C' % (obj2, i2, c2)))

    if mutant_selection == '':
        raise CmdException('No mutations found')

    # create selections
    cmd.select('mutations', mutant_selection[:-4])
    cmd.select('non_mutations', non_mutant_selection[:-4])
    cmd.select(
        'not_aligned',
        '(%s or %s) and not mutations and not non_mutations' % (obj1, obj2))

    # create the view and coloring
    cmd.hide('everything', '%s or %s' % (obj1, obj2))
    cmd.show('cartoon', '%s or %s' % (obj1, obj2))
    cmd.show(
        'lines',
        '(%s or %s) and ((non_mutations or not_aligned) and not name c+o+n)' %
        (obj1, obj2))
    cmd.show('sticks',
             '(%s or %s) and mutations and not name c+o+n' % (obj1, obj2))
    cmd.color('gray', 'elem C and not_aligned')
    cmd.color('white', 'elem C and non_mutations')
    cmd.color('blue', 'elem C and mutations and %s' % obj1)
    for (col, sel) in colors:
        cmd.color(col, sel)

    cmd.hide('everything', '(hydro) and (%s or %s)' % (obj1, obj2))
    cmd.center('%s or %s' % (obj1, obj2))
    if labels:
        cmd.label('mutations and name CA', '"(%s-%s-%s)"%(chain, resi, resn)')
    if waters:
        cmd.set('sphere_scale', '0.1')
        cmd.show('spheres', 'resn HOH and (%s or %s)' % (obj1, obj2))
        cmd.color('red', 'resn HOH and %s' % obj1)
        cmd.color('salmon', 'resn HOH and %s' % obj2)
    print('''
             Mutations are highlighted in blue and red.
             All mutated sidechains of %s are colored blue, the corresponding ones from %s are
             colored on a spectrum from blue to red according to how similar the two amino acids are
             (as measured by the BLOSUM90 substitution matrix).
             Aligned regions without mutations are colored white.
             Regions not used for the alignment are gray.
             NOTE: There could be mutations in the gray regions that were not detected.'''
          % (obj1, obj2))
    cmd.delete(aln)
    cmd.deselect()
Example #35
0
                                  "ligand",
                                  "polar_atoms",
                                  mode=2)
        print("Polar contact: ")
        print polar_distance, halo.name, halo.resn, halo.resi
        model_polar = cmd.get_model("current_polar")
        for pol in model_polar.atom:
            cmd.select("current_polar", "id %s" % (pol.id))
            # check for halogen bonds, distances 5.0, angles: > 140
            current_distance = cmd.distance("current_distance",
                                            "current_halogen", "current_polar")
            current_angle = cmd.angle("current_angle", "current_neighbor",
                                      "current_halogen", "current_polar")

            if (current_angle >= 140) and (current_distance <= 5.0):
                print("Halogen bond: ")
                print current_distance, current_angle, pol.name, pol.resn, pol.resi

            cmd.delete("current_angle")
            cmd.delete("current_distance")

    # visualizations
    cmd.hide("lines")
    cmd.hide(
        "nonbonded")  # hide all nonbonded atoms, i.e. oxygen of water or ions
    cmd.show("sticks", "ligand")
    cmd.show("lines", "bindingsite")
    cmd.show("nb_spheres", "water_bs")  # nb_spheres = non bonded spheres
    cmd.color("skyblue", "water_bs")
    cmd.zoom("ligand", 5)  # high numbers = far away
Example #36
0
 def deleteArrows(self):
     for arrow in cmd.get_names_of_type("object:cgo"):
         if "rrow" in arrow:
             cmd.delete(arrow)
Example #37
0
 def showInteractions(self):
     if not "filtered" in self.logData:
         return
     currentSel = self.tree_data.focus()
     if currentSel == "" :
         return
     
     rowId = self.tree_data.item(currentSel)["values"][0] 
     data = self.logData["filtered"].iloc[[rowId]]
     pdbCode = data["PDB Code"].values[0]
     
     
     if self.currentMolecule["PdbCode"] and self.currentMolecule["PdbCode"] != pdbCode:
         cmd.delete(self.currentMolecule["PdbCode"])
         
     actual_objects = cmd.get_object_list()
     
     for obj in actual_objects:
         if obj.upper() != pdbCode.upper():
             cmd.delete(obj)
         
     if self.currentMolecule["PdbCode"] != pdbCode:
         if self.logData["cifDir"] != None:
             potentialPaths = [ path.join( self.logData["cifDir"] ,  pdbCode.lower() +".cif" ), path.join( self.logData["cifDir"] ,  pdbCode.upper() +".cif" )  ]
             cifFound = False
             for filePath in potentialPaths:
                 if path.isfile(filePath):
                     cmd.load(filePath)
                     cifFound = True
                     break
             if not cifFound:
                 cmd.fetch(pdbCode)
         else:    
             cmd.fetch(pdbCode)
     
     frame = int(data["Model No"].values[0])
     if frame != 0:
         cmd.frame(frame+1)
     
     
     selection = self.getSelection(data)
     
     selectionName = "suprSelection"
     
     cmd.select(selectionName, selection)
     cmd.show( "sticks" , selectionName  )
     cmd.center(selectionName)
     cmd.zoom(selectionName)
     
     if self.chkvar_around.get() > 0:
         selectionAroundName = "suprAround"
         radius = self.ent_around.get()
         try:
             radius = float(radius)
         except:
             return
         cmd.select( selectionAroundName,  "byres ( suprSelection around "+str(radius)+" ) " )
         cmd.select( selectionAroundName,  "byres ( suprSelection around 5 ) " )
         cmd.show("lines", selectionAroundName)
         self.logData["displayingAround"] = True
     else:
         self.logData["displayingAround"] = False
     
     self.deleteArrows()
         
     arrowBegin, arrowEnd = self.getArrow(data)
     cgo_arrow(arrowBegin, arrowEnd, 0.1, name = self.arrowName, color = self.arrowColor)
 
     self.logData["displaying"] = True
     self.currentMolecule["PdbCode"] = pdbCode
     
     cmd.deselect()
     
     self.actualDisplaying["rowData"] = data
     self.actualDisplaying["selectionTime"] = time()
Example #38
0
    def Btn_CreatePartition(self):

        DestFile = ''
        Output = self.Step3Output.get()

        if General.validate_String(Output, '', False, False, True):
            self.DisplayMessage(
                "  ERROR: Could not save the partition file because you entered an invalid name.",
                2)
            return

        auto_zoom = cmd.get("auto_zoom")

        if Output != '':

            if not self.Vertex:
                self.top.DisplayMessage(
                    "  ERROR: Cannot save an empty cleft. Add spheres that include volume of the parent.",
                    1)
                return

            if General_cmd.object_Exists(Output):
                answer = tkMessageBox.askquestion(
                    "Question",
                    message=
                    "An object with that name already exists. Would you like to overwrite it?",
                    icon='warning')
                if str(answer) == 'no':
                    return

            try:
                cmd.set("auto_zoom", 0)

                DestFile = os.path.join(self.top.GetCleftTempProject_Dir,
                                        Output + '.pdb')
                self.top.Manage.copy_TempPartition(self.TempPartition,
                                                   DestFile)

                cmd.load(DestFile, Output, state=1)
                cmd.refresh()

                cmd.hide('everything', Output)
                cmd.refresh()

                cmd.show('surface', Output)
                cmd.refresh()

                partition_rgb = self.top.Default.SetPartitionColor(
                    self.Cleft.CleftName)

                if len(partition_rgb):

                    cmd.color('partition', Output)
                    cmd.refresh()

                    cmd.delete(self.PartitionDisplay)
                    cmd.refresh()

                    Cleft = CleftObj.CleftObj()
                    Cleft.CleftFile = DestFile
                    Cleft.CleftName = self.Step3Output.get()
                    Cleft.PartitionParent = self.Cleft
                    Cleft.Partition = True
                    Cleft.UTarget = self.Cleft.UTarget
                    Cleft.Set_CleftMD5()
                    Cleft.Color = General.rgb_to_hex(partition_rgb)

                    self.top.Default.TempBindingSite.Add_Cleft(Cleft)
                    self.top.CopySession = False

                    # Put the partition cleft over its parent
                    General_cmd.Oscillate(self.Cleft.CleftName, 0.0)

                    self.Reset_Step1()

                else:
                    self.top.DisplayMessage(
                        "  ERROR: Cleft '" + self.Cleft.CleftName +
                        "' could not be found to set partition color", 1)

            except:
                self.top.DisplayMessage(
                    "  ERROR: Could not create partition object: File not found.",
                    1)

        else:
            self.top.DisplayMessage(
                "  ERROR: Could not create partition object: Output is null.",
                1)

        cmd.set("auto_zoom", auto_zoom)
Example #39
0
def draw_ligand(pdbmat2, pdb2, gcen2, iconf):
    #=============================
    ibeg = iconf * pdb2.natom
    ifin = ibeg + pdb2.natom
    ltype = LINES
    ligand_obj = pymol_cgo_new(ltype)
    # print('drawing conf: ',iconf,ibeg,ifin,pdb2.natom)
    #
    vbeg = [0., 0., 0.]
    vend = [0., 0., 0.]
    cbeg = .5
    cend = .9
    #
    # extract rot mat
    rmt2 = [[pdbmat2[0], pdbmat2[1], pdbmat2[2]],
            [pdbmat2[4], pdbmat2[5], pdbmat2[6]],
            [pdbmat2[8], pdbmat2[9], pdbmat2[10]]]
    #
    # extract trans
    trn2 = [pdbmat2[3], pdbmat2[7], pdbmat2[11]]
    #
    # find rotated origin in molc. local coords
    gcen2_rot = rot_vec(rmt2, gcen2)
    #
    # displacement of origin subtracted from apparant trans to get actual trans
    for k in range(3):
        trn2[k] = trn2[k] - (gcen2[k] - gcen2_rot[k])
    #
    # extract and transform coords from required model
    xyz = [0., 0., 0.]
    crd2 = []
    for i in range(ibeg, ifin):
        # apply rotations and translations
        for k in range(3):
            xyz[k] = pdb2.coords[i][k]
        for k in range(3):
            xyz[k] = pdb2.coords[i][k] - gcen2[k]
        xyz2 = rot_vec(rmt2, xyz)
        for k in range(3):
            xyz[k] = xyz2[k] + gcen2[k] + trn2[k]
        crd2.append([xyz[0], xyz[1], xyz[2]])
    #
    # generate bonds
    nbond = 0
    margin = 1.4
    for i in range(pdb2.natom):
        if (pdb2.name[i][2:3] == 'H'):
            radi = 1.1
        else:
            radi = pdb2.radius[i]
        for j in range(i + 1, pdb2.natom):
            #        print 'checking: ',i,j
            dist2 = 0.
            if (pdb2.name[j][2:3] == 'H'):
                radj = 1.1
            else:
                radj = pdb2.radius[j]
            for k in range(3):
                dist2 += (crd2[i][k] - crd2[j][k])**2
            dist = math.sqrt(dist2)
            overlap = dist + margin - radi - radj
            if (overlap < 0.):
                nbond += 1
                for k in range(3):
                    vbeg[k] = crd2[i][k]
                    vend[k] = crd2[j][k]
                if (pdb2.bfact[i] > 0.1):
                    cbeg = 0.1
                elif (pdb2.bfact[i] < -0.1):
                    cbeg = 0.9
                else:
                    cbeg = 2.
                if (pdb2.bfact[j] > 0.1):
                    cend = 0.1
                elif (pdb2.bfact[j] < -0.1):
                    cend = 0.9
                else:
                    cend = 2.
                pymol_cgo_addline(ligand_obj, vbeg, vend, cbeg, cend)
    # print "number of bonds: ",nbond
    pymol_cgo_end(ligand_obj)
    cmd.delete('ligand_obj')
    cmd.load_cgo(ligand_obj, 'ligand_obj')
Example #40
0
def show_contacts(selection,
                  selection2,
                  result="contacts",
                  cutoff=3.6,
                  bigcutoff=4.0,
                  SC_DEBUG=DEBUG):
    """
    USAGE
    
    show_contacts selection, selection2, [result=contacts],[cutoff=3.6],[bigcutoff=4.0]
    
    Show various polar contacts, the good, the bad, and the ugly.
    
    Edit MPB 6-26-14: The distances are heavy atom distances, so I upped the default cutoff to 4.0
    
    Returns:
    True/False -  if False, something went wrong
    """
    if SC_DEBUG > 4:
        print('Starting show_contacts')
        print('selection = "' + selection + '"')
        print('selection2 = "' + selection2 + '"')

    result = cmd.get_legal_name(result)

    #if the group of contacts already exist, delete them
    cmd.delete(result)

    # ensure only N and O atoms are in the selection
    all_don_acc1 = selection + " and (donor or acceptor)"
    all_don_acc2 = selection2 + " and  (donor or acceptor)"

    if SC_DEBUG > 4:
        print('all_don_acc1 = "' + all_don_acc1 + '"')
        print('all_don_acc2 = "' + all_don_acc2 + '"')

    #if theses selections turn out not to have any atoms in them, pymol throws cryptic errors when calling the dist function like:
    #'Selector-Error: Invalid selection name'
    #So for each one, manually perform the selection and then pass the reference to the distance command and at the end, clean up the selections
    #the return values are the count of the number of atoms
    all1_sele_count = cmd.select('all_don_acc1_sele', all_don_acc1)
    all2_sele_count = cmd.select('all_don_acc2_sele', all_don_acc2)

    #print out some warnings
    if DEBUG > 3:
        if not all1_sele_count:
            print('Warning: all_don_acc1 selection empty!')
        if not all2_sele_count:
            print('Warning: all_don_acc2 selection empty!')

    ########################################
    allres = result + "_all"
    if all1_sele_count and all2_sele_count:
        cmd.distance(allres,
                     'all_don_acc1_sele',
                     'all_don_acc2_sele',
                     bigcutoff,
                     mode=0)
        cmd.set("dash_radius", "0.05", allres)
        cmd.set("dash_color", "purple", allres)
        cmd.hide("labels", allres)

    ########################################
    #compute good polar interactions according to pymol
    polres = result + "_polar"
    if all1_sele_count and all2_sele_count:
        cmd.distance(polres,
                     'all_don_acc1_sele',
                     'all_don_acc2_sele',
                     cutoff,
                     mode=2)  #hopefully this checks angles? Yes
        cmd.set("dash_radius", "0.126", polres)

    ########################################
    #When running distance in mode=2, the cutoff parameter is ignored if set higher then the default of 3.6
    #so set it to the passed in cutoff and change it back when you are done.
    old_h_bond_cutoff_center = cmd.get(
        'h_bond_cutoff_center')  # ideal geometry
    old_h_bond_cutoff_edge = cmd.get(
        'h_bond_cutoff_edge')  # minimally acceptable geometry
    cmd.set('h_bond_cutoff_center', bigcutoff)
    cmd.set('h_bond_cutoff_edge', bigcutoff)

    #compute possibly suboptimal polar interactions using the user specified distance
    pol_ok_res = result + "_polar_ok"
    if all1_sele_count and all2_sele_count:
        cmd.distance(pol_ok_res,
                     'all_don_acc1_sele',
                     'all_don_acc2_sele',
                     bigcutoff,
                     mode=2)
        cmd.set("dash_radius", "0.06", pol_ok_res)

    #now reset the h_bond cutoffs
    cmd.set('h_bond_cutoff_center', old_h_bond_cutoff_center)
    cmd.set('h_bond_cutoff_edge', old_h_bond_cutoff_edge)

    ########################################

    onlyacceptors1 = selection + " and (acceptor and !donor)"
    onlyacceptors2 = selection2 + " and (acceptor and !donor)"
    onlydonors1 = selection + " and (!acceptor and donor)"
    onlydonors2 = selection2 + " and (!acceptor and donor)"

    #perform the selections
    onlyacceptors1_sele_count = cmd.select('onlyacceptors1_sele',
                                           onlyacceptors1)
    onlyacceptors2_sele_count = cmd.select('onlyacceptors2_sele',
                                           onlyacceptors2)
    onlydonors1_sele_count = cmd.select('onlydonors1_sele', onlydonors1)
    onlydonors2_sele_count = cmd.select('onlydonors2_sele', onlydonors2)

    #print out some warnings
    if SC_DEBUG > 2:
        if not onlyacceptors1_sele_count:
            print('Warning: onlyacceptors1 selection empty!')
        if not onlyacceptors2_sele_count:
            print('Warning: onlyacceptors2 selection empty!')
        if not onlydonors1_sele_count:
            print('Warning: onlydonors1 selection empty!')
        if not onlydonors2_sele_count:
            print('Warning: onlydonors2 selection empty!')

    accres = result + "_aa"
    if onlyacceptors1_sele_count and onlyacceptors2_sele_count:
        aa_dist_out = cmd.distance(accres, 'onlyacceptors1_sele',
                                   'onlyacceptors2_sele', cutoff, 0)

        if aa_dist_out < 0:
            print(
                '\n\nCaught a pymol selection error in acceptor-acceptor selection of show_contacts'
            )
            print('accres:', accres)
            print('onlyacceptors1', onlyacceptors1)
            print('onlyacceptors2', onlyacceptors2)
            return False

        cmd.set("dash_color", "red", accres)
        cmd.set("dash_radius", "0.125", accres)

    ########################################

    donres = result + "_dd"
    if onlydonors1_sele_count and onlydonors2_sele_count:
        dd_dist_out = cmd.distance(donres, 'onlydonors1_sele',
                                   'onlydonors2_sele', cutoff, 0)

        #try to catch the error state
        if dd_dist_out < 0:
            print(
                '\n\nCaught a pymol selection error in dd selection of show_contacts'
            )
            print('donres:', donres)
            print('onlydonors1', onlydonors1)
            print('onlydonors2', onlydonors2)
            print("cmd.distance('" + donres + "', '" + onlydonors1 + "', '" +
                  onlydonors2 + "', " + str(cutoff) + ", 0)")
            return False

        cmd.set("dash_color", "red", donres)
        cmd.set("dash_radius", "0.125", donres)

    ##########################################################
    ##### find the buried unpaired atoms of the receptor #####
    ##########################################################

    #initialize the variable for when CALC_SASA is False
    unpaired_atoms = ''

    ## Group
    cmd.group(
        result, "%s %s %s %s %s %s" %
        (polres, allres, accres, donres, pol_ok_res, unpaired_atoms))

    ## Clean up the selection objects
    #if the show_contacts debug level is high enough, don't delete them.
    if SC_DEBUG < 5:
        cmd.delete('all_don_acc1_sele')
        cmd.delete('all_don_acc2_sele')
        cmd.delete('onlyacceptors1_sele')
        cmd.delete('onlyacceptors2_sele')
        cmd.delete('onlydonors1_sele')
        cmd.delete('onlydonors2_sele')

    return True
Example #41
0
 def __call__(self):
     # 1st check for a dockeye action flag
     de_action = 'none'
     mark_number = 0
     do_mm = True
     try:
         actionfile = open('dockeye_action', 'r')
         line = actionfile.readline()
         fields = line.split()
         de_action = fields[0]
         mark_number = int(fields[1])
         actionfile.close()
         os.system('/bin/rm -f dockeye_action')
         #print(de_action,mark_number)
     except:
         #
         de_action = 'none'
         mark_number = 0
     # get view on screen
     my_view = cmd.get_view()
     delta_mv = 0.
     for i in range(18):
         delta_mv = max(delta_mv, abs(my_view[i] - self.my_view[i]))
         self.my_view[i] = my_view[i]
     #print my_view
     # get orientation/position matrices for two molecules
     # how does pymol define rotation center of molecule?
     # apparnetly by geometric average
     pdbmat1 = cmd.get_object_matrix(self.pdbobj1)
     pdbmat2 = cmd.get_object_matrix(self.pdbobj2)
     #
     if (de_action == 'mark'):
         # write bookmark
         print('bookmarking... ', mark_number)
         et = self.energy[0]
         ee = self.energy[1]
         ev = self.energy[2]
         print('current energies: %12.5g %12.5g %12.5g model %4d \n' %
               (ee, ev, et, self.nbest[0]))
         #mark_prt = 'dockeye_prt_mark_%d.pdb' % (mark_number)
         mark_lig = 'dockeye_lig_mark_%d.pdb' % (mark_number)
         ligfile = open(mark_lig, 'w')
         ligfile.write('REMARK pdbfile 1: ' + self.pdbfile1 + '\n')
         ligfile.write('REMARK pdbfile 2: ' + self.pdbfile2 + '\n')
         ligfile.write('REMARK # of atoms 1: %6d   2: %6d\n' %
                       (self.pdb1.natom, self.pdb2.natom))
         ligfile.write('REMARK geometric centers: \n')
         ligfile.write('REMARK 1:  %8.3f %8.3f %8.3f \n' %
                       (self.gcen1[0], self.gcen1[1], self.gcen1[2]))
         ligfile.write('REMARK 2:  %8.3f %8.3f %8.3f \n' %
                       (self.gcen2[0], self.gcen2[1], self.gcen2[2]))
         ligfile.write('REMARK net charge 1:  %8.3f 2:  %8.3f \n' %
                       (self.qtot1, self.qtot2))
         ligfile.write(
             'REMARK energy parameters dielectric: blank VDW depth: blank\n'
         )
         ligfile.write('REMARK # of ligand conformers: %6d\n' %
                       (self.pdb2.nmodel))
         ligfile.write(
             'REMARK current energies: %12.5g %12.5g %12.5g model %4d \n' %
             (ee, ev, et, self.nbest[0]))
         for i in range(4):
             for j in range(4):
                 indx = j + 4 * i
                 ligfile.write('REMARK %12.5f ' % (pdbmat1[indx]))
             ligfile.write('\n')
         for i in range(4):
             for j in range(4):
                 indx = j + 4 * i
                 ligfile.write('REMARK %12.5f ' % (pdbmat2[indx]))
             ligfile.write('\n')
         #
         # extract rot
         rmtp = [[pdbmat1[0], pdbmat1[1], pdbmat1[2]],
                 [pdbmat1[4], pdbmat1[5], pdbmat1[6]],
                 [pdbmat1[8], pdbmat1[9], pdbmat1[10]]]
         rmtl = [[pdbmat2[0], pdbmat2[1], pdbmat2[2]],
                 [pdbmat2[4], pdbmat2[5], pdbmat2[6]],
                 [pdbmat2[8], pdbmat2[9], pdbmat2[10]]]
         #
         # extract trans
         trnp = [pdbmat1[3], pdbmat1[7], pdbmat1[11]]
         trnl = [pdbmat2[3], pdbmat2[7], pdbmat2[11]]
         #
         # apply transrot to coords
         # write out transrot to temporary pdb files
         gcenp_rot = rot_vec(rmtp, self.gcen1)
         gcenl_rot = rot_vec(rmtl, self.gcen2)
         for k in range(3):
             trnp[k] = trnp[k] - (self.gcen1[k] - gcenp_rot[k])
             trnl[k] = trnl[k] - (self.gcen2[k] - gcenl_rot[k])
         i1 = 0
         #print(rmtp,trnp)
         #print(rmtl,trnl)
         xyz = [0., 0., 0.]
         tmpfile = 'dockeye_lig_tmp.pdb'
         for n in range(self.pdb2.nmodel):
             ligfile.write('MODEL%4d \n' % (n + 1))
             for i in range(self.pdb2.natom):
                 #
                 # apply rotations and translations
                 # and inverse of protein rot/trans to ligand
                 # in case user moved protein too- now ligand should be in
                 # coord frame of original protein pdb
                 for k in range(3):
                     xyz[k] = self.pdb2.coords[i1][k] - self.gcen2[k]
                 xyz1 = rot_vec(rmtl, xyz)
                 for k in range(3):
                     xyz[k] = xyz1[k] + self.gcen2[k] + trnl[
                         k] - self.gcen1[k] - trnp[k]
                 xyz2 = rot_vec(rmtp, xyz, inv=1)
                 for k in range(3):
                     xyz[k] = xyz2[k] + self.gcen1[k]
                 string = 'ATOM %6d%6s%4s%1s%4s    %8.3f%8.3f%8.3f%6.2f%7.3f \n' \
                 % (i,self.pdb2.name[i],self.pdb2.res[i], \
                 self.pdb2.chain[i], self.pdb2.resnum[i], xyz[0],xyz[1],xyz[2], \
                 self.pdb2.radius[i],self.pdb2.bfact[i])
                 ligfile.write(string)
                 i1 += 1
             ligfile.write('ENDMDL\n')
         ligfile.close()
         mark_pml = 'dockeye_mark_%d.pml' % (mark_number)
         pmlfile = open(mark_pml, 'w')
         pmlfile.write(
             '#------------------------------------------------\n')
         pmlfile.write('run $HOME/source/dockeye_multi/src/dockeyeM_c.py\n')
         pmlfile.write('de("%s","%s")\n' % (self.pdbfile1, mark_lig))
         pmlfile.write('#optional view settings\n')
         pmlfile.write('hide lines\n')
         pmlfile.write('spectrum b, red_white_blue\n')
         pmlfile.write('show sticks, dockeye_lig\n')
         pmlfile.write('show surface, dockeye_prt\n')
         pmlfile.write('set transparency, 0.4\n')
         pmlfile.write(
             '#------------------------------------------------\n')
         pmlfile.close()
         # done with bookmarking
         #
     # check for new view or pose
     #
     delta_mm = 0.
     for i in range(12):
         delta_mm = max(delta_mm, abs(pdbmat1[i] - self.objmat1[i]))
         delta_mm = max(delta_mm, abs(pdbmat2[i] - self.objmat2[i]))
         self.objmat1[i] = pdbmat1[i]
         self.objmat2[i] = pdbmat2[i]
     if (delta_mm >
             0.01):  # we only do expensive energy calc if pose changed
         do_mm = True
     else:
         do_mm = False
     if ((delta_mv > 0.01)
             or do_mm):  # we only update if pose or view changed
         cgo_obj = pdb_interaction(pdbmat1, pdbmat2, self.pdb1, self.pdb2,
                                   self.gcen1, self.gcen2, self.energy,
                                   do_mm, self.logscale, self.dielectric,
                                   self.eps, self.nbest, self.energy_min)
         if (self.nbest[0] != self.nbest[1]):
             # print('Switching models ',self.nbest)
             self.nbest[1] = self.nbest[0]
         #
         # write new best pose to logfile
         #
         et = self.energy[0]
         ee = self.energy[1]
         ev = self.energy[2]
         if (self.energy[0] < self.energy_min):
             print(
                 '       NEW MIN ee: %12.3g ev: %12.3g et: %12.3g model %4d '
                 % (ee, ev, et, self.nbest[0]))
             self.energy_min = et
             self.dockeye_log.write(
                 'new min: %12.5g %12.5g %12.5g model %4d \n' %
                 (ee, ev, et, self.nbest[0]))
             for i in range(4):
                 for j in range(4):
                     indx = j + 4 * i
                     self.dockeye_log.write('%12.5f ' % (pdbmat1[indx]))
                 self.dockeye_log.write('\n')
             for i in range(4):
                 for j in range(4):
                     indx = j + 4 * i
                     self.dockeye_log.write('%12.5f ' % (pdbmat2[indx]))
                 self.dockeye_log.write('\n')
         #else:
         #  if(do_mm):
         #    #print('Current energy: ee: %12.3g ev: %12.3g et: %12.3g' % (ee,ev,et))
         #    continue
     if (do_mm):
         cmd.delete('dockeye_obj')
         cmd.load_cgo(cgo_obj, 'dockeye_obj')
         draw_ligand(pdbmat2, self.pdb2, self.gcen2, self.nbest[0])
Example #42
0
    os.rename(path_to_file, output_path)  # .ent -> .pdb

    # see https://github.com/dsw7/BridgingInteractions/tree/master/scalene-triangle/pymol-get-surface-example
    cmd.load(output_path)
    cmd.create(
        tmpObj,
        "({} and polymer and chain {}) and not resn HOH".format(CODE, CHAIN))
    cmd.set("dot_solvent")
    cmd.get_area(selection=tmpObj, load_b=1)
    cmd.remove(tmpObj + " and b < " + str(SOLVENT_EXPOSED_CUTOFF))
    cmd.show(selection=tmpObj, representation="dots")  # show the exposed atoms
    stored.tmp_dict = {}
    cmd.iterate_state(state=-1, selection=tmpObj, expression=ITER_STATE_EXP)
    exposed = stored.tmp_dict.keys()
    exposed.sort()
    cmd.delete(tmpObj)
    cmd.delete('all')
    os.rename(
        output_path,
        path_to_file)  # .pdb -> .ent such that file_pdb.clear() can del dir

    # compute closest surface coordinate if protein ends up having both bridge and metal
    # --------------------------------------------------------------------------
    try:
        # must put this in a try / catch block as SOME R3 coords are float dtype but
        # still string crashed: 2m48 for example, -27.595-106.521-108.313
        for _, value in dict_bridges.iteritems():
            for m in metals:

                # need to convert to float dtype before passing into get_closest()
                array_b_coord = array(value[1][6:9]).astype(float)  # bridge SD
Example #43
0
def draw(prot_name, seqfile, pdbfile, cfile, factor):
    seq = read_fasta(open(seqfile, 'r')).values()[0][0]
    seqlen = len(seq)
    contacts = parse_contacts(open(cfile, 'r'))

    cmd.load(pdbfile, prot_name)
    cmd.set('dash_gap', 0.0)
    cmd.set('dash_radius', 0.1)
    cmd.bg_color('white')
    cmd.hide('everything')
    cmd.show('cartoon')
    cmd.color('gray', prot_name)
    
    """
    view = (\
        -0.271442711,   -0.905138493,    0.327085078,\
         0.034359235,   -0.348747194,   -0.936563492,\
         0.961805284,   -0.242983535,    0.125761271,\
         0.000000000,    0.000000000, -128.858474731,\
        17.616867065,   -0.161788940,   -4.633638382,\
       103.167495728,  154.549499512,  -20.000000000 )

    #PconsFold paper:
        -0.087676540,   -0.441159278,   -0.893107057,\
         0.482956320,    0.765313327,   -0.425448418,\
         0.871214509,   -0.468636513,    0.145965248,\
        -0.000171857,    0.001094781, -158.355941772,\
        23.238109589,   -7.513275623,    6.870838165,\
       131.660964966,  185.186004639,  -20.000000000 )
    cmd.set_view(view)
    """

    count = 0
    maxdist = 20.0

    for contact in contacts:
        if count > seqlen * factor:
            break
        if seq[contact[1]-1] == 'G':
            atm1a = '/%s//A/%s/CA' % (prot_name, contact[1])
            atm1b = atm1a
        else:
            atm1a = '/%s//A/%s/CA' % (prot_name, contact[1])
            atm1b = '/%s//A/%s/CB' % (prot_name, contact[1])
        if seq[contact[2]-1] == 'G':
            atm2a = '/%s//A/%s/CA' % (prot_name, contact[2])
            atm2b = atm2a
        else:
            atm2a = '/%s//A/%s/CA' % (prot_name, contact[2])
            atm2b = '/%s//A/%s/CB' % (prot_name, contact[2])
        cmd.select('a', atm1a)
        cmd.select('b', atm2a)
        d_name = 'd' + str(count)
        dist = cmd.distance(d_name, atm1a, atm2a)
        if dist == -1:
            ## atom pair not in structure (xtal vs. seqres)
            continue
        cmd.hide('labels', d_name)

        col_name = 'own_color' + str(count)
        score = contact[0]
        dist = cmd.distance(d_name + 'b', atm1b, atm2b)
        cmd.delete(d_name + 'b')
        #if score > 0.5:
        print '%s: %f => %f' % (d_name, dist, dist/(maxdist/2))
        if dist < maxdist/2:
            #cmd.hide('labels', d_name)
            #cmd.set_color(col_name, [0.0 + score, 1.0 - score, 0.0])
            cmd.set_color(col_name, [0.0 + (dist/(maxdist/2)-0.4), 1.0, 0.0])
            cmd.color(col_name, d_name)
            #cmd.color("forest", d_name)
        #elif dist < 10:
            #cmd.color("tv_orange", d_name)
        elif dist > maxdist/2 and dist < maxdist:
            #cmd.set_color(col_name, [0.0, 0.1 + score,1.0 - score])
            cmd.set_color(col_name, [1.0, 1.0 - (dist/(maxdist/2)-1), 0.0])
            cmd.color(col_name, d_name)
        else:
            cmd.color("red", d_name)

        count = count +1

    cmd.set('ray_shadows', 0)
    cmd.set('antialias', 1)
    cmd.ray(1635,1038)
    cmd.png(prot_name + '.png')
Example #44
0
def pnl_make(rmt1, rmt2, gcen1, gcen2, trn1, trn2, energy, emin):
    """
  refresh and display panel with energy bars and orientations
  2 sept 2019, move energy bars up for more room for -ve energies
  and dynamically rescale to keep bars in window
  """
    my_view = cmd.get_view()
    mod_center = [my_view[12], my_view[13], my_view[14]]
    rmtView = [[my_view[0], my_view[3], my_view[6]],
               [my_view[1], my_view[4], my_view[7]],
               [my_view[2], my_view[5], my_view[8]]]
    cam_center = [my_view[9], my_view[10], my_view[11]]
    d_front = my_view[15]
    d_back = my_view[16]
    scale = d_back - d_front
    xsize = abs(cam_center[2]) / 22.
    xmove = 3.0
    ymove = 3.0
    if (emin < -4.):
        bscale = abs(emin) // 4
    else:
        bscale = 1
    #
    # create pnl objects
    #
    #
    # energy bars
    # +ve energies on log scale, -ve on linear scale now
    #
    ltype = TRIANGLES
    bar_obj = pymol_cgo_new(ltype)
    dy = -0.2
    #ecut = 0.5
    ecut = 0.2
    et = energy[0]
    ee = energy[1]
    ev = energy[2]
    if (et < -ecut):
        et_color = 0.  # blue
        #et_size = -1.*xsize
        # log scale
        #et_size = (0.1 -1.*math.log10(-et/ecut))*xsize*2.
        # linear scale
        et_size = 0.5 * et * xsize / bscale
    elif (et > ecut):
        et_color = 1.  # red
        #et_size = 1.*xsize
        et_size = (0.1 + 1. * math.log10(et / ecut)) * xsize * 2.
    else:
        et_color = 2.  # white
        et_size = 0.1 * xsize
    et_size_min = 0.5 * emin * xsize / bscale
    #
    if (ee < -ecut):
        ee_color = 0.  # blue
        #ee_size = -1.*xsize
        #ee_size = (0.1 -1.*math.log10(-ee/ecut))*xsize*2.
        # linear scale
        ee_size = 0.5 * ee * xsize / bscale
    elif (ee > ecut):
        ee_color = 1.  # red
        #ee_size = 1.*xsize
        ee_size = (0.1 + 1. * math.log10(ee / ecut)) * xsize * 2.
    else:
        ee_color = 2.  # white
        ee_size = 0.1 * xsize
    #
    if (ev < -ecut):
        ev_color = 0.  # blue
        #ev_size = -1.*xsize
        #ev_size = (0.1 -1.*math.log10(-ev/ecut))*xsize*2.
        # linear scale
        ev_size = 0.5 * ev * xsize / bscale
    elif (ev > ecut):
        ev_color = 1.  # red
        #ev_size = 1.*xsize
        ev_size = (0.1 + 1. * math.log10(ev / ecut)) * xsize * 2.
    else:
        ev_color = 2.  # white
        ev_size = 0.1 * xsize
    #
    # at left, vertical bars
    #
    dx = -0.2  # bar separation
    #-----------------
    # E total
    #-----------------
    dend = [0.85 * dx * xsize, 0., 0.]
    dend_rot = rot_vec(rmtView, dend, inv=1)
    nm = [0., 0., 1.]
    nm_rot = rot_vec(rmtView, nm, inv=1)
    end1 = [0., 0., 0.]
    beg1 = [0., 0., 0.]
    end2 = [0., 0., 0.]
    #
    et_beg = [0., 0., 0.]
    et_end = [0., et_size, 0.]
    et_end_min = [0., et_size_min, 0.]
    et_end_rot = rot_vec(rmtView, et_end, inv=1)
    et_end_min_rot = rot_vec(rmtView, et_end_min, inv=1)
    #et_offset = [-1.3*xmove*xsize,0.,0.]
    et_offset = [-1.3 * xmove * xsize, +1.0 * ymove * xsize, 0.]
    et_offset_rot = rot_vec(rmtView, et_offset, inv=1)
    for k in range(3):
        et_beg[k] = et_offset_rot[k] + mod_center[k]
        et_end_rot[k] += et_offset_rot[k] + mod_center[k]
        et_end_min_rot[k] += et_offset_rot[k] + mod_center[k]
        end1[k] = et_end_rot[k] - dend_rot[k]
        beg1[k] = et_beg[k] - dend_rot[k]
    color = [2., et_color, et_color]
    pymol_cgo_addtri(bar_obj, et_beg, et_end_rot, end1, color, nm_rot)
    color = [2., 2., et_color]
    pymol_cgo_addtri(bar_obj, et_beg, beg1, end1, color, nm_rot)
    #
    # low energy mark
    #
    for k in range(3):
        color[k] = 0.5
        end1[k] = et_end_min_rot[k] - dend_rot[k]
        beg1[k] = et_end_min_rot[k]
    beg1[1] = beg1[1] + 0.2
    pymol_cgo_addtri(bar_obj, beg1, et_end_min_rot, end1, color, nm_rot)
    end2[0] = end1[0]
    end2[1] = end1[1] + 0.2
    end2[2] = end1[2]
    pymol_cgo_addtri(bar_obj, beg1, end2, end1, color, nm_rot)
    #-----------------
    # E electrostatic
    #-----------------
    ee_beg = [0., 0., 0.]
    ee_end = [0., ee_size, 0.]
    ee_end_rot = rot_vec(rmtView, ee_end, inv=1)
    #ee_offset = [(-1.3*xmove+2.*dx)*xsize,0.,0.]
    ee_offset = [(-1.3 * xmove + 2. * dx) * xsize, +1.0 * ymove * xsize, 0.]
    ee_offset_rot = rot_vec(rmtView, ee_offset, inv=1)
    for k in range(3):
        ee_beg[k] = ee_offset_rot[k] + mod_center[k]
        ee_end_rot[k] += ee_offset_rot[k] + mod_center[k]
        end1[k] = ee_end_rot[k] - dend_rot[k]
        beg1[k] = ee_beg[k] - dend_rot[k]
    color = [2., ee_color, ee_color]
    pymol_cgo_addtri(bar_obj, ee_beg, ee_end_rot, end1, color, nm_rot)
    color = [2., 2., ee_color]
    pymol_cgo_addtri(bar_obj, ee_beg, beg1, end1, color, nm_rot)
    #-----------------
    # E vdw
    #-----------------
    ev_beg = [0., 0., 0.]
    ev_end = [0., ev_size, 0.]
    # apply view angle
    ev_end_rot = rot_vec(rmtView, ev_end, inv=1)
    #ev_offset = [(-1.3*xmove+dx)*xsize,0.,0.]
    ev_offset = [(-1.3 * xmove + dx) * xsize, +1.0 * ymove * xsize, 0.]
    ev_offset_rot = rot_vec(rmtView, ev_offset, inv=1)
    for k in range(3):
        ev_beg[k] = ev_offset_rot[k] + mod_center[k]
        ev_end_rot[k] += ev_offset_rot[k] + mod_center[k]
        end1[k] = ev_end_rot[k] - dend_rot[k]
        end1[k] = ev_end_rot[k] - dend_rot[k]
        beg1[k] = ev_beg[k] - dend_rot[k]
    color = [2., ev_color, ev_color]
    pymol_cgo_addtri(bar_obj, ev_beg, ev_end_rot, end1, color, nm_rot)
    color = [2., 2., ev_color]
    pymol_cgo_addtri(bar_obj, ev_beg, beg1, end1, color, nm_rot)
    #
    # finish up & display energy bars
    #
    pymol_cgo_end(bar_obj)
    cmd.delete('bar_obj')
    cmd.load_cgo(bar_obj, 'bar_obj')
def pairwise_dist(pdbfile,
                  sel1,
                  sel2,
                  max_dist,
                  output="P",
                  sidechain="N",
                  show="N",
                  outfile="./"):
    """
	usage: pairwise_dist sel1, sel2, max_dist, [output=S/P/N, [sidechain=N/Y, [show=Y/N]]]
	sel1 and sel2 can be any to pre-existing or newly defined selections
	max_dist: maximum distance in Angstrom between atoms in the two selections
	--optional settings:
	output: accepts Screen/Print/None (default N)
	sidechain: limits (Y) results to sidechain atoms (default N)
	show: shows (Y) individual distances in pymol menu (default=N)
	"""
    print ""
    cmd.delete("dist*")
    extra = ""
    if sidechain == "Y": extra = " and not name c+o+n"

    #builds models
    m1 = cmd.get_model(sel2 + " around " + str(max_dist) + " and " + sel1 +
                       extra)
    m1o = cmd.get_object_list(sel1)
    m2 = cmd.get_model(sel1 + " around " + str(max_dist) + " and " + sel2 +
                       extra)
    m2o = cmd.get_object_list(sel2)

    #defines selections
    cmd.select("__tsel1a",
               sel1 + " around " + str(max_dist) + " and " + sel2 + extra)
    cmd.select("__tsel1", "__tsel1a and " + sel2 + extra)
    cmd.select("__tsel2a",
               sel2 + " around " + str(max_dist) + " and " + sel1 + extra)
    cmd.select("__tsel2", "__tsel2a and " + sel1 + extra)
    cmd.select("IntAtoms_" + str(max_dist), "__tsel1 or __tsel2")
    cmd.select("IntRes_" + str(max_dist), "byres IntAtoms_" + str(max_dist))

    #controlers-1
    if len(m1o) == 0:
        print "warning, '" + sel1 + extra + "' does not contain any atoms."
        return
    if len(m2o) == 0:
        print "warning, '" + sel2 + extra + "' does not contain any atoms."
        return

    #measures distances
    s = ""
    counter = 0
    for c1 in range(len(m1.atom)):
        for c2 in range(len(m2.atom)):
            distance = math.sqrt(
                sum(
                    map(lambda f: (f[0] - f[1])**2,
                        zip(m1.atom[c1].coord, m2.atom[c2].coord))))
            if distance < float(max_dist):
                s += "%s/%s/%s/%s/%s to %s/%s/%s/%s/%s: %.3f\n" % (
                    m1o[0], m1.atom[c1].chain, m1.atom[c1].resn,
                    m1.atom[c1].resi, m1.atom[c1].name, m2o[0],
                    m2.atom[c2].chain, m2.atom[c2].resn, m2.atom[c2].resi,
                    m2.atom[c2].name, distance)
                counter += 1
                if show == "Y":
                    cmd.distance(
                        m1o[0] + " and " + m1.atom[c1].chain + "/" +
                        m1.atom[c1].resi + "/" + m1.atom[c1].name,
                        m2o[0] + " and " + m2.atom[c2].chain + "/" +
                        m2.atom[c2].resi + "/" + m2.atom[c2].name)

    #controler-2
    if counter == 0:
        print "warning, no distances were measured! Check your selections/max_dist value"
        return

    #outputs
    if output == "S": print s
    if output == "P":
        filename = os.getcwd(
        ) + '/interface_analyzer/' + pdbfile + '_distance' + str(max_dist)
        f = open(filename, 'w')
        f.write("Number of distances calculated: %s\n" % (counter))
        f.write(s)
        f.close()
        print "Results saved in _%s" % filename
    print "Number of distances calculated: %s" % (counter)
    cmd.hide("lines", "IntRes_*")
    if show == "Y": cmd.show("lines", "IntRes_" + max_dist)
    cmd.deselect()
Example #46
0
cmd.pseudoatom(object="myline1pa1", pos=(0, 0, 0), color=(1, 1, 1))

cmd.pseudoatom(object="myline1pa2", pos=(1, 1, 1), color=(1, 1, 1))

cmd.distance(name="myline1",
             selection1="myline1pa1",
             selection2="myline1pa2",
             width=0.5,
             gap=0.2,
             label=0,
             state=1)

cmd.set("dash_color",
        (0.9411764705882353, 0.20392156862745098, 0.20392156862745098),
        selection="myline1")
cmd.set("dash_width", 10)
cmd.delete("myline1pa1")
cmd.delete("myline1pa2")
cmd.pseudoatom(object="mypseudoatom1",
               pos=(0, 0, 0),
               color=(0.9411764705882353, 0.20392156862745098,
                      0.20392156862745098, 0.5))

cmd.pseudoatom(object="mypseudoatom2",
               pos=(1, 1, 1),
               color=(0.9411764705882353, 0.20392156862745098,
                      0.20392156862745098, 0.5))

cmd.group("mygroup", members="myline1")
cmd.group("mygroup", members="mypseudoatom1")
cmd.group("mygroup", members="mypseudoatom2")
Example #47
0
 def reset(self):
     cmd.delete(self.object_prefix + "*")
     cmd.delete("sele*")
     cmd.delete("_indicate*")
     cmd.unpick()
     cmd.refresh_wizard()
Example #48
0
cmd.load("protein.mol2", "protein")
donor_projected_point_0 = [COLOR, 0.0, 0.0, 1.0] +  [ALPHA, 1.0] + [SPHERE, float(27.308), float(3.547), float(65.078), float(0.5)]

cmd.load_cgo(donor_projected_point_0, "donor_projected_point_0_obj", 1)
donor_projected_projection_0 = [COLOR, 0.6, 0.6, 1.0] +  [ALPHA, 1.0] + [SPHERE, float(26.877), float(0.821), float(65.99), float(0.5)]

cmd.load_cgo(donor_projected_projection_0, "donor_projected_projection_0_obj", 1)
cmd.pseudoatom(object="donor_projected_line_0pa1", pos=(27.308, 3.547, 65.078), color=(1, 1, 1))

cmd.pseudoatom(object="donor_projected_line_0pa2", pos=(26.877, 0.821, 65.99), color=(1, 1, 1))

cmd.distance(name="donor_projected_line_0", selection1="donor_projected_line_0pa1", selection2="donor_projected_line_0pa2", width=0.5, gap=0.2, label=0, state=1)

cmd.set("dash_color", (0.6, 0.6, 1.0), selection="donor_projected_line_0")
cmd.set("dash_width", 4.0)
cmd.delete("donor_projected_line_0pa1")
cmd.delete("donor_projected_line_0pa2")
cmd.group("donor_projected_0", members="donor_projected_point_0_obj")
cmd.group("donor_projected_0", members="donor_projected_projection_0")
cmd.group("donor_projected_0", members="donor_projected_line_0")
cmd.select("sele", "resi 81")
cmd.show("sticks", "sele")
acceptor_projected_point_1 = [COLOR, 1.0, 0.0, 0.0] +  [ALPHA, 1.0] + [SPHERE, float(28.364), float(4.137), float(65.698), float(0.5)]

cmd.load_cgo(acceptor_projected_point_1, "acceptor_projected_point_1_obj", 1)
acceptor_projected_projection_1 = [COLOR, 1.0, 0.6, 0.6] +  [ALPHA, 1.0] + [SPHERE, float(30.481), float(2.301), float(66.766), float(0.5)]

cmd.load_cgo(acceptor_projected_projection_1, "acceptor_projected_projection_1_obj", 1)
cmd.pseudoatom(object="acceptor_projected_line_1pa1", pos=(28.364, 4.137, 65.698), color=(1, 1, 1))

cmd.pseudoatom(object="acceptor_projected_line_1pa2", pos=(30.481, 2.301, 66.766), color=(1, 1, 1))
Example #49
0
def fetch_similar_blast(
    chain_id,
    similarity=95,
    ligand=None,
    dist=5,
    compounds="organic or inorganic",
    prosthetic_groups="HEM FAD NAP NDP ADP FMN",
    max_resolution=None,
    max_structures=50,
):
    """
    Fetch sequence similar structures from RCSB PDB and optionally keep only
    apo structures. Apo are evaluated respective to a choosen ligand on the
    reference chain.

    On the first use update the database with the command `update_cluster_data`.
    Update the database weekly.

    OPTIONS
        chain_id        Reference structure chain id.
        similarity      Sequence similarity threshold (one of the available
                        from RCSB PDB).
        ligand          Reference ligand PDB id.
        dist            Distance cut-off around reference ligand for apo
                        evaluation.
        compounds       Selection that should be considered ligands upon apo
                        computation. Only used when ligand is given.
        prothestic_groups   List of ligands to be ignored when evaluating apo.
        max_resolution  Fetch only X-ray structures with up to such
                        resolution.
        max_structures  Fetch at most n structures. 0 for all structures.
    EXAMPLES
        fetch_similar_blast 2XY9_A, 100
        fetch_similar_blast 2XY9_A, 95, 3ES, 3, organic
        fetch_similar_blast 6Y2F_A, max_structures=0
    SEE ALSO
        update_cluster_data
        fetch_similar_shape3d
    """
    chain_id = chain_id.upper()
    max_structures = int(max_structures)
    pm.fetch(chain_id, chain_id)

    sims = []
    similars = find_similar_chain_ids(chain_id, similarity)
    cont = 0
    for sim_pdb, sim_chain in similars:

        if max_structures != 0 and cont >= max_structures:
            break

        sim_obj = f"{sim_pdb}_{sim_chain}"
        if sim_obj.upper() == chain_id.upper():
            continue

        pm.fetch(sim_obj, **{"async": 0})
        pm.align(sim_obj, chain_id)

        # Check the resolution
        resol = None
        if max_resolution:
            resol = get_resolution(sim_pdb)
            if not resol or resol > max_resolution:
                pm.delete(sim_obj)
                continue

        # Check nearby ligands
        if ligand:
            model = pm.get_model(
                f"({sim_obj} and ({compounds}))"
                f" within {dist} of"
                f"({chain_id} and (resn {ligand}))"
            )
            resns = set(a.resn for a in model.atom)

            is_apo = True
            for resn in resns:
                if resn not in prosthetic_groups.split():
                    is_apo = False
                    break

            if not is_apo:
                pm.delete(sim_obj)
                continue

        cont += 1
        sims.append((sim_obj, sim_chain, sim_pdb, resol))

    plot_hierarquical_cluster([chain_id] + [s[0] for s in sims])
    return sims
Example #50
0
 def delete_all(self):
     cmd.delete("plane*")
Example #51
0
    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)
Example #52
0
 def remove(self):
     cmd.delete(self.name)
def interface(sele1=None, sele2=None, d=4, sc_only=0):
    """Select and name the interfaces between selections.

    Defaults to combinations between all chains.

    Args:
        sele1 (str): First PyMol selection
        sele2 (str): Second PyMol selection
        d (int): Depth of interface
        sc_only (int): Filter by side-chain contacts only, instead of all atoms

    Returns:
        Nothing

    """

    d = str(d)
    stored.chains = []

    if "\"\"" in [sele1, sele2] or None in [sele1, sele2]:
        chain_names = cmd.get_chains('polymer')
        stored.chains = [ "chain "+s for s in chain_names ]

    else:
        stored.chains.append(sele1)
        stored.chains.append(sele2)

    for a, b in combinations(stored.chains, 2):
        if int(sc_only) == 1:
            selection = ( "(br. ("+a+" and not name c+ca+o+n+h+ha) "+
                         "within "+d+" of ("+b+" and not name c+ca+o+n+h+ha)) "+
                         " or (br. ("+b+" and not name c+ca+o+n+h+ha) "+
                         "within "+d+" of ("+a+" and not name c+ca+o+n+h+ha)) "
                        )
        else:
            selection = ( "(br. "+a+" within "+d+" of "+b+")"+
                         " or (br. "+b+" within "+d+" of "+a+")"
                        )
        # Make nicer names for the default case
        a_name = "".join(a.split()).replace("chain","")
        b_name = "".join(b.split()).replace("chain","")
        sel_name = "int_"+a_name+b_name
        try:
            sele = cmd.select(sel_name, selection)
        except:
            print("Error in selection: "+selection)
            raise CmdException

        # Remove empty selections
        stored.test = []
        try:
            cmd.iterate(sel_name+" and name ca",
                        "stored.test.append(\"\"+resi)")
        except:
            print("Cannot iterate through "+sel_name)
            raise CmdException
        if not stored.test:
            try:
                cmd.delete(sel_name)
            except:
                print("Cannot delete "+sel_name)
                raise CmdException
Example #54
0
    def do_library(self):
        cmd = self.cmd
        pymol = cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N" % src_sele) == 1) and
                (cmd.count_atoms("(%s) and name C" % src_sele) == 1) and
                (cmd.count_atoms("(%s) and name O" % src_sele) == 1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable", "selector", "everythin")
        cmd.feedback("disable", "editor", "actions")
        self.prompt = ['Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)" % src_sele,
                    'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight", src_sele)

        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom', "0", quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele, animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode == "current":
            pymol.stored.resn = ""
            cmd.iterate("(%s & name CA)" % src_sele, "stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn)
            if (self.c_cap != 'none') or (self.n_cap != 'none') or (self.hyd !=
                                                                    'auto'):
                self.lib_mode = rot_type  # force fragment-based load
            else:
                cmd.create(frag_name, src_sele, 1, 1)
                if self.c_cap == 'open':
                    cmd.remove("%s and name OXT" % frag_name)

        if self.lib_mode != 'current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3] != 'NT_'):
                if not (cmd.count_atoms(
                        "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE" %
                    (src_sele, src_sele))):
                    # use N-terminal fragment
                    frag_type = "NT_" + frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3] != 'CT_'):
                if not (cmd.count_atoms(
                        "elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"
                        % (src_sele, src_sele))):
                    # use C-terminal fragment
                    frag_type = "CT_" + frag_type
            if rot_type[0:3] in ['NT_', 'CT_']:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("(" + frag_name + " and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                    cmd.remove("(" + frag_name + " and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele,
                      "stored.identifiers = (segi, chain, resi, ss, color)",
                      space=self.space)
            cmd.alter("?%s" % frag_name,
                      "(segi, chain, resi, ss) = stored.identifiers[:4]",
                      space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)" % frag_name) == 1)
                    and (cmd.count_atoms("(%s & name CB)" % src_sele) == 1)):
                cmd.pair_fit(
                    "(%s & name CA)" % frag_name, "(%s & name CA)" % src_sele,
                    "(%s & name CB)" % frag_name, "(%s & name CB)" % src_sele,
                    "(%s & name C)" % frag_name, "(%s & name C)" % src_sele,
                    "(%s & name N)" % frag_name, "(%s & name N)" % src_sele)
            else:
                cmd.pair_fit("(%s & name CA)" % frag_name,
                             "(%s & name CA)" % src_sele,
                             "(%s & name C)" % frag_name,
                             "(%s & name C)" % src_sele,
                             "(%s & name N)" % frag_name,
                             "(%s & name N)" % src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1, "(%s & name O)" % src_sele,
                              "stored.list=[x,y,z]")
            cmd.alter_state(1, "(%s & name O)" % frag_name,
                            "(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)" % src_sele):
                cmd.iterate_state(1, "(%s & name OXT)" % src_sele,
                                  "stored.list=[x,y,z]")
                cmd.alter_state(1, "(%s & name OXT)" % frag_name,
                                "(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)" %
                                 frag_name):  # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)" % frag_name,
                                         "(%s & name CA)" % frag_name,
                                         "(%s & name C)" % frag_name,
                                         "(%s & name O)" % frag_name)
                cmd.protect("(%s & name O)" % frag_name)
                cmd.set_dihedral("(%s & name N)" % frag_name,
                                 "(%s & name CA)" % frag_name,
                                 "(%s & name C)" % frag_name,
                                 "(%s & name OXT)" % frag_name, 180.0 + angle)
                cmd.deprotect(frag_name)

            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))" %
                               frag_name) == 1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))" %
                                   src_sele) == 1:
                    cmd.iterate_state(
                        1, "(hydro and bound_to (name N & (%s)))" % src_sele,
                        "stored.list=[x,y,z]")
                    cmd.alter_state(
                        1, "(hydro and bound_to (name N & (%s)))" % frag_name,
                        "(x,y,z)=stored.list")
                elif cmd.select(
                        tmp_sele1,
                        "(name C & bound_to (%s and elem N))" % src_sele) == 1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)" % frag_name,
                                             "(%s & name CA)" % frag_name,
                                             "(%s & name N)" % frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)" % frag_name,
                                     "(%s & name CA)" % frag_name,
                                     "(%s & name N)" % frag_name,
                                     "(%s & name H)" % frag_name,
                                     180.0 + angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in ['amin', 'nmet']:
                if not cmd.count_atoms(
                        "elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"
                        % (src_sele, src_sele)):
                    if cmd.count_atoms("name C & (%s)" % (frag_name)) == 1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)" %
                                                     (frag_name),
                                                     'nhh',
                                                     _self=cmd)
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)" %
                                                     (frag_name),
                                                     'nme',
                                                     _self=cmd)
                        if cmd.count_atoms(
                                "hydro & bound_to (name N & bound_to (name C & (%s)))"
                                % frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))" %
                                      frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("(" + src_sele +
                                               ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in ['acet']:
                if not cmd.count_atoms(
                        "elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "
                        % (src_sele, src_sele)):
                    if cmd.count_atoms("name N & (%s)" % (frag_name)) == 1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)" %
                                                     (frag_name),
                                                     'ace',
                                                     _self=cmd)
                        if cmd.count_atoms(
                                "hydro & bound_to (name N & bound_to (name C & (%s)))"
                                % frag_name):
                            cmd.h_fix("name N & (%s)" % frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("(" + src_sele +
                                               ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)" % src_sele) >
                   0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)" % src_sele) >
                  0)

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s" % src_sele)
                if len(result) == 1:
                    (phi, psi) = list(result.values())[0]
                    (phi, psi) = (int(10 * round(phi / 10)),
                                  int(10 * (round(psi / 10))))
                    key = (rot_type, phi, psi)
                    if key not in self.dep_library:
                        (phi, psi) = (int(20 * round(phi / 20)),
                                      int(20 * (round(psi / 20))))
                        key = (rot_type, phi, psi)
                        if key not in self.dep_library:
                            (phi, psi) = (int(60 * round(phi / 60)),
                                          int(60 * (round(psi / 60))))
                            key = (rot_type, phi, psi)
                    lib = self.dep_library.get(key, None)
            except:
                pass
        if lib is None:
            key = rot_type
            lib = self.ind_library.get(key, None)
            if (lib is not None) and self.dep == 'dep':
                print(
                    ' Mutagenesis: no phi/psi, using backbone-independent rotamers.'
                )
        if lib is not None:
            state = 1
            for a in lib:
                cmd.create(obj_name, frag_name, 1, state)
                if state == 1:
                    cmd.select(mut_sele,
                               "(byres (%s like %s))" % (obj_name, src_sele))
                if rot_type == 'PRO':
                    cmd.unbond("(%s & name N)" % mut_sele,
                               "(%s & name CD)" % mut_sele)
                for b in a.keys():
                    if b != 'FREQ':
                        cmd.set_dihedral("(%s & n;%s)" % (mut_sele, b[0]),
                                         "(%s & n;%s)" % (mut_sele, b[1]),
                                         "(%s & n;%s)" % (mut_sele, b[2]),
                                         "(%s & n;%s)" % (mut_sele, b[3]),
                                         a[b],
                                         state=state)
                    else:
                        cmd.set_title(obj_name, state,
                                      "%1.1f%%" % (a[b] * 100))
                if rot_type == 'PRO':
                    cmd.bond("(%s & name N)" % mut_sele,
                             "(%s & name CD)" % mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded." % len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(
                    bump_name,
                    "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"
                    % (src_sele, mut_sele, src_sele, mut_sele),
                    singletons=1)
                cmd.color("gray50", bump_name + " and elem C")
                cmd.set("seq_view", 0, bump_name, quiet=1)
                cmd.hide("everything", bump_name)
                if ((cmd.select(
                        tmp_sele1, "(name N & (%s in (neighbor %s)))" %
                    (bump_name, src_sele)) == 1) and (cmd.select(
                        tmp_sele2, "(name C & (%s in %s))" %
                        (bump_name, mut_sele)) == 1)):
                    cmd.bond(tmp_sele1, tmp_sele2)
                if ((cmd.select(
                        tmp_sele1, "(name C & (%s in (neighbor %s)))" %
                    (bump_name, src_sele)) == 1) and (cmd.select(
                        tmp_sele2, "(name N & (%s in %s))" %
                        (bump_name, mut_sele)) == 1)):
                    cmd.bond(tmp_sele1, tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect(
                    "%s and not (%s in (%s and not name N+C+CA+O+H+HA))" %
                    (bump_name, bump_name, mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo", bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode", 1, bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name, frag_name, 1, 1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view", 0, obj_name, quiet=1)
        pymol.util.cbaw(obj_name, _self=cmd)
        cmd.hide("(" + obj_name + ")")
        cmd.show(self.rep, obj_name)
        cmd.show('lines', obj_name)  #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon", obj_name)
        if sticks:
            cmd.show("sticks", obj_name)
        cmd.set('auto_zoom', auto_zoom, quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)

        # this might be redundant if frame(state_best) changed the state
        self.do_state(state_best)

        cmd.unpick()
        cmd.feedback("pop")
Example #55
0
    def runDSSP(self):
        """
            @return: whether DSSP has been executed successfully
            @rtype: boolean
        """
        # delete old results
        self.sel_obj_list = []
        self.dssp_rlt_dict = {}
        self.SSE_res_dict = {}
        self.SSE_sel_dict = {}

        pdb_fn = None
        sel_name = None
        sel = self.pymol_sel.get()

        if len(sel) > 0:  # if any pymol selection/object is specified
            # save the pymol selection/object in the tmp dir
            all_sel_names = cmd.get_names('all')  # get names of all selections
            if sel in all_sel_names:
                if cmd.count_atoms(sel) == 0:
                    err_msg = 'ERROR: The selection %s is empty.' % (sel, )
                    print 'ERROR: %s' % (err_msg, )
                    tkMessageBox.showinfo(title='ERROR', message=err_msg)
                    return False
                else:
                    sel_name = sel
            # no selection/object with the input name is found
            # we assume either a single-word selector or
            # some other selection-expression is used
            # NOTE: if more than one selection is selected, they should be
            #       saved separately and SSE should be calculated for each
            #       of the selections.
            else:
                print 'The selection/object you specified is not found.'
                print 'Your input will be interpreted as a selection-expression.'
                # check whether the selection is empty
                tmpsel = self.randomSeleName(prefix='your_sele_')
                cmd.select(tmpsel, sel)
                if cmd.count_atoms(tmpsel) == 0:
                    cmd.delete(tmpsel)
                    err_msg = 'ERROR: The selection %s is empty.' % (sel, )
                    print 'ERROR: %s' % (err_msg, )
                    tkMessageBox.showinfo(title='ERROR', message=err_msg)
                    return False
                else:
                    sel_name = tmpsel
        else:  # what structure do you want DSSP to work on?
            err_msg = 'No PyMOL selection/object specified!'
            print 'ERROR: %s' % (err_msg, )
            tkMessageBox.showinfo(title='ERROR', message=err_msg)
            return False

        # each object in the selection is treated as an independent struc
        objlist = cmd.get_object_list(sel_name)
        self.ss_asgn_prog = 'DSSP'
        print 'Starting %s ...' % (self.ss_asgn_prog, )

        for objname in objlist:
            self.sel_obj_list.append('%s and %s' % (sel_name, objname))
            self.runDSSPOneObj(self.sel_obj_list[-1])

##        cmd.delete(tmpsel)

        return True
Example #56
0
 def clear(self):
     cmd = self.cmd
     self.status = 0
     self.bump_scores = []
     cmd.delete(tmp_hbonds)
     cmd.delete(tmp_obj2)
     cmd.delete(mut_sele)
     cmd.delete(src_sele)
     cmd.delete(obj_name)
     cmd.delete(bump_name)
     cmd.delete("_seeker_hilight")
     cmd.refresh_wizard()
def elbow_angle(obj, light='L', heavy='H', limit_l=107, limit_h=113, draw=0):
    """

DESCRIPTION

    Calculates the integer elbow angle of an antibody Fab complex and
    optionally draws a graphical representation of the vectors used to
    determine the angle.

ARGUMENTS

    obj = string: object

    light/heavy = strings: chain ID of light and heavy chains, respectively

    limit_l/limit_h = integers: residue numbers of the last residue in the
    light and heavy chain variable domains, respectively

    draw = boolean: Choose whether or not to draw the angle visualization

REQUIRES: com.py, transformations.py, numpy (see above)


    """

    # store current view
    orig_view = cmd.get_view()

    limit_l = int(limit_l)
    limit_h = int(limit_h)
    draw = int(draw)

    # for temp object names
    tmp_prefix = "tmp_elbow_"

    prefix = tmp_prefix + obj + '_'

    # names
    vl = prefix + 'VL'
    vh = prefix + 'VH'
    cl = prefix + 'CL'
    ch = prefix + 'CH'

    # selections
    vl_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, light, limit_l)
    vh_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, heavy, limit_h)
    cl_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, light, limit_l)
    ch_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, heavy, limit_h)
    v_sel = '((' + vl_sel + ') or (' + vh_sel + '))'
    c_sel = '((' + cl_sel + ') or (' + ch_sel + '))'

    # create temp objects
    cmd.create(vl, vl_sel)
    cmd.create(vh, vh_sel)
    cmd.create(cl, cl_sel)
    cmd.create(ch, ch_sel)

    # superimpose vl onto vh, calculate axis and angle
    Rv = calc_super_matrix(vl, vh)
    angle_v, direction_v, point_v = transformations.rotation_from_matrix(Rv)

    # superimpose cl onto ch, calculate axis and angle
    Rc = calc_super_matrix(cl, ch)
    angle_c, direction_c, point_c = transformations.rotation_from_matrix(Rc)

    # delete temporary objects
    cmd.delete(vl)
    cmd.delete(vh)
    cmd.delete(cl)
    cmd.delete(ch)

    # if dot product is positive, angle is acute
    if (numpy.dot(direction_v, direction_c) > 0):
        direction_c = direction_c * -1   # ensure angle is > 90 (need to standardize this)

        # TODO: make both directions point away from the elbow axis.

    elbow = int(numpy.degrees(numpy.arccos(numpy.dot(direction_v, direction_c))))
    # while (elbow < 90):
    # elbow = 180 - elbow   # limit to physically reasonable range

    # compare the direction_v and direction_c axes to the vector defined by
    # the C-alpha atoms of limit_l and limit_h of the original fab
    hinge_l_sel = "%s//%s/%s/CA" % (obj, light, limit_l)
    hinge_h_sel = "%s//%s/%s/CA" % (obj, heavy, limit_h)
    hinge_l = cmd.get_atom_coords(hinge_l_sel)
    hinge_h = cmd.get_atom_coords(hinge_h_sel)
    hinge_vec = numpy.array(hinge_h) - numpy.array(hinge_l)

    test = numpy.dot(hinge_vec, numpy.cross(direction_v, direction_c))
    if (test > 0):
        elbow = 360 - elbow

    print("    Elbow angle: %i degrees" % elbow)

    if (draw == 1):
        # there is probably a more elegant way to do this, but
        # it works so I'm not going to mess with it for now

        pre = obj + '_elbow_'

        # draw hinge vector
        cmd.pseudoatom(pre + "hinge_l", pos=hinge_l)
        cmd.pseudoatom(pre + "hinge_h", pos=hinge_h)
        cmd.distance(pre + "hinge_vec", pre + "hinge_l", pre + "hinge_h")
        cmd.set("dash_gap", 0)

        # draw the variable domain axis
        com_v = COM(v_sel)
        start_v = [a - 10 * b for a, b in zip(com_v, direction_v)]
        end_v = [a + 10 * b for a, b in zip(com_v, direction_v)]
        cmd.pseudoatom(pre + "start_v", pos=start_v)
        cmd.pseudoatom(pre + "end_v", pos=end_v)
        cmd.distance(pre + "v_vec", pre + "start_v", pre + "end_v")

        # draw the constant domain axis
        com_c = COM(c_sel)
        start_c = [a - 10 * b for a, b in zip(com_c, direction_c)]
        end_c = [a + 10 * b for a, b in zip(com_c, direction_c)]
        cmd.pseudoatom(pre + "start_c", pos=start_c)
        cmd.pseudoatom(pre + "end_c", pos=end_c)
        cmd.distance(pre + "c_vec", pre + "start_c", pre + "end_c")

        # customize appearance
        cmd.hide("labels", pre + "hinge_vec")
        cmd.hide("labels", pre + "v_vec")
        cmd.hide("labels", pre + "c_vec")
        cmd.color("green", pre + "hinge_l")
        cmd.color("red", pre + "hinge_h")
        cmd.color("black", pre + "hinge_vec")
        cmd.color("black", pre + "start_v")
        cmd.color("black", pre + "end_v")
        cmd.color("black", pre + "v_vec")
        cmd.color("black", pre + "start_c")
        cmd.color("black", pre + "end_c")
        cmd.color("black", pre + "c_vec")
        # draw spheres
        cmd.show("spheres", pre + "hinge_l or " + pre + "hinge_h")
        cmd.show("spheres", pre + "start_v or " + pre + "start_c")
        cmd.show("spheres", pre + "end_v or " + pre + "end_c")
        cmd.set("sphere_scale", 2)
        cmd.set("dash_gap", 0, pre + "hinge_vec")
        cmd.set("dash_width", 5)
        cmd.set("dash_radius", 0.3)

        # group drawing objects
        cmd.group(pre, pre + "*")

    # restore original view
    cmd.set_view(orig_view)

    return 0
Example #58
0
    def selectSSE(self, sel, sse):
        """ generate selector for selecting all residues having the given sse.
            return the selection name.
        """
        #sel = self.pymol_sel.get()
        sel_list_chn = []

        if VERBOSE: print '\nSelecting SSE %s ... \n' % (sse)

        for chn in self.SSE_res_dict[sel][sse]:  # color one chain at a time
            if chn == ' ': chn_str = '-'
            else: chn_str = chn
            if VERBOSE:
                print 'Selecting SSE %s on chain %s ... \n' % (sse, chn)
            limit = 150  # color every 150 residues
            sel_name_chn = self.randomSeleName(
                prefix='%s_%s_%s_' % ('_'.join(sel.split()), chn_str, sse))

            if len(self.SSE_res_dict[sel][sse][chn]) < limit:
                #sel_expr = '/%s//%s/%s/' % (sel,chn.strip(), '+'.join(self.SSE_res[sse][chn]))
                # always quote chain name in case it is empty (otherwise sel misinterpreted)
                sel_expr = '(%s) and \"%s\"/%s/' % (sel, chn.strip(), '+'.join(
                    self.SSE_res_dict[sel][sse][chn]))
                cmd.select(sel_name_chn, sel_expr)
                if VERBOSE: print 'select %s, %s' % (sel_name_chn, sel_expr)
                sel_list_chn.append(sel_name_chn)
            else:
                rn = len(self.SSE_res_dict[sel][sse][chn])
                print 'total number of res with %s = %d' % (sse, rn)
                sz = int(math.ceil(rn / float(limit)))
                sel_list_seg = []
                for i in xrange(sz):
                    s, e = i * limit, min((i + 1) * limit, rn)
                    print s, e
                    #sel_expr = '/%s//%s/%s/' % (sel,chn.strip(), '+'.join(self.SSE_res[sse][chn][s:e]))
                    # always quote chain name in case it is empty (otherwise sel misinterpreted)
                    sel_expr = '(%s) and \"%s\"/%s/' % (
                        sel, chn.strip(), '+'.join(
                            self.SSE_res_dict[sel][sse][chn][s:e]))
                    sel_name_seg = self.randomSeleName(
                        prefix='%s_%s_%s_tmp_' %
                        ('_'.join(sel.split()), chn_str, sse))
                    cmd.select(sel_name_seg, sel_expr)
                    if VERBOSE:
                        print 'select %s, %s' % (sel_name_seg, sel_expr)
                    sel_list_seg.append(sel_name_seg)

                sel_expr = ' or '.join(sel_list_seg)
                cmd.select(sel_name_chn, sel_expr)
                if VERBOSE: print 'select %s, %s' % (sel_name_chn, sel_expr)
                [cmd.delete(asel) for asel in sel_list_seg]
                sel_list_chn.append(sel_name_chn)

        if len(sel_list_chn) > 0:
            sel_name = self.randomSeleName(
                prefix='%s_%s_%s_' %
                ('_'.join(sel.split()), sse, self.ss_asgn_prog))
            sel_expr = ' or '.join(sel_list_chn)
            cmd.select(sel_name, sel_expr)
            [cmd.delete(asel) for asel in sel_list_chn]
        else:
            print 'INFO: No residues are assigned to SSE \'%s\'.' % (sse, )
            sel_name = None

        return sel_name
Example #59
0
def supercell(a=1, b=1, c=1, object=None, color='green', name='supercell',
        withmates=1, prefix='m'):
    '''
DESCRIPTION

    Draw a supercell, as requested by Nicolas Bock on the pymol-users
    mailing list (Subject: [PyMOL] feature request: supercell construction
    Date: 04/12/2010 10:12:17 PM (Mon, 12 Apr 2010 14:12:17 -0600))

USAGE

    supercell a, b, c [, object [, color [, name [, withmates]]]]

ARGUMENTS

    a, b, c = integer: repeat cell in x,y,z direction a,b,c times
    {default: 1,1,1}

    object = string: name of object to take cell definition from

    color = string: color of cell {default: blue}

    name = string: name of the cgo object to create {default: supercell}

    withmates = bool: also create symmetry mates in displayed cells
    {default: 1}

SEE ALSO

    show cell

    '''
    import numpy
    from pymol import cgo

    if object is None:
        object = cmd.get_object_list()[0]
    withmates = int(withmates)

    sym = cmd.get_symmetry(object)
    cell_edges = sym[0:3]
    cell_angles = sym[3:6]

    basis = cellbasis(cell_angles, cell_edges)
    assert isinstance(basis, numpy.ndarray)

    ts = list()
    for i in range(int(a)):
        for j in range(int(b)):
            for k in range(int(c)):
                ts.append([i,j,k])

    obj = [
        cgo.BEGIN,
        cgo.LINES,
    ]

    groupname_fmt = prefix + ('%d_%d_%d' if any(int(i) > 9
            for i in [a, b, c]) else '%d%d%d')

    for t in ts:
        shift = basis[0:3,0:3] * t
        shift = shift[:,0] + shift[:,1] + shift[:,2]

        for i in range(3):
            vi = basis[0:3,i]
            vj = [
                numpy.array([0.,0.,0.]),
                basis[0:3,(i+1)%3],
                basis[0:3,(i+2)%3],
                basis[0:3,(i+1)%3] + basis[0:3,(i+2)%3]
            ]
            for j in range(4):
                obj.append(cgo.VERTEX)
                obj.extend((shift + vj[j]).tolist())
                obj.append(cgo.VERTEX)
                obj.extend((shift + vj[j] + vi).tolist())

        if withmates:
            groupname = groupname_fmt % tuple(t)
            symexpcell(groupname + '_', object, *t)
            cmd.group(groupname, groupname + '_*')

    obj.append(cgo.END)

    if name != 'none':
        cmd.delete(name)
        cmd.load_cgo(obj, name)
        cmd.color(color, name)
Example #60
0
    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)