Count molecules in selection
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 run count_molecules_in_sel.py # grab a protein from the PDB fetch 2f56, async=0 # select all the urea molecules select resn URE # should count 11 molecules count_molecules_in_selection # change the selection and try again select polymer # should return 3, as there's 3 chains count_molecules_in_selection
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" cmd.select(sel_copy, sel) num_objs = 0 atoms_in_sel = cmd.count_atoms(sel_copy) while atoms_in_sel > 0: num_objs += 1 cmd.select(sel_copy, "%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)