a
    s=icu                     @   s  d Z ddlZddlZddlmZ ddlZddlZddlmZ ddl	m
Z
 ddlZddlZddlZddlZddlZddlmZmZ ddlmZ ddlZddlZddlmZ ddlmZ dd	lmZmZmZ ed
 dZ dd Z!dd Z"dd Z#dd Z$dd Z%G dd deZ&dd Z'dd Z(dd Z)ej*ddd d!d" Z+e*dd#d$ Z,d%d& Z-d'Z.d(Z/e0 Z1G d)d* d*Z2d=d+d,Z3G d-d. d.e4Z5e*dd>d/d0Z6d?d1d2Z7d@d4d5Z8d6d7 Z9dAd9d:Z:d;d< Z;dS )BaM  
A directive for including a Matplotlib plot in a Sphinx document
================================================================

By default, in HTML output, `plot` will include a .png file with a link to a
high-res .png and .pdf.  In LaTeX output, it will include a .pdf.

The source code for the plot may be included in one of three ways:

1. **A path to a source file** as the argument to the directive::

     .. plot:: path/to/plot.py

   When a path to a source file is given, the content of the
   directive may optionally contain a caption for the plot::

     .. plot:: path/to/plot.py

        The plot caption.

   Additionally, one may specify the name of a function to call (with
   no arguments) immediately after importing the module::

     .. plot:: path/to/plot.py plot_function1

2. Included as **inline content** to the directive::

     .. plot::

        import matplotlib.pyplot as plt
        import matplotlib.image as mpimg
        import numpy as np
        img = mpimg.imread('_static/stinkbug.png')
        imgplot = plt.imshow(img)

3. Using **doctest** syntax::

     .. plot::

        A plotting example:
        >>> import matplotlib.pyplot as plt
        >>> plt.plot([1, 2, 3], [4, 5, 6])

Options
-------

The ``plot`` directive supports the following options:

    format : {'python', 'doctest'}
        The format of the input.  If unset, the format is auto-detected.

    include-source : bool
        Whether to display the source code. The default can be changed using
        the `plot_include_source` variable in :file:`conf.py` (which itself
        defaults to False).

    encoding : str
        If this source file is in a non-UTF8 or non-ASCII encoding, the
        encoding must be specified using the ``:encoding:`` option.  The
        encoding will not be inferred using the ``-*- coding -*-`` metacomment.

    context : bool or str
        If provided, the code will be run in the context of all previous plot
        directives for which the ``:context:`` option was specified.  This only
        applies to inline code plot directives, not those run from files. If
        the ``:context: reset`` option is specified, the context is reset
        for this and future plots, and previous figures are closed prior to
        running the code. ``:context: close-figs`` keeps the context but closes
        previous figures before running the code.

    nofigs : bool
        If specified, the code block will be run, but no figures will be
        inserted.  This is usually useful with the ``:context:`` option.

    caption : str
        If specified, the option's argument will be used as a caption for the
        figure. This overwrites the caption given in the content, when the plot
        is generated from a file.

Additionally, this directive supports all of the options of the `image`
directive, except for *target* (since plot will add its own target).  These
include *alt*, *height*, *width*, *scale*, *align* and *class*.

Configuration options
---------------------

The plot directive has the following configuration options:

    plot_include_source
        Default value for the include-source option (default: False).

    plot_html_show_source_link
        Whether to show a link to the source in HTML (default: True).

    plot_pre_code
        Code that should be executed before each plot. If None (the default),
        it will default to a string containing::

            import numpy as np
            from matplotlib import pyplot as plt

    plot_basedir
        Base directory, to which ``plot::`` file names are relative to.
        If None or empty (the default), file names are relative to the
        directory where the file containing the directive is.

    plot_formats
        File formats to generate (default: ['png', 'hires.png', 'pdf']).
        List of tuples or strings::

            [(suffix, dpi), suffix, ...]

        that determine the file format and the DPI. For entries whose
        DPI was omitted, sensible defaults are chosen. When passing from
        the command line through sphinx_build the list should be passed as
        suffix:dpi,suffix:dpi, ...

    plot_html_show_formats
        Whether to show links to the files in HTML (default: True).

    plot_rcparams
        A dictionary containing any non-standard rcParams that should
        be applied before each plot (default: {}).

    plot_apply_rcparams
        By default, rcParams are applied when ``:context:`` option is not used
        in a plot directive.  If set, this configuration option overrides this
        behavior and applies rcParams before each plot.

    plot_working_directory
        By default, the working directory will be changed to the directory of
        the example, so the code can get at its data files, if any.  Also its
        path will be added to `sys.path` so it can import any helper modules
        sitting beside it.  This configuration option can be used to specify
        a central directory (also added to `sys.path`) where data files and
        helper modules for all code are located.

    plot_template
        Provide a customized template for preparing restructured text.
    N)StringIO)relpath)Path)
directives	Directive)Image)FigureManagerBase)_api_pylab_helperscbookZagg   c                 C   sJ   | r|   sdS |    dv r$dS |    dv r8dS t| dd S )NT)no0falseF)yes1truez unknown boolean)striplower
ValueErrorarg r   t/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/matplotlib/sphinxext/plot_directive.py_option_boolean   s    r   c                 C   s   | dv r| S t dd S )N)Nreset
close-figsz2Argument should be None or 'reset' or 'close-figs')r   r   r   r   r   _option_context   s    r   c                 C   s   t | dS )N)pythondoctest)r   choicer   r   r   r   _option_format   s    r!   c                 C   s   t jdddd t| S )N3.5encodingoption)nameobj_type)r	   Zwarn_deprecatedr   r#   r   r   r   r   _deprecated_option_encoding   s    r'   c           	      C   s   |j  D ]\}}|sq
|j| }|du r,q
|j| }|jdv r
|D ]}|jdkrD|}|D ]}|jdkrZ| } qvqZ|d | |d | |d | |d | |jj	j
||f|jj	j|<  q
qDq
dS )z
    To make plots referenceable, we need to move the reference from the
    "htmlonly" (or "latexonly") node to the actual figure node itself.
    N)Z	html_onlyZ
latex_onlyfigurecaptionidsnames)Z	nametypesitemsZnameidsr*   tagnameZastextremoveappendsettingsenvZdocnamelabels)	appdocumentr%   explicitZlabelidnodensectnamecr   r   r   mark_plot_labels   s,    




r:   c                   @   sV   e Zd ZdZdZdZdZdZej	ej
ejejejejeeeejeej	dZdd Zd	S )
PlotDirectivezEThe ``.. plot::`` directive, as documented in the module's docstring.Tr   r   F)altheightwidthscalealignclassinclude-sourceformatcontextnofigsr#   r)   c              
   C   sX   z t | j| j| j| j| j| jW S  tyR } z| t	|W Y d}~n
d}~0 0 dS )zRun the plot directive.N)
run	argumentscontentoptionsstate_machinestatelineno	Exceptionerrorstr)selfer   r   r   rF      s    zPlotDirective.runN)__name__
__module____qualname____doc__Zhas_contentZrequired_argumentsZoptional_argumentsZfinal_argument_whitespacer   Z	unchangedZlength_or_unitlessZ length_or_percentage_or_unitlessZnonnegative_intr   r@   Zclass_optionr   r!   r   flagr'   Zoption_specrF   r   r   r   r   r;      s&   r;   c                 C   sP   |d u rL| j jdkrLtd}| jtd }|jdd t||td  d S )Nhtmlz!plot_directive/plot_directive.cssZ_staticTexist_okplot_directive.css)	builderrC   r   Z_get_data_pathoutdirr   mkdirshutilcopyfile)r3   excsrcdstr   r   r   _copy_css_file  s
    
rc   c                 C   s   | t _| jt _| jt _| dt | dd d | ddd | ddd | dg dd | d	d d | d
dd | di d | ddd | dd d | dd d | dt | 	d | dt
 ddtjd}|S )NZplotplot_pre_codeTplot_include_sourceFplot_html_show_source_linkplot_formatsZpngz	hires.pngZpdfplot_basedirplot_html_show_formatsplot_rcparamsplot_apply_rcparamsplot_working_directoryplot_templatezdoctree-readrZ   zbuild-finished)Zparallel_read_safeZparallel_write_safeversion)setupr3   configconfdirZadd_directiver;   Zadd_config_valueconnectr:   Zadd_css_filerc   
matplotlib__version__)r3   metadatar   r   r   rp     s*    
rp   c                 C   sF   zt | dd W dS  ty$   Y n0 t dtj}|| }t|S )Nz<string>execFz^\s*>>>)compileSyntaxErrorreMsearchbool)textrmr   r   r   contains_doctest+  s    
r   r"   zdoctest.script_from_examples)alternativec                 C   sn   t | s| S d}| dD ]N}td|}|rB||dd 7 }q| r`|d|  d 7 }q|d7 }q|S )z_
    Extract code from a piece of text, which contains either Python code
    or doctests.
     
z^\s*(>>>|\.\.\.) (.*)$r   z# )r   splitrz   matchgroupr   )r~   codeliner   r   r   r   unescape_doctest7  s    
r   c                 C   s   t | d S )Split code at plt.show().   )_split_code_at_show)r~   r   r   r   split_code_at_showK  s    r   c                 C   s   g }t | }g }| dD ]N}|s.| dks>|r^| dkr^|| |d| g }q|| qd| r|d| ||fS )r   r   z
plt.show()z>>> plt.show())r   r   r   r/   join)r~   parts
is_doctestpartr   r   r   r   r   Q  s     

r   a(  
{{ source_code }}

.. only:: html

   {% if source_link or (html_show_formats and not multi_image) %}
   (
   {%- if source_link -%}
   `Source code <{{ source_link }}>`__
   {%- endif -%}
   {%- if html_show_formats and not multi_image -%}
     {%- for img in images -%}
       {%- for fmt in img.formats -%}
         {%- if source_link or not loop.first -%}, {% endif -%}
         `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
       {%- endfor -%}
     {%- endfor -%}
   {%- endif -%}
   )
   {% endif %}

   {% for img in images %}
   .. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
      {% for option in options -%}
      {{ option }}
      {% endfor %}

      {% if html_show_formats and multi_image -%}
        (
        {%- for fmt in img.formats -%}
        {%- if not loop.first -%}, {% endif -%}
        `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
        {%- endfor -%}
        )
      {%- endif -%}

      {{ caption }}  {# appropriate leading whitespace added beforehand #}
   {% endfor %}

.. only:: not html

   {% for img in images %}
   .. figure:: {{ build_dir }}/{{ img.basename }}.*
      {% for option in options -%}
      {{ option }}
      {% endfor -%}

      {{ caption }}  {# appropriate leading whitespace added beforehand #}
   {% endfor %}

zi
.. only:: html

   [`source code <%(linkdir)s/%(basename)s.py>`__]

Exception occurred rendering plot.

c                   @   s$   e Zd Zdd Zdd Zdd ZdS )	ImageFilec                 C   s   || _ || _g | _d S N)basenamedirnameformats)rP   r   r   r   r   r   __init__  s    zImageFile.__init__c                 C   s   t j| jd| j|f S )Nz%s.%s)ospathr   r   r   )rP   rC   r   r   r   filename  s    zImageFile.filenamec                    s    fdd j D S )Nc                    s   g | ]}  |qS r   )r   ).0fmtrP   r   r   
<listcomp>      z'ImageFile.filenames.<locals>.<listcomp>)r   r   r   r   r   	filenames  s    zImageFile.filenamesN)rR   rS   rT   r   r   r   r   r   r   r   r     s   r   c                    sR   t j|sdS |du rg }| g|}dd t |j t fdd|D S )a4  
    Return whether *derived* is out-of-date relative to *original* or any of
    the RST files included in it using the RST include directive (*includes*).
    *derived* and *original* are full paths, and *includes* is optionally a
    list of full paths which may have been included in the *original*.
    TNc                 S   s   t j| o|t | jk S r   )r   r   existsstatst_mtime)originalderived_mtimer   r   r   out_of_date_one  s    z$out_of_date.<locals>.out_of_date_onec                 3   s   | ]}| V  qd S r   r   r   fr   r   r   r   	<genexpr>  r   zout_of_date.<locals>.<genexpr>)r   r   r   r   r   any)r   ZderivedincludesZfiles_to_checkr   r   r   out_of_date  s    
r   c                   @   s   e Zd ZdS )	PlotErrorN)rR   rS   rT   r   r   r   r   r     s   r   c                 C   s   t t| ||| dS )s
    Import a Python module from a path, and run the function given by
    name, if function_name is not None.
    N)	_run_coder   )r   	code_pathnsfunction_namer   r   r   run_code  s    r   c                 C   s0  t  }tjjdurzt tjj W q ty\ } ztt|d |W Y d}~qd}~0  ty } ztt|d |W Y d}~qd}~0 0 n&|durt j	
t j	|}t | tjt|gt  gtj	d@ tt  zz|du ri }|s.tjjdu rtd| ntttjj| d| v r@d|d< tjtdd	 d
2 t| | |durvt|d | W d   n1 s0    Y  W n8 ttfy } ztt |W Y d}~n
d}~0 0 W t | nt | 0 W d   n1 s0    Y  W d   n1 s"0    Y  |S )r   Nz[
`plot_working_directory` option inSphinx configuration file must be a valid directory pathzV
`plot_working_directory` option in Sphinx configuration file must be a string or None)argvr   z8import numpy as np
from matplotlib import pyplot as plt
__main__rR   c                 S   s   d S r   r   r   r   r   r   <lambda>  r   z_run_code.<locals>.<lambda>)showz())r   getcwdrp   rq   rm   chdirOSErrorrO   	TypeErrorr   abspathr   r   Z_setattr_cmsys
contextlibredirect_stdoutr   rd   rw   r   rM   
SystemExitr   	traceback
format_exc)r   r   r   r   pwderrr   r   r   r   r     sN    	





2&Xr   Tc                 C   s&   |rt d t  tj|  d S )Nall)pltclosert   Zrc_file_defaultsZrcParamsupdate)rk   r   r   r   r   clear_state  s    
r   c                 C   s   dddd}g }| j }|D ]}t|trnd|v rV|d\}}|t|t|f q||||df qt|ttfrt	|dkr|t|d t|d f qt
d| q|S )	NP      rh   :r   r   r   z)invalid image format "%r" in plot_formats)rg   
isinstancerO   r   r/   intgettuplelistlenr   )rq   Zdefault_dpir   rg   r   suffixdpir   r   r   get_plot_formats  s    
 r   Fc
                 C   s  t |}
t| \}}d}t||}|
D ]4\}}|sFt||||	drNd} q\|j| q&|rl| |gfgS g }d}t|D ]\}}g }t	 D ]}t
|dkrtd|||f |}ntd||f |}|
D ]6\}}|st||||	drd} q|j| q|s|dk} q$|| q|s0 q@|||f q||rJ|S g }|rXtni }|rtt|j t  | p~|}t|D ]Z\}}|r|jrt|j| n|rtd t|rt|n|||| g }tj }t|D ]\}}t
|dkr"t
|dkr"t||}n6t
|dkrDtd||f |}ntd|||f |}|| |
D ]h\}}z|jjj|||d	 W n4 ty } ztt |W Y d
}~n
d
}~0 0 |j| qfq|||f q|r|jrt|j| d |S )z
    Run a pyplot script and save the images in *output_dir*.

    Save the images under *output_dir* with file names derived from
    *output_base*
    T)r   Fr   z%s_%02d_%02dz%s_%02dr   r   )r   N)r   )r   r   r   r   r   r   r/   	enumerate	itertoolscountr   plot_contextr   rk   clearrl   r   r   r   r   script_from_examplesr
   ZGcfZget_all_fig_managersZcanvasr(   ZsavefigrM   r   r   r   )r   r   
output_diroutput_baserD   r   rq   context_reset
close_figscode_includesr   r   Zcode_piecesZ
all_existsimgrC   r   resultsi
code_pieceimagesjr   r   Zfig_managersZfigmanr   r   r   r   render_figures'  s    





$r   c           3      C   s  |j }|jjj}d|v }t|}	|	d d }
|d|j d|v rVdg|d  |d< n|ddg d|v }|std n|d }|jd }tj	
|}t| rD|jstj	tjjjt| d }ntj	tj|jt| d }d|}d	|v r
|rtd
|d	 }t| dkr"| d }nd }t|jdd}tj	|}nj|}tdtt|}|jddd }||jd< tj	tj	|\}}d||f }d }|d	d}tj	|\}}|dv r|}nd}|dd}t |}d|v r|d dkrd}nd}t!|tj}tj	
|"tj	j#}tj	tj	
tjj$d|}tj	%|}tj&|dd tj	'tj	tjjj(|}tj&|dd tj	t!tj||tj	j#d}zt!||tj	j#d}W n ty   |}Y n0 |d | | }zdd |j j)D } W n4 t*y:   dd |j+j,D }!d d |!D } Y n0 z| -| W n ty^   Y n0 z,t.||||||||d!k|d"k| d#
}"g }#W nX t/y }$ z>|j0j1}%|%j2dd$3|||$|d%}&|g fg}"|&g}#W Y d }$~$n
d }$~$0 0 ddd&d' |4dD  }g }'t5|"D ]\}(\})}*|d r`|r<dg|)6 }+nd(dgt7|)d)6 }+d|+},nd},|rng }*d*d |, D }-|(dkr|j8r|}.nd }.t9:|j;pt<j=|
|||.t|*dk|-|*|,|j>ot|*|d+
}/|'?|/4d |'?d q|'r|j@|'|d, t|jAddd- |"D ]R\})}*|*D ]B}0|0B D ]2}1tj	|tj	|1}2|1|2kr<tCD|1|2 q<q0q$|j8rt||| jE||kr|rtFG|n|dd |#S ).NrE   r   rB   rA   zplot-directiverD   sourcer   r)   zGCaption specified in both content and options. Please remove ambiguity.r   r   zutf-8)r#   Z_plot_counterz%s-%d.pyr   )z.pyz.rstz.txt.-rC   r   FTZplot_directiverX   /c                 S   s"   g | ]}t jt  |d  qS r   )r   r   r   r   r   tr   r   r   r     s   zrun.<locals>.<listcomp>c                 S   s    h | ]}t jtj|d  qS r   )r   r   r   rp   rr   r   r   r   r   	<setcomp>  s   zrun.<locals>.<setcomp>c                 S   s   g | ]}t j|r|qS r   )r   r   isfiler   r   r   r   r   	  s   r   r   )r   r   r   z.Exception occurred in plotting {}
 from {}:
{})r   c                 s   s   | ]}d |   V  qdS )z      N)r   )r   r   r   r   r   r   (  s   zrun.<locals>.<genexpr>z.. code-block:: pythonz    c                 S   s$   g | ]\}}|d v rd||f qS ))r<   r=   r>   r?   r@   rA   z:%s: %sr   )r   keyvalr   r   r   r   ;  s   )
default_fmtdest_dir	build_dirsource_linkZmulti_imagerI   r   source_codeZhtml_show_formatsr)   )r   )parentsrY   )Hr4   r0   r1   rq   r   
setdefaultre   
attributesr   r   r   r   ri   r   rp   r3   r[   srcdirr   urirr   r   r   	read_textr   textwrapdedentmaprO   r   splitextreplacer   r   lstripsepZ
doctreedirnormpathmakedirsr   r\   Zinclude_logAttributeErrorZinput_linesr,   r.   r   r   memoreporterZsystem_messagerC   r   r   
splitlinesindentrf   jinja2Templatern   TEMPLATErenderrj   extendZinsert_inputr]   r   r^   r_   
write_textr   r   )3rG   rH   rI   rJ   rK   rL   r4   rq   rE   r   r   Zkeep_contextZcontext_optZrst_fileZrst_dirZsource_file_namer)   r   r   r   counterbaseextZ
source_extr   Zsource_rel_nameZsource_rel_dirr   r   Zdest_dir_linkZbuild_dir_linkr   Zsource_file_includesZpossible_sourcesr   errorsr   r  smZtotal_linesr   r   r   linesr   optsZsrc_linkresultr   fnZdestimgr   r   r   rF     sF   
















rF   )N)NN)NN)T)FFN)<rU   r   r   ior   r   r   os.pathr   pathlibr   rz   r^   r   r   r   Zdocutils.parsers.rstr   r   Z&docutils.parsers.rst.directives.imagesr   r  rt   Zmatplotlib.backend_basesr   Zmatplotlib.pyplotZpyplotr   r	   r
   r   Zuseru   r   r   r!   r'   r:   r;   rc   rp   r   
deprecatedr   r   r   r  Zexception_templatedictr   r   r   RuntimeErrorr   r   r   r   r   r   rF   r   r   r   r   <module>   sh    
	

4

5
   
k