
    wg6                     n   d Z ddlZddlZddlZddlZddlmZmZmZ ddl	m
Z
 ddlmZ 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mZ ddlmZmZmZmZmZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( dddZ) G d de*      Z+ G d d      Z, G d de,      Z- G d de,      Z. G d de,      Z/dddddZ0d Z1d  Z2e e(d!d      	 	 d-d"              Z3 e(d!d      d#        Z4 e
d$      Z5 e
d%      Z6 e
d&      Z7 e
d'      Z8 e
d(      Z9 e
d)      Z: G d* d+e,      Z;e e(dd      	 	 d.d,              Z<y)/aR  Module for compiling codegen output, and wrap the binary for use in
python.

.. note:: To use the autowrap module it must first be imported

   >>> from sympy.utilities.autowrap import autowrap

This module provides a common interface for different external backends, such
as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are
implemented) The goal is to provide access to compiled binaries of acceptable
performance with a one-button user interface, e.g.,

    >>> from sympy.abc import x,y
    >>> expr = (x - y)**25
    >>> flat = expr.expand()
    >>> binary_callable = autowrap(flat)
    >>> binary_callable(2, 3)
    -1.0

Although a SymPy user might primarily be interested in working with
mathematical expressions and not in the details of wrapping tools
needed to evaluate such expressions efficiently in numerical form,
the user cannot do so without some understanding of the
limits in the target language. For example, the expanded expression
contains large coefficients which result in loss of precision when
computing the expression:

    >>> binary_callable(3, 2)
    0.0
    >>> binary_callable(4, 5), binary_callable(5, 4)
    (-22925376.0, 25165824.0)

Wrapping the unexpanded expression gives the expected behavior:

    >>> e = autowrap(expr)
    >>> e(4, 5), e(5, 4)
    (-1.0, 1.0)

The callable returned from autowrap() is a binary Python function, not a
SymPy object.  If it is desired to use the compiled function in symbolic
expressions, it is better to use binary_function() which returns a SymPy
Function object.  The binary callable is attached as the _imp_ attribute and
invoked when a numerical evaluation is requested with evalf(), or with
lambdify().

    >>> from sympy.utilities.autowrap import binary_function
    >>> f = binary_function('f', expr)
    >>> 2*f(x, y) + y
    y + 2*f(x, y)
    >>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2})
    0.e-110

When is this useful?

    1) For computations on large arrays, Python iterations may be too slow,
       and depending on the mathematical expression, it may be difficult to
       exploit the advanced index operations provided by NumPy.

    2) For *really* long expressions that will be called repeatedly, the
       compiled binary should be significantly faster than SymPy's .evalf()

    3) If you are generating code with the codegen utility in order to use
       it in another project, the automatic Python wrappers let you test the
       binaries immediately from within SymPy.

    4) To create customized ufuncs for use with numpy arrays.
       See *ufuncify*.

When is this module NOT the best approach?

    1) If you are really concerned about speed or memory optimizations,
       you will probably get better results by working directly with the
       wrapper tools and the low level code.  However, the files generated
       by this utility may provide a useful starting point and reference
       code. Temporary files will be left intact if you supply the keyword
       tempdir="path/to/files/".

    2) If the array computation can be handled easily by numpy, and you
       do not need the binaries for another project.

    N)STDOUTCalledProcessErrorcheck_output)Template)warn)cacheit)Lambda)Eq)DummySymbol)IdxIndexedBase)	make_routineget_code_generatorOutputArgumentInOutArgumentInputArgumentCodeGenArgumentListErrorResult
ResultBase
C99CodeGen)iterable)implemented_function)doctest_depends_on)f2pygfortrangcc)numpy)exemodulesc                       e Zd Zy)CodeWrapErrorN)__name__
__module____qualname__     ]/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/utilities/autowrap.pyr"   r"   l   s    r'   r"   c                   ~    e Zd ZdZdZdZdZed        Zed        Z	dg dfd	Z
ed
        Zed        Zd ZddZd Zy)CodeWrapperzBase Class for code wrapperswrapped_codewrapper_moduler   c                 @    | j                   dt        j                  S N_)	_filenamer*   _module_counterselfs    r(   filenamezCodeWrapper.filenamev   s    ..+*E*EFFr'   c                 @    | j                   dt        j                  S r.   )_module_basenamer*   r1   r2   s    r(   module_namezCodeWrapper.module_namez   s    //1L1LMMr'   NFc                 >    || _         || _        || _        | | _        y)z8
        generator -- the code generator to use
        N)	generatorfilepathflagsquiet)r3   r9   r:   r;   verboses        r(   __init__zCodeWrapper.__init__~   s"     # 
 [
r'   c                 ,    t        | j                        S Nboolr:   r2   s    r(   include_headerzCodeWrapper.include_header       DMM""r'   c                 ,    t        | j                        S r@   rA   r2   s    r(   include_emptyzCodeWrapper.include_empty   rD   r'   c                     |j                  |       | j                  j                  || j                  d| j                  | j
                         y NT)appendr9   writer4   rC   rF   )r3   main_routineroutiness      r(   _generate_codezCodeWrapper._generate_code   s<    %dmmT4+>+>	 r'   c                 v   |xs g }| j                   r*t        j                  j                  | j                         }nt	        j
                  d      }t        j                  |t        j                        st        j                  |       t        j                         }t        j                  |       	 t        j                  j                  |       | j                  ||       | j                  |       | j                  |       t!        | j"                        }t        j                  j%                  |       t&        xj(                  dz  c_        t        j                  |       | j                   s	 t+        j,                  |       | j1                  ||j2                        S # t.        $ r Y 'w xY w# t        j                  j%                  |       t&        xj(                  dz  c_        t        j                  |       | j                   s&	 t+        j,                  |       w # t.        $ r Y w w xY ww xY w)N_sympy_compile   )r:   ospathabspathtempfilemkdtempaccessF_OKmkdirgetcwdchdirsysrI   rM   _prepare_files_process_files
__import__r7   remover*   r1   shutilrmtreeOSError_get_wrapped_functionname)r3   routinehelpersworkdiroldworkmods         r(   	wrap_codezCodeWrapper.wrap_code   s   -R==ggoodmm4G&&'78Gyy"''*HHW))+
	HHOOG$1((T--.CHHOOG$''1,'HHW==MM'*
 ))#w||<<	   HHOOG$''1,'HHW==MM'*  !sD   5A(F7 7F( (	F43F47AH8H('H8(	H41H83H44H8c           	      :   | j                   }|j                  | j                         	 t        |t              }| j                  st        |       y y # t
        $ r>}t        ddj                  |      d|j                  j                  d            d }~ww xY w)N)stderrzError while executing command:  z. Command output is:
zutf-8)commandextendr;   r   r   r   r"   joinoutputdecoder<   print)r3   re   rn   	retoutputes        r(   r]   zCodeWrapper._process_files   s    ,,tzz"	B$WV<I
 zz) 	 " 	BHHW%qxxw'?AB B	Bs   A 	B9BBr@   )r#   r$   r%   __doc__r0   r6   r1   propertyr4   r7   r>   rC   rF   rM   rj   r]   r&   r'   r(   r*   r*   p   s    &I'OG G N N ,0r5 ! # # # # =:
r'   r*   c                   6    e Zd ZdZdZd Zd Zd Zed        Z	y)DummyWrapperz/Class used for testing independent of backends z# dummy module for testing of SymPy
def %(name)s():
    return "%(expr)s"
%(name)s.args = "%(args)s"
%(name)s.returns = "%(retvals)s"
c                      y r@   r&   r3   re   s     r(   r\   zDummyWrapper._prepare_files       r'   c                    t        d| j                  z  d      5 }dj                  |j                  D cg c]  }t	        |j
                         c}      }t        d |j                        }g }|j                  D ]?  }t        |t              r|j                  d       %|j                  |j                         A t        t        j                  |j                  |dj                  |D 	cg c]  }	t	        |	j                         c}	      dj                  |D cg c]  }t	        |       c}      dz  d|       d d d        y c c}w c c}	w c c}w # 1 sw Y   y xY w)	Nz%s.pyw, c                 $    t        | t               S r@   )
isinstancer   )xs    r(   <lambda>z-DummyWrapper._generate_code.<locals>.<lambda>   s    
>)# %# r'   nameless)rd   exprargsretvals )endfile)openr7   rp   result_variablesstrr   filter	argumentsr   r   rI   
result_varrs   ry   templaterd   )
r3   re   rf   fresprintedr   r   valas
             r(   rM   zDummyWrapper._generate_code   s*   'D,,,c2 	aii*1*B*BC3SXXCEG  #$+$5$57DG// 3c6*NN:.NN3>>2	3 ,''		"=13qvv;"=>99'%B3c#h%BC	+ 
 A	 	C #>%B#	 	s5   EE
BE-E	EE0EEE#c                      y r@   r&   r{   s     r(   r]   zDummyWrapper._process_files   r|   r'   c                     t        ||      S r@   getattrclsri   rd   s      r(   rc   z"DummyWrapper._get_wrapped_function       sD!!r'   N)
r#   r$   r%   rv   r   r\   rM   r]   classmethodrc   r&   r'   r(   ry   ry      s/    9H* " "r'   ry   c                        e Zd ZdZdZdddiiZdZdZdZd	Z	 fd
Z
ed        Zej                  fdZed        Zd Zd Zd Zd Zd Zd Z xZS )CythonCodeWrapperzWrapper that uses Cythona  from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize
cy_opts = {cythonize_options}
{np_import}
ext_mods = [Extension(
    {ext_args},
    include_dirs={include_dirs},
    library_dirs={library_dirs},
    libraries={libraries},
    extra_compile_args={extra_compile_args},
    extra_link_args={extra_link_args}
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
compiler_directiveslanguage_level3z(import numpy as np
cimport numpy as np

z5cdef extern from '{header_file}.h':
    {prototype}

z1def {name}_c({arg_string}):

{declarations}{body}z-std=c99c                    |j                  dg       | _        |j                  dg       | _        |j                  dg       | _        |j                  dg       | _        | j                  j                  | j                         |j                  dg       | _        |j                  d| j                        | _        d| _	        t        | ,  |i | y)	a  Instantiates a Cython code wrapper.

        The following optional parameters get passed to ``setuptools.Extension``
        for building the Python extension module. Read its documentation to
        learn more.

        Parameters
        ==========
        include_dirs : [list of strings]
            A list of directories to search for C/C++ header files (in Unix
            form for portability).
        library_dirs : [list of strings]
            A list of directories to search for C/C++ libraries at link time.
        libraries : [list of strings]
            A list of library names (not filenames or paths) to link against.
        extra_compile_args : [list of strings]
            Any extra platform- and compiler-specific information to use when
            compiling the source files in 'sources'.  For platforms and
            compilers where "command line" makes sense, this is typically a
            list of command-line arguments, but for other platforms it could be
            anything. Note that the attribute ``std_compile_flag`` will be
            appended to this list.
        extra_link_args : [list of strings]
            Any extra platform- and compiler-specific information to use when
            linking object files together to create the extension (or to create
            a new static Python interpreter). Similar interpretation as for
            'extra_compile_args'.
        cythonize_options : [dictionary]
            Keyword arguments passed on to cythonize.

        include_dirslibrary_dirs	librariesextra_compile_argsextra_link_argscythonize_optionsFN)pop_include_dirs_library_dirs
_libraries_extra_compile_argsrI   std_compile_flag_extra_link_args_cythonize_options_need_numpysuperr>   )r3   r   kwargs	__class__s      r(   r>   zCythonCodeWrapper.__init__  s    B $ZZ;#ZZ; **["5#)::.BB#G   ''(=(=> &

+<b A"(**-@$BYBY"Z $)&)r'   c                 .    t         j                  dddg}|S Nsetup.py	build_extz	--inplacer[   
executabler3   rn   s     r(   rn   zCythonCodeWrapper.command<      >>:{KHr'   c                 r   | j                   dz   }| j                  d| j                  j                  }t	        t
        j                  j                  ||      d      5 }| j                  |g|| j                         d d d        t        | j                         t        ||g      g}| j                  rd}| j                  j                  d       nd}t	        t
        j                  j                  |d      d      5 }t        | j                        j                  dd      }|j                  | j                   j#                  d	j                  |      ||| j$                  | j&                  | j(                  | j*                  | j,                  
             d d d        y # 1 sw Y   $xY w# 1 sw Y   y xY w)Nz.pyx.r~   zimport numpy as np
znp.get_include()r   r   z'np.get_include()'r   )ext_args	np_importr   r   r   r   r   r   )r7   r4   r9   code_extensionr   rQ   rR   rp   dump_pyxreprr   r   rI   r   replacerJ   setup_templateformatr   r   r   r   r   )	r3   re   	build_dirpyxfilenamecodefilenamer   r   r   includess	            r(   r\   z CythonCodeWrapper._prepare_filesA  ss   &&/"&--1N1NO "'',,y+6< 	7MM7)Q6	7 ))*D+|1L,MN.I%%&89I"'',,y*5s; 	q4--.667K7IKHGGD''..8,#%!////#'#;#; $ 5 5"&"9"9 / 	 		 		7 	7	 	s   F >BF- F*-F6c                      t        ||dz         S )N_cr   r   s      r(   rc   z'CythonCodeWrapper._get_wrapped_function`  s    sD4K((r'   c                 ~    g }g }|D ]7  } j                   j                  |      }|j                   j                  j	                  ||              j                  |j                        \  }}	}
}|j                  }dj                   fd|	D              }g }|j                         D ]Z  \  }} j                  |      }|D cg c]  } j                  |       c}\  }}|j                  dj	                  |||             \ |j                  |
D cg c]"  }dj	                   j                  |            $ c}       dj                  |      }|r|dz   }dj                  |j                  D cg c]  } j                  |       c}      }dj                  |D cg c]  } j                  |j                         c}      }|j                  rd|j                  d|d	}|r$|dz   |z   }nd
|j                  d|d}|dz   |z   }|j                   j                   j	                  ||||             :  j"                  r|j%                   j&                         |j%                  dj                  |             |j%                  dj                  |             yc c}w c c}w c c}w c c}w )a  Write a Cython file with Python wrappers

        This file contains all the definitions of the routines in c code and
        refers to the header file.

        Arguments
        ---------
        routines
            List of Routine instances
        f
            File-like object to write the file to
        prefix
            The filename prefix, used to refer to the proper header file.
            Only the basename of the prefix is used.
        )header_file	prototyper   c              3   @   K   | ]  }j                  |        y wr@   )_prototype_arg).0argr3   s     r(   	<genexpr>z-CythonCodeWrapper.dump_pyx.<locals>.<genexpr>  s     "O4#6#6s#;"Os   z    cdef {} = {}.shape[{}]z    cdef {}
z    return ()z    z)
)rd   
arg_stringdeclarationsbodyN)r9   get_prototyperI   
pyx_headerr   _partition_argsr   rd   rp   itemsr   _string_varro   _declare_arg	_call_argresultspyx_funcr   rJ   pyx_imports)r3   rL   r   prefixheaders	functionsre   r   py_retspy_argspy_locpy_infrd   r   
local_decsr   r   protovmatindr   r   args_crretsr   s   `                          r(   r   zCythonCodeWrapper.dump_pyxd  s}     	 %	;G44W=I NN4??11f<E 2 G H 04/C/CGDUDU/V,GWff <<D"Ow"OOJ J"LLN XS++C09<=AD,,Q/=S!!">"E"EeSRU"VWX SYZa}33D4E4Ea4HIZ[99Z0L+d2 YY7;L;LMaq 1MNF99H1d..qvv6HID.5llFC$;-D 
 *1v>m+d2T]]11t
!-D 2 : ;I%	;P GGD$$%			'"#			)$%5 >Z  NHs   J+'J0
6J5
$"J:
c           	         g }g }g }i }|D ]  }t        |t              r#|j                  |       |j                  |       nDt        |t              r#|j                  |       |j                  |       n|j                  |       t        |t        t        f      s|j
                  s|j
                  D cg c]
  }|d   dz    }}t        |      D 	cg c]  \  }	}t        |t              r|	|f }
}	}|
D ]  \  }	}|j                  |	f||<    
 |D ]/  }|j                  |v s|j                  |j                        ||<   1 |D cg c]	  }||vs| }}||||fS c c}w c c}}	w c c}w ))Group function arguments into categories.rP   )
r   r   rI   r   r   
dimensions	enumerater   rd   r   )r3   r   r   
py_returns	py_localspy_inferredr   ddimsisym_dimsr   s               r(   r   z!CythonCodeWrapper._partition_args  su   
	 	3C#~.!!#&  %C/!!#&s#s# #}=>3>>*-..9Q!q991:4 3v1&q&1 F 3 3& 3FQ&)hh]KN3	3"  	=Cxx;&#.??388#<C 	= &>+)=1>>7I{:: :3 ?s   8E$E)	E/E/c                 &   d}ddd}|j                  d      }|j                  rNd| _        t        |j                        }||   }|j	                  ||| j                  |j                              S |d| j                  |j                        S )	Nz'np.ndarray[{mtype}, ndim={ndim}] {name}znp.double_tznp.int_t)doubleintcT)mtypendimrd   rm   )get_datatyper   r   lenr   r   rd   )r3   r   mat_decnp_typestr  r  s          r(   r   z CythonCodeWrapper._prototype_arg  s    ;+%'S!>>#Ds~~&DQKE>>Dt?O?OPSPXPX?Y>ZZ!1!1#((!;<<r'   c                       j                  |      }|j                  r?ddj                   fd|j                  D              z   dz   }|dj                  |      z   S |dz   S )Nr   ,c              3   L   K   | ]  }j                  |d    d z           yw)rP   N)r   )r   r   r3   s     r(   r   z1CythonCodeWrapper._declare_arg.<locals>.<genexpr>  s$     "V!4#3#3AaD1H#="Vs   !$r   z = np.empty({shape}))shapez = 0)r   r   rp   r   )r3   r   r   r  s   `   r(   r   zCythonCodeWrapper._declare_arg  sa    ##C(>>#(("Vs~~"VVVY\\E188u8EEE6>!r'   c                 <   |j                   r<|j                  d      }dj                  || j                  |j                              S t        |t              r*dj                  | j                  |j                              S | j                  |j                        S )Nr  z<{}*> {}.dataz&{})r   r  r   r   rd   r   r   )r3   r   r  s      r(   r   zCythonCodeWrapper._call_arg  sx    >>  %A"))!T-=-=chh-GHHZ(<< 0 0 :;;##CHH--r'   c                 R    | j                   j                  j                  } ||      S r@   )r9   printerdoprint)r3   varr  s      r(   r   zCythonCodeWrapper._string_var  s!    ..((00s|r'   )r#   r$   r%   rv   r   r   r   r   r   r   r>   rw   rn   rQ   curdirr\   r   rc   r   r   r   r   r   r   __classcell__r   s   @r(   r   r      s    "N" 01AC0HI	" 
	 
	  "+*Z   13		 > ) )>&@;<=".r'   r   c                   H     e Zd ZdZ fdZed        Zd Zed        Z	 xZ
S )F2PyCodeWrapperzWrapper that uses f2pyc                     g d}d}|D ]@  }||j                         v rt        |j                  |             |j                  |d        B t	        |   |i | y )Nr   r   r   r   r   zGThe compilation option kwarg {} is not supported with the f2py backend.keysr   r   r   r   r>   r3   r   r   ext_keysmsgkr   s         r(   r>   zF2PyCodeWrapper.__init__  sb    =  	 AFKKM!SZZ]#JJq$	 
 	$)&)r'   c                     | j                   dz   | j                  j                  z   }dd| j                  |g}t        j
                  ddg|z   }|S )Nr   z-cz-mz)import numpy.f2py as f2py2e;f2py2e.main())r4   r9   r   r7   r[   r   )r3   r4   r   rn   s       r(   rn   zF2PyCodeWrapper.command  sO    ==3&)F)FFdD,,h7>>4)TUVZZr'   c                      y r@   r&   r{   s     r(   r\   zF2PyCodeWrapper._prepare_files  s    r'   c                     t        ||      S r@   r   r   s      r(   rc   z%F2PyCodeWrapper._get_wrapped_function   r   r'   )r#   r$   r%   rv   r>   rw   rn   r\   r   rc   r  r  s   @r(   r  r    s8     *   " "r'   r  )C99C89C)F95)CYTHONF2PYNUMPYDUMMYc                 t    t         j                  | j                         d      }|st        d| z         |d   S )z6For a given backend, return the top choice of languageFUnrecognized backend: r   )_lang_lookupgetupper
ValueError)backendlangss     r(   _infer_languager5    s7    W]]_e4E1G;<<8Or'   c                     t         j                  | j                         d      }|st        d| z         |j                         |vrt        dj	                  | |            y)z5Throws error if backend and language are incompatibleFr.  z+Backend {} and language {} are incompatibleN)r/  r0  r1  r2  r   )r3  languager4  s      r(   _validate_backend_languager8    sb    W]]_e4E1G;<<~~u$ )*0&(*CE 	E %r'   )r   r   c	                    |rt        |t              st        ||       nt        |      }t	        |      r#t        |      dk7  rt	        |d         r|r|nd}n|r|gnd}t	        |t              rt        |      n|}|t        |d      }t        t        t        d|j                            }
 |
|||r|nd|fi |	}g }|D ](  \  }}}|j                  |j                  |||             * |D ];  \  }}}| j                  |      st!        ||d      }| j#                  | ||       } = 	 |j                  d	| |      }|j-                  ||
      S # t$        $ r_}g }|j&                  D ].  }t        |t(              s |j                  |j*                         0 |j                  d	| ||z         }Y d}~vd}~ww xY w)ah  Generates Python callable binaries based on the math expression.

    Parameters
    ==========

    expr
        The SymPy expression that should be wrapped as a binary routine.
    language : string, optional
        If supplied, (options: 'C' or 'F95'), specifies the language of the
        generated code. If ``None`` [default], the language is inferred based
        upon the specified backend.
    backend : string, optional
        Backend used to wrap the generated code. Either 'f2py' [default],
        or 'cython'.
    tempdir : string, optional
        Path to directory for temporary files. If this argument is supplied,
        the generated code and the wrapper input files are left intact in the
        specified path.
    args : iterable, optional
        An ordered iterable of symbols. Specifies the argument sequence for the
        function.
    flags : iterable, optional
        Additional option flags that will be passed to the backend.
    verbose : bool, optional
        If True, autowrap will not mute the command line backends. This can be
        helpful for debugging.
    helpers : 3-tuple or iterable of 3-tuples, optional
        Used to define auxiliary expressions needed for the main expr. If the
        main expression needs to call a specialized function it should be
        passed in via ``helpers``. Autowrap will then make sure that the
        compiled main expression can link to the helper routine. Items should
        be 3-tuples with (<function_name>, <sympy_expression>,
        <argument_tuple>). It is mandatory to supply an argument sequence to
        helper routines.
    code_gen : CodeGen instance
        An instance of a CodeGen subclass. Overrides ``language``.
    include_dirs : [string]
        A list of directories to search for C/C++ header files (in Unix form
        for portability).
    library_dirs : [string]
        A list of directories to search for C/C++ libraries at link time.
    libraries : [string]
        A list of library names (not filenames or paths) to link against.
    extra_compile_args : [string]
        Any extra platform- and compiler-specific information to use when
        compiling the source files in 'sources'.  For platforms and compilers
        where "command line" makes sense, this is typically a list of
        command-line arguments, but for other platforms it could be anything.
    extra_link_args : [string]
        Any extra platform- and compiler-specific information to use when
        linking object files together to create the extension (or to create a
        new static Python interpreter).  Similar interpretation as for
        'extra_compile_args'.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.utilities.autowrap import autowrap
    >>> expr = ((x - y + z)**(13)).expand()
    >>> binary_func = autowrap(expr)
    >>> binary_func(1, 4, 2)
    -1.0

    r   r&   )excludeNautowrap)r*  r)  r,  dummy)r3  autofuncrf   )r   typer8  r5  r   r  setlistr   r  r   ry   r1  rI   re   hasbinary_functionsubsr   missing_argsr   rd   rj   )r   r7  r3  tempdirr   r;   r=   rf   code_genr   CodeWrapperClasscode_wrapperhelpsname_hexpr_hargs_hre   ru   new_argsmissings                       r(   r;  r;     s   J (D)&w9"7+ S\Q.8GAJ3G$'"&7)B!$44:$D%h
;  # mmo	
 $Hgu2$+7/57L E") ?X%%fff=>? #* 688F$VVWEF99VVV_5D6F"":tT: !!'5!99 $ 	F ~~ 	*Gg~6OOGLL)	* "":tTH_E	Fs   /E 	F=AF88F=c                 2    t        |fi |}t        | |      S )aM  Returns a SymPy function with expr as binary implementation

    This is a convenience function that automates the steps needed to
    autowrap the SymPy expression and attaching it to a Function object
    with implemented_function().

    Parameters
    ==========

    symfunc : SymPy Function
        The function to bind the callable to.
    expr : SymPy Expression
        The expression used to generate the function.
    kwargs : dict
        Any kwargs accepted by autowrap.

    Examples
    ========

    >>> from sympy.abc import x, y
    >>> from sympy.utilities.autowrap import binary_function
    >>> expr = ((x - y)**(25)).expand()
    >>> f = binary_function('f', expr)
    >>> type(f)
    <class 'sympy.core.function.UndefinedFunction'>
    >>> 2*f(x, y)
    2*f(x, y)
    >>> f(x, y).evalf(2, subs={x: 1, y: 2})
    -1.0

    )r;  r   )symfuncr   r   binarys       r(   rC  rC    s!    B d%f%F00r'   z#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include ${include_file}

static PyMethodDef ${module}Methods[] = {
        {NULL, NULL, 0, NULL}
};z6*((double *)out${outnum}) = ${funcname}(${call_args});aD  #ifdef NPY_1_19_API_VERSION
static void ${funcname}_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data)
#else
static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
#endif
{
    npy_intp i;
    npy_intp n = dimensions[0];
    ${declare_args}
    ${declare_steps}
    for (i = 0; i < n; i++) {
        ${outcalls}
        ${step_increments}
    }
}
PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc};
static char ${funcname}_types[${n_types}] = ${types}
static void *${funcname}_data[1] = {NULL};a  #if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,
    "${module}",
    NULL,
    -1,
    ${module}Methods,
    NULL,
    NULL,
    NULL,
    NULL
};

PyMODINIT_FUNC PyInit_${module}(void)
{
    PyObject *m, *d;
    ${function_creation}
    m = PyModule_Create(&moduledef);
    if (!m) {
        return NULL;
    }
    import_array();
    import_umath();
    d = PyModule_GetDict(m);
    ${ufunc_init}
    return m;
}
#else
PyMODINIT_FUNC init${module}(void)
{
    PyObject *m, *d;
    ${function_creation}
    m = Py_InitModule("${module}", ${module}Methods);
    if (m == NULL) {
        return;
    }
    import_array();
    import_umath();
    d = PyModule_GetDict(m);
    ${ufunc_init}
}
#endifa  ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out},
            PyUFunc_None, "${module}", ${docstring}, 0);
    PyDict_SetItemString(d, "${funcname}", ufunc${ind});
    Py_DECREF(ufunc${ind});a(  from setuptools.extension import Extension
from setuptools import setup

from numpy import get_include

if __name__ == "__main__":
    setup(ext_modules=[
        Extension('${module}',
                  sources=['${module}.c', '${filename}.c'],
                  include_dirs=[get_include()])])
c                   j     e Zd ZdZ fdZed        ZddZd Zd Z	e
d        Zd Zdd	Zd
 Z xZS )UfuncifyCodeWrapperzWrapper for Ufuncifyc                     g d}d}|D ]@  }||j                         v rt        |j                  |             |j                  |d        B t	        |   |i | y )Nr  zHThe compilation option kwarg {} is not supported with the numpy backend.r  r  s         r(   r>   zUfuncifyCodeWrapper.__init__$  sb    =  	 AFKKM!SZZ]#JJq$	 
 	$)&)r'   c                 .    t         j                  dddg}|S r   r   r   s     r(   rn   zUfuncifyCodeWrapper.command2  r   r'   c                 Z   ||ng }dt        t        |      t        |      z         z   }| j                  xs t        j                  d      }t        j                  |t
        j                        st        j                  |       t        j                         }t        j                  |       	 t        j                  j                  |       | j                  ||       | j                  ||       | j!                  |       t#        | j$                        }t        j                  j'                  |       t(        xj*                  dz  c_        t        j                  |       | j                  s	 t-        j.                  |       | j3                  ||      S # t0        $ r Y w xY w# t        j                  j'                  |       t(        xj*                  dz  c_        t        j                  |       | j                  s&	 t-        j.                  |       w # t0        $ r Y w w xY ww xY w)Nwrapped_rO   rP   )r   idr:   rT   rU   rQ   rV   rW   rX   rY   rZ   r[   rR   rI   rM   r\   r]   r^   r7   r_   r*   r1   r`   ra   rb   rc   )r3   rL   rf   funcnamerg   rh   ri   s          r(   rj   zUfuncifyCodeWrapper.wrap_code7  s   
 %0'bBxL2g;$> ??--E8#3#34D#Eyy"''*HHW))+
	HHOOG$'2(3)T--.CHHOOG$''1,'HHW==MM'*
 ))#x88	   HHOOG$''1,'HHW==MM'*  !sD   0A)F) 3F 	F&%F&)AH*HH*	H&#H*%H&&H*c                     ||z   }| j                   j                  || j                  d| j                  | j                         y rH   )r9   rJ   r4   rC   rF   )r3   main_routineshelper_routinesall_routiness       r(   rM   z"UfuncifyCodeWrapper._generate_codeX  s:    $6$--t/B/B	 r'   c                    | j                   dz   }t        |d      5 }| j                  ||| j                  |       d d d        t        dd      5 }| j	                  |       d d d        y # 1 sw Y   0xY w# 1 sw Y   y xY w)Nz.cr~   )rZ  r   )r7   r   dump_cr4   
dump_setup)r3   rL   rZ  r   r   s        r(   r\   z"UfuncifyCodeWrapper._prepare_files^  s     ''$.,$ 	GKK!T]]XKF	G *c" 	aOOA	 			G 	G	 	s    A+A7+A47B c                     t        ||      S r@   r   r   s      r(   rc   z)UfuncifyCodeWrapper._get_wrapped_functioni  r   r'   c                 |    t         j                  | j                  | j                        }|j	                  |       y )N)moduler4   )_ufunc_setup
substituter7   r4   rJ   )r3   r   setups      r(   ra  zUfuncifyCodeWrapper.dump_setupm  s2    ''t/?/?15 ( @	r'   c                    |+t        |      dk(  r|d   j                  }nd}t        |      g }g }g }| j                  }	dj	                  |      }
t
        j                  |
|	      }|}d}| j                  |d   j                        \  }}t        |      }t        |      }d}t        |      D cg c]  }|j	                  d||       }}|j                  t        |      D cg c]  }|j	                  d	|||z          c}       d
j                  |      }d}t        |      D cg c]  }|j	                  d||       }}|j                  t        |      D cg c]  }|j	                  d	|||z          c}       d
j                  |      }d}dj                  t        |      D cg c]  }|j	                  |       c}      }d}t        |      D cg c]  }|j	                  d|       }}|j                  t        |      D cg c]  }|j	                  d	||       c}       dj                  |      }||z   }ddj                  dg|z        z   dz   }d}|j                  dj	                  |             t        j                  |	|||||      }|j                  |       t        |      D cg c]'  }t        j                  ||||   j                        ) } }t        j                  |	|||||||dj                  |       	      }!|j                  |!       dj                  |      }!d
j                  |      }d
j                  |      }t         j                  |	||      }"||!|"g}#|j#                  dj                  |#             yc c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w )a  Write a C file with Python wrappers

        This file contains all the definitions of the routines in c code.

        Arguments
        ---------
        routines
            List of Routine instances
        f
            File-like object to write the file to
        prefix
            The filename prefix, used to name the imported module.
        funcname
            Name of the main function to be returned.
        NrP   r   z7funcname must be specified for multiple output routinesz"{}.h")include_filerd  zchar *{0}{1} = args[{2}];inoutz
    z"npy_intp {0}{1}_step = steps[{2}];z*(double *)in{0}r   z{0}{1} += {0}{1}_step;z	
        {
NPY_DOUBLEz};z "Created in SymPy with Ufuncify"zPyObject *ufunc{};)rd  rZ  	docstringn_inn_outr   )outnum	call_argsrZ  )	rd  rZ  declare_argsdeclare_stepsrr  step_incrementsn_typestypesoutcallsz

)rd  
ufunc_initfunction_creation)r  rd   r2  r7   r   
_ufunc_toprf  r   r   rangero   rp   rI   _ufunc_init_form_ufunc_outcalls_ufunc_body_ufunc_bottomrJ   )$r3   rL   r   r   rZ  r   r   rz  ry  rd  ri  toprd   r_indexpy_inr/   ro  rp  formr   arg_decsrs  	step_decsrt  r   rr  	step_incsru  rv  rw  rn  	init_formrx  r   bottomtexts$                                       r(   r`  zUfuncifyCodeWrapper.dump_cr  s     8}!#A;++O o%	
!!!((0##f#M ''(=(=>q5zH +5:4[ADKKa+AAeM1UAqv6MN}}X. 46;DkBT[[q!,B	BuNA$++eQ$7NO i0 "IIuT{C!t{{1~CD	 (38;?aT[[q)?	?E%LIq$++eQ2IJ&++I6 ,diiw 677$> 7	 	  !5!<!<W!EF %//v9=:C594;	 0 =	
 	)$ %LJK $..	HQK4D4D / F   %%Vd3?4A096E.5U/;/@/@/J & L 	{{9%]]:.
$MM*;<))5?<M * O T6"	D!"u BM
 CN
 D @I*s0   2N&N*N"N'-N,N1N6;,N;c                     g }g }|D ]P  }t        |t              r|j                  |       %t        |t              rt	        d      |j                  |       R ||fS )r   z'Ufuncify doesn't support InOutArguments)r   r   rI   r   r2  )r3   r   r  py_outr   s        r(   r   z#UfuncifyCodeWrapper._partition_args  s_     	"C#~.c"C/ !JKKS!	" f}r'   r@   )r#   r$   r%   rv   r>   rw   rn   rj   rM   r\   r   rc   ra  r`  r   r  r  s   @r(   rT  rT  !  sT    *  9B 	 " "
b#Hr'   rT  c           
         t        | t              r| f} nt        |       } |rt        ||       nt	        |      }|r|nd}|r|nd}|j                         dk(  rd}	g }
|D ]"  \  }}} |
j                  t        |||              $ t        t        d      |||      }t        |t        t        f      s|g}t        |      dk(  rt        d      t        |      t        |       z   |	kD  r0d}t        |j                  |	t        |       t        |                  t        |      D cg c]!  \  }}t        dj                  |      ||       # }}}|j                  ||
	      S t!        t#        d
            }t#        dd      }t%        t#        dd      |      }t#        d      }t'        d|j(                  |j*                  fz  t-        | |            }| D cg c]  }t!        t#        t/        |                  ! }}|g|z   |gz   } |D cg c]  }||   	 }}t1        t3        ||    ||       |||| |||fi |S c c}}w c c}w c c}w )a
  Generates a binary function that supports broadcasting on numpy arrays.

    Parameters
    ==========

    args : iterable
        Either a Symbol or an iterable of symbols. Specifies the argument
        sequence for the function.
    expr
        A SymPy expression that defines the element wise operation.
    language : string, optional
        If supplied, (options: 'C' or 'F95'), specifies the language of the
        generated code. If ``None`` [default], the language is inferred based
        upon the specified backend.
    backend : string, optional
        Backend used to wrap the generated code. Either 'numpy' [default],
        'cython', or 'f2py'.
    tempdir : string, optional
        Path to directory for temporary files. If this argument is supplied,
        the generated code and the wrapper input files are left intact in
        the specified path.
    flags : iterable, optional
        Additional option flags that will be passed to the backend.
    verbose : bool, optional
        If True, autowrap will not mute the command line backends. This can
        be helpful for debugging.
    helpers : iterable, optional
        Used to define auxiliary expressions needed for the main expr. If
        the main expression needs to call a specialized function it should
        be put in the ``helpers`` iterable. Autowrap will then make sure
        that the compiled main expression can link to the helper routine.
        Items should be tuples with (<funtion_name>, <sympy_expression>,
        <arguments>). It is mandatory to supply an argument sequence to
        helper routines.
    kwargs : dict
        These kwargs will be passed to autowrap if the `f2py` or `cython`
        backend is used and ignored if the `numpy` backend is used.

    Notes
    =====

    The default backend ('numpy') will create actual instances of
    ``numpy.ufunc``. These support ndimensional broadcasting, and implicit type
    conversion. Use of the other backends will result in a "ufunc-like"
    function, which requires equal length 1-dimensional arrays for all
    arguments, and will not perform any type conversions.

    References
    ==========

    .. [1] https://numpy.org/doc/stable/reference/ufuncs.html

    Examples
    ========

    >>> from sympy.utilities.autowrap import ufuncify
    >>> from sympy.abc import x, y
    >>> import numpy as np
    >>> f = ufuncify((x, y), y + x**2)
    >>> type(f)
    <class 'numpy.ufunc'>
    >>> f([1, 2, 3], 2)
    array([  3.,   6.,  11.])
    >>> f(np.arange(5), 3)
    array([  3.,   4.,   7.,  12.,  19.])

    For the 'f2py' and 'cython' backends, inputs are required to be equal length
    1-dimensional arrays. The 'f2py' backend will perform type conversion, but
    the Cython backend will error if the inputs are not of the expected type.

    >>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py')
    >>> f_fortran(1, 2)
    array([ 3.])
    >>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]))
    array([  2.,   6.,  12.])
    >>> f_cython = ufuncify((x, y), y + x**2, backend='Cython')
    >>> f_cython(1, 2)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
      ...
    TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int)
    >>> f_cython(np.array([1.0]), np.array([2.0]))
    array([ 3.])

    r&   r+      ufuncifyr   z#Expression iterable has zero lengthzKCannot create ufunc with more than {0} total arguments: got {1} in, {2} outz
autofunc{}r>  ymT)integerr   r   z%s_%d)r   r   tupler8  r5  r1  rI   r   rT  r   rA  r  r2  r   r   rj   r   r   r   r   rd   dummy_indexr	   r   r;  r
   )r   r   r7  r3  rF  r;   r=   rf   r   maxargsrJ  rd   rI  r   idxexprxrL   r  r  r   f_dummyr   r   indexed_argsargs_with_indicess                            r(   r  r    sS   r $wT{"7H5"7+ gbGEE}}'!  ' 	9D$LLdD$78	9*:j+A7+0';$u.6Dt9>BCCt9s4y 7*)CSZZTCIFGG"+D/3C !!4!4S!95$G 3 3%%h%>> c
##t$c4(!,* GLL':M:M+N!NPVW[]aPbc<@AqE#a&M2AAs\!QC'+78aQqT881Q4$5!677ugwJBHJ 	J!3 B 9s   &&H=$II)Nr   NNNFNN)Nr   NNFN)=rv   r[   rQ   r`   rT   
subprocessr   r   r   stringr   warningsr   sympy.core.cacher   sympy.core.functionr	   sympy.core.relationalr
   sympy.core.symbolr   r   sympy.tensor.indexedr   r   sympy.utilities.codegenr   r   r   r   r   r   r   r   r   sympy.utilities.iterablesr   sympy.utilities.lambdifyr   sympy.utilities.decoratorr   _doctest_depends_on	Exceptionr"   r*   ry   r   r  r/  r5  r8  r;  rC  r{  r~  r  r  r}  re  rT  r  r&   r'   r(   <module>r     s  Pd  	   ? ?   $ & $ + 1E E E / 9 89",. 	I 	L L^'"; '"Ty yx"k "F . ,!#E 	,jAEI?Cq: B 	q:h ,jA!1 B!1N  
 

 ST . /(  + +Z        @+ @F 	3ZHAE04GJ I 	GJr'   