a
    ضaL                     @   s*  d Z ddlmZ ddlZddlmZ ddlZddlZddlZ	ddl
mZ ddlmZmZmZmZmZ ddlmZmZ ddlmZ eeZejG d	d
 d
ZejZee_G dd dZG dd deZ ej!dddG dd de Z"ej!dddG dd deZ#ej!dddG dd deZ$ej!dddG dd deZ%G dd deZ&ej!dddG dd deZ'dgdd  ej() D d!d"d  ej*) D d#d$d  ej+) D d%d&D ]*Z,e!de-e,e.ee,fi e/ e,< qG d'd( d(e0Z1e!dd)d* Z2G d+d, d,Z3d/d-d.Z4dS )0a0  
A module for parsing a subset of the TeX math syntax and rendering it to a
Matplotlib backend.

For a tutorial of its usage, see :doc:`/tutorials/text/mathtext`.  This
document is primarily concerned with implementation details.

The module uses pyparsing_ to parse the TeX expression.

.. _pyparsing: https://pypi.org/project/pyparsing/

The Bakoma distribution of the TeX Computer Modern fonts, and STIX
fonts are supported.  There is experimental support for using
arbitrary fonts, but results may vary without proper tweaking and
metrics for those fonts.
    )
namedtupleN)StringIO)Image)_apicolorsrcParams	_mathtext_mathtext_data)FT2ImageLOAD_NO_HINTING)FontPropertiesc                   @   s6   e Zd Ze dd eg dfeg dffD  dS )__getattr__c              	   C   s8   i | ]0\}}|D ]"}|t d t||fddqqS )3.4c                 S   s
   t ||S N)getattr)selfZ_mod_name r   c/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/matplotlib/mathtext.py<lambda>'       z__getattr__.<dictcomp>.<lambda>)r   
deprecatedproperty).0modnamesnamer   r   r   
<dictcomp>%   s
   
z__getattr__.<dictcomp>)ZSHRINK_FACTORZGROW_FACTORZNUM_SIZE_LEVELS)Zlatex_to_bakomaZlatex_to_cmexZlatex_to_standardZstix_virtual_fontsZtex2uniN)__name__
__module____qualname__localsupdater   r	   r   r   r   r   r   #   s
   

r   c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )MathtextBackenda  
    The base class for the mathtext backend-specific code.  `MathtextBackend`
    subclasses interface between mathtext and specific Matplotlib graphics
    backends.

    Subclasses need to override the following:

    - :meth:`render_glyph`
    - :meth:`render_rect_filled`
    - :meth:`get_results`

    And optionally, if you need to use a FreeType hinting style:

    - :meth:`get_hinting_type`
    c                 C   s   d| _ d| _d| _d S Nr   widthheightdepthr   r   r   r   __init__D   s    zMathtextBackend.__init__c                 C   s   || _ || _|| _dS )z(Set the dimension of the drawing canvas.Nr%   r   whdr   r   r   set_canvas_sizeI   s    zMathtextBackend.set_canvas_sizec                 C   s
   t  dS )z_
        Draw a glyph described by *info* to the reference point (*ox*,
        *oy*).
        NNotImplementedErrorr   oxoyinfor   r   r   render_glyphO   s    zMathtextBackend.render_glyphc                 C   s
   t  dS )zR
        Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).
        Nr0   r   x1y1x2y2r   r   r   render_rect_filledV   s    z"MathtextBackend.render_rect_filledc                 C   s
   t  dS )zp
        Return a backend-specific tuple to return to the backend after
        all processing is done.
        Nr0   )r   boxr   r   r   get_results\   s    zMathtextBackend.get_resultsc                 C   s   t S )z\
        Get the FreeType hinting type to use with this particular
        backend.
        )r   r)   r   r   r   get_hinting_typec   s    z MathtextBackend.get_hinting_typeN)
r   r   r    __doc__r*   r/   r6   r<   r>   r?   r   r   r   r   r#   4   s   r#   c                       sT   e Zd ZdZ fddZdd Z fddZdd	 Zd
d Zdd Z	dd Z
  ZS )MathtextBackendAggz
    Render glyphs and rectangles to an FTImage buffer, which is later
    transferred to the Agg image by the Agg backend.
    c                    s0   d| _ d| _d | _d| _g d| _t   d S )Nr   bbox)r   r   r   r   )r3   r4   imagemoderB   superr*   r)   	__class__r   r   r*   p   s    
zMathtextBackendAgg.__init__c                 C   sB   t | jd |t | jd |t| jd |t| jd |g| _d S )Nr            )minrB   maxr7   r   r   r   _update_bboxx   s
    zMathtextBackendAgg._update_bboxc                    s@   t  ||| | jdkr<tt|t|t|d | _d S )NrB   r   )rE   r/   rD   r
   npceilrL   rC   r+   rF   r   r   r/   ~   s    
z"MathtextBackendAgg.set_canvas_sizec                 C   sf   | j dkr<| ||jj ||jj ||jj ||jj  n&|jj| j	|||jj
 |jtd d d S )NrB   ztext.antialiased)Zantialiased)rD   rM   metricsZxminZymaxZxmaxZyminfontZdraw_glyph_to_bitmaprC   ZicebergZglyphr   r2   r   r   r   r6      s    



zMathtextBackendAgg.render_glyphc                 C   s   | j dkr| |||| nhtt|| d d}|dkr\|| d }t||d d  }nt|}| jt||t|||  d S )NrB   rH   r   g       @)rD   rM   rL   intrC   Zdraw_rect_filledrN   rO   )r   r8   r9   r:   r;   r'   centeryr   r   r   r<      s    
z%MathtextBackendAgg.render_rect_filledc                 C   s   d| _ |j}|j}tdd| | j}|d d |d d |d d |d d g}d| _ | |d |d  |d |d  | |d |d  |  t|d  |d  | | j| j| j	| j| j | j| j
|f}d | _
|S )NrB   r   rH   rI   rJ   render)rD   r'   r(   r   shiprB   r/   r3   r4   r&   rC   )r   r=   used_charactersZorig_heightZ
orig_depthrB   resultr   r   r   r>      s.    ,
zMathtextBackendAgg.get_resultsc                 C   s   ddl m} | S )Nr   backend_agg)matplotlib.backendsrZ   Zget_hinting_flag)r   rZ   r   r   r   r?      s    z#MathtextBackendAgg.get_hinting_type)r   r   r    r@   r*   rM   r/   r6   r<   r>   r?   __classcell__r   r   rF   r   rA   k   s   rA   r   mathtext.math_to_imagealternativec                       s   e Zd Z fddZ  ZS )MathtextBackendBitmapc           
         s$   t  ||\}}}}}}}	||fS r   )rE   r>   )
r   r=   rW   r3   r4   r&   r'   r(   rC   
charactersrF   r   r   r>      s    z!MathtextBackendBitmap.get_results)r   r   r    r>   r\   r   r   rF   r   r`      s   r`   MathtextBackendPathc                       sB   e Zd ZdZeddZ fddZdd Zdd	 Zd
d Z	  Z
S )MathtextBackendPszT
    Store information to write a mathtext rendering to the PostScript backend.
    	_PSResultz+width height depth pswriter used_charactersc                    s   t    t | _d | _d S r   )rE   r*   r   pswriterlastfontr)   rF   r   r   r*      s    
zMathtextBackendPs.__init__c                 C   sv   | j | |j }|j}|j}||f| jkrN||f| _| jd| d| d | j|dd|dd|j d d S )N/z
 findfont
z scalefont
setfont
f z	 moveto
/z glyphshow
)r'   offsetpostscript_namefontsizerf   re   writesymbol_name)r   r3   r4   r5   rk   rl   r   r   r   r6      s    
zMathtextBackendPs.render_glyphc                 C   s.   d|| j | || || f }| j| d S )Nz%f %f %f %f rectfill
)r'   re   rm   )r   r8   r9   r:   r;   psr   r   r   r<      s    z$MathtextBackendPs.render_rect_filledc                 C   s.   t dd| | | j| j| j | j| j|S r$   )r   rV   rd   r&   r'   r(   re   r   r=   rW   r   r   r   r>      s    
zMathtextBackendPs.get_results)r   r   r    r@   r   rd   r*   r6   r<   r>   r\   r   r   rF   r   rc      s   rc   c                       sB   e Zd ZdZeddZ fddZdd Zdd	 Zd
d Z	  Z
S )MathtextBackendPdfzCStore information to write a mathtext rendering to the PDF backend.
_PDFResultz/width height depth glyphs rects used_charactersc                    s   t    g | _g | _d S r   rE   r*   glyphsrectsr)   rF   r   r   r*      s    
zMathtextBackendPdf.__init__c                 C   s:   |j j}| j| |j }| j||||j|j|jf d S r   )	rQ   fnamer'   rj   rt   appendrl   numrn   )r   r3   r4   r5   filenamer   r   r   r6      s    
zMathtextBackendPdf.render_glyphc                 C   s&   | j || j| || || f d S r   ru   rw   r'   r7   r   r   r   r<      s    z%MathtextBackendPdf.render_rect_filledc                 C   s2   t dd| | | j| j| j | j| j| j|S r$   )r   rV   rr   r&   r'   r(   rt   ru   rp   r   r   r   r>      s    
zMathtextBackendPdf.get_results)r   r   r    r@   r   rr   r*   r6   r<   r>   r\   r   r   rF   r   rq      s   rq   c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
MathtextBackendSvgzQ
    Store information to write a mathtext rendering to the SVG
    backend.
    c                    s   t    g | _g | _d S r   )rE   r*   
svg_glyphs	svg_rectsr)   rF   r   r   r*     s    
zMathtextBackendSvg.__init__c                 C   s4   | j | |j }| j|j|j|j|||jf d S r   )r'   rj   r|   rw   rQ   rl   rx   rP   r2   r   r   r   r6     s    zMathtextBackendSvg.render_glyphc                 C   s*   | j || j| d || || f d S )NrH   )r}   rw   r'   r7   r   r   r   r<     s    z%MathtextBackendSvg.render_rect_filledc                 C   s:   t dd| tj| j| jd}| j| j| j | j||fS )Nr   )r|   r}   )	r   rV   typesSimpleNamespacer|   r}   r&   r'   r(   )r   r=   rW   Zsvg_elementsr   r   r   r>     s    
zMathtextBackendSvg.get_results	r   r   r    r@   r*   r6   r<   r>   r\   r   r   rF   r   r{   
  s
   r{   c                       sB   e Zd ZdZeddZ fddZdd Zdd	 Zd
d Z	  Z
S )rb   zY
    Store information to write a mathtext rendering to the text path
    machinery.
    _Resultzwidth height depth glyphs rectsc                    s   t    g | _g | _d S r   rs   r)   rF   r   r   r*   2  s    
zMathtextBackendPath.__init__c                 C   s0   | j | |j }| j|j|j|j||f d S r   )r'   rj   rt   rw   rQ   rl   rx   r2   r   r   r   r6   7  s    z MathtextBackendPath.render_glyphc                 C   s&   | j || j| || || f d S r   rz   r7   r   r   r   r<   ;  s    z&MathtextBackendPath.render_rect_filledc                 C   s0   t dd| | | j| j| j | j| j| jS r$   )r   rV   r   r&   r'   r(   rt   ru   rp   r   r   r   r>   >  s    
zMathtextBackendPath.get_results)r   r   r    r@   r   r   r*   r6   r<   r>   r\   r   r   rF   r   rb   *  s   
c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
MathtextBackendCairozS
    Store information to write a mathtext rendering to the Cairo
    backend.
    c                    s   t    g | _g | _d S r   rs   r)   rF   r   r   r*   N  s    
zMathtextBackendCairo.__init__c                 C   s8   ||j  | j }t|j}| j|j|j|||f d S r   )rj   r'   chrrx   rt   rw   rQ   rl   )r   r3   r4   r5   Zthetextr   r   r   r6   S  s
    
z!MathtextBackendCairo.render_glyphc                 C   s&   | j ||| j || || f d S r   rz   r7   r   r   r   r<   Y  s    z'MathtextBackendCairo.render_rect_filledc                 C   s,   t dd| | j| j| j | j| j| jfS r$   )r   rV   r&   r'   r(   rt   ru   rp   r   r   r   r>   ]  s    
z MathtextBackendCairo.get_resultsr   r   r   rF   r   r   G  s
   r   Fontsc                 C   s   g | ]
}|j qS r   r   r   cr   r   r   
<listcomp>h  r   r   FontConstantsBasec                 C   s   g | ]
}|j qS r   r   r   r   r   r   r   j  r   Nodec                 C   s   g | ]
}|j qS r   r   r   r   r   r   r   l  r   ZShipParserc                   @   s   e Zd ZdS )MathTextWarningN)r   r   r    r   r   r   r   r   s  s   r   c                 C   s   t | || d S r   )r   rV   )r3   r4   r=   r   r   r   rV   w  s    rV   c                	   @   s   e Zd ZdZeeeeee	e
edZejejejejejejdZdd Zdddd	d
Zeddd ZejddddddZejddddddZejddddddZejdddd ddZdS )!MathTextParserN)bitmapZaggro   ZpdfsvgpathZcairomacosx)cmZdejavuserifZ
dejavusansZstixZstixsansZcustomc                 C   s   |  | _dS )z7Create a MathTextParser for the given backend *output*.N)lower_output)r   outputr   r   r   r*     s    zMathTextParser.__init__H   F)_force_standard_ps_fontsc                C   s$   |rt jdddd | ||||S )aZ  
        Parse the given math expression *s* at the given *dpi*.  If *prop* is
        provided, it is a `.FontProperties` object specifying the "default"
        font to use in the math expression, used for all non-math text.

        The results are cached, so multiple calls to `parse`
        with the same expression should be fast.
        r   z3.5zMathtext using only standard PostScript fonts has been likely to produce wrong output for a while, has been deprecated in %(since)s and will be removed in %(removal)s, after which ps.useafm will have no effect on mathtext.)Zremovalmessage)r   Zwarn_deprecated_parse_cached)r   sdpipropr   r   r   r   parse  s    	zMathTextParser.parse2   c           
      C   s   |d u rt  }|rtjntj| j| d}| j| j  }|||}|	 }| j
d u rbt | j_
| j
||||}	||	j|	j|	j ||	S )N)Zfontset)r   r   ZStandardPsFontsr   Zcheck_getitem_font_type_mappingZget_math_fontfamily_backend_mappingr   Zget_size_in_points_parserr   rG   r   r/   r&   r'   r(   r>   )
r   r   r   r   Zforce_standard_ps_fontsZfontset_classbackendZfont_outputrl   r=   r   r   r   r     s    



zMathTextParser._parse_cachedr   r]   r^   x      c                 C   s:   | j dksJ t|d}| j|||d\}}t||fS )a   
        Convert a mathtext string to a grayscale array and depth.

        Parameters
        ----------
        texstr : str
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
        dpi : float
            The dots-per-inch setting used to render the text.
        fontsize : int
            The font size in points

        Returns
        -------
        array : 2D uint8 alpha
            Mask array of rasterized tex.
        depth : int
            Offset of the baseline from the bottom of the image, in pixels.
        r   sizer   r   )r   r   r   rN   Zasarrayr   texstrr   rl   r   Zftimager(   r   r   r   to_mask  s    
zMathTextParser.to_maskblackc                 C   s   | j |||d\}}t|\}}}	}
tj|jd |jd dftjd}d| |dddddf< d| |dddddf< d|	 |dddddf< ||ddddd	f< ||fS )
ao  
        Convert a mathtext string to an RGBA array and depth.

        Parameters
        ----------
        texstr : str
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
        color : color
            The text color.
        dpi : float
            The dots-per-inch setting used to render the text.
        fontsize : int
            The font size in points.

        Returns
        -------
        array : (M, N, 4) array
            RGBA color values of rasterized tex, colorized with *color*.
        depth : int
            Offset of the baseline from the bottom of the image, in pixels.
        )r   rl   r   rH      )Zdtype   NrI   rJ   )r   mcolorsto_rgbarN   ZzerosshapeZuint8)r   r   colorr   rl   xr(   rgbaZRGBAr   r   r   r     s    "zMathTextParser.to_rgbac                 C   s.   | j ||||d\}}t|j|dd |S )a/  
        Render a tex expression to a PNG file.

        Parameters
        ----------
        filename
            A writable filename or fileobject.
        texstr : str
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
        color : color
            The text color.
        dpi : float
            The dots-per-inch setting used to render the text.
        fontsize : int
            The font size in points.

        Returns
        -------
        int
            Offset of the baseline from the bottom of the image, in pixels.
        )r   r   rl   Zpng)format)r   r   Z	fromarraysave)r   ry   r   r   r   rl   Zrgbar(   r   r   r   to_png  s
    
zMathTextParser.to_pngc                 C   s0   | j dksJ t|d}| j|||d\}}|S )a~  
        Get the depth of a mathtext string.

        Parameters
        ----------
        texstr : str
            A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
        dpi : float
            The dots-per-inch setting used to render the text.

        Returns
        -------
        int
            Offset of the baseline from the bottom of the image, in pixels.
        r   r   r   )r   r   r   r   r   r   r   	get_depth#  s    
zMathTextParser.get_depth)r   N)r   r   )r   r   r   )r   r   r   )r   r   )r   r   r    r   r`   rA   rc   rq   r{   rb   r   r   r   ZBakomaFontsZDejaVuSerifFontsZDejaVuSansFontsZ	StixFontsZStixSansFontsZUnicodeFontsr   r*   r   	functools	lru_cacher   r   r   r   r   r   r   r   r   r   r   r     s:   	
 r   c                 C   s   ddl m} ddlm} |du r&t }td}|j| d|d\}}	}
}}|j|d |	d fd	}|jd|
|	 | |d
 |	| |j
|||d |
S )a  
    Given a math expression, renders it in a closely-clipped bounding
    box to an image file.

    Parameters
    ----------
    s : str
        A math expression.  The math portion must be enclosed in dollar signs.
    filename_or_obj : str or path-like or file-like
        Where to write the image data.
    prop : `.FontProperties`, optional
        The size and style of the text.
    dpi : float, optional
        The output dpi.  If not set, the dpi is determined as for
        `.Figure.savefig`.
    format : str, optional
        The output format, e.g., 'svg', 'pdf', 'ps' or 'png'.  If not set, the
        format is determined as for `.Figure.savefig`.
    r   )figurerY   Nr   r   r   g      R@)Zfigsize)Zfontproperties)r   r   )
matplotlibr   r[   rZ   r   r   r   ZFiguretextZFigureCanvasAggZsavefig)r   Zfilename_or_objr   r   r   r   rZ   parserr&   r'   r(   _Zfigr   r   r   math_to_image:  s    
r   )NNN)5r@   collectionsr   r   ior   loggingr~   ZnumpyrN   ZPILr   r   r   r   r   r   r   r	   Zmatplotlib.ft2fontr
   r   Zmatplotlib.font_managerr   	getLoggerr   _logZcaching_module_getattrr   Zget_unicode_indexr   r#   rA   r   r`   rc   rq   r{   rb   r   r   __subclasses__r   r   	_cls_nametyper   globalsWarningr   rV   r   r   r   r   r   r   <module>   sj   
7K+	
 ;