check valences of all atoms

        :return: list of invalid atoms
547637
def check_valence(self):
        
        return [x for x, atom in self.atoms() if not atom.check_valence(self.environment(x))]
1110894
def get_atoms(self, inc_alt_states=False):
        
        if inc_alt_states:
            return itertools.chain(*[x[1].values() for x in sorted(list(self.states.items()))])
        return self.atoms.values()
1009774
def pd_coords(self, comp):
        
        if set(comp.elements).difference(self.elements):
            raise ValueError('{} has elements not in the phase diagram {}'
                             ''.format(comp, self.elements))
        return np.array(
            [comp.get_atomic_fraction(el) for el in self.elements[1:]])
1100766
def formula(mol):
    
    mol.require("Valence")
    mol.require("Topology")
    total_cntr = Counter()
    for m in sorted(mols_iter(mol), key=len, reverse=True):
        cntr = Counter()
        for i in m:
            cntr += mol.atom(i).composition()
        text = []
        Cs = cntr.pop("C", 0)
        if Cs:
            text.append("C")
            if Cs > 1:
                text.append(str(Cs))
        Hs = cntr.pop("H", 0)
        if Hs:
            text.append("H")
            if Hs > 1:
                text.append(str(Hs))
        heteros = sorted(cntr.items(), key=lambda x: atom_number(x[0]))
        for k, v in heteros:
            text.append(k)
            if v > 1:
                text.append(str(v))
        total_cntr["".join(text)] += 1
    total = sorted(total_cntr.items(), key=lambda x: len(x[0]), reverse=True)
    total_text = []
    for k, v in total:
        if v > 1:
            total_text.append(str(v) + k)
        else:
            total_text.append(k)
    return ".".join(total_text)
151523
def molecules2symbols(molecules, add_hydrogen=True):
    
    symbols = sorted(
        list(set(
            ase.symbols.string2symbols(''.join(
                map(
                    lambda _x:
                    ''.join(ase.symbols.string2symbols(_x)), molecules)
            ))
        )),
        key=lambda _y: ase.data.atomic_numbers[_y])

    if add_hydrogen and 'H' not in symbols:
        symbols.insert(0, 'H')

    return symbols
1054591
def addHydrogens(molecule, usedPyroles=None):
    """"""
    for atom in molecule.atoms:
        # if the atom has an explicit hcount, we can't set the
        # hcount
        if atom.has_explicit_hcount:
            atom.hcount = atom.explicit_hcount
            continue
        
        if atom.valences:            
            for valence in atom.valences:
                hcount = max(0, int(valence - atom.sumBondOrders() + atom.charge))
                if hcount >= 0:
                    break
            else:
                if usedPyroles and not usedPyroles.has_key(atom.handle):
                    #print atom.symbol, atom.valences, atom.hcount, atom.charge,\
                    #      atom.sumBondOrders()
                    #print [x.bondtype for x in atom.bonds]
                    #print molecule.cansmiles()
                    raise PinkyError("Valence error in atom %s"%molecule.atoms.index(atom))
                pass

            #hcount = int(hcount)
            atom.hcount = hcount
    return molecule
1282418
def _prepare_atoms(topology, compute_cycles=False):
    """"""
    atom1 = next(topology.atoms())
    has_whitelists = hasattr(atom1, 'whitelist')
    has_cycles = hasattr(atom1, 'cycles')
    compute_cycles = compute_cycles and not has_cycles

    if compute_cycles or not has_whitelists:
        for atom in topology.atoms():
            if compute_cycles:
                atom.cycles = set()
            if not has_whitelists:
                atom.whitelist = OrderedSet()
                atom.blacklist = OrderedSet()

    if compute_cycles:
        bond_graph = nx.Graph()
        bond_graph.add_nodes_from(topology.atoms())
        bond_graph.add_edges_from(topology.bonds())
        all_cycles = _find_chordless_cycles(bond_graph, max_cycle_size=8)
        for atom, cycles in zip(bond_graph.nodes, all_cycles):
            for cycle in cycles:
                atom.cycles.add(tuple(cycle))
293210
def select_molecules(name):
    ''''''
    mol_formula = current_system().get_derived_molecule_array('formula')
    mask = mol_formula == name
    ind = current_system().mol_to_atom_indices(mask.nonzero()[0])

    selection = {'atoms': Selection(ind, current_system().n_atoms)}

    # Need to find the bonds between the atoms
    b = current_system().bonds
    if len(b) == 0:
        selection['bonds'] = Selection([], 0)
    else:
        molbonds = np.zeros(len(b), 'bool')
        for i in ind:
            matching = (i == b).sum(axis=1).astype('bool')
            molbonds[matching] = True
        
        selection['bonds'] = Selection(molbonds.nonzero()[0], len(b))

    return select_selection(selection)
513361
def show_sbridges(self):
        """"""
        for i, saltb in enumerate(self.plcomplex.saltbridges):
            if saltb.protispos:
                for patom in saltb.positive_atoms:
                    cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (patom, self.protname))
                for latom in saltb.negative_atoms:
                    cmd.select('NegCharge-L', 'NegCharge-L or (id %i & %s)' % (latom, self.ligname))
                for sbgroup in [['ps-sbl-1-%i' % i, 'Chargecenter-P', saltb.positive_center],
                                ['ps-sbl-2-%i' % i, 'Chargecenter-L', saltb.negative_center]]:
                    cmd.pseudoatom(sbgroup[0], pos=sbgroup[2])
                    cmd.pseudoatom(sbgroup[1], pos=sbgroup[2])
                cmd.distance('Saltbridges', 'ps-sbl-1-%i' % i, 'ps-sbl-2-%i' % i)
            else:
                for patom in saltb.negative_atoms:
                    cmd.select('NegCharge-P', 'NegCharge-P or (id %i & %s)' % (patom, self.protname))
                for latom in saltb.positive_atoms:
                    cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (latom, self.ligname))
                for sbgroup in [['ps-sbp-1-%i' % i, 'Chargecenter-P', saltb.negative_center],
                                ['ps-sbp-2-%i' % i, 'Chargecenter-L', saltb.positive_center]]:
                    cmd.pseudoatom(sbgroup[0], pos=sbgroup[2])
                    cmd.pseudoatom(sbgroup[1], pos=sbgroup[2])
                cmd.distance('Saltbridges', 'ps-sbp-1-%i' % i, 'ps-sbp-2-%i' % i)

        if self.object_exists('Saltbridges'):
            cmd.set('dash_color', 'yellow', 'Saltbridges')
            cmd.set('dash_gap', 0.5, 'Saltbridges')
816307
def _get_facet_chempots(self, facet):
        
        complist = [self.qhull_entries[i].composition for i in facet]
        energylist = [self.qhull_entries[i].energy_per_atom for i in facet]
        m = [[c.get_atomic_fraction(e) for e in self.elements] for c in
             complist]
        chempots = np.linalg.solve(m, energylist)
        return dict(zip(self.elements, chempots))
684844
def all_energies(self):
        
        all_energies = []
        for i in range(len(self.electronic_steps)):
            energies = [step["E"] for step in self.electronic_steps[i]]
            energies.append(self.ionic_steps[i]["F"])
            all_energies.append(tuple(energies))
        return tuple(all_energies)
365301
def get_atomic_stoichiometry(references):
    
    n = len(references)
    stoichiometry = np.ndarray((n, n), float)
    stoichiometry[:] = 0.
    key_index = {}
    for i, (key, species) in enumerate(references):
        # in case species uses a suffix like _gas
        species = species.split('_')[0]
        key_index[key] = i

    for i, (key, species) in enumerate(references):
        composition = ase.symbols.string2symbols(species)
        for j, symbol in enumerate(composition):
            stoichiometry[i, key_index[symbol]] += 1
    istoichiometry = np.linalg.inv(stoichiometry)

    return istoichiometry.tolist()
1038882
def check_residues(self):
        ''''''
        for chain, residue_ids in self.residues.iteritems():
            for residue_id, residue in residue_ids.iteritems():
                for record_type, atoms in residue.records.iteritems():
                    freq = {}
                    for atom in atoms:
                        rec_id = atom.name + atom.conformation
                        freq[rec_id] = freq.get(rec_id, 0)
                        freq[rec_id] += 1
                    for atom_type, count in freq.items():
                        if count > 1:
                            raise Exception('{0} occurrences of atom type {1} for record type {2} occur in residue {3} in chain {4}.'.format(count, atom_type, record_type, residue_id.strip(), chain))
333700
private void calculateHBonds() {
		/**
		 * More efficient method for calculating C-Alpha pairs
		 */
		if (groups.length < 5) return;
		Iterator<AtomContact> otu = contactSet.iterator();
		while(otu.hasNext()){
			AtomContact ac = otu.next();
			Pair<Atom> pair = ac.getPair();
			Group g1 = pair.getFirst().getGroup();
			Group g2 = pair.getSecond().getGroup();
			// Now I need to get the index of the Group in the list groups
			int i = indResMap.get(g1.getResidueNumber());
			int j = indResMap.get(g2.getResidueNumber());
			// Now check this
			checkAddHBond(i,j);
			//"backwards" hbonds are not allowed
			if (j!=(i+1)) checkAddHBond(j,i);
		}
	}
141318
def get_bonds(input_group):
    """"""
    out_list = []
    for i in range(len(input_group.bond_order_list)):
        out_list.append((input_group.bond_atom_list[i * 2], input_group.bond_atom_list[i * 2 + 1],))
    return out_list
1268436
def get_electron_number(self, charge=0):
        
        atomic_number = constants.elements['atomic_number'].to_dict()
        return sum([atomic_number[atom] for atom in self['atom']]) - charge
1362473
def _get_elements(mol, label):
        
        elements = [int(mol.GetAtom(i).GetAtomicNum()) for i in label]
        return elements