rL idZddlZddlZddlmZddlZddlZddlmZddl m Z ddl Z ddl Z ddl Z ddlZddlZddlmZmZddlmZddlZddlmZddlZdd lmZddlmZdd lmZmZej@d d Z!d Z"dZ#dZ$dZ%GddeZ&dZ'dZ(dZ)dZ*dZ+e+dzZ,e+dzZ-dZ.e/Z0GddZ1d&dZ2Gdde3Z4d'd Z5d(d!Z6d"Z7d#Z8 d)d$Z9d%Z:y)*a A directive for including a Matplotlib plot in a Sphinx document ================================================================ This is a Sphinx extension providing a reStructuredText directive ``.. plot::`` for including a plot in a Sphinx document. 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 plot content may be defined 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 plt.plot([1, 2, 3], [4, 5, 6]) plt.title("A plotting exammple") 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). ``:show-source-link:`` : bool Whether to show a link to the source in HTML. The default can be changed using the ``plot_html_show_source_link`` variable in :file:`conf.py` (which itself defaults to True). ``: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 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. plot_srcset Allow the srcset image option for responsive image resolutions. List of strings with the multiplicative factors followed by an "x". e.g. ["2.0x", "1.5x"]. "2.0x" will create a png with the default "png" resolution from plot_formats, multiplied by 2. If plot_srcset is specified, the plot directive uses the :doc:`/api/sphinxext_figmpl_directive_api` (instead of the usual figure directive) in the intermediary rst file that is generated. The plot_srcset option is incompatible with *singlehtml* builds, and an error will be raised. Notes on how it works --------------------- The plot directive runs the code it is given, either in the source file or the code under the directive. The figure created (if any) is saved in the sphinx build directory under a subdirectory named ``plot_directive``. It then creates an intermediate rst file that calls a ``.. figure:`` directive (or ``.. figmpl::`` directive if ``plot_srcset`` is being used) and has links to the ``*.png`` files in the ``plot_directive`` directory. These translations can be customized by changing the *plot_template*. See the source of :doc:`/api/sphinxext_plot_directive_api` for the templates defined in *TEMPLATE* and *TEMPLATE_SRCSET*. N)StringIO)relpath)Path) directives Directive)Image)ExtensionError)FigureManagerBase)_pylab_helperscbookaggc|r|jsy|jjdvry|jjdvryt|d)NT)no0falseF)yes1truez unknown boolean)striplower ValueErrorargs i/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/matplotlib/sphinxext/plot_directive.py_option_booleanrsY ciik     4 4     4 4C7"2344c$|dvr|Std)N)Nreset close-figsz2Argument should be None or 'reset' or 'close-figs')rrs r_option_contextr!s ++ I JJrc.tj|dS)N)pythondoctest)rchoicers r_option_formatr&s   S"7 88rc`|jjD]\}}|s |j|}||j|}|jdvs:|D]}|jdk(s|}|D]#}|jdk(s|j }n|dj ||dj ||dj||dj||jjj||f|jjj|<y)z To make plots referenceable, we need to move the reference from the "htmlonly" (or "latexonly") node to the actual figure node itself. N) html_only latex_onlyfigurecaptionidsnames) nametypesitemsnameidsr,tagnameastextremoveappendsettingsenvdocnamelabels) appdocumentnameexplicitlabelidnodensectnamecs rmark_plot_labelsrBs+ #,,224h ""4( ? ||G$ <<6 6 99(#H"99 1'(xxzH!" K&&w/M((.eHOOG,gJ%%d+ ))--55wH%%))006 rc eZdZdZdZdZdZdZejejejeje jejeeeeej&ejd ZdZy) PlotDirectivezEThe ``.. plot::`` directive, as documented in the module's docstring.TrrF) altheightwidthscalealignclassinclude-sourceshow-source-linkformatcontextnofigsr+c t|j|j|j|j|j |j S#t$r}|jt|d}~wwxYw)zRun the plot directive.N) run argumentscontentoptions state_machinestatelineno Exceptionerrorstr)selfes rrQzPlotDirective.runs` %t~~t||T\\))4::t{{D D %**SV$ $ %sA A A6A11A6N)__name__ __module__ __qualname____doc__ has_contentrequired_argumentsoptional_argumentsfinal_argument_whitespacer unchangedlength_or_unitless length_or_percentage_or_unitlessnonnegative_intrrI class_optionrr&r!flag option_specrQrrrDrDsxOK %##//<<++(()+ "//''  K%rrDc|||jjdk(rbtjd}|jt dz }|j dtj||t dz yyy)Nhtmlz!plot_directive/plot_directive.css_staticTexist_okplot_directive.css) builderrMr _get_data_pathoutdirrmkdirshutilcopyfile)r9excsrcdsts r_copy_css_filer|si {s{{))V3""#FGjj4 ?* 4  S4(<#==> 4{rc|t_|jt_|jt_|j dt |j ddd|j ddd|j ddd|j dgdd|j d dd|j d dd|j d id|j d dd|j d dd|j ddd|j dgd|jdt|jd|jdtddtjd}|S)Nplot plot_pre_codeTplot_include_sourceFplot_html_show_source_link plot_formatspngz hires.pngpdf plot_basedirplot_html_show_formats plot_rcparamsplot_apply_rcparamsplot_working_directory plot_template plot_srcsetz doctree-readrrzbuild-finished)parallel_read_safeparallel_write_safeversion) setupr9configconfdir add_directiverDadd_config_valueconnectrB add_css_filer| matplotlib __version__)r9metadatas rrr&sBEI::ELKKEMfm,$5.t<5tTB)DdKt414>"d3.t<14>$5D1KK 01)*KK .1&*4%113H Orc t|ddy#t$rYnwxYwtjdtj}|j |}t |S)NzexecFz^\s*>>>)compile SyntaxErrorreMsearchbool)textrms rcontains_doctestrCsR j&)     :rtt$A A 7Ns  ct|}|g}g}|jdD]o}|s|jds|rG|jdk(r4|j ||j dj |g}_|j |qdj |jr |j dj |||fS|g}||fS)zSplit code at plt.show(). z plt.show(z>>> plt.show())rsplit startswithrr4join)r function_name is_doctestpartspartlines r_split_code_at_showrOs"$'JJJt$ "DDOOK$@4::<3C#C D! TYYt_- D! " 99T? " LL4 ) u  u ra  {{ source_code }} .. only:: html {% if src_name or (html_show_formats and not multi_image) %} ( {%- if src_name -%} :download:`Source code <{{ build_dir }}/{{ src_name }}>` {%- endif -%} {%- if html_show_formats and not multi_image -%} {%- for img in images -%} {%- for fmt in img.formats -%} {%- if src_name or not loop.first -%}, {% endif -%} :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>` {%- endfor -%} {%- endfor -%} {%- endif -%} ) {% endif %} a3 {% for img in images %} .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }} {% for option in options -%} {{ option }} {% endfor %} {%- if caption -%} {{ caption }} {# appropriate leading whitespace added beforehand #} {% endif -%} {%- if srcset -%} :srcset: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }} {%- for sr in srcset -%} , {{ build_dir }}/{{ img.basename }}.{{ sr }}.{{ default_fmt }} {{sr}} {%- endfor -%} {% endif %} {% if html_show_formats and multi_image %} ( {%- for fmt in img.formats -%} {%- if not loop.first -%}, {% endif -%} :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>` {%- endfor -%} ) {% endif %} {% endfor %} .. only:: not html {% for img in images %} .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.* {% for option in options -%} {{ option }} {% endfor -%} {{ caption }} {# appropriate leading whitespace added beforehand #} {% endfor %} a' {% 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 -%} :download:`{{ fmt }} <{{ build_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. ceZdZdZdZdZy) ImageFilec.||_||_g|_yN)basenamedirnameformats)r[rrs r__init__zImageFile.__init__s    rcttjj|j|jd|S)N.)ospathrrr)r[rMs rfilenamezImageFile.filenames*ww||DLLT]]O1VH*EFFrc^|jDcgc]}|j|c}Scc}wr)rr)r[fmts r filenameszImageFile.filenamess#.2ll;s c";;;s*N)r]r^r_rrrrlrrrrs G.out_of_date_ones3x(; 1 : :: zout_of_date..sIQq-0Is)rrrrrany)rderivedincludesfiles_to_checkrrs @@r out_of_daters\ 77>>' "**N<GGG$--M I.I IIrc eZdZy) PlotErrorN)r]r^r_rlrrrrsrrctj}tjj/ tj tjjnS|Qtjjtjj|}tj |tjt|gtjgtj5tjt!5 |i}|sTtjj" t%d|n-t%t'tjj"|d|vrd|d<tjt(d 5t%|||t%|d z|dddtj | dddddd|S#t $r}t |d|d}~wt$r}t|d|d}~wwxYw#1swYlxYw#t*t,f$r#}t/t1j2|d}~wwxYw#tj |wxYw#1swYxYw#1swY|SxYw) zs Import a Python module from a path, and run the function given by name, if function_name is not None. Nz\ `plot_working_directory` option in Sphinx configuration file must be a valid directory pathzV `plot_working_directory` option in Sphinx configuration file must be a string or None)argvrz8import numpy as np from matplotlib import pyplot as plt __main__r]cyrrl)r[s rz_run_code..'sr)showz())rgetcwdrrrchdirOSError TypeErrorrabspathrr _setattr_cmsys contextlibredirect_stdoutrrrrZr rX SystemExitr traceback format_exc)code code_pathnsrpwderrrs r _run_coders" ))+C ||**6 . HHU\\88 9  ''//"''//)"<=     yk(@sxx(@ B  & &xz 2 z<<--5BCEGU\\778"=T!!+:""#4;LM 3T2 ,-r2 3 HHSM12 IK 6SE"+,-25 6 .se$#$%*- . .0 3 3 :& =I0023 < = HHSM12 Is-G1JI4A?H%H.H%6I4 J H'G66 HHHH" H%%I4IIII11I44I= 9JJ c|rtjdtjtjj |y)Nall)pltcloserrc_file_defaultsrcParamsupdate)rrs r clear_stater3s1  %!}-rcdddd}g}|j}|D]}t|trbd|vr:|jd\}}|j t|t |fQ|j ||j |dfut|ttfr:t|dk(r,|j t|dt |dftd|z|S) NPr:rrz)invalid image format "%r" in plot_formats) r isinstancerZrr4intgettuplelistlenr)r default_dpirrrsuffixdpis rget_plot_formatsr:s3s;KG&&L O c3 cz!iin F SX67[__S"%=>? eT] +CA NNCAKSV5 6G#MN N O Nrci}|D]B}|j}t|dk\r|dd}||t|<5td|d|S)z' Parse srcset for multiples... rNzsrcset argument z is invalid.)rrfloatr )entriessrcsetentrymults r _parse_srcsetr LseFK  u:?":D"'F5;  #3E9L!IJ J K Mrc P||d|}t|} t||\} } t||} | D]C\}}|st|| j || rd}n| j j |Ed}|r|| gfgSg}t| D]\}}g}tjD]}t| dkDrtd|||fz|} ntd||fz|} | D]C\}}|st|| j || rd}n| j j |E|s|d kD}n|j | |sn|j ||fd}|r|Sg}|rtni}|r)t|jtj| xs|}t| D]!\}}|r |jrt|j|n|rt!j"d t%| rt'j(|n||||g}t*j,j/}t|D]x\}}t|dk(rt| dk(r t||} n2t| dk(rtd||fz|} ntd|||fz|} |j | | D]\}} |j0j2j5| j || || d d k(r|j6rt9|j6}|j;D]i\}}|d |}| j j ||j0j2j5| j |t=||z k| j j |{|j ||f$|r |jrt|j| |S#t>$r#}tAtCjD|d}~wwxYw)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* N_)rFTrz %s_%02d_%02dz%s_%02drr)rr)r)#rrrrrrr4 enumerate itertoolscountr plot_contextrrclearrrrrr$script_from_examplesr Gcfget_all_fig_managerscanvasr*savefigrr r/rrXrrr)rr output_dir output_baserNrr context_reset close_figs code_includesrr code_piecesimgrMr all_existsresultsi code_pieceimagesjrr fig_managersfigmanrr rfmrs rrender_figuresr'[s6 $ Q}o6 v&G2$ FJ K ,C  k)S\\&-A+8:J  6"  u G";/ :" A;!#+q!1D D *, [!,< >@ "<0 (IAv< A%#k*:a*? Z8[!Q& [!,< .qs%#D'+$,djjl#:#Dsz.. code-block:: pythonz rE)rErFrGrHrIrJrz: ) default_fmt build_dirsrc_name multi_imagerTrr" source_codehtml_show_formatsr+)r*)Jr:r5r6rrrr9rsr;r r setdefaultrr attributesrrrrrrsrcdirrurirrr read_textrtextwrapdedentmaprZrsplitextreplacerrlstripsep doctreedirnormpathmakedirs include_logrAttributeError input_linesr/isfiler3 write_textr$rr'rmemoreportersystem_messagerMrr  splitlinesindentr valuesTEMPLATE_SRCSETTEMPLATEjinja2Templaterrenderrextend insert_input)3rRrSrTrUrVrWr:rrOrr3 keep_context context_optrst_filerst_dirsource_file_namer+rrrcounterbaseext source_extrsource_rel_namesource_rel_dirr4build_dir_linktsource_file_includespossible_sourcesrrerrorsrrNsm total_linesr#r!r"linesr7keyvaloptsr5rtemplateresults3 rrQrQs%%H    " " ) )F  F eii//44 D GI Iv&G!*Q-K ')C)CD )6+L+LM'--0@@7%5$67'L*$ 0BK""8,Hggooh'G 9~""!ww||EII,=,=,D,D,6NN9Q<,H J  "ww||EMM6;N;N,6NN9Q<,H J ))G$   0 i(G y>Q %aLM M$%///Agg&&'78 #tyyS'):;<%%))/1=A/6O,GG$$RWW%5%56F%GH c D'?2  ++i,ww'' 4D*,,  %%c3/K"$'J7 8  (JJ. >OWW___5<GEN.5]]_M!)cKKuBse MM 6g01"Z/HH   B}V%7%78??ABF&HFH!5!5!ABII#$F a#$;;KF J  6<<-.4 ].!`"";7G"H Mc ### E 6&3%>%>%D%DF !GGLL!=FFF+; 6a#%77>>!#4!" 6 6 6 6    0 ::&&  $ $ AHH-s4%":,DMs4]], <]'],`2`a2 ]$#]$'],,!` 8_ `(_:9`` `` a/!Aa**a/r)NN)T)FFN);r`rr$iorrros.pathrpathlibrrrwrr>rdocutils.parsers.rstrr&docutils.parsers.rst.directives.imagesrrU sphinx.errorsr rmatplotlib.backend_basesr matplotlib.pyplotpyplotrr r userrr!r&rBrDr|rrr _SOURCECODErSrTexception_templatedictrrr RuntimeErrorrrrrr r'rQrlrrrseN  68 (6, u  5K 9<%I%>?: 4 ,'!'R  Bv  < <J,  2j.$  9>#!%upUr