@@ -0,0 +1,2518 @@
+%22%22%22%0A%0AParse strings of math into symbols.%0A%0ACopyright 2012, Casey W. Stark.%0A%0A%22%22%22%0A%0Adef get_unit_from_symbol(symbol):%0A    %22%22%22%0A    Parses a unit symbol for the dimensionality and conversion factor.%0A%0A    Parameters%0A    ----------%0A    symbol : string%0A        The unit symbol. Expected syntax is unit symbols taken to powers with%0A        %22%5E%22, separated by spaces. Examples are %22cm%5E3%22 or %22K g%5E-1%22.%0A%0A    Returns%0A    -------%0A    unit : tuple%0A        Tuple of the powers array and the conversion factor. Syntax above.%0A%0A    Examples%0A    --------%0A    %3E%3E%3E get_unit_from_symbol(%22K g%5E-1%22)%0A    (array(%5B-1, 0, 0, 1%5D), 1)%0A%0A    %3E%3E%3E get_unit_from_symbol(%22Msun Mpc%5E-3%22)%0A    (array(%5B1, -3, 0, 0%5D), 6.769494e-41)%0A%0A    %22%22%22%0A    # @todo: allow other math syntax%0A    # @todo: use regex instead of stupid parsing%0A    dimensions = np.zeros(num_base)%0A    conversion_factor = 1.0%0A%0A    symbol_string_split = symbol.split(%22 %22)%0A    for symbol_element in symbol_string_split:%0A        # split the element into unit symbol and power%0A        element_split = symbol_element.split(%22%5E%22)%0A        element_symbol = element_split%5B0%5D%0A        element_power = 1%0A        if len(element_split) == 2:  # might not have a power%0A            element_power = float(element_split%5B1%5D)%0A%0A        # get the unit's dimensions and prefix if given%0A        unit_prefix = 1%0A        if unit_symbols_dict.has_key(element_symbol):%0A            symbol_tuple = unit_symbols_dict%5Belement_symbol%5D%0A        else:%0A            possible_prefix = element_symbol%5B0%5D%0A            if unit_prefixes.has_key(possible_prefix):%0A                # the first character might be a prefix, check the rest of the%0A                # symbol%0A                symbol_wo_prefix = element_symbol%5B1:%5D%0A%0A                if unit_symbols_dict.has_key(symbol_wo_prefix):%0A                    symbol_tuple = unit_symbols_dict%5Bsymbol_wo_prefix%5D%0A                    unit_prefix = unit_prefixes%5Bpossible_prefix%5D%0A                else:%0A                    raise Exception(%22Unknown symbol: %25s.%22 %25 element_symbol)%0A            else:%0A                raise Exception(%22Unknown symbol: %25s.%22 %25 element_symbol)%0A%0A        element_dimensions = symbol_tuple%5B0%5D*element_power%0A        element_conversion = (unit_prefix * symbol_tuple%5B1%5D)**element_power%0A%0A        # @todo: make conversion a warning?%0A        #if symbol_tuple%5B1%5D != 1.0:%0A        #    print %22Conversion: %25s is %25e%22 %25 (symbol_element, element_conversion)%0A%0A        dimensions += element_dimensions%0A        conversion_factor *= element_conversion%0A%0A    return (dimensions, conversion_factor)%0A

Move parsing function in units to a new module.