a
    RG5d[                     @   s   d Z ddlmZmZ ddlmZmZmZm	Z	 ddl
mZ ddlmZ ddlmZmZ ddlmZ g dZd	d
ddddddZG dd deZdddZdd ZdS )a  
Julia code printer

The `JuliaCodePrinter` converts SymPy expressions into Julia expressions.

A complete code generator, which uses `julia_code` extensively, can be found
in `sympy.utilities.codegen`.  The `codegen` module can be used to generate
complete source code files.

    )AnyDict)MulPowSRational)_keep_coeff)CodePrinter)
precedence
PRECEDENCEsearch)3sincostancotseccscasinacosatanacotasecacscsinhcoshtanhcothsechcschasinhacoshatanhacothasechacschsincatan2signfloorlogexpcbrtsqrterferfcerfi	factorialgammadigammatrigamma	polygammabetaairyaiairyaiprimeairybiairybiprimebesseljbesselybesselibesselkerfinverfcinvabsceilconjZhankelh1Zhankelh2imagreal)Absceiling	conjugatehankel1hankel2imrec                	       s  e Zd ZdZdZdZddddZdd	d
i dddddZi f fdd	Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Z fd&d'Zd(d) Z fd*d+Z fd,d-Z fd.d/Z fd0d1Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= ZeZ d>d? Z!d@dA Z"dBdC Z#dDdE Z$dFdG Z%dHdI Z&dJdK Z'dLdM Z(dNdO Z)dPdQ Z*dRdS Z+dTdU Z,dVdW Z-dXdY Z.dZd[ Z/d\d] Z0d^d_ Z1d`da Z2  Z3S )bJuliaCodePrinterzD
    A printer to convert expressions to strings of Julia code.
    Z_juliaJuliaz&&z||!)andornotNauto   TF)order	full_prec	precisionuser_functionshumanallow_unknown_functionscontractinlinec                    sH   t  | tttt| _| jtt |di }| j| d S )NrX   )	super__init__dictzipknown_fcns_src1known_functionsupdateknown_fcns_src2get)selfsettings	userfuncs	__class__ P/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/printing/julia.pyr^   I   s
    zJuliaCodePrinter.__init__c                 C   s   |d S )N   rk   )rf   prk   rk   rl   _rate_index_positionQ   s    z%JuliaCodePrinter._rate_index_positionc                 C   s   d| S )Nz%srk   )rf   
codestringrk   rk   rl   _get_statementU   s    zJuliaCodePrinter._get_statementc                 C   s
   d |S )Nz# {}format)rf   textrk   rk   rl   _get_commentY   s    zJuliaCodePrinter._get_commentc                 C   s   d ||S )Nzconst {} = {}rr   )rf   namevaluerk   rk   rl   _declare_number_const]   s    z&JuliaCodePrinter._declare_number_constc                 C   s
   |  |S N)indent_code)rf   linesrk   rk   rl   _format_codea   s    zJuliaCodePrinter._format_codec                    s    |j \ } fddt|D S )Nc                 3   s$   | ]}t  D ]}||fV  qqd S ry   )range).0jirowsrk   rl   	<genexpr>h       z<JuliaCodePrinter._traverse_matrix_indices.<locals>.<genexpr>)shaper}   )rf   matcolsrk   r   rl   _traverse_matrix_indicese   s    
z)JuliaCodePrinter._traverse_matrix_indicesc                 C   s^   g }g }|D ]H}t | j|j|jd |jd g\}}}|d|||f  |d q||fS )N   zfor %s = %s:%send)map_printlabellowerupperappend)rf   indices
open_linesclose_linesr   varstartstoprk   rk   rl   _get_loop_opening_endingk   s    
z)JuliaCodePrinter._get_loop_opening_endingc                    sh  |j r0|jr0| d jr0dtj |  S t| | \}}|dk r^t| |}d}nd}g }g }g }j	dvr|
 }n
t|}|D ]}	|	jr$|	jr$|	jjr$|	jjr$|	jdkr|t|	j|	j dd nDt|	jd jd	krt|	jtr||	 |t|	j|	j  q|	jrV|	tjurV|	jd	krV|t|	j q||	 q|pntjg} fd
d|D }
 fdd|D }|D ]2}	|	j|v rd|||	j  |||	j< qdd }|s||||
 S t|d	kr*|d j r
dnd}d||||
 ||d f S tdd |D rBdnd}d||||
 ||||f S d S )Nr   z%sim- )oldnoneF)evaluater   c                    s   g | ]} | qS rk   parenthesizer~   xprecrf   rk   rl   
<listcomp>   r   z/JuliaCodePrinter._print_Mul.<locals>.<listcomp>c                    s   g | ]} | qS rk   r   r   r   rk   rl   r      r   (%s)c                 S   sH   |d }t dt| D ],}| |d  jr,dnd}d|||| f }q|S )Nr   r   *z.*%s %s %s)r}   len	is_number)aa_strrr   Zmulsymrk   rk   rl   multjoin   s
    z-JuliaCodePrinter._print_Mul.<locals>.multjoin/./r   c                 s   s   | ]}|j V  qd S ry   r   )r~   birk   rk   rl   r      r   z.JuliaCodePrinter._print_Mul.<locals>.<genexpr>z
%s %s (%s))r   is_imaginaryas_coeff_Mul
is_integerr   r   ImaginaryUnitr
   r   rU   as_ordered_factorsr   	make_argsis_commutativeis_Powr+   is_Rationalis_negativer   r   baser   args
isinstanceInfinityrn   r   qOneindexall)rf   exprcer(   r   b	pow_parenr   itemr   b_strr   Zdivsymrk   r   rl   
_print_Mulw   sT    



$
 $zJuliaCodePrinter._print_Mulc                 C   s,   |  |j}|  |j}|j}d|||S )Nz{} {} {})r   lhsrhsrel_oprs   )rf   r   lhs_coderhs_codeoprk   rk   rl   _print_Relational   s    z"JuliaCodePrinter._print_Relationalc                 C   s   t dd |jD rdnd}t|}|jtjkr@d| |j S |jr|jtj krx|jj	r`dnd}d|| |jf S |jtj
 kr|jj	rdnd}d	|| |j|f S d
| |j||| |j|f S )Nc                 s   s   | ]}|j V  qd S ry   r   r   rk   rk   rl   r      r   z.JuliaCodePrinter._print_Pow.<locals>.<genexpr>^z.^zsqrt(%s)r   r   z1 %s sqrt(%s)z1 %s %sr   )r   r   r
   r+   r   Halfr   r   r   r   r   r   )rf   r   Z	powsymbolPRECsymrk   rk   rl   
_print_Pow   s    zJuliaCodePrinter._print_Powc                 C   s(   t |}d| |j|| |j|f S )Nz%s ^ %s)r
   r   r   r+   rf   r   r   rk   rk   rl   _print_MatPow   s    zJuliaCodePrinter._print_MatPowc                    s   | j d rdS t |S d S )Nr\   pi	_settingsr]   _print_NumberSymbolrf   r   ri   rk   rl   	_print_Pi   s    
zJuliaCodePrinter._print_Pic                 C   s   dS )NrK   rk   r   rk   rk   rl   _print_ImaginaryUnit   s    z%JuliaCodePrinter._print_ImaginaryUnitc                    s   | j d rdS t |S d S )Nr\   r   r   r   ri   rk   rl   _print_Exp1   s    
zJuliaCodePrinter._print_Exp1c                    s   | j d rdS t |S d S )Nr\   
eulergammar   r   ri   rk   rl   _print_EulerGamma   s    
z"JuliaCodePrinter._print_EulerGammac                    s   | j d rdS t |S d S )Nr\   catalanr   r   ri   rk   rl   _print_Catalan   s    
zJuliaCodePrinter._print_Catalanc                    s   | j d rdS t |S d S )Nr\   Zgoldenr   r   ri   rk   rl   _print_GoldenRatio  s    
z#JuliaCodePrinter._print_GoldenRatioc                 C   s   ddl m} ddlm} ddlm} |j}|j}| jd st	|j|rg }g }|j
D ]"\}	}
||||	 ||
 qT|t|| }| |S | jd r||s||r| ||S | |}| |}| d||f S d S )Nr   )
Assignment)	Piecewise)IndexedBaser\   r[   z%s = %s)sympy.codegen.astr   $sympy.functions.elementary.piecewiser   sympy.tensor.indexedr   r   r   r   r   r   r   r`   r   has_doprint_loopsrq   )rf   r   r   r   r   r   r   expressions
conditionsr   r   tempr   r   rk   rk   rl   _print_Assignment  s(    


z"JuliaCodePrinter._print_Assignmentc                 C   s   dS )NInfrk   r   rk   rk   rl   _print_Infinity%  s    z JuliaCodePrinter._print_Infinityc                 C   s   dS )Nz-Infrk   r   rk   rk   rl   _print_NegativeInfinity)  s    z(JuliaCodePrinter._print_NegativeInfinityc                 C   s   dS )NNaNrk   r   rk   rk   rl   
_print_NaN-  s    zJuliaCodePrinter._print_NaNc                    s    dd  fdd|D  d S )NzAny[, c                 3   s   | ]}  |V  qd S ry   r   r~   r   rf   rk   rl   r   2  r   z/JuliaCodePrinter._print_list.<locals>.<genexpr>])joinr   rk   r   rl   _print_list1  s    zJuliaCodePrinter._print_listc                 C   s2   t |dkrd| |d  S d| |d S d S )Nr   z(%s,)r   r   r   )r   r   	stringifyr   rk   rk   rl   _print_tuple5  s    zJuliaCodePrinter._print_tuplec                 C   s   dS )Ntruerk   r   rk   rk   rl   _print_BooleanTrue=  s    z#JuliaCodePrinter._print_BooleanTruec                 C   s   dS )Nfalserk   r   rk   rk   rl   _print_BooleanFalseA  s    z$JuliaCodePrinter._print_BooleanFalsec                 C   s   t | S ry   )strr   r   rk   rk   rl   _print_boolE  s    zJuliaCodePrinter._print_boolc                    s   t j|jv rd|j|jf S |j|jfdkr8d|d  S |jdkrXd|j dddd S |jdkr~dd	 fd
d|D  S d|j ddddd S )Nzzeros(%s, %s))r   r   z[%s])r   r   r   r    )rowstartrowendcolsepr   c                    s   g | ]}  |qS rk   r   r   r   rk   rl   r   W  r   z6JuliaCodePrinter._print_MatrixBase.<locals>.<listcomp>z;
)r  r	  rowsepr
  )r   Zeror   r   r   tabler   )rf   Ark   r   rl   _print_MatrixBaseM  s    

z"JuliaCodePrinter._print_MatrixBasec                 C   sr   ddl m} | }|dd |D }|dd |D }|dd |D }d| || || ||j|jf S )Nr   )Matrixc                 S   s   g | ]}|d  d qS )r   r   rk   r~   krk   rk   rl   r   `  r   z;JuliaCodePrinter._print_SparseRepMatrix.<locals>.<listcomp>c                 S   s   g | ]}|d  d  qS )r   rk   r  rk   rk   rl   r   a  r   c                 S   s   g | ]}|d  qS )   rk   r  rk   rk   rl   r   b  r   zsparse(%s, %s, %s, %s, %s))sympy.matricesr  Zcol_listr   r   r   )rf   r  r  LIJZAIJrk   rk   rl   _print_SparseRepMatrix\  s    z'JuliaCodePrinter._print_SparseRepMatrixc                 C   s.   | j |jtd ddd|jd |jd f  S )NAtomT)strictz[%s,%s]r   )r   parentr   r   r   r   rk   rk   rl   _print_MatrixElementg  s    z%JuliaCodePrinter._print_MatrixElementc                    sL    fdd}  |jd ||j|jjd  d ||j|jjd  d S )Nc                    s   | d d }| d }| d }  |}||kr2dn  |}|dkrr|dkrX||krXdS ||krd|S |d | S nd|  ||fS d S )Nr   r   r  r   :)r   r   )r   limlhsteplstrZhstrr   rk   rl   strslicem  s    
z5JuliaCodePrinter._print_MatrixSlice.<locals>.strslice[r   ,r   r   )r   r  rowslicer   colslice)rf   r   r#  rk   r   rl   _print_MatrixSlicel  s    z#JuliaCodePrinter._print_MatrixSlicec                    s0    fdd|j D }d |jjd|f S )Nc                    s   g | ]}  |qS rk   r   )r~   r   r   rk   rl   r     r   z3JuliaCodePrinter._print_Indexed.<locals>.<listcomp>z%s[%s]r%  )r   r   r   r   r   )rf   r   indsrk   r   rl   _print_Indexed  s    zJuliaCodePrinter._print_Indexedc                 C   s   |  |jS ry   )r   r   r   rk   rk   rl   
_print_Idx  s    zJuliaCodePrinter._print_Idxc                 C   s   d|  |jd  S )Nzeye(%s)r   )r   r   r   rk   rk   rl   _print_Identity  s    z JuliaCodePrinter._print_Identityc                    s   d  fdd jD S )Nz .* c                    s   g | ]} |t qS rk   r   r
   r~   argr   rf   rk   rl   r     s   z;JuliaCodePrinter._print_HadamardProduct.<locals>.<listcomp>)r   r   r   rk   r0  rl   _print_HadamardProduct  s    z'JuliaCodePrinter._print_HadamardProductc                 C   s*   t |}d| |j|| |j|gS )Nz.**)r
   r   r   r   r+   r   rk   rk   rl   _print_HadamardPower  s
    z%JuliaCodePrinter._print_HadamardPowerc                 C   s$   |j dkrt|jS d|j|j f S )Nr   z%s // %s)r   r  rn   r   rk   rk   rl   _print_Rational  s    

z JuliaCodePrinter._print_Rationalc                 C   sD   ddl m}m} |j}|tjd|  ||jtj | }| |S )Nr   )r-   r;   r  )	sympy.functionsr-   r;   argumentr   PirU   r   r   )rf   r   r-   r;   r   expr2rk   rk   rl   	_print_jn  s    $zJuliaCodePrinter._print_jnc                 C   sD   ddl m}m} |j}|tjd|  ||jtj | }| |S )Nr   )r-   r<   r  )	r4  r-   r<   r5  r   r6  rU   r   r   )rf   r   r-   r<   r   r7  rk   rk   rl   	_print_yn  s    $zJuliaCodePrinter._print_ync           
         s   |j d jdkrtdg } jd rr fdd|j d d D }d |j d j }d|| }d	| d
 S t|j D ]\}\}}|dkr|d |  n:|t	|j d kr|dkr|d n|d |   |}	||	 |t	|j d kr||d q|d|S d S )Nr   TzAll Piecewise expressions must contain an (expr, True) statement to be used as a default condition. Without one, the generated expression may not evaluate to anything under some condition.r\   c                    s(   g | ] \}}d   | |qS )z({}) ? ({}) :)rs   r   )r~   r   r   r   rk   rl   r     s   z5JuliaCodePrinter._print_Piecewise.<locals>.<listcomp>z (%s)
()r   zif (%s)r   elsezelseif (%s)r   )
r   cond
ValueErrorr   r   r   r   	enumerater   r   )
rf   r   r{   ecpairsZelastpwr   r   r   code0rk   r   rl   _print_Piecewise  s*    



z!JuliaCodePrinter._print_Piecewisec                    s|      \}}d}|jr\| \}}|jr@|jr@t| | d}n|jr\|jr\t| | d}|d fdd jD  S )Nr   r   z * c                 3   s   | ]} |t V  qd S ry   r-  r.  r0  rk   rl   r     r   z1JuliaCodePrinter._print_MatMul.<locals>.<genexpr>)as_coeff_mmulr   as_real_imagis_zeror   r   r   r   )rf   r   r   mr(   rL   rK   rk   r0  rl   _print_MatMul  s    zJuliaCodePrinter._print_MatMulc           
         s   t |tr$| |d}d|S d}dd dd |D }fdd|D } fd	d|D }g }d
}t|D ]J\}}	|	dv r||	 qr||| 8 }|d|| |	f  ||| 7 }qr|S )z0Accepts a string of code or a list of code linesTr   z    )z
^function z^if ^elseif ^else$z^for )z^end$rJ  rK  c                 S   s   g | ]}| d qS )z 	)lstrip)r~   linerk   rk   rl   r     r   z0JuliaCodePrinter.indent_code.<locals>.<listcomp>c                    s&   g | ] t t fd dD qS )c                 3   s   | ]}t | V  qd S ry   r   r~   rL   rM  rk   rl   r     r   :JuliaCodePrinter.indent_code.<locals>.<listcomp>.<genexpr>intanyr~   )	inc_regexrO  rl   r     s   c                    s&   g | ] t t fd dD qS )c                 3   s   | ]}t | V  qd S ry   r   rN  rO  rk   rl   r     r   rP  rQ  rT  )	dec_regexrO  rl   r     s   r   )r   r:  z%s%s)r   r  rz   
splitlinesr   r@  r   )
rf   code
code_linestabincreasedecreaseprettylevelnrM  rk   )rV  rU  rl   rz     s.    




zJuliaCodePrinter.indent_code)4__name__
__module____qualname____doc__printmethodlanguage
_operators_default_settingsr^   ro   rq   ru   rx   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   _print_Tupler  r  r  r  r  r  r(  r*  r+  r,  r1  r2  r3  r8  r9  rD  rI  rz   __classcell__rk   rk   ri   rl   rM   .   sv   J$rM   Nc                 K   s   t || |S )a)  Converts `expr` to a string of Julia code.

    Parameters
    ==========

    expr : Expr
        A SymPy expression to be converted.
    assign_to : optional
        When given, the argument is used as the name of the variable to which
        the expression is assigned.  Can be a string, ``Symbol``,
        ``MatrixSymbol``, or ``Indexed`` type.  This can be helpful for
        expressions that generate multi-line statements.
    precision : integer, optional
        The precision for numbers such as pi  [default=16].
    user_functions : dict, optional
        A dictionary where keys are ``FunctionClass`` instances and values are
        their string representations.  Alternatively, the dictionary value can
        be a list of tuples i.e. [(argument_test, cfunction_string)].  See
        below for examples.
    human : bool, optional
        If True, the result is a single string that may contain some constant
        declarations for the number symbols.  If False, the same information is
        returned in a tuple of (symbols_to_declare, not_supported_functions,
        code_text).  [default=True].
    contract: bool, optional
        If True, ``Indexed`` instances are assumed to obey tensor contraction
        rules and the corresponding nested loops over indices are generated.
        Setting contract=False will not generate loops, instead the user is
        responsible to provide values for the indices in the code.
        [default=True].
    inline: bool, optional
        If True, we try to create single-statement code instead of multiple
        statements.  [default=True].

    Examples
    ========

    >>> from sympy import julia_code, symbols, sin, pi
    >>> x = symbols('x')
    >>> julia_code(sin(x).series(x).removeO())
    'x .^ 5 / 120 - x .^ 3 / 6 + x'

    >>> from sympy import Rational, ceiling
    >>> x, y, tau = symbols("x, y, tau")
    >>> julia_code((2*tau)**Rational(7, 2))
    '8 * sqrt(2) * tau .^ (7 // 2)'

    Note that element-wise (Hadamard) operations are used by default between
    symbols.  This is because its possible in Julia to write "vectorized"
    code.  It is harmless if the values are scalars.

    >>> julia_code(sin(pi*x*y), assign_to="s")
    's = sin(pi * x .* y)'

    If you need a matrix product "*" or matrix power "^", you can specify the
    symbol as a ``MatrixSymbol``.

    >>> from sympy import Symbol, MatrixSymbol
    >>> n = Symbol('n', integer=True, positive=True)
    >>> A = MatrixSymbol('A', n, n)
    >>> julia_code(3*pi*A**3)
    '(3 * pi) * A ^ 3'

    This class uses several rules to decide which symbol to use a product.
    Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
    A HadamardProduct can be used to specify componentwise multiplication ".*"
    of two MatrixSymbols.  There is currently there is no easy way to specify
    scalar symbols, so sometimes the code might have some minor cosmetic
    issues.  For example, suppose x and y are scalars and A is a Matrix, then
    while a human programmer might write "(x^2*y)*A^3", we generate:

    >>> julia_code(x**2*y*A**3)
    '(x .^ 2 .* y) * A ^ 3'

    Matrices are supported using Julia inline notation.  When using
    ``assign_to`` with matrices, the name can be specified either as a string
    or as a ``MatrixSymbol``.  The dimensions must align in the latter case.

    >>> from sympy import Matrix, MatrixSymbol
    >>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
    >>> julia_code(mat, assign_to='A')
    'A = [x .^ 2 sin(x) ceil(x)]'

    ``Piecewise`` expressions are implemented with logical masking by default.
    Alternatively, you can pass "inline=False" to use if-else conditionals.
    Note that if the ``Piecewise`` lacks a default term, represented by
    ``(expr, True)`` then an error will be thrown.  This is to prevent
    generating an expression that may not evaluate to anything.

    >>> from sympy import Piecewise
    >>> pw = Piecewise((x + 1, x > 0), (x, True))
    >>> julia_code(pw, assign_to=tau)
    'tau = ((x > 0) ? (x + 1) : (x))'

    Note that any expression that can be generated normally can also exist
    inside a Matrix:

    >>> mat = Matrix([[x**2, pw, sin(x)]])
    >>> julia_code(mat, assign_to='A')
    'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]'

    Custom printing can be defined for certain types by passing a dictionary of
    "type" : "function" to the ``user_functions`` kwarg.  Alternatively, the
    dictionary value can be a list of tuples i.e., [(argument_test,
    cfunction_string)].  This can be used to call a custom Julia function.

    >>> from sympy import Function
    >>> f = Function('f')
    >>> g = Function('g')
    >>> custom_functions = {
    ...   "f": "existing_julia_fcn",
    ...   "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
    ...         (lambda x: not x.is_Matrix, "my_fcn")]
    ... }
    >>> mat = Matrix([[1, x]])
    >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
    'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'

    Support for loops is provided through ``Indexed`` types. With
    ``contract=True`` these expressions will be turned into loops, whereas
    ``contract=False`` will just print the assignment expression that should be
    looped over:

    >>> from sympy import Eq, IndexedBase, Idx
    >>> len_y = 5
    >>> y = IndexedBase('y', shape=(len_y,))
    >>> t = IndexedBase('t', shape=(len_y,))
    >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
    >>> i = Idx('i', len_y-1)
    >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
    >>> julia_code(e.rhs, assign_to=e.lhs, contract=False)
    'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])'
    )rM   doprint)r   	assign_torg   rk   rk   rl   
julia_code  s     rl  c                 K   s   t t| fi | dS )z~Prints the Julia representation of the given expression.

    See `julia_code` for the meaning of the optional arguments.
    N)printrl  )r   rg   rk   rk   rl   print_julia_code  s    rn  )N)rc  typingr   r   tDict
sympy.corer   r   r   r   Zsympy.core.mulr   Zsympy.printing.codeprinterr	   sympy.printing.precedencer
   r   rL   r   ra   rd   rM   rl  rn  rk   rk   rk   rl   <module>   s,      W
 
