a
    RG5dP  ã                   @   sš   d dl mZ d dlmZmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ ddd	d
ddddddddddddddœZG dd„ de	ƒZddd„Zdd„ ZdS ) é    )ÚSet)ÚBasicÚS)ÚLambda)ÚCodePrinter)Ú
precedence©ÚreduceÚabsÚsinÚcosÚtanÚacosÚasinÚatanÚceilÚfloorÚsignÚexpÚlogÚaddÚsubÚmulÚpow)ÚAbsr   r   r   r   r   r   Úatan2Úceilingr   r   r   r   r   r   r   r   c                   @   s
  e Zd ZdZeƒ ZdZdZdddddddd	d
di ddddddœZi 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eZeZd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Zd2d3„ Zd4d5„ Zd6d7„ Zd<d8d9„Z d:d;„ Z!d	S )=ÚGLSLPrinterz¦
    Rudimentary, generic GLSL printing tools.

    Additional settings:
    'use_operators': Boolean (should the printer use operators for +,-,*, or functions?)
    Z_glslÚGLSLTr   Fz,
ÚfloatNÚautoé	   Ú_)Úuse_operatorsÚzeroÚ
mat_nestedÚmat_separatorÚmat_transposeÚ
array_typeÚ
glsl_typesÚorderÚ	full_precÚ	precisionÚuser_functionsÚhumanÚallow_unknown_functionsÚcontractÚerror_on_reservedÚreserved_word_suffixc                 C   s2   t  | |¡ ttƒ| _| di ¡}| j |¡ d S )Nr-   )r   Ú__init__ÚdictÚknown_functionsÚgetÚupdate)ÚselfÚsettingsZ	userfuncs© r:   úO/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/printing/glsl.pyr3   <   s    
zGLSLPrinter.__init__c                 C   s   |d S )Né   r:   )r8   Úpr:   r:   r;   Ú_rate_index_positionB   s    z GLSLPrinter._rate_index_positionc                 C   s   d| S )Nz%s;r:   )r8   Ú
codestringr:   r:   r;   Ú_get_statementE   s    zGLSLPrinter._get_statementc                 C   s
   d  |¡S )Nz// {}©Úformat)r8   Útextr:   r:   r;   Ú_get_commentH   s    zGLSLPrinter._get_commentc                 C   s   d  ||¡S )Nzfloat {} = {};rA   )r8   ÚnameÚvaluer:   r:   r;   Ú_declare_number_constK   s    z!GLSLPrinter._declare_number_constc                 C   s
   |   |¡S ©N)Úindent_code)r8   Úlinesr:   r:   r;   Ú_format_codeN   s    zGLSLPrinter._format_codec           
         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 linesTÚ z   )Ú{ú(z{
z(
)Ú}ú)c                 S   s   g | ]}|  d ¡‘qS )z 	)Úlstrip©Ú.0Úliner:   r:   r;   Ú
<listcomp>\   ó    z+GLSLPrinter.indent_code.<locals>.<listcomp>c                    s    g | ]}t tt|jˆ ƒƒƒ‘qS r:   )ÚintÚanyÚmapÚendswithrR   )Ú	inc_tokenr:   r;   rU   ^   rV   c                    s    g | ]}t tt|jˆ ƒƒƒ‘qS r:   )rW   rX   rY   Ú
startswithrR   )Ú	dec_tokenr:   r;   rU   _   rV   r   )rL   Ú
z%s%s)Ú
isinstanceÚstrrI   Ú
splitlinesÚjoinÚ	enumerateÚappend)
r8   ÚcodeZ
code_linesÚtabZincreaseZdecreaseÚprettyÚlevelÚnrT   r:   )r]   r[   r;   rI   Q   s&    


zGLSLPrinter.indent_codec           
      C   s˜  | j d }| j d }|r"|jdkn|jdk}||kr<| ¡ n|}| j d }| j d }|j|j }d ||¡}	|jdkr„|  |d ¡S |jdkr|jdkr|r|jdkrÆd	 |j|j| d
dd¡S |j|jkrîd |j|j| dddd¡S d |j|j|j| dddd¡S n„tj|j	v r8d |	|j| |ddd¡S | j d sfd |	|j| |ddd|j|j¡S | j d r”d ||j|j|j| |ddd¡S d S )Nr&   r'   é   r)   r(   ú{}[{}]r   é   zvec{}{}rN   rP   )ÚrowstartÚrowendz	mat{}({})ú, rL   )Úrowseprm   rn   zmat{}x{}({})ú{}({})r%   z{}(
{}
) /* a {}x{} matrix */z{}[{}][{}](
{}
)zfloat[]()
Ú	_settingsÚrowsÚcolsÚ	transposerB   Ú_printÚtabler   ÚOneÚshape)
r8   Úmatr&   r'   Zcolumn_vectorÚAr)   r(   Ú
array_sizeÚarray_constructorr:   r:   r;   Ú_print_MatrixBasel   sV    





ÿÿÿÿþþý
þzGLSLPrinter._print_MatrixBasec                 C   s
   |   |¡S rH   )Ú_print_not_supported)r8   rz   r:   r:   r;   Ú_print_SparseRepMatrixš   s    z"GLSLPrinter._print_SparseRepMatrixc                    s:   | j d }|r|j\‰ }n
|j\}‰ ‡ fdd„t|ƒD ƒS )Nr'   c                 3   s$   | ]}t ˆ ƒD ]}||fV  qqd S rH   )Úrange)rS   ÚiÚj©rs   r:   r;   Ú	<genexpr>¤   rV   z7GLSLPrinter._traverse_matrix_indices.<locals>.<genexpr>)rr   ry   r   )r8   rz   r'   rt   r:   r„   r;   Ú_traverse_matrix_indicesž   s
    

z$GLSLPrinter._traverse_matrix_indicesc           
      C   s¢   | j d }| j d }| j d }|r>|jj\}}|j|j }}n|jj\}}|j|j }}|  |j¡}	|rŠ|dkrx|dks||rŠd |	||¡S d |	|||  ¡S d S )Nr%   r)   r'   rl   z
{}[{}][{}]rk   )rr   Úparentry   rƒ   r‚   rv   rB   )
r8   ÚexprÚnestr)   r'   rt   rs   r‚   rƒ   Zpntr:   r:   r;   Ú_print_MatrixElement¦   s    


z GLSLPrinter._print_MatrixElementc                    sh   d  ‡ fdd„|D ƒ¡}ˆ jd }ˆ jd }t|ƒ}d ||¡}|dkrX|rXd ||¡S d	 ||¡S d S )
Nro   c                 3   s   | ]}ˆ   |¡V  qd S rH   ©rv   ©rS   Úitem©r8   r:   r;   r…   ¸   rV   z*GLSLPrinter._print_list.<locals>.<genexpr>r)   r(   rk   rl   z	vec{}({})rq   )rb   rr   ÚlenrB   )r8   rˆ   Úlr)   r(   r|   r}   r:   rŽ   r;   Ú_print_list·   s    

zGLSLPrinter._print_listc              
   C   sZ   g }g }d}|D ]@}|  ||  |j¡|  |j¡|  |jd ¡dœ ¡ |  d¡ q||fS )NzAfor (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){rj   )ZvarbleÚstartÚendrO   )rd   rv   ÚlabelÚlowerÚupper)r8   ÚindicesZ
open_linesZclose_linesZ	loopstartr‚   r:   r:   r;   Ú_get_loop_opening_endingÆ   s    

ý
z$GLSLPrinter._get_loop_opening_endingc              
      s²   |ˆ j v rŒˆ j | }d }t|tƒr(|}n|D ]\}}||ƒr, qBq,|d ur®z|‡ fdd„|D ƒŽ W S  tyˆ   d |ˆ  |d¡¡ Y S 0 n"t|tƒr¤ˆ  ||Ž ¡S ˆ  |¡S d S )Nc                    s   g | ]}ˆ   |d ¡‘qS )r   )ÚparenthesizerŒ   rŽ   r:   r;   rU   ß   rV   z9GLSLPrinter._print_Function_with_args.<locals>.<listcomp>rq   ro   )	r5   r_   r`   Ú	TypeErrorrB   Ú	stringifyr   rv   r   )r8   ÚfuncÚ	func_argsÚ	cond_funcÚcondr:   rŽ   r;   Ú_print_Function_with_argsÓ   s     



z%GLSLPrinter._print_Function_with_argsc           
         s"  ddl m} |jd jdkr$tdƒ‚g }| |¡rÊt|jƒD ]‚\}\}}|dkrf| dˆ  |¡ ¡ n:|t	|jƒd krŒ|dkrŒ| d¡ n| d	ˆ  |¡ ¡ ˆ  |¡}| |¡ | d
¡ q<d 
|¡S ‡ fdd„|jd d… D ƒ}dˆ  |jd j¡ }	d 
|¡|	 d 
dt	|ƒ g¡ S d S )Nr   )Ú
AssignmentéÿÿÿÿTz¼All 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.z	if (%s) {rj   zelse {zelse if (%s) {rO   r^   c                    s(   g | ] \}}d ˆ   |¡ˆ   |¡f ‘qS )z((%s) ? (
%s
)
r‹   )rS   ÚeÚcrŽ   r:   r;   rU     s   þ
ÿz0GLSLPrinter._print_Piecewise.<locals>.<listcomp>z: (
%s
)z: ú rP   )Úsympy.codegen.astr¡   ÚargsrŸ   Ú
ValueErrorÚhasrc   rd   rv   r   rb   rˆ   )
r8   rˆ   r¡   rJ   r‚   r£   r¤   Úcode0ÚecpairsÚ	last_liner:   rŽ   r;   Ú_print_Piecewiseè   s(    




þzGLSLPrinter._print_Piecewisec                 C   s   |   |j¡S rH   )rv   r”   ©r8   rˆ   r:   r:   r;   Ú
_print_Idx
  s    zGLSLPrinter._print_Idxc                 C   s`   |j }tj}tj}tt|jƒƒD ]"}||j| | 7 }||| 9 }q d |  	|j
j¡|  	|¡¡S )Nrk   )ry   r   ÚZerorx   Úreversedr   Úrankr—   rB   rv   Úbaser”   )r8   rˆ   ÚdimsÚelemÚoffsetr‚   r:   r:   r;   Ú_print_Indexed  s    þzGLSLPrinter._print_Indexedc                 C   sŽ   t |ƒ}|jdkr$d|  |j|¡ S |jdkr>d|  |j¡ S z|  t|jƒ¡}W n typ   |  |j¡}Y n0 |  d|  |j¡|f¡S d S )Nr¢   z1.0/%sg      à?zsqrt(%s)r   )r   r   r™   r³   rv   r   rš   r    )r8   rˆ   ÚPRECr£   r:   r:   r;   Ú
_print_Pow  s    


þzGLSLPrinter._print_Powc                 C   s   t t|ƒƒS rH   )r`   r   r®   r:   r:   r;   Ú
_print_int*  s    zGLSLPrinter._print_intc                 C   s   d  |j|j¡S )Nz	{}.0/{}.0)rB   r=   Úqr®   r:   r:   r;   Ú_print_Rational-  s    zGLSLPrinter._print_Rationalc                 C   s,   |   |j¡}|   |j¡}|j}d |||¡S )Nz{} {} {})rv   ÚlhsÚrhsÚrel_oprB   )r8   rˆ   Úlhs_codeÚrhs_codeÚopr:   r:   r;   Ú_print_Relational0  s    zGLSLPrinter._print_Relationalc                    s¾   ˆj d rtjˆ||dS | ¡ }dd„ }‡fdd„‰ |dd„ |ƒ\}}|rrt‡ fd	d„t‡fd
d„|ƒƒ }}nˆ ˆj d ¡ }}|rºt‡ fdd„t‡fdd„|ƒƒ}ˆ d||f¡}|S )Nr#   )r*   c                    s   t ‡ fdd„|g g fƒS )Nc                    s4   ˆ |ƒr| d |g | d fS | d | d |g fS )Nr   rj   r:   )ÚxÚy©r=   r:   r;   Ú<lambda>=  rV   z;GLSLPrinter._print_Add.<locals>.partition.<locals>.<lambda>r   )r=   r   r:   rÆ   r;   Ú	partition<  s    z)GLSLPrinter._print_Add.<locals>.partitionc                    s   ˆ   d| |f¡S )Nr   ©r    ©ÚaÚbrŽ   r:   r;   r   >  s    z#GLSLPrinter._print_Add.<locals>.addc                 S   s   |   ¡ S rH   )Úcould_extract_minus_sign)Úargr:   r:   r;   rÇ   A  rV   z(GLSLPrinter._print_Add.<locals>.<lambda>c                    s
   ˆ | |ƒS rH   r:   rÊ   ©r   r:   r;   rÇ   C  rV   c                    s
   ˆ   | ¡S rH   r‹   ©ÚtrŽ   r:   r;   rÇ   C  rV   r$   c                    s
   ˆ | |ƒS rH   r:   rÊ   rÏ   r:   r;   rÇ   I  rV   c                    s   ˆ   |  ¡S rH   r‹   )ri   rŽ   r:   r;   rÇ   I  rV   r   )rr   r   Ú
_print_AddÚas_ordered_termsr	   rY   rv   r    )r8   rˆ   r*   ÚtermsrÈ   ÚnegÚposÚsr:   )r   r8   r;   rÒ   6  s    
& zGLSLPrinter._print_Addc                    sV   ˆj d rtjˆ|fi |¤ŽS | ¡ }‡fdd„‰ t‡ fdd„t‡fdd„|ƒƒ}|S )Nr#   c                    s   ˆ   d| |f¡S )Nr   rÉ   rÊ   rŽ   r:   r;   r   S  s    z#GLSLPrinter._print_Mul.<locals>.mulc                    s
   ˆ | |ƒS rH   r:   rÊ   )r   r:   r;   rÇ   W  rV   z(GLSLPrinter._print_Mul.<locals>.<lambda>c                    s
   ˆ   | ¡S rH   r‹   rÐ   rŽ   r:   r;   rÇ   W  rV   )rr   r   Ú
_print_MulÚas_ordered_factorsr	   rY   )r8   rˆ   ÚkwargsrÔ   r×   r:   )r   r8   r;   rØ   O  s    
 zGLSLPrinter._print_Mul)N)"Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚsetÚ_not_supportedÚprintmethodÚlanguageÚ_default_settingsr3   r>   r@   rD   rG   rK   rI   r~   r€   r†   rŠ   r‘   Ú_print_tupleÚ_print_Tupler˜   r    r­   r¯   r·   r¹   rº   r¼   rÃ   rÒ   rØ   r:   r:   r:   r;   r      s\   ï."
r   Nc                 K   s   t |ƒ | |¡S )a¾  Converts an expr to a string of GLSL code

    Parameters
    ==========

    expr : Expr
        A SymPy expression to be converted.
    assign_to : optional
        When given, the argument is used for naming the variable or variables
        to which the expression is assigned. Can be a string, ``Symbol``,
        ``MatrixSymbol`` or ``Indexed`` type object. In cases where ``expr``
        would be printed as an array, a list of string or ``Symbol`` objects
        can also be passed.

        This is helpful in case of line-wrapping, or for expressions that
        generate multi-line statements.  It can also be used to spread an array-like
        expression into multiple assignments.
    use_operators: bool, optional
        If set to False, then *,/,+,- operators will be replaced with functions
        mul, add, and sub, which must be implemented by the user, e.g. for
        implementing non-standard rings or emulated quad/octal precision.
        [default=True]
    glsl_types: bool, optional
        Set this argument to ``False`` in order to avoid using the ``vec`` and ``mat``
        types.  The printer will instead use arrays (or nested arrays).
        [default=True]
    mat_nested: bool, optional
        GLSL version 4.3 and above support nested arrays (arrays of arrays).  Set this to ``True``
        to render matrices as nested arrays.
        [default=False]
    mat_separator: str, optional
        By default, matrices are rendered with newlines using this separator,
        making them easier to read, but less compact.  By removing the newline
        this option can be used to make them more vertically compact.
        [default=',
']
    mat_transpose: bool, optional
        GLSL's matrix multiplication implementation assumes column-major indexing.
        By default, this printer ignores that convention. Setting this option to
        ``True`` transposes all matrix output.
        [default=False]
    array_type: str, optional
        The GLSL array constructor type.
        [default='float']
    precision : integer, optional
        The precision for numbers such as pi [default=15].
    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, js_function_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].

    Examples
    ========

    >>> from sympy import glsl_code, symbols, Rational, sin, ceiling, Abs
    >>> x, tau = symbols("x, tau")
    >>> glsl_code((2*tau)**Rational(7, 2))
    '8*sqrt(2)*pow(tau, 3.5)'
    >>> glsl_code(sin(x), assign_to="float y")
    'float y = sin(x);'

    Various GLSL types are supported:
    >>> from sympy import Matrix, glsl_code
    >>> glsl_code(Matrix([1,2,3]))
    'vec3(1, 2, 3)'

    >>> glsl_code(Matrix([[1, 2],[3, 4]]))
    'mat2(1, 2, 3, 4)'

    Pass ``mat_transpose = True`` to switch to column-major indexing:
    >>> glsl_code(Matrix([[1, 2],[3, 4]]), mat_transpose = True)
    'mat2(1, 3, 2, 4)'

    By default, larger matrices get collapsed into float arrays:
    >>> print(glsl_code( Matrix([[1,2,3,4,5],[6,7,8,9,10]]) ))
    float[10](
       1, 2, 3, 4,  5,
       6, 7, 8, 9, 10
    ) /* a 2x5 matrix */

    The type of array constructor used to print GLSL arrays can be controlled
    via the ``array_type`` parameter:
    >>> glsl_code(Matrix([1,2,3,4,5]), array_type='int')
    'int[5](1, 2, 3, 4, 5)'

    Passing a list of strings or ``symbols`` to the ``assign_to`` parameter will yield
    a multi-line assignment for each item in an array-like expression:
    >>> x_struct_members = symbols('x.a x.b x.c x.d')
    >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=x_struct_members))
    x.a = 1;
    x.b = 2;
    x.c = 3;
    x.d = 4;

    This could be useful in cases where it's desirable to modify members of a
    GLSL ``Struct``.  It could also be used to spread items from an array-like
    expression into various miscellaneous assignments:
    >>> misc_assignments = ('x[0]', 'x[1]', 'float y', 'float z')
    >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=misc_assignments))
    x[0] = 1;
    x[1] = 2;
    float y = 3;
    float z = 4;

    Passing ``mat_nested = True`` instead prints out nested float arrays, which are
    supported in GLSL 4.3 and above.
    >>> mat = Matrix([
    ... [ 0,  1,  2],
    ... [ 3,  4,  5],
    ... [ 6,  7,  8],
    ... [ 9, 10, 11],
    ... [12, 13, 14]])
    >>> print(glsl_code( mat, mat_nested = True ))
    float[5][3](
       float[]( 0,  1,  2),
       float[]( 3,  4,  5),
       float[]( 6,  7,  8),
       float[]( 9, 10, 11),
       float[](12, 13, 14)
    )



    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,
    js_function_string)].

    >>> custom_functions = {
    ...   "ceiling": "CEIL",
    ...   "Abs": [(lambda x: not x.is_integer, "fabs"),
    ...           (lambda x: x.is_integer, "ABS")]
    ... }
    >>> glsl_code(Abs(x) + ceiling(x), user_functions=custom_functions)
    'fabs(x) + CEIL(x)'

    If further control is needed, addition, subtraction, multiplication and
    division operators can be replaced with ``add``, ``sub``, and ``mul``
    functions.  This is done by passing ``use_operators = False``:

    >>> x,y,z = symbols('x,y,z')
    >>> glsl_code(x*(y+z), use_operators = False)
    'mul(x, add(y, z))'
    >>> glsl_code(x*(y+z*(x-y)**z), use_operators = False)
    'mul(x, add(y, mul(z, pow(sub(x, y), z))))'

    ``Piecewise`` expressions are converted into conditionals. If an
    ``assign_to`` variable is provided an if statement is created, otherwise
    the ternary operator is used. 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
    >>> expr = Piecewise((x + 1, x > 0), (x, True))
    >>> print(glsl_code(expr, tau))
    if (x > 0) {
       tau = x + 1;
    }
    else {
       tau = 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]))
    >>> glsl_code(e.rhs, assign_to=e.lhs, contract=False)
    'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'

    >>> from sympy import Matrix, MatrixSymbol
    >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
    >>> A = MatrixSymbol('A', 3, 1)
    >>> print(glsl_code(mat, A))
    A[0][0] = pow(x, 2.0);
    if (x > 0) {
       A[1][0] = x + 1;
    }
    else {
       A[1][0] = x;
    }
    A[2][0] = sin(x);
    )r   Údoprint)rˆ   Ú	assign_tor9   r:   r:   r;   Ú	glsl_codeZ  s     Lrè   c                 K   s   t t| fi |¤Žƒ dS )zpPrints the GLSL representation of the given expression.

       See GLSLPrinter init function for settings.
    N)Úprintrè   )rˆ   r9   r:   r:   r;   Ú
print_glsl'  s    rê   )N)Útypingr   ÚtSetÚ
sympy.corer   r   Úsympy.core.functionr   Zsympy.printing.codeprinterr   Úsympy.printing.precedencer   Ú	functoolsr	   r5   r   rè   rê   r:   r:   r:   r;   Ú<module>   s:   ï  ?
 N