
    hS                     l   S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	\R                  " 5       rSSKrSSKJrJr  SSKJr  SSKJr  SSKJr  SSKJrJrJr   SSKJr  SS	KJr  S
SKJ r!  S
SK"J#r#  SSK$J%r%J&r&  SSK'J(r(  S
SK)J*r*J+r+  SS// SQS.S/S/S.S.r,\,S   \,S'   \ " S S\5      5       r-\ R]                  \" \-R^                  R                   Ra                  SS5      5      \" \-RJ                  R                   5      \" \-Rb                  R                   5      S9r g! \ a	    SSKJr   Nf = f)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                     ^  \ rS rSrU 4S jrS r\S 5       r\S 5       r\	R                  " 5       \	R                  " SSSS	S
SS9\	R                  " SSSS
SS9\	R                  " SSSSSS9\	R                  " SSSSSSS9\	R                  " SSSSSSS9\	R                  " SS SSS!S9\	R                  " S"S#S$/ S%S9\	R                  " S&S$/ S'S9\	R                  " S(S)S$/ S*S9\	R                  " S+S,S-S.9\	R                  " S/S0S1S$/ S2S39\	R                  " S4S5S$/ S6S9\	R                  " S7S8S$/ S9S9\	R                  " S:S;SSS<S=9\	R                  " S>S?S@SASBS=9\SC 5       5       5       5       5       5       5       5       5       5       5       5       5       5       5       5       5       rSD rSMSE jrSNSF jrSG r\SH 5       rSI rSSSS\4SJ jr\SMSK j5       rSLrU =r$ )OCythonMagics]   c                 N   > [         TU ]  U5        0 U l        0 U l        SU l        g )NF)super__init___reloads_code_cache_pyximport_installed)selfshell	__class__s     S/var/www/fran/franai/venv/lib/python3.13/site-packages/Cython/Build/IpythonMagic.pyr!   CythonMagics.__init__`   s'    $)!    c                    UR                   nSU;   a  US   nO)U Vs/ s H  oDR                  S5      (       a  M  UPM     nnU H#  n U R                  R                  XBU   05        M%     g s  snf ! [         a    SU-  n[        U5      ef = f)N__all___z%'module' object has no attribute '%s')__dict__
startswithr&   pushKeyErrorAttributeError)r%   modulemdictkeyskmsgs         r(   _import_allCythonMagics._import_allf   s    #D$>u!LL,=AuD>A*

!H.  ?
  *=A$S))*s   A,A,A11Bc                 n    U R                   R                  nU R                   R                  n[        X#US9$ )al  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   CythonMagics.cython_inlinet   s/     zz((

""T>>r*   c                    UR                  5       nU(       d  [        S5      eUS-   n[        USSS9 nUR                  U5        SSS5        S[        R
                  ;  d  U R                  (       d  SSKnUR                  5         S	U l        X0R                  ;   a  U R                  U   nO,[        U5        [        R
                  U   nXpR                  U'   U R                  U5        g! , (       d  f       N= f)
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$   rJ   installr"   
__import__r8   )r%   r?   r@   module_namefnamefrJ   r3   s           r(   cython_pyximportCythonMagics.cython_pyximport   s      jjl899f$%w/1GGDM 0ckk)1J1J(,D%--']];/F {#[[-F)/MM+& # 0/s   C**
C8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.)r[   rY   r^   z-3language_level   NzSelect Python 3 syntax.)r]   r[   r\   rY   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]   metavarr[   rY   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]   r[   rY   r^   z	--verbosequietstore_falseTz_Print debug information like generated .c/.cpp file location and exact gcc/g++ command invoked.c           	         [         R                  " U R                  U5      nUR                  S5      (       a  UOUS-   n[        R
                  R                  [        5       S5      nXA[        R                  [        R                  [        4n[        R
                  R                  U5      (       d  [        R                  " U5        UR                  (       a  US-  nUR                  (       a  U[         R                   " 5       4-  nUR"                  (       a  [%        UR"                  5      nO?S[&        R(                  " [%        U5      R+                  S5      5      R-                  5       -   n[        R
                  R                  XWS-   5      n[        R
                  R                  XWU R.                  -   5      n	[        R
                  R1                  U	5      n
UR                  =(       d    U
(       + nUR2                  (       a&  [        R
                  R1                  U5      (       d  SnSnU(       ae  U R5                  XtXSUR6                  S	9nUc  g[9        U5      S
:X  d   eUS   nXpR:                  U'   UR                  (       a  U R=                  X5        S nS=nn [?        S
5       n[?        S5       nU RA                  XUR                  (       a  SOSUR6                  S9  SSS5        SSS5        U" U" 5       U" 5       [        RL                  5        [O        Xy5      nU RQ                  U5        UR2                  (       aI   [S        USS9 nURU                  5       nSSS5        [V        RX                  " U R[                  W5      5      $ g! , (       d  f       N= f! , (       d  f       N= f! [B        RD                  RF                  [B        RD                  RH                  4 a%    U" U" 5       U" 5       [        RJ                  5         gf = f! , (       d  f       N= f! [\         a:  n[_        S[        RJ                  S9  [_        U[        RJ                  S9   SnAgSnAff = f)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)rg   _cython_magic_rG   z.htmlTN)rh   r   r   c                 4    [        XS5        [        XS5        g )NzContent of stdout:
zContent of stderr:
)r   )stdoutstderrwheres      r(   print_compiler_output2CythonMagics.cython.<locals>.print_compiler_outputI  s    6*@A6*@Ar*   r   r   )pgo_step_namerh   rH   zICython completed successfully but the annotated source could not be read.file)0r   parse_argstringrl   endswithospathjoinr   rO   version_info
executablecython_versionexistsmakedirsrg   forcetimenamestrhashlibsha256encode	hexdigestso_extisfilerZ   
_cythonizerh   lenr#   _profile_pgo_wrapperr   _build_extension	distutilserrorsr   	LinkErrorrp   ro   r   r8   rM   readr   HTMLclean_annotated_htmlOSErrorprint)r%   r?   r@   argscodelib_dirkeyrS   	html_filemodule_pathhave_moduleneed_cythonize	extension
extensionsrr   
get_stderr
get_stdoutr3   rU   annotated_htmles                        r(   rl   CythonMagics.cython   s/   d ..t{{DA}}T**tt'',,46A3++S^^^Lww~~g&&KK 888OC:: DIIK>!C99dii.K*W^^CHOOG<T-U-_-_-aaKGGLL*?@	ggll7$++,EFggnn[14_==77>>),,!%	GQUQ[Q[\J!z?a'''"1I$/S!xx)))=	B
 #'&
Z	Q: ^z))!488%QU]a]g]g * i $   	jlJL#**Ek7 ==O)g6!%&VVXN 7 ||D$=$=n$MNN  $^     --y/?/?/I/IJ 	!*,
cjjI	 76 *
  28;

Dacjj)*sy   !N2 ,N!8/N'N!/N2 
P# P"P# 
N	N!!
N/+N2 /N2 2APP
P P# #
Q'-0Q""Q'c           	         [         R                   " U5      nUR                  nSU-   n[        R                  R	                  X$S-   5      n[        USSS9 nUR                  [        R                  " SX4S.-  5      5        SSS5        UR                  U/-   Ul	        XAl        U R                  XS	S
9  [        R                  R	                  X$U R                  -   5      n[        XG5        g! , (       d  f       Nq= f)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.crF   rG   rH   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();
            }
            )rS   pgo_module_nameNr   )rt   )copyr   ry   rz   r{   rM   rN   textwrapr   sourcesr   r   r   )r%   r   r   rS   r   pgo_wrapper_c_filerU   so_module_paths           r(   r   !CythonMagics._profile_pgo_wrappern  s     IIi(	nn!K/WW\\'T3IJ$cG<GGHOO % #.R%S T U = &--1C0DD	(iF g/LM_5# =<s   +C++
C9c                    [         R                  R                  X1S-   5      nUR                  n[	        [        [        UR                  5      5      nSU;   a#  SS Kn	UR                  U	R                  5       5        [        USSS9 n
U
R                  U5        S S S 5        [        UU/U-   UUR                  UR                  UR                   UR"                  UR$                  (       a  SOSS	9n ['        UUR(                  S
[+        S[,        R.                  S   5      S9nUR0                  b!  UR0                  S;   d   eUR0                  US'   [3        U/40 UD6$ ! , (       d  f       N= f! [4         a     g f = f)NrE   numpyr   rF   rG   rH   zc++c)r   r   include_dirsrd   extra_compile_argsextra_link_args	librarieslanguageTrb   )rh   rZ   r   ra   )r   rb   ra   )ry   rz   r{   includelistmapr   srcr   rc   get_includerM   rN   r   rd   compile_args	link_argslibcplusdictrZ   minrO   r|   ra   r   r   )r%   rS   r   r   r   rh   pyx_filec_include_dirsc_src_filesr   rU   r   optss                r(   r   CythonMagics._cythonize  sM   77<<v)=>3sDHH-.d?!!%"3"3"56(C'2aGGDM 3J,'**#00 NNhh"jjUc	
		"1c&6&6q&9:	D "".**f444)-)<)<%&i[1D11- 32.  		s   E0A+E- 
E*-
E:9E:c                 |   U R                  XX4S9nS n U(       d7  [        R                  R                  [        R                  R                  5      nUR                  5         U(       d$  Ub   [        R                  R                  U5        g g g ! U(       d$  Ub   [        R                  R                  U5        f f f = f)N)r   temp_dirrt   )_get_build_extensionr   logset_thresholdDEBUGrun)r%   r   r   r   rt   rh   build_extensionold_thresholds           r(   r   CythonMagics._build_extension  s    33 4 X	; ) ; ;IMM<O<O P!]6++M: 755]6++M: 75s   AB -B;c                    UR                   R                  nUS:X  ae  UR                   R                  nU(       d  OGSU;   d	  SUS   ;   a  SnO5SU;   d	  SUS   ;   a  SnO#SU;   d	  SUS   ;   a  SnOSU;   d	  SUS   ;   a  Sn[        R	                  U5      n/ nU(       a  X&;   a  Xb    Vs/ s H  oR                  US9PM     n	nUR                   HR  n
UR                  U
R                  U
R                  45        U
R                  U	-   U
l        U
R                  U	-   U
l	        MT     U$ [        SU< S	U< S
3[        R                  S9  U$ s  snf )Nunixclangr   r   r   zg++)TEMPDIRzNo PGO z* configuration known for C compiler type ''ru   )compilercompiler_typecompiler_so
PGO_CONFIGgetformatr   rc   r   r   r   rO   rp   )r%   r   	step_namer   r   compiler_cmdconfig
orig_flagsrU   flagsr   s              r(   _add_pgo_flagsCythonMagics._add_pgo_flags  sQ   '00>>F"*33??LL(G|A,F ',&%<?*B %,&%<?*B %,&%<?*B %.
i)9?9JK9JAXXhX/9JEK,77	!!9#?#?AZAZ"[\/8/K/Ke/S	,,5,E,E,M	) 8  iYfgzz# Ls   +Ec                      U R                   $ ! [         a3    U R                  5       R                  S5      U l         U R                   s $ f = f)z*The extension suffix for compiled modules. )_so_extr2   r   get_ext_filename)r%   s    r(   r   CythonMagics.so_ext  sE    	 << 	 446GGKDL<<	 s    :A
Ac                 R     SSK Jn  UR                  5         g! [         a     gf = f)zjclear 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_cache*CythonMagics._clear_distutils_mkpath_cache  s,    
	"8 !  		s    
&&c                   ^^^	^
 U R                  5         [        5       nUR                  5       n UR                  S5        UR                  U5        T(       d  UmU R                  m	T(       a  Um
 " U	U
UU4S jSU5      nU" U5      nUR                  5         T(       a  TUl        U(       a  X(l	        Ub  U/Ul
        U$ ! [         a     Nf = f)Nz	setup.cfgc                   (   > \ rS rSrU UUU4S jrSrg)5CythonMagics._get_build_extension.<locals>._build_exti  c                 <   > T" U TT5        TR                  U 5        g )N)build_extensions)r%   add_pgo_flagsbase_build_extrt   r   s    r(   r   FCythonMagics._get_build_extension.<locals>._build_ext.build_extensions  s    !$x@"33D9r*    N)__name__
__module____qualname____firstlineno__r   __static_attributes__)r   r   rt   r   s   r(   
_build_extr     s    : :r*   r   )r   r   find_config_filesremoverL   parse_config_filesr   finalize_options
build_temp	build_libr   )r%   r   r   r   rt   r   distconfig_filesr   r   r   s      ``    @@r(   r   !CythonMagics._get_build_extension  s    **,~--/	, 	-H++'N: :Z :
 %T*((*)1O&(/% *3O&/  		s   C 
CCc                    / nU(       aH  [         R                  " SU [         R                  [         R                  -  5      nUR	                  U5        [         R
                  " SU [         R                  [         R                  -  5      R                  S5      n[         R                  " S5      nUR                  5        H,  nUR                  U5      (       a  M  UR                  U5        M.     SR                  U5      $ )a)  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>rk   )refindall	MULTILINEDOTALLextendsearchgroupcompile
splitlinesmatchrc   r{   )htmlinclude_stylechunksstylesbodyrr?   s          r(   r   !CythonMagics.clean_annotated_html  s     ZZ 2D",,:RSFMM&!yy%tR\\BII-E

%( 	
 JJ?@OO%D774==d# & yy  r*   )r#   r$   r"   r   )T)NNT)r   r   r   r   r!   r8   r
   r   rV   r   argumentrl   r   r   r   r   propertyr   r   r   r   staticmethodr   r   __classcell__)r'   s   @r(   r   r   ]   s   ** ? ?" $! $!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 					 'PwOr6@ D
;8    
" .24$+/I@ ! !r*   r   z-+, --cplusz--cplus    )
CYTHON_DOCCYTHON_INLINE_DOCCYTHON_PYXIMPORT_DOC)2__doc__iory   r  rO   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   rl   replacerV   r   r*   r(   <module>r2     s6  $\ 
 	 	 
    '')  2 1   ( ? ?93 & 2 * / # /
 %&?@S }}

 #5)
9  I!6 I! I!V .. l))11#*7=-#HJ\77??@ = = E EF  M  989s   D$ $D32D3