def nested_formula_parser(formula, check=True):
formula = formula.replace('<STR_LIT:[>', '<STR_LIT>').replace('<STR_LIT:]>', '<STR_LIT>')<EOL>charge_splits = bracketed_charge_re.split(formula)<EOL>if len(charge_splits) > <NUM_LIT:1>:<EOL><INDENT>formula = charge_splits[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>formula = formula.split('<STR_LIT:+>')[<NUM_LIT:0>].split('<STR_LIT:->')[<NUM_LIT:0>]<EOL><DEDENT>stack = [[]]<EOL>last = stack[<NUM_LIT:0>]<EOL>tokens = formula_token_matcher_rational.findall(formula)<EOL>if check:<EOL><INDENT>token_letters = set([j for i in tokens for j in i if j in letter_set])<EOL>formula_letters = set(i for i in formula if i in letter_set)<EOL>if formula_letters != token_letters:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT><DEDENT>for token in tokens:<EOL><INDENT>if token == "<STR_LIT:(>":<EOL><INDENT>stack.append([])<EOL>last = stack[-<NUM_LIT:1>]<EOL><DEDENT>elif token == "<STR_LIT:)>":<EOL><INDENT>temp_dict = {}<EOL>for d in last:<EOL><INDENT>for ele, count in d.items():<EOL><INDENT>if ele in temp_dict:<EOL><INDENT>temp_dict[ele] = temp_dict[ele] + count<EOL><DEDENT>else:<EOL><INDENT>temp_dict[ele] = count<EOL><DEDENT><DEDENT><DEDENT>stack.pop()<EOL>last = stack[-<NUM_LIT:1>]<EOL>last.append(temp_dict)<EOL><DEDENT>elif token.isalpha():<EOL><INDENT>last.append({token: <NUM_LIT:1>})<EOL><DEDENT>else:<EOL><INDENT>v = float(token)<EOL>v_int = int(v)<EOL>if v_int == v:<EOL><INDENT>v = v_int<EOL><DEDENT>last[-<NUM_LIT:1>] = {ele: count*v for ele, count in last[-<NUM_LIT:1>].items()}<EOL><DEDENT><DEDENT>ans = {}<EOL>for d in last:<EOL><INDENT>for ele, count in d.items():<EOL><INDENT>if ele in ans:<EOL><INDENT>ans[ele] = ans[ele] + count<EOL><DEDENT>else:<EOL><INDENT>ans[ele] = count<EOL><DEDENT><DEDENT><DEDENT>return ans<EOL>
r'''Improved formula parser which handles braces and their multipliers, 
    as well as rational element counts.

    Strips charges from the end of a formula first. Accepts repeated chemical
    units. Performs no sanity checking that elements are actually elements.
    As it uses regular expressions for matching, errors are mostly just ignored.

    Parameters
    ----------
    formula : str
        Formula string, very simply formats only.
    check : bool
        If `check` is True, a simple check will be performed to determine if
        a formula is not a formula and an exception will be raised if it is
        not, [-]

    Returns
    -------
    atoms : dict
        dictionary of counts of individual atoms, indexed by symbol with
        proper capitalization, [-]

    Notes
    -----
    Inspired by the approach taken by CrazyMerlyn on a reddit DailyProgrammer
    challenge, at https://www.reddit.com/r/dailyprogrammer/comments/6eerfk/20170531_challenge_317_intermediate_counting/

    Examples
    --------
    >>> pprint(nested_formula_parser('Pd(NH3)4.0001+2'))
    {'H': 12.0003, 'N': 4.0001, 'Pd': 1}