
    -PhS                     h   d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	 ej
                    ZddlZddlmZmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZ 	 ddlmZ n# e$ r	 ddlmZ Y nw xY wdd	lmZ d
dlm Z! d
dl"m#Z# ddl$m%Z%m&Z& ddl'm(Z( d
dl)m*Z*m+Z+ ddgg dddgdgddZ,e,d         e,d<   e G d de                      Z-e .                     ee-j/        j         0                    dd                     ee-j%        j                    ee-j1        j                             Z dS )uA  
=====================
Cython related magics
=====================

Magic command interface for interactive work with Cython

.. note::

  The ``Cython`` package needs to be installed separately. It
  can be obtained using ``easy_install`` or ``pip``.

Usage
=====

To enable the magics below, execute ``%load_ext cython``.

``%%cython``

{CYTHON_DOC}

``%%cython_inline``

{CYTHON_INLINE_DOC}

``%%cython_pyximport``

{CYTHON_PYXIMPORT_DOC}

Author:
* Brian Granger

Code moved from IPython and adapted by:
* Martín Gaitán

Parts of this code were taken from Cython.inline.
    N)Distribution	Extension)	build_ext)display)magic_arguments)Magicsmagics_class
cell_magic)get_ipython_cache_dir)dedent   )__version__)CompileError   )cython_inlineload_dynamic)	cythonize)captured_fdprint_capturedz-fprofile-generate-fprofile-dir={TEMPDIR})z-fprofile-usez-fprofile-correctionr   )genusez	-prof-genz	-prof-use)gcciccr   mingw32c                       e Zd Z fdZd Zed             Zed             Z ej                     ej	        ddddd	d
           ej	        dddd	d           ej	        ddddd           ej	        dddddd           ej	        dddddd           ej	        ddddd            ej	        d!d"d#g d$           ej	        d%d#g d&           ej	        d'd(d#g d)           ej	        d*d+d,-           ej	        d.d/d0d#g d12           ej	        d3d4d#g d5           ej	        d6d7d#g d8           ej	        d9d:ddd;<           ej	        d=d>d?d@dA<          edB                                                                                                                                                                                                             Z
dC ZdKdDZdLdEZdF ZedG             ZdH ZddddefdIZedKdJ            Z xZS )MCythonMagicsc                 t    t                                          |           i | _        i | _        d| _        d S )NF)super__init___reloads_code_cache_pyximport_installed)selfshell	__class__s     Y/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/Cython/Build/IpythonMagic.pyr    zCythonMagics.__init__`   s8    $)!!!    c                     |j         }d|v r	|d         }nd |D             }|D ]G}	 | j                            |||         i           &# t          $ r d|z  }t	          |          w xY wd S )N__all__c                 <    g | ]}|                     d           |S )_)
startswith).0ks     r'   
<listcomp>z,CythonMagics._import_all.<locals>.<listcomp>k   s)    >>>!ALL,=,=>A>>>r(   z%'module' object has no attribute '%s')__dict__r%   pushKeyErrorAttributeError)r$   modulemdictkeysr/   msgs         r'   _import_allzCythonMagics._import_allf   s    #DD>>u>>>D 	* 	*A*
E!H.... * * *=A$S)))*	* 	*s   "A		A(c                 V    | j         j        }| j         j        }t          |||          S )a  Compile and run a Cython code cell using Cython.inline.

        This magic simply passes the body of the cell to Cython.inline
        and returns the result. If the variables `a` and `b` are defined
        in the user's namespace, here is a simple example that returns
        their sum::

            %%cython_inline
            return a+b

        For most purposes, we recommend the usage of the `%%cython` magic.
        )localsglobals)r%   user_global_nsuser_nsr   )r$   linecelllocsglobss        r'   r   zCythonMagics.cython_inlinet   s-     z(
"T$>>>>r(   c                    |                                 }|st          d          |dz   }t          |dd          5 }|                    |           ddd           n# 1 swxY w Y   dt          j        vs| j        sddl}|                                 d	| _        || j	        v r| j	        |         }n+t          |           t          j        |         }|| j	        |<   |                     |           dS )
a)  Compile and import a Cython code cell using pyximport.

        The contents of the cell are written to a `.pyx` file in the current
        working directory, which is then imported using `pyximport`. This
        magic requires a module name to be passed::

            %%cython_pyximport modulename
            def f(x):
                return 2.0*x

        The compiled module is then imported and all of its symbols are
        injected into the user's namespace. For most purposes, we recommend
        the usage of the `%%cython` magic.
        zmodule name must be given.pyxwutf-8encodingN	pyximportr   T)strip
ValueErroropenwritesysmodulesr#   rI   installr!   
__import__r9   )r$   r?   r@   module_namefnamefrI   r5   s           r'   cython_pyximportzCythonMagics.cython_pyximport   s@     jjll 	:8999f$%w/// 	1GGDMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	ck))1J)(,D%$-''];/FF {###[-F)/DM+&     s   AA#&A#z-az
--annotatestore_constdefaultannotatez/Produce a colorized HTML version of the source.)actionconstdesthelpz--annotate-fullcfullczZProduce a colorized HTML version of the source which includes entire generated C/C++-code.z-+z--cplus
store_trueFz Output a C++ rather than C file.)rY   rW   r\   z-3language_level   NzSelect Python 3 syntax.)r[   rY   rZ   rW   r\   z-2r   zSelect Python 2 syntax.z-fz--forcezWForce the compilation of a new module, even if the source has been previously compiled.z-cz--compile-argsappendzoExtra flags to pass to compiler via the `extra_compile_args` Extension flag (can be specified  multiple times).z--link-argszjExtra flags to pass to linker via the `extra_link_args` Extension flag (can be specified  multiple times).z-lz--libzNAdd a library to link the extension against (can be specified multiple times).z-nz--namez%Specify a name for the Cython module.)r\   z-Llibrary_dirsdirzPAdd a path to the list of library directories (can be specified multiple times).)r[   metavarrY   rW   r\   z-Iz	--includezPAdd a path to the list of include directories (can be specified multiple times).z-Sz--srczFAdd a path to the list of src files (can be specified multiple times).z--pgopgozEnable profile guided optimisation in the C compiler. Compiles the cell twice and executes it in between to generate a runtime profile.)r[   rY   rW   r\   z	--verbosequietstore_falseTz_Print debug information like generated .c/.cpp file location and exact gcc/g++ command invoked.c                 J   t          j        | j        |          }|                    d          r|n|dz   }t          j                            t                      d          }||t          j	        t          j
        t          f}t          j                            |          st	          j        |           |j        r|dz  }|j        r|t!          j                    fz  }|j        rt%          |j                  }nIdt'          j        t%          |                              d                                                    z   }t          j                            ||dz             }t          j                            ||| j        z             }	t          j                            |	          }
|j        p|
 }|j        r!t          j                            |          sd}d}|rg|                     |||||j        	          }|dS t9          |          d
k    sJ |d         }|| j        |<   |j        r|                     ||           d }dx}}	 t?          d
          5 }t?          d          5 }|                      |||j        rdnd|j                   ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   nS# tB          j"        j#        tB          j"        j$        f$ r+  | |             |            t          j%                   Y dS w xY w | |             |            t          j&                   tO          ||	          }| (                    |           |j        r	 tS          |d          5 }|*                                }ddd           n# 1 swxY w Y   tW          j,        | -                    |                    S # t\          $ rA}t_          dt          j%                   t_          |t          j%                   Y d}~dS d}~ww xY wdS )a  Compile and import everything from a Cython code cell.

        The contents of the cell are written to a `.pyx` file in the
        directory returned by `get_ipython_cache_dir()/cython` using a filename
        with the hash of the code. This file is then cythonized and compiled.
        The resulting module is imported and all of its symbols are injected
        into the user's namespace. The usage is similar to that of
        `%%cython_pyximport` but you don't have to pass a module name::

            %%cython
            def f(x):
                return 2.0*x

        To compile OpenMP codes, pass the required  `--compile-args`
        and `--link-args`.  For example with gcc::

            %%cython --compile-args=-fopenmp --link-args=-fopenmp
            ...

        To enable profile guided optimisation, pass the ``--pgo`` option.
        Note that the cell itself needs to take care of establishing a suitable
        profile when executed. This can be done by implementing the functions to
        optimise, and then calling them directly in the same cell on some realistic
        training data like this::

            %%cython --pgo
            def critical_function(data):
                for item in data:
                    ...

            # execute function several times to build profile
            from somewhere import some_typical_data
            for _ in range(100):
                critical_function(some_typical_data)

        In Python 3.5 and later, you can distinguish between the profile and
        non-profile runs as follows::

            if "_pgo_" in __name__:
                ...  # execute critical code here
        
cython)re   _cython_magic_rF   z.htmlTN)rf   r   r   c                 J    t          | |d           t          ||d           d S )NzContent of stdout:
zContent of stderr:
)r   )stdoutstderrwheres      r'   print_compiler_outputz2CythonMagics.cython.<locals>.print_compiler_outputI  s.    65*@AAA65*@AAAAAr(   r   r   )pgo_step_namerf   rG   zICython completed successfully but the annotated source could not be read.file)0r   parse_argstringrj   endswithospathjoinr   rN   version_info
executablecython_versionexistsmakedirsre   forcetimenamestrhashlibsha256encode	hexdigestso_extisfilerX   
_cythonizerf   lenr"   _profile_pgo_wrapperr   _build_extension	distutilserrorsr   	LinkErrorrn   rm   r   r9   rL   readr   HTMLclean_annotated_htmlOSErrorprint)r$   r?   r@   argscodelib_dirkeyrR   	html_filemodule_pathhave_moduleneed_cythonize	extension
extensionsrp   
get_stderr
get_stdoutr5   rT   annotated_htmles                        r'   rj   zCythonMagics.cython   s   d .t{DAA}}T**;ttt',,466AAT3+S^^Lw~~g&& 	!K   8 	8OC: 	" DIKK>!C9 	bdi..KK*W^CHHOOG<T<T-U-U-_-_-a-aaKGLL+*?@@	gll7K$+,EFFgnn[114_= 	&7>>),, &!%	 
	>dGTQUQ[\\J!tz??a''''"1I$/DS!x >)))W===	B 	B 	B
 #'&
Z	Q i: ^^ iz))!748:U%%QU]a]g * i i ii i i i i i i i i i i i i i ii i i i i i i i i i i i i i i  -y/?/IJ 	 	 	!!**,,

cjIII44	 	jjllJJLL#*EEEk;77   = 	OO)g666 .!%&VVXXN. . . . . . . . . . . . . . . |D$=$=n$M$MNNN  * * *
  28;
D D D Dacj))))))))))*		O 	Os   K
 #J>3(J'J>'J+	+J>.J+	/J>2K
 >KK
 KK
 
ALL1O N#O #N''O *N'+O 
P 6PP c           	         t          j         |          }|j        }d|z   }t          j                            ||dz             }t          |dd          5 }|                    t          j        d||dz                       ddd           n# 1 swxY w Y   |j	        |gz   |_	        ||_        | 
                    ||d	
           t          j                            ||| j        z             }t          ||           dS )a  
        Generate a .c file for a separate extension module that calls the
        module init function of the original module.  This makes sure that the
        PGO profiler sees the correct .o file of the final module, but it still
        allows us to import the module under a different name for profiling,
        before recompiling it into the PGO optimised module.  Overwriting and
        reimporting the same shared library is not portable.
        _pgo_z.crE   rF   rG   a1  
            #include "Python.h"
            extern PyMODINIT_FUNC PyInit_%(module_name)s(void);
            PyMODINIT_FUNC PyInit_%(pgo_module_name)s(void); /*proto*/
            PyMODINIT_FUNC PyInit_%(pgo_module_name)s(void) {
                return PyInit_%(module_name)s();
            }
            )rR   pgo_module_nameNr   )rq   )copyr   rv   rw   rx   rL   rM   textwrapr   sourcesr   r   r   )r$   r   r   rR   r   pgo_wrapper_c_filerT   so_module_paths           r'   r   z!CythonMagics._profile_pgo_wrappern  sd    Ii((	n!K/W\\'?T3IJJ$cG<<< 	UGGHO % #./RR%S T T U U U	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U &-1C0DD	(	iFFF g/LMM_n55555s   .BBBc           
         t           j                            ||dz             }|j        }t	          t          t          |j                            }d|v r+dd l}	|	                    |	
                                           t          |dd          5 }
|
                    |           d d d            n# 1 swxY w Y   t          ||g|z   ||j        |j        |j        |j        |j        rdnd	          }	 t'          ||j        d
t+          dt,          j        d                             }|j        |j        dv sJ |j        |d<   t3          |gfi |S # t4          $ r Y d S w xY w)NrD   numpyr   rE   rF   rG   zc++c)r   r   include_dirsrb   extra_compile_argsextra_link_args	librarieslanguageTr`   )rf   rX   r~   r_   )r   r`   r_   )rv   rw   rx   includelistmapr   srcr   ra   get_includerL   rM   r   rb   compile_args	link_argslibcplusdictrX   minrN   ry   r_   r   r   )r$   rR   r   r   r   rf   pyx_filec_include_dirsc_src_filesr   rT   r   optss                r'   r   zCythonMagics._cythonize  s   7<<v)=>>3sDH--..d??LLL!!%"3"3"5"5666(C'222 	aGGDMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	J,'*#0 Nh"j1UUc	
 	
 	
		"1c&6q&9::	  D ".*f4444)-)<%&i[11D111 	 	 	44	s%   B55B9<B99AE 
E'&E'c                 h   |                      ||||          }d }	 |s.t          j                            t          j        j                  }|                                 |s#|#t          j                            |           d S d S d S # |s"|!t          j                            |           w w w xY w)N)r   temp_dirrq   )_get_build_extensionr   logset_thresholdDEBUGrun)r$   r   r   r   rq   rf   build_extensionold_thresholds           r'   r   zCythonMagics._build_extension  s    33w 4 X X	; Q ) ; ;IM<O P P!!! ;]6++M:::::; ;665 ;]6++M::::;6s   AB
 
'B1c                    |j         j        }|dk    rR|j         j        }|snCd|v s
d|d         v rd}n2d|v s
d|d         v rd}n!d|v s
d|d         v rd}nd|v s
d|d         v rd}t                              |          }g }|rb||v r^fd||         D             }|j        D ]A}	|                    |	j        |	j        f           |	j        |z   |	_        |	j        |z   |	_        Bn"t          d|d	|d
t          j                   |S )Nunixclangr   r   r   zg++c                 <    g | ]}|                                S ))TEMPDIR)format)r.   rT   r   s     r'   r0   z/CythonMagics._add_pgo_flags.<locals>.<listcomp>  s'    KKKAQXXhX//KKKr(   zNo PGO z* configuration known for C compiler type ''rr   )compilercompiler_typecompiler_so
PGO_CONFIGgetr   ra   r   r   r   rN   rn   )
r$   r   	step_namer   r   compiler_cmdconfig
orig_flagsflagsr   s
      `      r'   _add_pgo_flagszCythonMagics._add_pgo_flags  s   '0>F""*3?L 	&L((G|A,F,F ',&&%<?*B*B %,&&%<?*B*B %,&&%<?*B*B %..
 	#i6))KKKK	9JKKKE,7 N N	!!9#?AZ"[\\\/8/Ke/S	,,5,E,M	))N
 EiiiYfYfYfgz# # # #r(   c                     	 | j         S # t          $ r6 |                                                     d          | _         | j         cY S w xY w)z*The extension suffix for compiled modules. )_so_extr4   r   get_ext_filename)r$   s    r'   r   zCythonMagics.so_ext  sY    	 < 	  	  	 4466GGKKDL<	 s   	 =A	A	c                 ^    	 ddl m} |                                 dS # t          $ r Y dS w xY w)zzclear distutils mkpath cache

        prevents distutils from skipping re-creation of dirs that have been removed
        r   )_path_createdN)distutils.dir_utilr   clearImportError)r$   r   s     r'   _clear_distutils_mkpath_cachez*CythonMagics._clear_distutils_mkpath_cache  sW    
	"888888 !!!!!  	 	 	DD	s    
,,c                   	
 |                                   t                      }|                                }	 |                    d           n# t          $ r Y nw xY w|                    |           s|| j        	r|
 G 	
fdd|          } ||          }|                                 r|_        |r||_	        ||g|_
        |S )Nz	setup.cfgc                        e Zd Z fdZdS )5CythonMagics._get_build_extension.<locals>._build_extc                 L     |                                 |            d S )N)build_extensions)r$   add_pgo_flagsbase_build_extrq   r   s    r'   r   zFCythonMagics._get_build_extension.<locals>._build_ext.build_extensions  s1    !M$x@@@"33D99999r(   N)__name__
__module____qualname__r   )r   r   rq   r   s   r'   
_build_extr     s=        : : : : : : : : : :r(   r   )r   r   find_config_filesremoverK   parse_config_filesr   finalize_options
build_temp	build_libr   )r$   r   r   r   rq   r   distconfig_filesr   r   r   s      ``    @@r'   r   z!CythonMagics._get_build_extension  s@   **,,,~~--//	,,,, 	 	 	D	--- 	H+ 	:'N: : : : : : : : : :Z : : :
 %*T**((*** 	2)1O& 	0(/O% *3O&s   A 
AAc                    g }|rBt          j        d| t           j        t           j        z            }|                    |           t          j        d| t           j        t           j        z                                d          }t          j        d          }|                                D ],}|	                    |          s|
                    |           -d                    |          S )aY  Clean up the annotated HTML source.

        Strips the link to the generated C or C++ file, which we do not
        present to the user.

        Returns an HTML snippet (no <html>, <head>, or <body>),
        containing only the style tag(s) and _contents_ of the body,
        appropriate for embedding multiple times in cell output.
        z<style.*</style>z<body[^>]*>(.+)</body>r   z&<p>Raw output: <a href="(.*)">(.*)</a>ri   )refindall	MULTILINEDOTALLextendsearchgroupcompile
splitlinesmatchra   rx   )htmlinclude_stylechunksstylesbodyrr?   s          r'   r   z!CythonMagics.clean_annotated_html  s      	"Z 2D",:RSSFMM&!!!y%tR\BI-E
 

%(( 	
 J?@@OO%% 	$ 	$D774== $d###yy   r(   )T)NNT)r   r   r   r    r9   r
   r   rU   r   argumentrj   r   r   r   r   propertyr   r   r   r   staticmethodr   __classcell__)r&   s   @r'   r   r   ]   sI       * * * * ** * * ? ? Z?" $! $! Z$!L %_$&&_l=	
>   _=j;  
 _ie/   _#MD&   _#MD&   _ie$  
 _xB  
 _hB  
 _gh   
 _h4   _>52   
 _k(B   
 _gh   
 _eL%b  
 _'-3  
 wO wO Z     	     	 	 	  	  '&PwOr6 6 6@       D
; 
; 
; 
;  8     X 
" 
" 
" .24$+/I   @ ! ! ! \! ! ! ! !r(   r   z-+, --cplusz--cplus    )
CYTHON_DOCCYTHON_INLINE_DOCCYTHON_PYXIMPORT_DOC)2__doc__iorv   r   rN   r   r   distutils.logr   r   getfilesystemencodingIO_ENCODINGr   distutils.corer   r   distutils.command.build_extr   IPython.corer   r   IPython.core.magicr   r	   r
   IPython.pathsr   r   IPython.utils.pathIPython.utils.textr   Shadowr   r{   Compiler.Errorsr   Inliner   r   Dependenciesr   Utilsr   r   r   r   r   rj   replacerU    r(   r'   <module>r$     s  $ $\ 
			 				 				 



       'c'))  2 2 2 2 2 2 2 2 1 1 1 1 1 1             ( ( ( ( ( ( ? ? ? ? ? ? ? ? ? ?93333333 9 9 9888888889 & % % % % % 2 2 2 2 2 2 * * * * * * / / / / / / / / # # # # # # / / / / / / / /
 %&?@SSS  }} 
 

 #5)
9  I! I! I! I! I!6 I! I! I!V .. vl)1#*7=-#H#HJ Jf\7?@@ = EFF   s   A" "A0/A0