B
    Afxa8                 @   s  U d Z ddlZddlmZmZ ddlmZmZ ddlm	Z	 e
dZdd	 Zd
Zdd Zddddddedddddddddddddddddddddd d!ddddd"dd#ddd$Zeeef ed%< i Zeeef ed&< d'd( Zed)d*d+ Zed,d-d. Zed/d0d1 Zed2d3d4 Zed5d6d7 Zed8d9d: Zdddd d!d;d<d= dd>d?dfd@dAZedBZdCdD ZdZdEdFZdGdH Z dIdJ Z!dKdL Z"dMd= fdNdOZ#dPd= fdQdRZ$dSd= dTfdUdVZ%dWd= dTfdXdYZ&dS )[z
    pint.formatter
    ~~~~~~~~~~~~~~

    Format units for pint.

    :copyright: 2016 by Pint Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
    N)CallableDict   )_babel_lengths_babel_units)babel_parsez{\d*}c             C   sN   |sdS t | s| |S t|}t|}x|D ]}| ||}|}q2W |S )a1  Join an iterable with the format specified in fmt.

    The format can be specified in two ways:
    - PEP3101 format with two replacement fields (eg. '{} * {}')
    - The concatenating string (eg. ' * ')

    Parameters
    ----------
    fmt : str

    iterable :


    Returns
    -------
    str

     )__JOIN_REG_EXPsearchjoiniternextformat)fmtiterableZmiterfirstvalret r   .lib/python3.7/site-packages/pint/formatting.py_join   s    


r   u   ⁰¹²³⁴⁵⁶⁷⁸⁹c             C   sB   | d dd dd}x$tdD ]}| t|t| }q"W |S )zFormat an number into a pretty printed exponent.

    Parameters
    ----------
    num : int

    Returns
    -------
    str

    n-u   ⁻.u   ⋅
   )replacerangestr_PRETTY_EXPONENTS)Znumr   r   r   r   r   _pretty_fmt_exponent6   s    r   TF   ·/z{}{}z({}))as_ratiosingle_denominatorproduct_fmtdivision_fmt	power_fmtparentheses_fmtexp_callz \cdot z\frac[{}][{}]z{}^[{}]z\left({}\right))r"   r#   r$   r%   r&   r'   r   z +- )ZsioptsZpm_fmt z{}/{}z{}<sup>{}</sup>z * z / z{} ** {}*z{}**{})PLLxHr   C_FORMATS_FORMATTERSc                s    fdd}|S )a  register a function as a new format for units

    The registered function must have a signature of:

    .. code:: python

        def new_format(unit, registry, **options):
            pass

    Parameters
    ----------
    name : str
        The name of the new format (to be used in the format mini-language). A error is
        raised if the new format would overwrite a existing format.

    Examples
    --------
    .. code:: python

        @pint.register_unit_format("custom")
        def format_custom(unit, registry, **options):
            result = "<formatted unit>"  # do the formatting
            return result


        ureg = pint.UnitRegistry()
        u = ureg.m / ureg.s ** 2
        f"{u:custom}"
    c                s&    t krtd dd| t  < d S )Nzformat z!rz already exists)r1   
ValueError)func)namer   r   wrapper   s    z%register_unit_format.<locals>.wrapperr   )r4   r5   r   )r4   r   register_unit_format|   s    r6   r+   c          
   K   s$   t |  fddddddtd|S )NTFr    r!   z{}{}z({}))r"   r#   r$   r%   r&   r'   r(   )	formatteritemsr   )unitregistryoptionsr   r   r   format_pretty   s    r<   r,   c          	   K   sH   dd |   D }t|  fddddddd|}|d	d
ddS )Nc          	   S   s$   i | ]\}}|d  |ddqS )z\mathrm{{{}}}_z\_)r   r   ).0upr   r   r   
<dictcomp>   s   z format_latex.<locals>.<dictcomp>Tz \cdot z\frac[{}][{}]z{}^[{}]z\left({}\right))r"   r#   r$   r%   r&   r'   [{]})r8   r7   r   )r9   r:   r;   Zpreprocessed	formattedr   r   r   format_latex   s    rG   r-   c             K   s&   |d krt dt| |}d| dS )NzCan't format as siunitx without a registry. This is usually triggered when formatting a instance of the internal `UnitsContainer` with a spec of `"Lx"` and might indicate a bug in `pint`.z\si[]{rE   )r2   siunitx_format_unit)r9   r:   r;   rF   r   r   r   format_latex_siunitx   s
    
rI   r.   c          	   K   s"   t |  fddddddd|S )NTr)   z{}/{}z{}<sup>{}</sup>z({}))r"   r#   r$   r%   r&   r'   )r7   r8   )r9   r:   r;   r   r   r   format_html   s    rJ   Dc          	   K   s"   t |  fddddddd|S )NTFz * z / z{} ** {}z({}))r"   r#   r$   r%   r&   r'   )r7   r8   )r9   r:   r;   r   r   r   format_default   s    rL   r/   c          	   K   s"   t |  fddddddd|S )NTFr*   r!   z{}**{}z({}))r"   r#   r$   r%   r&   r'   )r7   r8   )r9   r:   r;   r   r   r   format_compact   s    rM   z({0})c             C   s   | dS )Nr   r   )xr   r   r   <lambda>      rO   Zlongonec                s   | sdS |rfdd}n}g g  }}|r4t | } xX| D ]N\}}|r" r"|
r"|tkr"t| }t|}|jd }|jd }t|dkrdn|
} tkr fdd	ttD }ng }xF g| D ]8}||i |i |}|d
k	r|dd	 }P qW |di  |}d}t
|dkr8|| q<|dkrZ||||| q<|dkrv|rv|| q<||||| q<W |st||| S t||pd}|s|S |rt||}t|dkr||}n
t||}t|||gS )a  Format a list of (name, exponent) pairs.

    Parameters
    ----------
    items : list
        a list of (name, exponent) pairs.
    as_ratio : bool, optional
        True to display as ratio, False as negative powers. (Default value = True)
    single_denominator : bool, optional
        all with terms with negative exponents are
        collected together. (Default value = False)
    product_fmt : str
        the format used for multiplication. (Default value = " * ")
    division_fmt : str
        the format used for division. (Default value = " / ")
    power_fmt : str
        the format used for exponentiation. (Default value = "{} ** {}")
    parentheses_fmt : str
        the format used for parenthesis. (Default value = "({0})")
    locale : str
        the locale object as defined in babel. (Default value = None)
    babel_length : str
        the length of the translated unit, as defined in babel cldr. (Default value = "long")
    babel_plural_form : str
        the plural form, calculated as defined in babel. (Default value = "one")
    exp_call : callable
         (Default value = lambda x: f"{x:n}")
    sort : bool, optional
        True to sort the formatted units alphabetically (Default value = True)

    Returns
    -------
    str
        the formula as a string.

    r   c                s    t | S )N)abs)rN   )r(   r   r   rO   3  rP   zformatter.<locals>.<lambda>unit_patternscompound_unit_patternsr   rQ   c                s   g | ]} |kr|qS r   r   )r>   _babel_length)babel_lengthr   r   
<listcomp>D  s   zformatter.<locals>.<listcomp>Nz{0}Zperz{}{}r   1)sortedr   r   _datarR   r   reversedgetr   stripr   appendr   r   len)r8   r"   r#   r$   r%   r&   r'   r(   localerV   Zbabel_plural_formsortZfunZ	pos_termsZ	neg_termskeyvalueZ_keyrS   rT   pluralZother_lengthsrU   ZpatZpos_retZneg_retr   )rV   r(   r   r7      s\    3







r7   zbcdeEfFgGnosxX%uSc             C   sp   d}xft | D ]Z}|dks|tkr&qq|tt dg krP|rJtdqh|}q| rftd| qP qW |S )Nr   ~z#expected ':' after format specifierzUnknown conversion specified )r\   _BASIC_TYPESlistr1   keysr2   isalpha)specresultZchr   r   r   _parse_specx  s    
rm   c             K   sR   | s| drdS dS |sd}t|}|d kr>td| || fd|i|S )N%r   ZdimensionlessrK   zUnknown conversion specified: r:   )endswithr1   r]   r2   )r9   rk   r:   r;   r   r   r   r   format_unit  s    

rp   c       
      C   s   dd }g }g }xt |  D ]\}}|dkr2|n|}d}xF|j D ]8}	t|	}	t|	dkrF||	dkrF|	}||dd}qFW |dk r|d |dk	r|d	| |d	| |d		|t
| qW d|d| S )
zHReturns LaTeX code for the unit that can be put into an siunitx command.c             S   sd   t | tst | trP|  rP| dkr(dS | dkr4dS | dkr@dS dt| S nd| d	S d S )
Nr   r      z\squared   z\cubedz\tothe{{{:d}}}z\tothe{{{:.3f}}}0)
isinstanceintfloat
is_integerr   rstrip)powerr   r   r   _tothe  s    z#siunitx_format_unit.<locals>._tother   Nr   r   z\perz\{}z{})rZ   r8   Z	_prefixesvaluesr   r`   findr   r_   r   rR   r   )
Zunitsr:   rz   lposZlnegr9   ry   Zlpickprefixr@   r   r   r   rH     s$    
rH   c             C   sB   dd l }|ddtt dg  d }|| }d|S )Nr   (|rf   )r   )recompiler   rh   r1   ri   findall)rk   r   Zflag_reZcustom_flagsr   r   r   extract_custom_flags  s    &
r   c             C   s0   x*t t dg D ]}|r| |d} qW | S )Nrf   r   )rh   r1   ri   r   )rk   flagr   r   r   remove_custom_flags  s    r   c             C   s
   t | dS )Nz.2f)r   )rN   r   r   r   rO     rP   c             C   s   t | g|S )N)matrix_to_latex)Zvecfmtfunr   r   r   vector_to_latex  s    r   c             C   s
   t | dS )Nz.2f)r   )rN   r   r   r   rO     rP   c                s>   g }x*| D ]"}|d  fdd|D g7 }q
W dd | S )Nz & c             3   s   | ]} |V  qd S )Nr   )r>   f)r   r   r   	<genexpr>  s    z"matrix_to_latex.<locals>.<genexpr>z\begin{pmatrix}%s\end{pmatrix}z\\ 
)r   )Zmatrixr   r   rowr   )r   r   r     s    
"r   c             C   s
   t | dS )Nz.2f)r   )rN   r   r   r   rO     rP   r   c                s   t |tr|  fdd}| jdkr:| d}t||gS | jdkrPt| |gS | jdkrft| |gS g }| jdkrddd	d
 |D  d }x^t| D ]$\}}||| d t|| g7 }qW n,x*t| D ]\}}|t||||f 7 }qW |S d S )Nc                s
   t |  S )N)r   )rN   )r   r   r   rO     rP   z(ndarray_to_latex_parts.<locals>.<lambda>r   r   rq   rr   zarr[%s,,c             s   s   | ]}d | V  qdS )z%dNr   )r>   dr   r   r   r     s    z)ndarray_to_latex_parts.<locals>.<genexpr>z%d,:,:]z = )	rt   r   ndimZreshaper   r   r   	enumeratendarray_to_latex_parts)ndarrr   dimZ_ndarrr   headerZelnoelr   )r   r   r     s$    





"r   c             C   s
   t | dS )Nz.2f)r   )rN   r   r   r   rO     rP   c             C   s   d t| ||S )N
)r   r   )r   r   r   r   r   r   ndarray_to_latex  s    r   )N)'__doc__r   typingr   r   Zbabel_namesr   r   compatr   r   r	   r   r   r   r0   r   dict__annotations__r1   r6   r<   rG   rI   rJ   rL   rM   r7   	frozensetrg   rm   rp   rH   r   r   r   r   r   r   r   r   r   r   <module>	   s   
'm
*		