Count molecules in selection

From PyMOLWiki
Jump to navigation Jump to search


This script will return the number of distinct molecular objects in a given selection. If no selection is given, the script assumes "sele" the named mouse selection.


# run the script


# grab a protein from the PDB

fetch 2f56, async=0

# select all the urea molecules

select resn URE

# should count 11 molecules


# change the selection and try again

select polymer

# should return 3, as there's 3 chains


The Code

import pymol
from pymol import cmd

def count_mols_in_sel(sel="sele"):
    Returns the number of distinct molecules in a given selection.

    sel_copy = "__selcopy", sel)

    num_objs = 0

    atoms_in_sel = cmd.count_atoms(sel_copy)

    while atoms_in_sel > 0:

        num_objs += 1, "%s and not (bm. first %s)" % (sel_copy, sel_copy))

        atoms_in_sel = cmd.count_atoms(sel_copy)

    print "There are %d distinct molecules in the selection '%s'." % (num_objs, sel)

    return num_objs

cmd.extend("count_molecules_in_selection", count_mols_in_sel)