
    wgO                        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lmZ i 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Z G d de
      Zd dZd Zy)!    )annotations)BasicS)Lambda)equal_valued)CodePrinter)
precedencereduceAbsabssincostanacosasinatanatan2ceilingceilfloorsignexplogaddsubmulpowc                     e Zd ZU dZ e       Zded<   dZdZ e	e
j                  fi dddd	dd
ddi dd
Zi fdZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZeZeZd Zd Zd Zd Zd Zd Zd Z d  Z!d! Z"d%d#Z#d$ Z$y")&GLSLPrinterz
    Rudimentary, generic GLSL printing tools.

    Additional settings:
    'use_operators': Boolean (should the printer use operators for +,-,*, or functions?)
    z
set[Basic]_not_supported_glslGLSLTr   Fz,
float	   )
use_operatorszero
mat_nestedmat_separatormat_transpose
array_type
glsl_types	precisionuser_functionscontractc                    t        j                  | |       t        t              | _        |j	                  di       }| j                  j                  |       y )Nr.   )r   __init__dictknown_functionsgetupdate)selfsettings	userfuncss      X/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/printing/glsl.pyr1   zGLSLPrinter.__init__7   sD    T8,#O4LL!126	##I.    c                    |dz  S )N    )r6   ps     r9   _rate_index_positionz GLSLPrinter._rate_index_position=   s    s
r:   c                    d|z  S )Nz%s;r=   )r6   
codestrings     r9   _get_statementzGLSLPrinter._get_statement@   s    z!!r:   c                $    dj                  |      S )Nz// {}format)r6   texts     r9   _get_commentzGLSLPrinter._get_commentC   s    ~~d##r:   c                &    dj                  ||      S )Nzfloat {} = {};rD   )r6   namevalues      r9   _declare_number_constz!GLSLPrinter._declare_number_constF   s    &&tU33r:   c                $    | j                  |      S N)indent_code)r6   liness     r9   _format_codezGLSLPrinter._format_codeI   s    &&r:   c                l   t        |t              r1| j                  |j                  d            }dj	                  |      S d}d}d}|D cg c]  }|j                  d       }}|D cg c]*  }t        t        t        |j                  |                  , }}|D cg c]*  }t        t        t        |j                  |                  , }}g }	d}
t        |      D ]C  \  }}|dv r|	j                  |       |
||   z  }
|	j                  ||
z  |       |
||   z  }
E |	S c c}w c c}w c c}w )	z0Accepts a string of code or a list of code linesT z   ){(z{
z(
)})z 	r   )rR   
)
isinstancestrrN   
splitlinesjoinlstripintanymapendswith
startswith	enumerateappend)r6   code
code_linestab	inc_token	dec_tokenlineincreasedecreaseprettylevelns               r9   rN   zGLSLPrinter.indent_codeL   s,    dC ))$//$*?@J77:&&,		/34tE"44HLMCCy9:;MMJNO$CC;<=OO  	!GAtz!d#Xa[ EMMCIt45Xa[ E	!  5MOs   D'*/D,/D1c                   | j                   d   }| j                   d   }|r|j                  dk(  n|j                  dk(  }||k7  r|j                         n|}| j                   d   }| j                   d   }|j                  |j                  z  }dj	                  ||      }	|j                  dk(  r| j                  |d         S |j                  dk  r|j                  dk  r|r|j                  dk(  r.d	j	                  |j                  |j                  | d
d            S |j                  |j                  k(  r/dj	                  |j                  |j                  | ddd            S dj	                  |j                  |j                  |j                  | ddd            S t        j                  |j                  v r%dj	                  |	|j                  | |dd            S | j                   d   s;dj	                  |	|j                  | |dd      |j                  |j                        S | j                   d   r;dj	                  ||j                  |j                  |j                  | |dd            S y )Nr)   r*      r,   r+   {}[{}]r      zvec{}{}rT   rV   )rowstartrowendz	mat{}({}), rR   )rowseprs   rt   zmat{}x{}({}){}({})r(   z{}(
{}
) /* a {}x{} matrix */z{}[{}][{}](
{}
)zfloat[]()
	_settingsrowscols	transposerE   _printtabler   Oneshape)
r6   matr)   r*   column_vectorAr,   r+   
array_sizearray_constructors
             r9   _print_MatrixBasezGLSLPrinter._print_MatrixBaseg   s=   77+8Qsxx1},=CMMO3^^L1
^^L1
VVAFF]
$OOJ
C66Q;;;qt$$66Q;166Q;:vv{ ''FFAGGD#SGA  166!"))FFAGGDr $ + 
 &,,FFAFFGGDr  + 
 UUagg??!M2RH  -4;;!M2RH 
 ^^L)'..AFFAFFM:SQ  *r:   c                $    | j                  |      S rM   )_print_not_supported)r6   r   s     r9   _print_SparseRepMatrixz"GLSLPrinter._print_SparseRepMatrix   s    ((--r:   c                    | j                   d   }|r|j                  \  }n|j                  \  }fdt        |      D        S )Nr*   c              3  F   K   | ]  }t              D ]  }||f 
  y wrM   )range).0ijry   s      r9   	<genexpr>z7GLSLPrinter._traverse_matrix_indices.<locals>.<genexpr>   s%     A1U4[AAAAs   !)rx   r   r   )r6   r   r*   rz   ry   s       @r9   _traverse_matrix_indicesz$GLSLPrinter._traverse_matrix_indices   s=    7		ID		IDAdAAr:   c                   | j                   d   }| j                   d   }| j                   d   }|r2|j                  j                  \  }}|j                  |j                  }}n1|j                  j                  \  }}|j                  |j                  }}| j                  |j                        }	|r|dk  r|dk  s|rdj                  |	||      S dj                  |	|||z  z         S )Nr(   r,   r*   rr   z
{}[{}][{}]rq   )rx   parentr   r   r   r|   rE   )
r6   exprnestr,   r*   rz   ry   r   r   pnts
             r9   _print_MatrixElementz GLSLPrinter._print_MatrixElement   s    ~~l+^^L1
7))ID&&aA))ID&&aAkk$++&DAI$(t&&sAq11??3AdF
33r:   c                    dj                   fd|D              } j                  d   } j                  d   }t        |      }dj                  ||      }|dk  r|rdj                  ||      S dj                  ||      S )	Nru   c              3  @   K   | ]  }j                  |        y wrM   r|   )r   itemr6   s     r9   r   z*GLSLPrinter._print_list.<locals>.<genexpr>   s     9Ddkk$'9   r,   r+   rq   rr   z	vec{}({})rw   )r[   rx   lenrE   )r6   r   lr,   r+   r   r   s   `      r9   _print_listzGLSLPrinter._print_list   s{    II9D99^^L1
^^L1
Y
$OOJ
C?z%%j!44??#4a88r:   c           
        g }g }d}|D ]y  }|j                  || j                  |j                        | j                  |j                        | j                  |j                  dz         dz         |j                  d       { ||fS )NzAfor (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){rp   )varblestartendrU   )rc   r|   labellowerupper)r6   indices
open_linesclose_lines	loopstartr   s         r9   _get_loop_opening_endingz$GLSLPrinter._get_loop_opening_ending   s    
W	 	$Ai++agg.QWW-{{177Q;/+1 1 2 s#	$ ;&&r:   c           	        || j                   v r_| j                   |   }d }t        |t              r|}n|D ]  \  }} ||      s n |$	  ||D cg c]  }| j                  |d       c} S y t        |t              r| j                   ||       S | j                  |      S c c}w # t        $ r% dj                  || j                  |d            cY S w xY w)Nr   rw   ru   )
r3   rX   rY   parenthesize	TypeErrorrE   	stringifyr   r|   r   )r6   func	func_args	cond_funccondr   s         r9   _print_Function_with_argsz%GLSLPrinter._print_Function_with_args   s    4''',,T2ID)S) "+ JD$I R!S$"3"3D!"<!STT  
 f%;;tY/00,,T22 "T  R#??4	41PQQRs$   
B( B#)B( #B( (+CCc           
        ddl m} |j                  d   j                  dk7  rt	        d      g }|j                  |      rt        |j                        D ]  \  }\  }}|dk(  r$|j                  d| j                  |      z         nU|t        |j                        dz
  k(  r|dk(  r|j                  d       n#|j                  d	| j                  |      z         | j                  |      }|j                  |       |j                  d
        dj                  |      S |j                  d d D cg c],  \  }}d| j                  |      d| j                  |      d. }}}d| j                  |j                  d   j                        z  }	dj                  |      |	z   dj                  dt        |      z  g      z   S c c}}w )Nr   )
AssignmentTzAll 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) {rp   zelse {zelse if (%s) {rU   rW   z((z) ? (
z
)
z: (
%s
)z:  rV   )sympy.codegen.astr   argsr   
ValueErrorhasrb   rc   r|   r   r[   r   )
r6   r   r   rO   r   eccode0ecpairs	last_lines
             r9   _print_PiecewisezGLSLPrinter._print_Piecewise   s   099R=%  / 0 0
 88J&tyy1 	"	6Aq6LLt{{1~!=>#dii.1,,dLL*LL!1DKKN!BCAU#S!	" 99U## !%		#201 04{{1~/3{{1~? 0G 0 %t{{499R=3E3E'FFI99W%	1CHHc#g,>N=O4PPP	0s   51Gc                8    | j                  |j                        S rM   )r|   r   r6   r   s     r9   
_print_IdxzGLSLPrinter._print_Idx  s    {{4::&&r:   c                b   |j                   }t        j                  }t        j                  }t	        t        |j                              D ]  }||j                  |   |z  z  }|||   z  }! dj                  | j                  |j                  j                        | j                  |            S )Nrq   )r   r   Zeror~   reversedr   rankr   rE   r|   baser   )r6   r   dimselemoffsetr   s         r9   _print_IndexedzGLSLPrinter._print_Indexed  s    zzvv%		*+ 	ADLLOF**Dd1gF	 KK		(KK
 	
r:   c                   t        |      }t        |j                  d      rd| j                  |j                  |      z  S t        |j                  d      rd| j                  |j                        z  S 	 | j                  t        |j                              }| j                  d| j                  |j                        |f      S # t        $ r | j                  |j                        }Y Sw xY w)Nr   z1.0/%sg      ?zsqrt(%s)r   )	r	   r   r   r   r   r|   r$   r   r   )r6   r   PRECr   s       r9   
_print_PowzGLSLPrinter._print_Pow  s    $"%t00DABB$((C(DII 666*KKdhh0 11%DII&:    *KK)*s   6$C $C.-C.c                *    t        t        |            S rM   )rY   r$   r   s     r9   
_print_intzGLSLPrinter._print_int%  s    5;r:   c                N    dj                  |j                  |j                        S )Nz	{}.0/{}.0)rE   r>   qr   s     r9   _print_RationalzGLSLPrinter._print_Rational(  s    !!$&&$&&11r:   c                    | j                  |j                        }| j                  |j                        }|j                  }dj	                  |||      S )Nz{} {} {})r|   lhsrhsrel_oprE   )r6   r   lhs_coderhs_codeops        r9   _print_RelationalzGLSLPrinter._print_Relational+  sD    ;;txx(;;txx([[  2x88r:   Nc                x     j                   d   rt        j                   ||      S |j                         }d } fd |d |      \  }}|rt	        fd fd|D              x}}n  j                   j                   d         x}}|r,t	        fd	 fd
|D              } j                  d||f      }|S )Nr&   )orderc                (     t         fd|g g f      S )Nc                L     |      r| d   |gz   | d   fS | d   | d   |gz   fS )Nr   rp   r=   )xyr>   s     r9   <lambda>z;GLSLPrinter._print_Add.<locals>.partition.<locals>.<lambda>8  s9    1Q4!aS!A$'7 adAaDRSQTHEU r:   r
   )r>   r   s   ` r9   	partitionz)GLSLPrinter._print_Add.<locals>.partition7  s    UWX\^`b[cddr:   c                ,    j                  d| |f      S )Nr   r   abr6   s     r9   r   z#GLSLPrinter._print_Add.<locals>.add9  s    11%!Q@@r:   c                "    | j                         S rM   )could_extract_minus_sign)args    r9   r   z(GLSLPrinter._print_Add.<locals>.<lambda><  s    )E)E)G r:   c                     | |      S rM   r=   r   r   r   s     r9   r   z(GLSLPrinter._print_Add.<locals>.<lambda>>  s    Qq r:   c              3  @   K   | ]  }j                  |        y wrM   r   r   tr6   s     r9   r   z)GLSLPrinter._print_Add.<locals>.<genexpr>>  s     3PqDKKN3Pr   r'   c                     | |      S rM   r=   r   s     r9   r   z(GLSLPrinter._print_Add.<locals>.<lambda>D  s    S1X r:   c              3  B   K   | ]  }j                  |         y wrM   r   )r   rn   r6   s     r9   r   z)GLSLPrinter._print_Add.<locals>.<genexpr>D  s     /MAQB/Ms   r   )rx   r   
_print_Addas_ordered_termsr   r|   r   )	r6   r   r   termsr   negpossr   s	   `       @r9   r   zGLSLPrinter._print_Add1  s    >>/*))$EBB%%'	e	A GOS13PC3PQQAkk$.."899A-/M/MNC..us3i@Ar:   c                      j                   d   rt        j                   |fi |S |j                         } fdt	        fd fd|D              }|S )Nr&   c                ,    j                  d| |f      S )Nr   r   r   s     r9   r   z#GLSLPrinter._print_Mul.<locals>.mulN  s    11%!A??r:   c                     | |      S rM   r=   )r   r   r   s     r9   r   z(GLSLPrinter._print_Mul.<locals>.<lambda>R  s    s1Qx r:   c              3  @   K   | ]  }j                  |        y wrM   r   r   s     r9   r   z)GLSLPrinter._print_Mul.<locals>.<genexpr>R  s     )HQ$++a.)Hr   )rx   r   
_print_Mulas_ordered_factorsr   )r6   r   kwargsr   r   r   s   `    @r9   r   zGLSLPrinter._print_MulJ  sU    >>/*))$???'')	@ ')H%)HIr:   rM   )%__name__
__module____qualname____doc__setr!   __annotations__printmethodlanguager2   r   _default_settingsr1   r?   rB   rG   rK   rP   rN   r   r   r   r   r   _print_tuple_print_Tupler   r   r   r   r   r   r   r   r   r   r   r=   r:   r9   r    r       s     "%NJ&KH[:: ?  !# /"$4'6,\.B4"
9 LL'3* QD'
  292	r:   r    Nc                8    t        |      j                  | |      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_tor7   s      r9   	glsl_coder  U  s    V x ((i88r:   c                .    t        t        | fi |       y)zpPrints the GLSL representation of the given expression.

       See GLSLPrinter init function for settings.
    N)printr  )r   r7   s     r9   
print_glslr  "  s    
 
)D
%H
%&r:   rM   )
__future__r   
sympy.corer   r   sympy.core.functionr   sympy.core.numbersr   sympy.printing.codeprinterr   sympy.printing.precedencer	   	functoolsr   r3   r    r  r  r=   r:   r9   <module>r     s   "  & + 2 0 	5	5 
5 
5	
 F F F V v W F 
5 
5 
5 
5  
5!" 
5#(u+ un	K9Z'r:   