Beispiel #1
0
 def testGetNamesOfType(self):
     cmd.fragment('gly', 'm1')
     cmd.fragment('ala', 'm2')
     cmd.ramp_new('ramp1', 'none')
     self.assertEqual(cmd.get_names_of_type('object:molecule'),
                      ['m1', 'm2'])
     self.assertEqual(cmd.get_names_of_type('object:ramp'), ['ramp1'])
     self.assertEqual(cmd.get_names_of_type('object:map'), [])
 def updateSels(self,event):
     
     if (event.widget.widgetName == "toplevel"):
         selections = self.getSels()
         
         #set objects in box for adding Hs
         objects = cmd.get_names_of_type("object:molecule");
         if list(self.h_sel.get()) != list(objects):
             self.h_sel.setlist(objects)
         
         selections = objects+selections
         for cBox in self.cBoxes:
             listEles = cBox.component('scrolledlist').get()
             #listEles = cBox.get()
             if list(selections) != list(listEles):
                 cBox.setlist(selections)
         
         #Rotamer Dihedral Code
         if('pkresi' in cmd.get_names("public_selections")):
             cmd.select('_kropkresi','pkresi')       
             myspace = {'resName': [], 'resNum': []}
             cmd.iterate('_kropkresi and name CA', 'resName.append(resn);resNum.append(resi)',  space=myspace)
             
             if(list(myspace['resName']) != list(self.rotResList) or list(myspace['resNum']) != list(self.rotResIList)):
                 self.rotResList = myspace['resName']
                 self.rotResIList = myspace['resNum']
                 if(len(self.rotResList) == 1):
                     resn = self.rotResList[0].upper()
                 
                     if(resn in self.AAtypes):
                         aa = self.AAtypes[resn]
                         self.curAAtype = aa
                         numDih = len(aa.dihAtomNames)
                         
                         #set orig dihVals
                         self.origRotVals = []
                         for atoms in self.AAtypes[resn].dihAtomNames:
                             self.origRotVals.append(cmd.get_dihedral('_kropkresi and name ' + atoms[0], '_kropkresi and name ' + atoms[1], '_kropkresi and name ' + atoms[2], 
                                              '_kropkresi and name ' + atoms[3]))
                             
                         for i,val in enumerate(self.origRotVals):
                             self.dihScale[i].grid()
                             self.dihScale[i].set(val)
                         for i in range(numDih,4):
                             self.dihScale[i].grid_remove()    
                             
                         self.rotsToAdd = []
                         self.rotsToAdd.append("orig")
                         for vals in self.AAtypes[resn].dihVals:
                             self.rotsToAdd.append(vals)
                             
                         self.rotBox.setlist(self.rotsToAdd)
                         resStr = self.rotResList[0] + " " + str(self.rotResIList[0])
                         self.resLabel.config(text=resStr)
                         self.dotCheckCB()    
                                 
                     else:
                         self.clearRot()
                 else:
                     self.clearRot()
 def hideRotDots(self):
     dotList = ["small_overlap_scRotDots", "bad_overlap_scRotDots","vdw_contact_scRotDots","H-bonds_scRotDots"]
     selections = cmd.get_names_of_type("object:cgo");
     
     for name in dotList:
         if name in selections:
             cmd.hide("cgo", name)   
Beispiel #4
0
def get_intrs_all_vs_all(verbose=True, redundant=True):
    """
    get_intrs_all_vs_all()
    get_raw_distances contacts_all # U6_C-CWC2_C_all

        # if true all vs all (a-b and b-a) then set redundant to True
        # this is sometimes useful if you want to have interactions of b in form of
        # b-a
        # b-c
        # if redundant False then you will have only
        # a-b
        # b-c

    """
    # cmd.delete('contacts')
    objs = cmd.get_names_of_type("object:molecule")
    if verbose:
        print(objs)
    # objs = ['U6_C', 'CWC25_C']
    objs2 = objs.copy()
    for o in objs:
        if not redundant:
            objs2.pop(0)
        if verbose:
            print(' ', objs2)
        for o2 in objs2:
            if o != o2:  # don't compare object to itself
                print(o,'<>',o2)
                results = o + '-' + o2
                if show_contacts(o, o2, results): #, 'contacts) #) # results to U6_C-CWC15_C
                    # if not None
                    p = '/Users/magnus/Desktop/spl-csv/'  # TODO
                    # _all or 
                    get_raw_distances(results + '_all', filename=p + results + '.csv')
def align_all(cycles=5, filename="_rmsd_.csv"):
    """
    Args:

        cycles (int): maximum number of outlier rejection cycles {default: 5}

    Returns:

        Prints a table of ref vs models with 7 items:

        RaR  RMSD after refinement
        #AA  Number of aligned atoms after refinement
        CoR  Number of refinement cycles
        RbR  RMSD before refinement
        #AbR Number of aligned atoms before refinement
        RS   Raw alignment score
        AR   Number of residues aligned 

        and saves the table to filename as csv

    old version:

          1_solution_0_rpr 1_santalucia_1_rpr 5.60600471496582 958 4 5.763411521911621 974 416.0 46 -- RMSD 5.76  of  46 residues

"""
    molecules = cmd.get_names_of_type("object:molecule")
    ref = molecules.pop(0)
    print("""
    RaR  RMSD after refinement
    #AA  Number of aligned atoms after refinement
    CoR  Number of refinement cycles
    RbR  RMSD before refinement
    #AbR Number of aligned atoms before refinement
    RS   Raw alignment score
    AR   Number of residues aligned 
    """)
    report = []
    header = 'Ref                  Model                RaR  #AA  CoR  RbR  #AbR RS   AR'
    print(header)
    txt = 'Ref,Model,RMSD after refinement,Number of aligned atoms after refinement, Number of refinement cycles, RMSD before refinement, Number of aligned atoms before refinement, Raw alignment score, Number of residues aligned\n'
    for molecule in molecules:
        values = cmd.align(molecule, ref, cycles=cycles)
        l = ([
            ref[:20].ljust(20), molecule[:20].ljust(20),
            str(round(values[0], 2)).ljust(4),
            str(round(values[1], 2)).ljust(4),
            str(round(values[2], 2)).ljust(4),
            str(round(values[3], 2)).ljust(4),
            str(round(values[4], 2)).ljust(4),
            str(round(values[5])).ljust(4),
            str(round(values[6], 2)).ljust(4)
        ])
        print(' '.join(l))
        txt += ','.join([x.strip() for x in l]) + '\n'
        report.append([ref, molecule, values[3], values[6]])

    with open(filename, 'w') as f:
        f.write(txt)
def save_all(dir=''):
    """save_all molecule objects as pdb files. Use `cd` to get to the right folder
       or use dir argument"""
    if dir:
        dir += '/'
    molecules = cmd.get_names_of_type("object:molecule")
    for molecule in molecules:
        print('Saving %s ...' % molecule)
        cmd.save(dir + molecule + '.pdb', molecule)
 def test_load_hypothesis_phypo(self):
     from epymol import ph4
     ph4.load_phypo(
             self.datafile('phase/ADHHRR_1_trans.phypo'),
             'g1', zoom=-1, mimic=1, atom_props='', _self=cmd)
     self.assertEqual(cmd.count_atoms('g1.ADHHRR_1 and name A2+H6'), 2)
     self.assertEqual(cmd.count_atoms('g1.endo-1'), 35)
     self.assertEqual(cmd.count_atoms('g1.endo-2'), 37)
     self.assertEqual(cmd.count_atoms('g1.endo-36'), 28)
     self.assertEqual(cmd.count_atoms('g1.ADHHRR_1_xvol'), 936)
     self.assertTrue('g1.ADHHRR_1_cgo' in cmd.get_names_of_type('object:cgo'))
Beispiel #8
0
def rmsdx(cycles=5, matrix_fn='matrix.txt'):
    """
    Args:

    cycles (int): refinement cycles of PyMOL align, default: 5
    matrix_fn (string): a file to save the matrix
                        matrix is pretty much saved in space-separated values 
                        so you can load it to pandas with

                        df = pd.read_csv('matrix.txt', sep=' ', index_col=False)
                        df = df.set_index(df.columns)
                        print(df)
                                      Bact_7DCO_S  Bact_5gm6_S
                        Bact_7DCO_S         0.000        0.562

    Returns:

    string: matrix 
            and matrix_fn file ;-)

    """
    models = cmd.get_names_of_type("object:molecule")
    print(' # of models:', len(models))

    f = open(matrix_fn, 'w')
    #t = '# ' # for numpy
    t = ''  # for pandas
    for r1 in models:
        # print r1,
        t += str(r1) + ' '  # here ' ' could be changed to , or \t
    t = t.strip() + '\n'

    c = 1
    for r1 in models:
        for r2 in models:
            if r1 == r2:
                rmsd = 0
            else:
                print(r1, r2)
                values = cmd.align(r1, r2, cycles=cycles)
                # RaR [1]       RbR [3]
                # RaR  #AA  CoR               RbR  #AbR RS   AR'
                # (0.668652355670929, 241, 5, 1.1646124124526978, 293, 199.0, 38)
                rmsd = round(values[0], 3)
            t += str(rmsd) + ' '
        #print('...', c, r1)
        c += 1
        t += '\n'

    f.write(t)
    f.close()

    print(t.strip())  # matrix
    return t
 def dotCheckCB(self):
     dotList = ["small_overlap_scRotDots", "bad_overlap_scRotDots","vdw_contact_scRotDots","H-bonds_scRotDots"]
     selections = cmd.get_names_of_type("object:cgo");
     
     if(self.showDotsCheckVar.get()==0):
         for name in dotList:
             if name in selections:
                 cmd.hide("cgo", name)
     else:
         curObj = self.getSelObject("_kropkresi")
         self.dotQueue.put(curObj)
         for name in dotList:
             if name in selections:
                 cmd.show("cgo", name) 
Beispiel #10
0
 def test_load_hypothesis_phypo(self):
     from epymol import ph4
     ph4.load_phypo(self.datafile('phase/ADHHRR_1_trans.phypo'),
                    'g1',
                    zoom=-1,
                    mimic=1,
                    atom_props='',
                    _self=cmd)
     self.assertEqual(cmd.count_atoms('g1.ADHHRR_1 and name A2+H6'), 2)
     self.assertEqual(cmd.count_atoms('g1.endo-1'), 35)
     self.assertEqual(cmd.count_atoms('g1.endo-2'), 37)
     self.assertEqual(cmd.count_atoms('g1.endo-36'), 28)
     self.assertEqual(cmd.count_atoms('g1.ADHHRR_1_xvol'), 936)
     self.assertTrue(
         'g1.ADHHRR_1_cgo' in cmd.get_names_of_type('object:cgo'))
Beispiel #11
0
def align_all():
    """
    This returns a list with 7 items:
 
    RMSD after refinement
    Number of aligned atoms after refinement
    Number of refinement cycles
    RMSD before refinement
    Number of aligned atoms before refinement
    Raw alignment score
    Number of residues aligned 

    old version:

          1_solution_0_rpr 1_santalucia_1_rpr 5.60600471496582 958 4 5.763411521911621 974 416.0 46 -- RMSD 5.76  of  46 residues

"""
    molecules = cmd.get_names_of_type("object:molecule")
    ref = molecules.pop(0)
    report = []
    print('Ref                  Model                RaR  #AA  CoR  RbR  #AbR RS   AR')
    for molecule in molecules:
        values = cmd.align(molecule, ref)
        print(ref[:20].ljust(20), molecule[:20].ljust(20),
              str(round(values[0], 2)).ljust(4),
              str(round(values[1], 2)).ljust(4),
              str(round(values[2], 2)).ljust(4),
              str(round(values[3], 2)).ljust(4),
              str(round(values[4], 2)).ljust(4),
              str(round(values[5])).ljust(4),
              str(round(values[6], 2)).ljust(4),
              )
              #' '.join([str(v) for v in values]), '-- RMSD', round(values[3], 2), ' of ', values[6], 'residues')
        #print(ref, molecule, 'RMSD: ', round(values[3], 2), ' of ', values[6], 'residues')
        report.append([ref, molecule, values[3], values[6]])

    for l in report:
       if not l[1].startswith('_align'):
         # rp14_5ddp_bound_clean_ligand rp14_farna_eloop_nol2fixed_cst.out.1 RMSD:  4.49360132217 of 52 residues
         if l[1] not in ['sele', 'rov_pc']: # skip them
              #print(l[0], l[1], 'RMSD:', round(l[2],2), str(l[3]) + 'nt')
              pass
Beispiel #12
0
        if not preserve:
            shutil.rmtree(tmpdir)
        elif not quiet:
            print(' Notice: not deleting', tmpdir)

if 'join_states' not in cmd.keyword:
    cmd.extend('join_states', join_states)
cmd.extend('sidechaincenters', sidechaincenters)
cmd.extend('ramp_levels', ramp_levels)
cmd.extend('pdb2pqr', pdb2pqr)
cmd.extend('corina', corina)
cmd.extend('prepwizard', prepwizard)
cmd.extend('fiber', fiber)

cmd.auto_arg[0].update([
    ('ramp_levels', [lambda: cmd.Shortcut(cmd.get_names_of_type('object:')), 'ramp object', '']),
])
cmd.auto_arg[1].update([
    ('join_states'          , cmd.auto_arg[0]['zoom']),
    ('sidechaincenters'     , cmd.auto_arg[0]['zoom']),
    ('pdb2pqr'              , cmd.auto_arg[0]['zoom']),
    ('corina'               , cmd.auto_arg[0]['zoom']),
    ('prepwizard'           , cmd.auto_arg[0]['zoom']),
])
cmd.auto_arg[2].update([
    ('sidechaincenters', [cmd.Shortcut(sidechaincentermethods), 'method', '']),
    ('pdb2pqr', [cmd.Shortcut(['AMBER', 'CHARMM', 'PARSE', 'TYL06']), 'forcefield', '']),
])

# vi: ts=4:sw=4:smarttab:expandtab
    def test_surface(self):
        cmd.load(self.datafile("surf2.vis"))

        self.assertEqual(1, len(cmd.get_names_of_type('object:cgo')))
Beispiel #14
0
 def get_object_list():
     all_obj = cmd.get_names_of_type('object:molecule')
     # filter to exclude plugin-generated objects
     ret = [o for o in all_obj if not o.startswith('mp_')]
     logger.debug('available objects are: {}'.format(ret))
     return ret
Beispiel #15
0
def get_raw_distances(names='', state=1, selection='all', quiet=1):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (index1, index2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    from chempy import cpv

    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print(' Error: no such distance object: ' + name)
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state, selection, 'xyz2idx[x,y,z] = (model,index)',
            space=locals())

    r = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state-1][1]
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i+3])
            xyz2 = tuple(points[i+3:i+6])
            try:
                r.append((xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                if not quiet:
                    print(' get_raw_distances: ' + str(r[-1]))
            except KeyError:
                if quiet < 0:
                    print(' Debug: no index for %s %s' % (xyz1, xyz2))
    return r
Beispiel #16
0
        if not preserve:
            shutil.rmtree(tmpdir)
        elif not quiet:
            print(' Notice: not deleting', tmpdir)

    if not quiet:
        print(' corina: done')

if 'join_states' not in cmd.keyword:
    cmd.extend('join_states', join_states)
cmd.extend('sidechaincenters', sidechaincenters)
cmd.extend('ramp_levels', ramp_levels)
cmd.extend('pdb2pqr', pdb2pqr)
cmd.extend('corina', corina)

cmd.auto_arg[0].update([
    ('ramp_levels', [lambda: cmd.Shortcut(cmd.get_names_of_type('object:')), 'ramp object', '']),
])
cmd.auto_arg[1].update([
    ('join_states'          , cmd.auto_arg[0]['zoom']),
    ('sidechaincenters'     , cmd.auto_arg[0]['zoom']),
    ('pdb2pqr'              , cmd.auto_arg[0]['zoom']),
    ('corina'               , cmd.auto_arg[0]['zoom']),
])
cmd.auto_arg[2].update([
    ('sidechaincenters', [cmd.Shortcut(sidechaincentermethods), 'method', '']),
    ('pdb2pqr', [cmd.Shortcut(['amber', 'charmm', 'parse', 'tyl06']), 'forcefield', '']),
])

# vi: ts=4:sw=4:smarttab:expandtab
Beispiel #17
0
def get_raw_distances(names='',
                      state=1,
                      selection='all',
                      quiet=1,
                      filename='intrs.txt'):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (index1, index2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

    quiet = boolen

    filename

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    foo = cmd.do('l = [];')  ## ugly hack!
    from chempy import cpv

    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print(' Error: no such distance object: ' + name)
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state,
                      selection,
                      'xyz2idx[x,y,z] = (model,index)',
                      space=locals())

    r = []
    rresi = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state - 1][1]
            if not quiet:
                print(points)
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i + 3])
            xyz2 = tuple(points[i + 3:i + 6])
            try:
                r.append(
                    (xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                # (('yC_5lj3_U6', 1183)
                if not quiet:
                    print(' get_raw_distances: ' + str(r[-1]))
                rresi.append([
                    unid(xyz2idx[xyz1][0], xyz2idx[xyz1][1]),
                    unid(xyz2idx[xyz2][0], xyz2idx[xyz2][1])
                ])
                if not quiet:
                    print('  ', unid(xyz2idx[xyz1][0], xyz2idx[xyz1][1]),
                          '<->', unid(xyz2idx[xyz2][0], xyz2idx[xyz2][1]))
            except KeyError:
                if quiet < 0:
                    print(' Debug: no index for %s %s' % (xyz1, xyz2))

    if rresi:
        with open(filename, 'w') as f:
            for r in rresi:
                # not fully correct
                # f.write('Prp8' +',' + r[0] + '\n')
                f.write(r[0] + ',' + r[1] + '\n')
        print('File saved:', filename)
    return r, rresi
Beispiel #18
0
 def deleteMergedArrows(self):
     for arrow in cmd.get_names_of_type("object:cgo"):
         if "rrowA" in arrow:
             cmd.delete(arrow)
Beispiel #19
0
        color = get_model_color(selection)

        if scatter:
            plt.scatter(x_values, y_values, c=color)
        else:
            plt.plot(x_values, y_values, c=color)

    _showfigure(fig, filename, quiet)

# pymol commands
cmd.extend('rms_plot', rms_plot)
cmd.extend('pca_plot', pca_plot)
cmd.extend('iterate_plot', iterate_plot)

_auto_arg_aln_objects = [
    lambda: cmd.Shortcut(cmd.get_names_of_type('object:')),
    'alignment object', '']

# autocompletion
cmd.auto_arg[0].update([
    ('pca_plot', _auto_arg_aln_objects),
    ('rms_plot', cmd.auto_arg[0]['align']),
    ('iterate_plot', cmd.auto_arg[0]['iterate']),
])
cmd.auto_arg[1].update([
    ('pca_plot', cmd.auto_arg[0]['disable']),
    ('rms_plot', cmd.auto_arg[0]['align']),
])
cmd.auto_arg[2].update([
    ('rms_plot', cmd.auto_arg[1]['align']),
])
Beispiel #20
0
def get_raw_distances(names='',
                      state=1,
                      selection='all',
                      fc=2.0,
                      amber=0,
                      gro=0,
                      label='ID',
                      quiet=1):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (ID1, ID2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

    amber = integer: generate AMBER rst file {default: 0}

    gro = integer: generate GROMACS rst file {default: 0}

    label = string: label type ('ID' or 'index') {default: ID}

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    from chempy import cpv

    state, quiet, fc = int(state), int(quiet), float(fc)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print(' Error: no such distance object: ' + name)
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state,
                      selection,
                      'xyz2idx[x,y,z] = (model, resi, resn, name, ' + label +
                      ')',
                      space=locals())

    r = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state - 1][1]
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i + 3])
            xyz2 = tuple(points[i + 3:i + 6])
            try:
                r.append(
                    (xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                if not quiet:
                    print(' get_raw_distances: ' + str(r[-1]))
            except KeyError:
                if quiet < 0:
                    print(' Debug: no index for %s %s' % (xyz1, xyz2))
    # print(r)
    # for generate amber MD restraint file.
    if (int(amber)):
        for i in r:
            print("""# {0}{1}  {2} - {3}{4}  {5}
&rst
   iat={6}, {7},
   r1=0, r2=0.5,
   r3={8:.2f}, r4=8,
   rk2={9}, rk3={9},
/""".format(str(i[0][1]), str(i[0][2]), str(i[0][3]), str(i[1][1]),
            str(i[1][2]), str(i[1][3]), str(i[0][4]), str(i[1][4]),
            float(i[2]), float(fc)))

    # for generate GROMACS MD restraint file.
    if (int(gro)):
        for i in r:
            print(
                "{6} {7} 10 0.00 {8:.3f} 0.800 800 ; {0}{1} {2} - {3}{4} {5} 2kcal/mol/A2"
                .format(str(i[0][1]), str(i[0][2]), str(i[0][3]), str(i[1][1]),
                        str(i[1][2]), str(i[1][3]), str(i[0][4]), str(i[1][4]),
                        float(i[2]) / 10))

    return r
Beispiel #21
0
def dialog(_self=None):
    if _self is None:
        from pymol import cmd as _self

    dialog = QtWidgets.QDialog()
    uifile = os.path.join(os.path.dirname(__file__), 'apbs.ui')
    form = loadUi(uifile, dialog)
    form._dialog = dialog
    form._proclist = []

    def set_apbs_in(contents):
        form.apbs_template.setPlainText(contents.strip())

    # hide options widgets
    form.optarea_prep.setVisible(False)
    form.optarea_apbs.setVisible(False)
    form.optarea_surf.setVisible(False)
    form.optarea_other.setVisible(False)

    # pre-fill form with likely data
    names = _self.get_object_list()
    names += ['(' + n + ')' for n in _self.get_names('public_selections')]
    if names:
        form.input_sele.clear()
        form.input_sele.addItems([
            ('polymer & ' +
             name) if _self.count_atoms('polymer & ' + name) > 0 else name
            for name in names
        ])
    form.surf_map.addItems(_self.get_names_of_type('object:map'))
    set_apbs_in(electrostatics.template_apbs_in)

    # executables
    from distutils.spawn import find_executable
    form.apbs_exe.setText(electrostatics.find_apbs_exe() or 'apbs')
    form.pdb2pqr_exe.setText(
        find_executable('pdb2pqr') or
        # acellera::htmd-pdb2pqr provides pdb2pqr_cli
        find_executable('pdb2pqr_cli') or find_executable(
            'share/pdb2pqr/pdb2pqr.py', os.getenv('FREEMOL', '/usr'))
        or 'pdb2pqr')

    # for async panels
    form._callInMainThread = MainThreadCaller()
    run_impl_async = AsyncFunc(run_impl)

    # "Run" button callback
    def run():
        form.tabWidget.setEnabled(False)
        form.button_ok.clicked.disconnect()
        form.button_ok.clicked.connect(abort)
        form.button_ok.setText('Abort')

        form._capture = StdOutCapture()

        # detach from main thread
        run_impl_async(form, _self)

    # "Run" button "finally" actions (main thread)
    @run_impl_async.finished.connect
    def run_finally(args):
        _, exception = args

        form._proclist[:] = []
        stdout = form._capture.release()
        print(stdout)

        form.button_ok.setText('Run')
        form.button_ok.clicked.disconnect()
        form.button_ok.clicked.connect(run)
        form.button_ok.setEnabled(True)
        form.tabWidget.setEnabled(True)

        if exception is not None:
            handle_exception(exception, stdout)
            return

        quit_msg = "Finished with Success. Close the APBS dialog?"
        if QMessageBox.Yes == QMessageBox.question(form._dialog, 'Finished',
                                                   quit_msg, QMessageBox.Yes,
                                                   QMessageBox.No):
            form._dialog.close()

    def handle_exception(e, stdout):
        if isinstance(e, SilentAbort):
            return

        msg = str(e) or 'unknown error'
        msgbox = QMessageBox(QMessageBox.Critical, 'Error', msg,
                             QMessageBox.Close, form._dialog)
        if stdout.strip():
            msgbox.setDetailedText(stdout)
        msgbox.exec_()

    # "Abort" button callback
    def abort():
        form.button_ok.setEnabled(False)
        while form._proclist:
            p = form._proclist.pop()
            try:
                p.terminate()
                p.returncode = -15  # SIGTERM
            except OSError as e:
                print(e)

    # selection checker
    check_sele_timer = QtCore.QTimer()
    check_sele_timer.setSingleShot(True)

    # grid auto-value
    form.apbs_grid_userchanged = False
    form.apbs_grid.setStyleSheet('background: #ff6')

    @form.apbs_grid.editingFinished.connect
    def _():
        form.apbs_grid_userchanged = True
        form.apbs_grid.setStyleSheet('')

    @check_sele_timer.timeout.connect
    def _():
        has_props = ['no', 'no']

        def callback(partial_charge, elec_radius):
            if partial_charge: has_props[0] = 'YES'
            if elec_radius > 0: has_props[1] = 'YES'

        n = _self.iterate(form.input_sele.currentText(),
                          'callback(partial_charge, elec_radius)',
                          space={'callback': callback})

        # grid auto-value (keep map size in the order of 200x200x200)
        if n > 1 and not form.apbs_grid_userchanged:
            e = _self.get_extent(form.input_sele.currentText())
            volume = (e[1][0] - e[0][0]) * (e[1][1] - e[0][1]) * (e[1][2] -
                                                                  e[0][2])
            grid = max(0.5, volume**0.333 / 200.0)
            form.apbs_grid.setValue(grid)

        if n < 1:
            label = 'Selection is invalid'
            color = '#f66'
        elif has_props == ['YES', 'YES']:
            label = 'No preparation necessary, selection has charges and radii'
            form.do_prepare.setChecked(False)
            color = '#6f6'
        else:
            label = 'Selection needs preparation (partial_charge: %s, elec_radius: %s)' % tuple(
                has_props)
            form.do_prepare.setChecked(True)
            color = '#fc6'

        form.label_sele_has.setText(label)
        form.label_sele_has.setStyleSheet('background: %s; padding: 5' % color)

    check_sele_timer.start(0)

    @form.apbs_exe_browse.clicked.connect
    def _():
        fnames = getOpenFileNames(None,
                                  filter='apbs (apbs*);;All Files (*)')[0]
        if fnames:
            form.apbs_exe.setText(fnames[0])

    @form.pdb2pqr_exe_browse.clicked.connect
    def _():
        fnames = getOpenFileNames(
            None, filter='pdb2pqr (pdb2pqr*);;All Files (*)')[0]
        if fnames:
            form.pdb2pqr_exe.setText(fnames[0])

    # hook up events
    form.input_sele.currentIndexChanged.connect(
        lambda: check_sele_timer.start(0))
    form.input_sele.editTextChanged.connect(
        lambda: check_sele_timer.start(1000))

    form.button_ok.clicked.connect(run)

    # "Register" opens a web browser
    @form.button_register.clicked.connect
    def _():
        import webbrowser
        webbrowser.open("http://www.poissonboltzmann.org/")

    @form.button_load.clicked.connect
    def _():
        fnames = getOpenFileNames(None,
                                  filter='APBS Input (*.in);;All Files (*)')[0]
        if fnames:
            contents = load_apbs_in(form, fnames[0])
            set_apbs_in(contents)

    @form.button_reset.clicked.connect
    def _():
        set_apbs_in(electrostatics.template_apbs_in)

    form._dialog.show()
    form._dialog.resize(500, 600)
Beispiel #22
0
def get_raw_distances(names='', state=1, selection='all', quiet=1):
    '''
DESCRIPTION

    Get the list of pair items from distance objects. Each list item is a
    tuple of (index1, index2, distance).

    Based on a script from Takanori Nakane, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg10143.html

ARGUMENTS

    names = string: names of distance objects (no wildcards!) {default: all
    measurement objects}

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

SEE ALSO

    select_distances, cmd.find_pairs, cmd.get_raw_alignment
    '''
    from chempy import cpv

    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()

    valid_names = cmd.get_names_of_type('object:measurement')
    if names == '':
        names = ' '.join(valid_names)
    else:
        for name in names.split():
            if name not in valid_names:
                print((' Error: no such distance object:', name))
                raise CmdException

    raw_objects = cmd.get_session(names, 1, 1, 0, 0)['names']

    xyz2idx = {}
    cmd.iterate_state(state,
                      selection,
                      'xyz2idx[x,y,z] = (model,index)',
                      space=locals())

    r = []
    for obj in raw_objects:
        try:
            points = obj[5][2][state - 1][1]
            if points is None:
                raise ValueError
        except (KeyError, ValueError):
            continue
        for i in range(0, len(points), 6):
            xyz1 = tuple(points[i:i + 3])
            xyz2 = tuple(points[i + 3:i + 6])
            try:
                r.append(
                    (xyz2idx[xyz1], xyz2idx[xyz2], cpv.distance(xyz1, xyz2)))
                if not quiet:
                    print((' get_raw_distances:', r[-1]))
            except KeyError:
                if quiet < 0:
                    print((' Debug: no index for', xyz1, xyz2))
    return r
Beispiel #23
0
def color_chains(rainbow=0):
 
        """
 
AUTHOR 

        Kevin Houlihan
        adapted from a script by Gareth Stockwell
 
USAGE
 
        color_chains(rainbow=0)
 
        This function colours each object currently in the PyMOL heirarchy
        with a different colour.  Colours used are either the 22 named
        colours used by PyMOL (in which case the 23rd object, if it exists,
        gets the same colour as the first), or are the colours of the rainbow
 
SEE ALSO
 
        util.color_objs()
        """
 
        # Process arguments
        rainbow = int(rainbow)
 
        # Get names of all PyMOL objects
        # obj_list = cmd.get_names('objects')
	# don't color selections, alignments, measurements, etc.
	obj_list = cmd.get_names_of_type("object:molecule")
	chain_list = []
	for obj in obj_list:
		for ch in cmd.get_chains(obj):
			# there seems to be a bug in pymol, some CA don't get colored
			#sele = obj + " and c. " + ch + " and (e. C or name CA)"
			#sele = obj + " and c. " + ch + " and e. C"
			sele = obj + " and c. " + ch
			chain_list.append(sele)
 
        if rainbow:
 
           #print "\nColouring objects as rainbow\n"
 
           nobj = len(obj_list)
	   nchain = len(chain_list)
 
           # Create colours starting at blue(240) to red(0), using intervals
           # of 240/(nobj-1)
           for j in range(nchain):
              # hsv = (240-j*240/(nobj-1), 1, 1)
	      # disparate colors for adjacent objects in sequence, colors heterodimers nicely
	      hsv = (240 - ( (120*(j - j%2))/(nchain-1) + 120*(j%2) ), 1, 1)
              # Convert to RGB
              rgb = hsv_to_rgb(hsv)
              # Define the new colour
              cmd.set_color("col" + str(j), rgb)
              #print chain_list[j], rgb
              # Colour the object
              cmd.color("col" + str(j), chain_list[j])
	      util.cnc(chain_list[j])
 
        else:
 
           #print "\nColouring objects using PyMOL defined colours\n"
 
           # List of available colours
	   # standard pymol colors, I like these better
	   # color sets listed at http://www.pymolwiki.org/index.php/Color_Values
	   mainset1_colours = ['carbon', 'cyan', 'lightmagenta', 'yellow', 'salmon', 'hydrogen', 'slate', 'orange']
	   mainset2_colours = ['lime', 'deepteal', 'hotpink', 'yelloworange', 'violetpurple', 'grey70', 'marine', 'olive']
	   mainset3_colours = ['smudge', 'teal', 'dirtyviolet', 'wheat', 'deepsalmon', 'lightpink', 'aquamarine', 'paleyellow']
           mainset4_colours = ['limegreen', 'skyblue', 'warmpink', 'limon', 'violet', 'bluewhite', 'greencyan', 'sand']
	   mainset5_colours = ['forest', 'lightteal', 'darksalmon', 'splitpea', 'raspberry', 'grey50', 'deepblue', 'brown']
	   #colours = mainset1_colours + mainset4_colours
	   colours = mainset1_colours + mainset2_colours + mainset3_colours + mainset4_colours + mainset5_colours
	   # colors in original script
           extra_colours = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
           'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
           'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
           'wheat', 'white', 'grey' ]
           ncolours = len(colours)
 
           # Loop over objects
           i = 0
           for ch in chain_list:
              #print "  ", obj, ch, colours[i]
              cmd.color(colours[i], ch)
	      util.cnc(ch)
              i += 1
	      i %= ncolours
Beispiel #24
0
def get_ensemble_coords(selection):
    '''
DESCRIPTION

    API only. Returns the (nstates, natoms, 3) coordinate matrix. Considers
    the object rotation matrix. 
    '''
    return [get_coords(selection, state)
            for state in range(1, cmd.count_states(selection) + 1)]

if 'centerofmass' not in cmd.keyword:
    cmd.extend('centerofmass', centerofmass)
cmd.extend('gyradius', gyradius)
cmd.extend('get_sasa', get_sasa)
cmd.extend('get_sasa_ball', get_sasa_ball)
cmd.extend('get_sasa_mmtk', get_sasa_mmtk)
cmd.extend('get_raw_distances', get_raw_distances)

cmd.auto_arg[0].update([
    ('centerofmass', cmd.auto_arg[0]['zoom']),
    ('gyradius', cmd.auto_arg[0]['zoom']),
    ('get_sasa', cmd.auto_arg[0]['zoom']),
    ('get_sasa_ball', cmd.auto_arg[0]['zoom']),
    ('get_sasa_mmtk', cmd.auto_arg[0]['zoom']),
    ('get_raw_distances', [
        lambda: cmd.Shortcut(cmd.get_names_of_type('object:measurement')),
        'distance object', '']),
])

# vi: ts=4:sw=4:smarttab:expandtab
Beispiel #25
0
    def test_surface(self):
        cmd.load(self.datafile("surf2.vis"))

        self.assertEqual(1, len(cmd.get_names_of_type("object:cgo")))
Beispiel #26
0
        color = get_model_color(selection)

        if scatter:
            plt.scatter(x_values, y_values, c=color)
        else:
            plt.plot(x_values, y_values, c=color)

    _showfigure(fig, filename, quiet)

# pymol commands
cmd.extend('rms_plot', rms_plot)
cmd.extend('pca_plot', pca_plot)
cmd.extend('iterate_plot', iterate_plot)

_auto_arg_aln_objects = [
    lambda: cmd.Shortcut(cmd.get_names_of_type('object:alignment')),
    'alignment object', '']

# autocompletion
cmd.auto_arg[0].update([
    ('pca_plot', _auto_arg_aln_objects),
    ('rms_plot', cmd.auto_arg[0]['align']),
    ('iterate_plot', cmd.auto_arg[0]['iterate']),
])
cmd.auto_arg[1].update([
    ('pca_plot', cmd.auto_arg[0]['disable']),
    ('rms_plot', cmd.auto_arg[0]['align']),
])
cmd.auto_arg[2].update([
    ('rms_plot', cmd.auto_arg[1]['align']),
])
Beispiel #27
0
        if not preserve:
            shutil.rmtree(tmpdir)
        elif not quiet:
            print(" Notice: not deleting", tmpdir)


if "join_states" not in cmd.keyword:
    cmd.extend("join_states", join_states)
cmd.extend("sidechaincenters", sidechaincenters)
cmd.extend("ramp_levels", ramp_levels)
cmd.extend("pdb2pqr", pdb2pqr)
cmd.extend("corina", corina)
cmd.extend("prepwizard", prepwizard)
cmd.extend("fiber", fiber)

cmd.auto_arg[0].update([("ramp_levels", [lambda: cmd.Shortcut(cmd.get_names_of_type("object:")), "ramp object", ""])])
cmd.auto_arg[1].update(
    [
        ("join_states", cmd.auto_arg[0]["zoom"]),
        ("sidechaincenters", cmd.auto_arg[0]["zoom"]),
        ("pdb2pqr", cmd.auto_arg[0]["zoom"]),
        ("corina", cmd.auto_arg[0]["zoom"]),
        ("prepwizard", cmd.auto_arg[0]["zoom"]),
    ]
)
cmd.auto_arg[2].update(
    [
        ("sidechaincenters", [cmd.Shortcut(sidechaincentermethods), "method", ""]),
        ("pdb2pqr", [cmd.Shortcut(["amber", "charmm", "parse", "tyl06"]), "forcefield", ""]),
    ]
)
Beispiel #28
0
        print(' Selector: selection "%s" defined with %d atoms.' % (name, r))
    return r


# commands
cmd.extend('select_pepseq', select_pepseq)
cmd.extend('select_sspick', select_sspick)
cmd.extend('symdiff', symdiff)
cmd.extend('diff', diff)
cmd.extend('collapse_resi', collapse_resi)
cmd.extend('select_distances', select_distances)

# autocompletion
cmd.auto_arg[0].update([
    ('select_sspick', cmd.auto_arg[0]['align']),
    ('symdiff', cmd.auto_arg[0]['align']),
    ('diff', cmd.auto_arg[0]['align']),
    ('collapse_resi', cmd.auto_arg[0]['zoom']),
    ('select_distances', [
        lambda: cmd.Shortcut(cmd.get_names_of_type('object:measurement')),
        'distance object', ''
    ]),
])
cmd.auto_arg[1].update([
    ('select_pepseq', cmd.auto_arg[1]['select']),
    ('symdiff', cmd.auto_arg[1]['align']),
    ('diff', cmd.auto_arg[1]['align']),
])

# vi:expandtab:smarttab
Beispiel #29
0
        color = get_model_color(selection)

        if scatter:
            plt.scatter(x_values, y_values, c=color)
        else:
            plt.plot(x_values, y_values, c=color)

    _showfigure(fig, filename, quiet)


# pymol commands
cmd.extend("rms_plot", rms_plot)
cmd.extend("pca_plot", pca_plot)
cmd.extend("iterate_plot", iterate_plot)

_auto_arg_aln_objects = [lambda: cmd.Shortcut(cmd.get_names_of_type("object:")), "alignment object", ""]

# autocompletion
cmd.auto_arg[0].update(
    [
        ("pca_plot", _auto_arg_aln_objects),
        ("rms_plot", cmd.auto_arg[0]["align"]),
        ("iterate_plot", cmd.auto_arg[0]["iterate"]),
    ]
)
cmd.auto_arg[1].update([("pca_plot", cmd.auto_arg[0]["disable"]), ("rms_plot", cmd.auto_arg[0]["align"])])
cmd.auto_arg[2].update([("rms_plot", cmd.auto_arg[1]["align"])])

# vi: ts=4:sw=4:smarttab:expandtab
Beispiel #30
0
def pca_plot(
    aln_object,
    ref="all",
    state=0,
    maxlabels=20,
    size=20,
    invert="",
    which=(0, 1),
    alpha=0.75,
    filename=None,
    quiet=1,
    load_b=0,
):
    """
DESCRIPTION

    Principal Component Analysis on a set of superposed conformations, given
    by an alignment object. By default all states in all objects are
    considered. Generates a 2d-plot of the first two principal components.

USAGE

    pca_plot aln_object [, ref [, state [, maxlabels ]]]

ARGUMENTS

    aln_object = string: name of alignment object, defines the selection
    and the atom mapping between objects

    ref = string: object names for which to calculate PCA for {default: all}

    state = integer: if state=0 use all states {default: 0}

    maxlabels = integer: label dots in plot if maxlabels<0 or number of models
    not more than maxlabels {default: 20}

    size = float: size of plot points in px^2 {default: 20}

    invert = string: invert plotting axes x, y or xy {default: ''}

    which = (int,int): indices of principal components to plot {default: (0,1)}

    alpha = float: opacity of plotting points

    filename = string: if given, plot to file {default: None}

EXAMPLE

    fetch 1ake 4ake 1dvr 1ak2, async=0
    split_chains
    extra_fit (*_*) and name CA, reference=1ake_A, cycles=0, object=aln
    pca_plot aln, 1ake_* 4ake_*

    fetch 1ubq 2k39, async=0
    align 2k39, 1ubq and guide, cycles=0, object=aln2
    color blue, 1ubq
    color orange, 2k39
    pca_plot aln2, filename=pca-ubq.pdf
    """
    from numpy import array, dot
    from numpy.linalg import svd, LinAlgError
    from . import matplotlib_fix
    from matplotlib.pyplot import figure

    state, quiet = int(state), int(quiet)
    maxlabels = int(maxlabels)
    if cmd.is_string(which):
        which = cmd.safe_list_eval(which)

    if aln_object not in cmd.get_names_of_type("object:"):
        print(" Warning: first argument should be an alignment object")

        from .fitting import extra_fit

        selection = aln_object
        aln_object = cmd.get_unused_name("aln")
        extra_fit(selection, cycles=0, transform=0, object=aln_object)

    if state == 0:
        states = list(range(1, cmd.count_states() + 1))
    elif state < 0:
        states = [cmd.get_state()]
    else:
        states = [state]

    models = cmd.get_object_list(aln_object)
    references = set(cmd.get_object_list("(" + ref + ")")).intersection(models)
    others = set(models).difference(references)
    aln = cmd.get_raw_alignment(aln_object)

    if not quiet:
        print(" PCA References:", ", ".join(references))
        print(" PCA Others:", ", ".join(others))

    if len(references) == 0:
        print(" PCA Error: No reference objects")
        raise CmdException

    model_count = len(models)
    coords = dict((model, []) for model in models)
    aln = [pos for pos in aln if len(pos) == model_count]

    for state in states:
        idx2xyz = dict()
        cmd.iterate_state(state, aln_object, "idx2xyz[model,index] = (x,y,z)", space={"idx2xyz": idx2xyz})

        for pos in aln:
            for idx in pos:
                if idx not in idx2xyz:
                    continue

                c = coords[idx[0]]
                if len(c) < state:
                    c.append([])
                c[-1].extend(idx2xyz[idx])

    c_iter = lambda models: ((c, model, i + 1) for model in models for (i, c) in enumerate(coords[model]))
    X = array([i[0] for i in c_iter(references)])
    Y = array([i[0] for i in c_iter(others)])
    center = X.mean(0)
    X = X - center

    try:
        U, L, V = svd(X)
    except LinAlgError as e:
        print(" PCA Error: ", e)
        raise CmdException

    if int(load_b):
        cmd.alter("byobj " + aln_object, "b=-0.01")
        b_dict = {}
        i = which[0]
        b_array = (V[i].reshape((-1, 3)) ** 2).sum(1) ** 0.5
        for pos, b in zip(aln, b_array):
            for idx in pos:
                b_dict[idx] = b
        cmd.alter(aln_object, "b=b_dict.get((model,index), -0.01)", space=locals())
        cmd.color("yellow", "byobj " + aln_object)
        cmd.spectrum("b", "blue_red", aln_object + " and b > -0.01")

    X_labels = [i[1:3] for i in c_iter(references)]
    Y_labels = [i[1:3] for i in c_iter(others)]

    x_list = []
    y_list = []
    colors = []
    text_list = []

    def plot_pc_2d(X, labels):
        pca_12 = dot(X, V.T)[:, which]
        for (x, y), (model, state) in zip(pca_12, labels):
            x_list.append(x)
            y_list.append(y)
            colors.append(get_model_color(model))
            if maxlabels < 0 or len(pca_12) <= maxlabels:
                text_list.append("%s(%d)" % (model, state))
            else:
                text_list.append(None)

    plot_pc_2d(X, X_labels)
    if len(Y) > 0:
        Y = Y - center
        plot_pc_2d(Y, Y_labels)

    if "x" in invert:
        x_list = [-x for x in x_list]
    if "y" in invert:
        y_list = [-y for y in y_list]

    fig = figure()
    plt = fig.add_subplot(111, xlabel="PC %d" % (which[0] + 1), ylabel="PC %d" % (which[1] + 1))
    plt.scatter(x_list, y_list, float(size), colors, linewidths=0, alpha=float(alpha))

    for (x, y, text) in zip(x_list, y_list, text_list):
        if text is not None:
            plt.text(x, y, text, horizontalalignment="left")

    _showfigure(fig, filename, quiet)
Beispiel #31
0
            print(' Notice: not deleting', tmpdir)

    if not quiet:
        print(' corina: done')


if 'join_states' not in cmd.keyword:
    cmd.extend('join_states', join_states)
cmd.extend('sidechaincenters', sidechaincenters)
cmd.extend('ramp_levels', ramp_levels)
cmd.extend('pdb2pqr', pdb2pqr)
cmd.extend('corina', corina)

cmd.auto_arg[0].update([
    ('ramp_levels', [
        lambda: cmd.Shortcut(cmd.get_names_of_type('object:')), 'ramp object',
        ''
    ]),
])
cmd.auto_arg[1].update([
    ('join_states', cmd.auto_arg[0]['zoom']),
    ('sidechaincenters', cmd.auto_arg[0]['zoom']),
    ('pdb2pqr', cmd.auto_arg[0]['zoom']),
    ('corina', cmd.auto_arg[0]['zoom']),
])
cmd.auto_arg[2].update([
    ('sidechaincenters', [cmd.Shortcut(sidechaincentermethods), 'method', '']),
    ('pdb2pqr',
     [cmd.Shortcut(['amber', 'charmm', 'parse', 'tyl06']), 'forcefield', '']),
])
Beispiel #32
0
    def test_map(self):
        cmd.load(self.datafile("Structure_potential.vis"))

        self.assertEqual(1, len(cmd.get_names_of_type("object:map")))
        self.assertEqual(2, len(cmd.get_names_of_type("object:surface")))
    def test_map(self):
        cmd.load(self.datafile("Structure_potential.vis"))

        self.assertEqual(1, len(cmd.get_names_of_type('object:map')))
        self.assertEqual(2, len(cmd.get_names_of_type('object:surface')))
Beispiel #34
0
def pca_plot(aln_object, ref='all', state=0, maxlabels=20, size=20, invert='',
        which=(0,1), alpha=0.75, filename=None, quiet=1, load_b=0):
    '''
DESCRIPTION

    Principal Component Analysis on a set of superposed conformations, given
    by an alignment object. By default all states in all objects are
    considered. Generates a 2d-plot of the first two principal components.

USAGE

    pca_plot aln_object [, ref [, state [, maxlabels ]]]

ARGUMENTS

    aln_object = string: name of alignment object, defines the selection
    and the atom mapping between objects

    ref = string: object names for which to calculate PCA for {default: all}

    state = integer: if state=0 use all states {default: 0}

    maxlabels = integer: label dots in plot if maxlabels<0 or number of models
    not more than maxlabels {default: 20}

    size = float: size of plot points in px^2 {default: 20}

    invert = string: invert plotting axes x, y or xy {default: ''}

    which = (int,int): indices of principal components to plot {default: (0,1)}

    alpha = float: opacity of plotting points

    filename = string: if given, plot to file {default: None}

EXAMPLE

    fetch 1ake 4ake 1dvr 1ak2, async=0
    split_chains
    extra_fit (*_*) and name CA, reference=1ake_A, cycles=0, object=aln
    pca_plot aln, 1ake_* 4ake_*

    fetch 1ubq 2k39, async=0
    align 2k39, 1ubq and guide, cycles=0, object=aln2
    color blue, 1ubq
    color orange, 2k39
    pca_plot aln2, filename=pca-ubq.pdf
    '''
    from numpy import array, dot
    from numpy.linalg import svd, LinAlgError
    from . import matplotlib_fix
    from matplotlib.pyplot import figure

    state, quiet = int(state), int(quiet)
    maxlabels = int(maxlabels)
    if cmd.is_string(which):
        which = cmd.safe_list_eval(which)

    if aln_object not in cmd.get_names_of_type('object:alignment'):
        print(' Warning: first argument should be an alignment object')

        from .fitting import extra_fit

        selection = aln_object
        aln_object = cmd.get_unused_name('aln')
        extra_fit(selection, cycles=0, transform=0, object=aln_object)

    if state == 0:
        states = list(range(1, cmd.count_states()+1))
    elif state < 0:
        states = [cmd.get_state()]
    else:
        states = [state]

    models = cmd.get_object_list(aln_object)
    references = set(cmd.get_object_list('(' + ref + ')')).intersection(models)
    others = set(models).difference(references)
    aln = cmd.get_raw_alignment(aln_object)

    if not quiet:
        print(' PCA References:', ', '.join(references))
        print(' PCA Others:', ', '.join(others))

    if len(references) == 0:
        print(' PCA Error: No reference objects')
        raise CmdException

    model_count = len(models)
    coords = dict((model, []) for model in models)
    aln = [pos for pos in aln if len(pos) == model_count]

    for state in states:
        idx2xyz = dict()
        cmd.iterate_state(state, aln_object, 'idx2xyz[model,index] = (x,y,z)',
                space={'idx2xyz': idx2xyz})

        for pos in aln:
            for idx in pos:
                if idx not in idx2xyz:
                    continue

                c = coords[idx[0]]
                if len(c) < state:
                    c.append([])
                c[-1].extend(idx2xyz[idx])

    c_iter = lambda models: ((c,model,i+1) for model in models
            for (i,c) in enumerate(coords[model]))
    X = array([i[0] for i in c_iter(references)])
    Y = array([i[0] for i in c_iter(others)])
    center = X.mean(0)
    X = X - center

    try:
        U, L, V = svd(X)
    except LinAlgError as e:
        print(' PCA Error: ', e)
        raise CmdException

    if int(load_b):
        cmd.alter('byobj ' + aln_object, 'b=-0.01')
        b_dict = {}
        i = which[0]
        b_array = (V[i].reshape((-1, 3))**2).sum(1)**0.5
        for pos, b in zip(aln, b_array):
            for idx in pos:
                b_dict[idx] = b
        cmd.alter(aln_object, 'b=b_dict.get((model,index), -0.01)', space=locals())
        cmd.color('yellow', 'byobj ' + aln_object)
        cmd.spectrum('b', 'blue_red', aln_object + ' and b > -0.01')

    X_labels = [i[1:3] for i in c_iter(references)]
    Y_labels = [i[1:3] for i in c_iter(others)]

    x_list = []
    y_list = []
    colors = []
    text_list = []

    def plot_pc_2d(X, labels):
        pca_12 = dot(X, V.T)[:,which]
        for (x,y), (model,state) in zip(pca_12, labels):
            x_list.append(x)
            y_list.append(y)
            colors.append(get_model_color(model))
            if maxlabels < 0 or len(pca_12) <= maxlabels:
                text_list.append('%s(%d)' % (model, state))
            else:
                text_list.append(None)

    plot_pc_2d(X, X_labels)
    if len(Y) > 0:
        Y = Y - center
        plot_pc_2d(Y, Y_labels)

    if 'x' in invert:
        x_list = [-x for x in x_list]
    if 'y' in invert:
        y_list = [-y for y in y_list]

    fig = figure()
    plt = fig.add_subplot(111, xlabel='PC %d' % (which[0]+1), ylabel='PC %d' % (which[1]+1))
    plt.scatter(x_list, y_list, float(size), colors, linewidths=0, alpha=float(alpha))

    for (x, y, text) in zip(x_list, y_list, text_list):
        if text is not None:
            plt.text(x, y, text, horizontalalignment='left')

    _showfigure(fig, filename, quiet)
Beispiel #35
0
 def get_object_list():
     all_obj = cmd.get_names_of_type('object:molecule')
     # filter to exclude plugin-generated objects
     ret = [o for o in all_obj if not o.startswith('mp_')]
     logger.debug('available objects are: {}'.format(ret))
     return ret