Finds all the atomic formulas
542239
def find_atomics(formula: Formula) -> Set[PLAtomic]:
    """"""
    f = formula
    res = set()
    if isinstance(formula, PLFormula):
        res = formula.find_atomics()
    # elif isinstance(f, PLNot):
    #     res = res.union(find_atomics(f.f))
    # elif isinstance(f, PLBinaryOperator):
    #     for subf in f.formulas:
    #         res = res.union(find_atomics(subf))
    else:
        res.add(f)
    return res
54809
def read_atoms(fn, cycfn=None, pos_only=False, conv=1.0):
    
    f = paropen(fn, "r")

    l = f.readline().lstrip()
    while len(l) > 0 and ( l[0] == '#' or l[0] == '<' ):
        l = f.readline().lstrip()

    n_atoms = int(l)

    l = f.readline().lstrip()
    while len(l) > 0 and ( l[0] == '#' or l[0] == '<' ):
        l = f.readline().lstrip()

    l = f.readline().lstrip()
    while len(l) > 0 and ( l[0] == '#' or l[0] == '<' ):
        l = f.readline().lstrip()

    #
    # Read positions
    #

    forces = np.zeros( [ n_atoms, 3 ] )
    groups = np.zeros( [ n_atoms ] )
    gamma  = np.zeros( [ n_atoms ] )
    T      = np.zeros( [ n_atoms ] )

    ats = [ ]
    for i in range(n_atoms):
        s = l.split()
        #      type   x            y            z
        sym = None
        try:
            Z    = int(s[0])
            sym  = ase.data.chemical_symbols[Z]
        except:
            sym  = s[0]
        a = ase.Atom(sym, ( float(s[2])*conv, float(s[3])*conv, float(s[4])*conv ) )
        groups[i] = int(s[5])
        gamma[i]  = float(s[6])
        T[i]      = float(s[7])

        ats += [ a ]
        l = f.readline()
    this = ase.Atoms(ats, pbc=True)

    if not pos_only:
        while l and l == "":
            l = f.readline().strip()

        while l:
            key = l.strip(" <-#\r\n")

            if key.upper() == "VELOCITIES":
                for i in range(n_atoms):
                    s = f.readline().split()
                    m = this[i].mass
                    if m is None:
                        m = ase.data.atomic_masses[ase.data.chemical_symbols.index(this[i].symbol)]
                    this[i].momentum = ( m*float(s[0]), m*float(s[1]), m*float(s[2]) )

                l = None

            elif key.upper() == "FORCES":
                for i in range(n_atoms):
                    s = f.readline().split()
                    forces[i] =  np.array( [ float(s[0]), float(s[1]), float(s[2]) ] )

                l = None

            elif key.upper() == "CHARGES":
                for i in this:
                    l = f.readline()
                    if l and len(l.split()) == 1:
                        i.charge = float(l)

                l = None

            elif key.upper() == "CELL" or key.upper().split()[0:2] == ("BOX", "VECTORS" ):
                l1 = f.readline()
                l2 = f.readline()
                l3 = f.readline()

                this.set_cell( [ [float(x) for x in l1.split()],
                                 [float(x) for x in l2.split()],
                                 [float(x) for x in l3.split()] ] )

                l = None

            else:
                aux = [ ]
                l = f.readline().strip()
                while l and l[0] not in [ '<', '#' ]:
                    s = l.split()

                    aux += [ [float(x) for x in s] ]

                    l = f.readline().strip()

                if len(aux) == n_atoms:
                    this.set_array(key, np.asarray(aux))
                else:
                    print("Warning: Encountered field '%s' which does not seem to be per-atom data." % key)

            if l is None:
                l = f.readline().strip()
            while l and l == "":
                l = f.readline().strip()


    f.close()

    this.set_array("forces", forces)
    this.set_array("groups", groups)
    this.set_array("gamma", gamma)
    this.set_array("T", T)

    if cycfn:
        read_cyc(this, cycfn, conv=conv)

    return this
956897
def chemical_formula(self):
        """"""
        counts = {}
        for number in self.numbers:
            counts[number] = counts.get(number, 0)+1
        items = []
        for number, count in sorted(counts.items(), reverse=True):
            if count == 1:
                items.append(periodic[number].symbol)
            else:
                items.append("%s%i" % (periodic[number].symbol, count))
        return "".join(items)
70614
def invariants(mol):
    """"""
    atom_ids = {}
    for a in mol.atoms:
        components = []
        components.append(a.number)
        components.append(len(a.oatoms))
        components.append(a.hcount)
        components.append(a.charge)
        components.append(a.mass)
        if len(a.rings) > 0:
            components.append(1)

        atom_ids[a.index] = gen_hash(components)

    return atom_ids
1096072
def formulas_iter(self):
        
        for var in it.ifilter(self.has_node, self.variables()):
            yield var, frozenset(self.predecessors(var))
737546
private List<Integer[]> getAtomNoPairsForRingGroup(IAtomContainer molecule, List<Integer> bondsToCheck) {
        List<Integer[]> aptc = new ArrayList<Integer[]>();
        for (Integer i : bondsToCheck) {
            Integer[] aps = new Integer[2];
            aps[0] = molecule.indexOf(molecule.getBond(i).getBegin());
            aps[1] = molecule.indexOf(molecule.getBond(i).getEnd());
            aptc.add(aps);
        }
        return aptc;
    }
690283
def __get_formulas(self):
        
        array = self._get_target().getFormulaArray()
        return tuple(itertools.chain.from_iterable(array))
929538
def _get_atomsection(mol2_lst):
        """"""
        started = False
        for idx, s in enumerate(mol2_lst):
            if s.startswith('@<TRIPOS>ATOM'):
                first_idx = idx + 1
                started = True
            elif started and s.startswith('@<TRIPOS>'):
                last_idx_plus1 = idx
                break
        return mol2_lst[first_idx:last_idx_plus1]
881780
def all_formula_values(precision = 14)
      formulas = []
      worksheets.each do |c_sheet|
        next unless c_sheet

        c_sheet.rows.each do |c_row|
          next unless c_row

          c_row.cells.each do |c_cell|
            next unless c_cell
            next unless c_cell.formula
            next if c_cell.formula.empty?

            text = c_cell.raw_text
            if StringHelper.numeric?(text)
              text = text.to_f.round(10).to_s[0..precision]
            elsif StringHelper.complex?(text)
              complex_number = Complex(text.tr(',', '.'))
              real_part = complex_number.real
              real_rounded = real_part.to_f.round(10).to_s[0..precision].to_f

              imag_part = complex_number.imag
              imag_rounded = imag_part.to_f.round(10).to_s[0..precision].to_f
              complex_rounded = Complex(real_rounded, imag_rounded)
              text = complex_rounded.to_s
            end
            formulas << text
          end
        end
      end
      formulas
    end
641057
def get_element_dos(self):
        

        el_dos = {}
        for site, atom_dos in self.pdos.items():
            el = site.specie
            if el not in el_dos:
                el_dos[el] = np.array(atom_dos)
            else:
                el_dos[el] += np.array(atom_dos)
        return {el: PhononDos(self.frequencies, densities)
                for el, densities in el_dos.items()}
860696
@Override
    public int getConnectedAtomsCount(IAtom atom) {
        int count = 0;
        for (int i = 0; i < bondCount; i++) {
            if (bonds[i].contains(atom)) ++count;
        }
        return count;
    }
859645
@Override
    public IRingSet getRings(IAtom atom) {
        IRingSet rings = new RingSet();
        IRing ring;
        for (int i = 0; i < getAtomContainerCount(); i++) {
            ring = (Ring) getAtomContainer(i);
            if (ring.contains(atom)) {
                rings.addAtomContainer(ring);
            }
        }
        return rings;
    }
288926
private static String calculateMolecularFormula(List<AbstractMolecule> molecules) throws BuilderMoleculeException, CTKException, ChemistryException {
    Map<String, Integer> atomNumberMap = new TreeMap<String, Integer>();
    for (AbstractMolecule molecule : molecules) {
      LOG.info(molecule.getMolecule().toString());
      atomNumberMap = generateAtomNumberMap(molecule, atomNumberMap);
    }
    LOG.info("GET map");
    StringBuilder sb = new StringBuilder();
    Set<String> atoms = atomNumberMap.keySet();
    for (Iterator<String> i = atoms.iterator(); i.hasNext();) {
      String atom = i.next();
      String num = atomNumberMap.get(atom).toString();
      if (num.equals("1")) {
        num = "";
      }
      sb.append(atom);
      sb.append(num.toString());
    }
    return sb.toString();
  }
322141
private IAtomContainer getUnplacedAtoms(IAtom atom) {
        IAtomContainer unplacedAtoms = atom.getBuilder().newInstance(IAtomContainer.class);
        List bonds = molecule.getConnectedBondsList(atom);
        IAtom connectedAtom;
        for (int f = 0; f < bonds.size(); f++) {
            connectedAtom = ((IBond) bonds.get(f)).getOther(atom);
            if (!connectedAtom.getFlag(CDKConstants.ISPLACED)) {
                unplacedAtoms.addAtom(connectedAtom);
            }
        }
        return unplacedAtoms;
    }
824784
def stoichiometry( self ):
        
        return Counter( { label: number for label, number in zip( self.atoms, self.atom_numbers ) } )
51727
private static Atom[] getAtoms(Atom[] ca, int[] positions, int length,
			boolean clone) {

		List<Atom> atoms = new ArrayList<Atom>();
		for (int i = 0; i < length; i++) {
			int p = positions[i];
			Atom a;
			if (clone) {
				a = (Atom) ca[p].clone();
				a.setGroup((Group) ca[p].getGroup().clone());
			} else {
				a = ca[p];
			}
			atoms.add(a);
		}
		return atoms.toArray(new Atom[atoms.size()]);
	}
934394
def atoms_order(self):
        
        if not len(self):  # for empty containers
            return {}
        elif len(self) == 1:  # optimize single atom containers
            return dict.fromkeys(self, 2)

        params = {n: (int(node), tuple(sorted(int(edge) for edge in self._adj[n].values())))
                  for n, node in self.atoms()}
        newlevels = {}
        countprime = iter(primes)
        weights = {x: newlevels.get(y) or newlevels.setdefault(y, next(countprime))
                   for x, y in sorted(params.items(), key=itemgetter(1))}

        tries = len(self) * 4

        numb = len(set(weights.values()))
        stab = 0

        while tries:
            oldnumb = numb
            neweights = {}
            countprime = iter(primes)

            # weights[n] ** 2 NEED for differentiation of molecules like A-B or any other complete graphs.
            tmp = {n: reduce(mul, (weights[x] for x in m), weights[n] ** 2) for n, m in self._adj.items()}

            weights = {x: (neweights.get(y) or neweights.setdefault(y, next(countprime)))
                       for x, y in sorted(tmp.items(), key=itemgetter(1))}

            numb = len(set(weights.values()))
            if numb == len(self):  # each atom now unique
                break
            elif numb == oldnumb:
                x = Counter(weights.values())
                if x[min(x)] > 1:
                    if stab == 3:
                        break
                elif stab >= 2:
                    break

                stab += 1
            elif stab:
                stab = 0

            tries -= 1
            if not tries and numb < oldnumb:
                warning('morgan. number of attempts exceeded. uniqueness has decreased. next attempt will be made')
                tries = 1
        else:
            warning('morgan. number of attempts exceeded')

        return weights