U
    L?h[                  3   @  s  d Z ddlmZ ddl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 ddlmZmZ dd	lmZ d
dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<g3Zd=d>d?d@dAdBdCdDZG dEdF dFeZdLdHdIZdJdK ZdGS )Ma  
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.

    )annotations)Any)MulPowSRational)_keep_coeff)equal_valued)CodePrinter)
precedence
PRECEDENCEsearchsincostanZcotsecZcscasinacosatanZacotZasecZacscsinhcoshtanhZcothZsechZcschasinhacoshatanhZacothZasechZacschZsincatan2signfloorlogexpZcbrtsqrterferfcZerfi	factorialgammaZdigammaZtrigammaZ	polygammabetaZairyaiZairyaiprimeZairybiZairybiprimebesseljbesselyZbesseliZbesselkZerfinvZerfcinvabsceilZconjZhankelh1Zhankelh2imagreal)ZAbsZceiling	conjugateZhankel1Zhankel2imrec                      s  e Zd ZU dZdZdZddddZeej	fdi d	d	d
Z	de
d< 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d/d0Zd1d2 Zd3d4 Zd5d6 Zd7d8 Z d9d: Z!d;d< Z"e"Z#d=d> Z$d?d@ Z%dAdB Z&dCdD Z'dEdF Z(dGdH Z)dIdJ Z*dKdL Z+dMdN Z,dOdP Z-dQdR Z.dSdT Z/dUdV Z0dWdX Z1dYdZ Z2d[d\ Z3d]d^ Z4d_d` Z5  Z6S )aJuliaCodePrinterzD
    A printer to convert expressions to strings of Julia code.
    Z_juliaJuliaz&&z||!)andornot   T)	precisionuser_functionscontractinlinezdict[str, Any]_default_settingsc                   sH   t  | tttt| _| jtt |di }| j| d S )Nr8   )	super__init__dictzipknown_fcns_src1Zknown_functionsupdateknown_fcns_src2get)selfsettingsZ	userfuncs	__class__ F/var/www/html/venv/lib/python3.8/site-packages/sympy/printing/julia.pyr=   G   s
    zJuliaCodePrinter.__init__c                 C  s   |d S )N   rH   )rD   prH   rH   rI   _rate_index_positionO   s    z%JuliaCodePrinter._rate_index_positionc                 C  s   d| S )Nz%srH   )rD   Z
codestringrH   rH   rI   _get_statementS   s    zJuliaCodePrinter._get_statementc                 C  s
   d |S )Nz# {}format)rD   textrH   rH   rI   _get_commentW   s    zJuliaCodePrinter._get_commentc                 C  s   d ||S )Nzconst {} = {}rN   )rD   namevaluerH   rH   rI   _declare_number_const[   s    z&JuliaCodePrinter._declare_number_constc                 C  s
   |  |S N)indent_code)rD   linesrH   rH   rI   _format_code_   s    zJuliaCodePrinter._format_codec                   s    |j \ } fddt|D S )Nc                 3  s$   | ]}t  D ]}||fV  qqd S rU   )range).0jirowsrH   rI   	<genexpr>f   s     
  z<JuliaCodePrinter._traverse_matrix_indices.<locals>.<genexpr>)shaperY   )rD   ZmatcolsrH   r]   rI   _traverse_matrix_indicesc   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)rD   indicesZ
open_linesZclose_linesr\   varstartstoprH   rH   rI   _get_loop_opening_endingi   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k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k	rV|	jd	krV|t|	j q||	 q|pntjg} fd
d|D }
 fdd|D }|D ]2}	|	j|k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)evaluaterc   c                   s   g | ]} | qS rH   parenthesizerZ   xprecrD   rH   rI   
<listcomp>   s     z/JuliaCodePrinter._print_Mul.<locals>.<listcomp>c                   s   g | ]} | qS rH   rv   rx   rz   rH   rI   r|      s     (%s)c                 S  sH   |d }t dt| D ],}| |d  jr,dnd}d|||| f }q|S )Nr   rc   *z.*%s %s %s)rY   len	is_number)aa_strrr\   ZmulsymrH   rH   rI   multjoin   s
    z-JuliaCodePrinter._print_Mul.<locals>.multjoin/./r   c                 s  s   | ]}|j V  qd S rU   r   )rZ   ZbirH   rH   rI   r_      s     z.JuliaCodePrinter._print_Mul.<locals>.<genexpr>z
%s %s (%s))r   Zis_imaginaryZas_coeff_Mul
is_integerrf   r   ZImaginaryUnitr   r   orderZas_ordered_factorsr   Z	make_argsis_commutativeZis_Powr    Zis_Rationalis_negativerj   r   baser   args
isinstanceInfinityrK   r   qZOneindexall)rD   exprcer   r   bZ	pow_parenr   itemr   Zb_strr   ZdivsymrH   rz   rI   
_print_Mulu   sT    



$
 $zJuliaCodePrinter._print_Mulc                 C  s,   |  |j}|  |j}|j}d|||S )Nz{} {} {})rf   lhsrhsZrel_oprO   )rD   r   lhs_coderhs_codeoprH   rH   rI   _print_Relational   s    z"JuliaCodePrinter._print_Relationalc                 C  s   t dd |jD rdnd}t|}t|jdr@d| |j S |jrt|jdrv|jjr^dnd	}d
|| |jf S t|jdr|jjrdnd	}d|| 	|j|f S d| 	|j||| 	|j|f S )Nc                 s  s   | ]}|j V  qd S rU   r   rx   rH   rH   rI   r_      s     z.JuliaCodePrinter._print_Pow.<locals>.<genexpr>^z.^g      ?zsqrt(%s)g      r   r   z1 %s sqrt(%s)rt   z1 %s %sr   )
r   r   r   r	   r    rf   r   r   r   rw   )rD   r   Z	powsymbolPRECsymrH   rH   rI   
_print_Pow   s    zJuliaCodePrinter._print_Powc                 C  s(   t |}d| |j|| |j|f S )Nz%s ^ %s)r   rw   r   r    rD   r   r   rH   rH   rI   _print_MatPow   s    zJuliaCodePrinter._print_MatPowc                   s   | j d rdS t |S d S )Nr:   pi	_settingsr<   Z_print_NumberSymbolrD   r   rF   rH   rI   	_print_Pi   s    
zJuliaCodePrinter._print_Pic                 C  s   dS )Nr.   rH   r   rH   rH   rI   _print_ImaginaryUnit   s    z%JuliaCodePrinter._print_ImaginaryUnitc                   s   | j d rdS t |S d S )Nr:   r   r   r   rF   rH   rI   _print_Exp1   s    
zJuliaCodePrinter._print_Exp1c                   s   | j d rdS t |S d S )Nr:   Z
eulergammar   r   rF   rH   rI   _print_EulerGamma   s    
z"JuliaCodePrinter._print_EulerGammac                   s   | j d rdS t |S d S )Nr:   catalanr   r   rF   rH   rI   _print_Catalan   s    
zJuliaCodePrinter._print_Catalanc                   s   | j d rdS t |S d S )Nr:   Zgoldenr   r   rF   rH   rI   _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:   r9   z%s = %s)Zsympy.codegen.astr   Z$sympy.functions.elementary.piecewiser   Zsympy.tensor.indexedr   r   r   r   r   r   rj   r?   rf   hasZ_doprint_loopsrM   )rD   r   r   r   r   r   r   Zexpressions
conditionsr   r   tempr   r   rH   rH   rI   _print_Assignment  s(    


z"JuliaCodePrinter._print_Assignmentc                 C  s   dS )NZInfrH   r   rH   rH   rI   _print_Infinity#  s    z JuliaCodePrinter._print_Infinityc                 C  s   dS )Nz-InfrH   r   rH   rH   rI   _print_NegativeInfinity'  s    z(JuliaCodePrinter._print_NegativeInfinityc                 C  s   dS )NNaNrH   r   rH   rH   rI   
_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 rU   rf   rZ   r   rD   rH   rI   r_   0  s     z/JuliaCodePrinter._print_list.<locals>.<genexpr>])joinr   rH   r   rI   _print_list/  s    zJuliaCodePrinter._print_listc                 C  s2   t |dkrd| |d  S d| |d S d S )Nrc   z(%s,)r   r}   r   )r   rf   	stringifyr   rH   rH   rI   _print_tuple3  s    zJuliaCodePrinter._print_tuplec                 C  s   dS )NtruerH   r   rH   rH   rI   _print_BooleanTrue;  s    z#JuliaCodePrinter._print_BooleanTruec                 C  s   dS )NfalserH   r   rH   rH   rI   _print_BooleanFalse?  s    z$JuliaCodePrinter._print_BooleanFalsec                 C  s   t | S rU   )strrh   r   rH   rH   rI   _print_boolC  s    zJuliaCodePrinter._print_boolc                   s   t j|jk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))rc   rc   z[%s])r   r   rc   rq    )rowstartrowendcolsepr   c                   s   g | ]}  |qS rH   r   r   r   rH   rI   r|   U  s     z6JuliaCodePrinter._print_MatrixBase.<locals>.<listcomp>z;
)r   r   Zrowsepr   )r   ZZeror`   r^   ra   tabler   )rD   ArH   r   rI   _print_MatrixBaseK  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   rc   rH   rZ   krH   rH   rI   r|   ^  s     z;JuliaCodePrinter._print_SparseRepMatrix.<locals>.<listcomp>c                 S  s   g | ]}|d  d  qS )rc   rH   r   rH   rH   rI   r|   _  s     c                 S  s   g | ]}|d  qS )   rH   r   rH   rH   rI   r|   `  s     zsparse(%s, %s, %s, %s, %s))Zsympy.matricesr   Zcol_listrf   r^   ra   )rD   r   r   LIJZAIJrH   rH   rI   _print_SparseRepMatrixZ  s      z'JuliaCodePrinter._print_SparseRepMatrixc                 C  s.   | j |jtd ddd|jd |jd f  S )NZAtomT)strictz[%s,%s]rc   )rw   parentr   r\   r[   r   rH   rH   rI   _print_MatrixElemente  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   rc   r   rd   :)rf   r   )ry   ZlimlhstepZlstrZhstrr   rH   rI   strslicek  s    
z5JuliaCodePrinter._print_MatrixSlice.<locals>.strslice[r   ,rc   r   )rf   r   Zrowslicer`   Zcolslice)rD   r   r   rH   r   rI   _print_MatrixSlicej  s    z#JuliaCodePrinter._print_MatrixSlicec                   s0    fdd|j D }d |jjd|f S )Nc                   s   g | ]}  |qS rH   r   )rZ   r\   r   rH   rI   r|     s     z3JuliaCodePrinter._print_Indexed.<locals>.<listcomp>z%s[%s]r   )rk   rf   r   rg   r   )rD   r   ZindsrH   r   rI   _print_Indexed  s    zJuliaCodePrinter._print_Indexedc                 C  s   |  |jS rU   )rf   rg   r   rH   rH   rI   
_print_Idx  s    zJuliaCodePrinter._print_Idxc                 C  s   d|  |jd  S )Nzeye(%s)r   )rf   r`   r   rH   rH   rI   _print_Identity  s    z JuliaCodePrinter._print_Identityc                   s   d  fdd jD S )Nz .* c                   s   g | ]} |t qS rH   rw   r   rZ   argr   rD   rH   rI   r|     s   z;JuliaCodePrinter._print_HadamardProduct.<locals>.<listcomp>)r   r   r   rH   r   rI   _print_HadamardProduct  s    z'JuliaCodePrinter._print_HadamardProductc                 C  s*   t |}d| |j|| |j|gS )Nz.**)r   r   rw   r   r    r   rH   rH   rI   _print_HadamardPower  s
    z%JuliaCodePrinter._print_HadamardPowerc                 C  s$   |j dkrt|jS d|j|j f S )Nrc   z%s // %s)r   r   rK   r   rH   rH   rI   _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   Pir   Halfrf   )rD   r   r!   r'   ry   expr2rH   rH   rI   	_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   )	r   r!   r(   r   r   r   r   r   rf   )rD   r   r!   r(   ry   r   rH   rH   rI   	_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 )Nrt   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({}) ? ({}) :)rO   rf   )rZ   r   r   r   rH   rI   r|     s
    z5JuliaCodePrinter._print_Piecewise.<locals>.<listcomp>z (%s)
()r   zif (%s)rc   elsezelseif (%s)rd   )
r   Zcond
ValueErrorr   rf   r   r   	enumeraterj   r   )
rD   r   rW   ZecpairsZelastpwr\   r   r   Zcode0rH   r   rI   _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 )Nrq   rp   z * c                 3  s   | ]} |t V  qd S rU   r   r   r   rH   rI   r_     s     z1JuliaCodePrinter._print_MatMul.<locals>.<genexpr>)Zas_coeff_mmulr   Zas_real_imagis_zeror   r   r   r   )rD   r   r   mr   r/   r.   rH   r   rI   _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kr||	 qr||| 8 }|d|| |	f  ||| 7 }qr|S )z0Accepts a string of code or a list of code linesTrq   z    )z
^function z^if ^elseif ^else$z^for )z^end$r  r  c                 S  s   g | ]}| d qS )z 	)lstrip)rZ   linerH   rH   rI   r|     s     z0JuliaCodePrinter.indent_code.<locals>.<listcomp>c                   s&   g | ] t t fd dD qS )c                 3  s   | ]}t | V  qd S rU   r   rZ   r/   r  rH   rI   r_     s     :JuliaCodePrinter.indent_code.<locals>.<listcomp>.<genexpr>intanyrZ   )	inc_regexr  rI   r|     s   c                   s&   g | ] t t fd dD qS )c                 3  s   | ]}t | V  qd S rU   r   r  r  rH   rI   r_     s     r  r  r  )	dec_regexr  rI   r|     s   r   )rq   r   z%s%s)r   r   rV   
splitlinesr   r   rj   )
rD   codeZ
code_linestabZincreaseZdecreaseprettylevelnr  rH   )r  r  rI   rV     s.    




zJuliaCodePrinter.indent_code)7__name__
__module____qualname____doc__Zprintmethodlanguage
_operatorsr>   r
   r;   __annotations__r=   rL   rM   rQ   rT   rX   rb   ro   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z_print_Tupler   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rV   __classcell__rH   rH   rF   rI   r0   0   sp   

J$r0   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])'
    )r0   Zdoprint)r   Z	assign_torE   rH   rH   rI   
julia_code   s     r  c                 K  s   t t| f| dS )z~Prints the Julia representation of the given expression.

    See `julia_code` for the meaning of the optional arguments.
    N)printr  )r   rE   rH   rH   rI   print_julia_code  s    r  )N)r  
__future__r   typingr   Z
sympy.corer   r   r   r   Zsympy.core.mulr   Zsympy.core.numbersr	   Zsympy.printing.codeprinterr
   Zsympy.printing.precedencer   r   r/   r   r@   rB   r0   r  r  rH   rH   rH   rI   <module>   s                                         S
 
