K iVOddlmZddlmZmZddlmZddlmZddl m Z ddl m Z ddl mZidd d d d d d d d d ddddddddddddddddddddddddZGdde Zd dZdZy)!) annotations)BasicS)Lambda) equal_valued) CodePrinter) precedencereduceAbsabssincostanacosasinatanatan2ceilingceilfloorsignexplogaddsubmulpowceZdZUdZeZded<dZdZe e jfidddd dd dd idd Z ifd Z dZ dZdZdZdZdZdZdZdZdZdZeZeZdZdZdZdZdZdZdZ 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_glslGLSLTrFz, float ) use_operatorszero mat_nested mat_separator mat_transpose array_type glsl_types precisionuser_functionscontractctj||tt|_|j di}|jj |y)Nr.)r__init__dictknown_functionsgetupdate)selfsettings userfuncss Y/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/printing/glsl.pyr1zGLSLPrinter.__init__7sDT8,#O4LL!126  ##I.c |dzS)N)r6ps r9_rate_index_positionz GLSLPrinter._rate_index_position=s s r:c d|zS)Nz%s;r=)r6 codestrings r9_get_statementzGLSLPrinter._get_statement@s z!!r:c$dj|S)Nz// {}format)r6texts r9 _get_commentzGLSLPrinter._get_commentCs~~d##r:c&dj||S)Nzfloat {} = {};rD)r6namevalues r9_declare_number_constz!GLSLPrinter._declare_number_constFs&&tU33r:c$|j|SN) indent_code)r6liness r9 _format_codezGLSLPrinter._format_codeIs&&r:c lt|tr1|j|jd}dj |Sd}d}d}|Dcgc]}|j d}}|Dcgc]*}t tt|j|,}}|Dcgc]*}t tt|j|,}}g} d} t|D]C\} }|dvr| j|| || z} | j|| z|| || z } E| Scc}wcc}wcc}w) z0Accepts a string of code or a list of code linesTz ){(z{ z( )})z r)rR ) isinstancestrrN splitlinesjoinlstripintanymapendswith startswith enumerateappend) r6code code_linestab inc_token dec_tokenlineincreasedecreaseprettylevelns r9rNzGLSLPrinter.indent_codeLs, dC ))$//$*?@J77:& &,  /34t E"44HLMCC y9:;MMJNO$CC;<=OO  !GAtz! d# Xa[ E MMCIt4 5 Xa[ E  ! 5MOs D'*/D,/D1c |jd}|jd}|r|jdk(n|jdk(}||k7r|jn|}|jd}|jd}|j|jz}dj ||} |jdk(r|j |dS|jdkr|jdkr|r|jdk(r.d j |j|j |d d S|j|jk(r/d j |j|j |dddSdj |j|j|j |dddStj|jvr%dj | |j ||ddS|jds;dj | |j ||dd|j|jS|jdr;dj ||j|j|j ||dd Sy)Nr)r*r,r+{}[{}]rzvec{}{}rTrV)rowstartrowendz mat{}({}), rR)rowseprsrtz mat{}x{}({}){}({})r(z{}( {} ) /* a {}x{} matrix */z{}[{}][{}]( {} )zfloat[]() _settingsrowscols transposerE_printtablerOneshape) r6matr)r* column_vectorAr,r+ array_sizearray_constructors r9_print_MatrixBasezGLSLPrinter._print_MatrixBasegs=7 7 +8Qsxx1} , =CMMO3^^L1 ^^L1 VVAFF] $OOJ C 66Q;;;qt$ $ 66Q;166Q;:vv{ ''FFAGGD#SGA166!"))FFAGGDr$+ &,,FFAFFGGDr+ UUagg ??!M2RH  -4;;!M2RH  ^^L )'..AFFAFFM:SQ *r:c$|j|SrM)_print_not_supported)r6rs r9_print_SparseRepMatrixz"GLSLPrinter._print_SparseRepMatrixs((--r:c|jd}|r|j\}n|j\}fdt|DS)Nr*c3FK|]}tD]}||f ywrM)range).0ijrys r9 z7GLSLPrinter._traverse_matrix_indices..s%A1U4[AAAAs!)rxrr)r6rr*rzrys @r9_traverse_matrix_indicesz$GLSLPrinter._traverse_matrix_indicess=7  ID IDAd AAr:c|jd}|jd}|jd}|r2|jj\}}|j|j}}n1|jj\}}|j|j}}|j |j} |r|dkr|dks|rdj | ||Sdj | |||zzS)Nr(r,r*rrz {}[{}][{}]rq)rxparentrrrr|rE) r6exprnestr,r*rzryrrpnts r9_print_MatrixElementz GLSLPrinter._print_MatrixElements~~l+^^L1 7  ))ID&&aA ))ID&&aAkk$++& DAI$(t&&sAq1 1??3AdF 3 3r:cdjfd|D}jd}jd}t|}dj||}|dkr|rdj||Sdj||S) Nruc3@K|]}j|ywrMr|)ritemr6s r9rz*GLSLPrinter._print_list..s9Ddkk$'9r,r+rqrrz vec{}({})rw)r[rxlenrE)r6rlr,r+rrs` r9 _print_listzGLSLPrinter._print_lists{ II9D9 9^^L1 ^^L1 Y $OOJ C ?z%%j!4 4??#4a8 8r:c g}g}d}|D]y}|j||j|j|j|j|j|jdzdz|jd{||fS)NzAfor (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){rp)varblestartendrU)rcr|labellowerupper)r6indices open_lines close_lines loopstartrs r9_get_loop_opening_endingz$GLSLPrinter._get_loop_opening_endings  W  $A   i++agg.QWW-{{177Q;/+11 2   s #  $;&&r:c ||jvr_|j|}d}t|tr|}n|D]\}}||sn|$ ||Dcgc]}|j|dc}Syt|tr|j||S|j|Scc}w#t$r%dj ||j |dcYSwxYw)Nrrwru) r3rXrY parenthesize TypeErrorrE stringifyrr|r)r6func func_args cond_funccondrs r9_print_Function_with_argsz%GLSLPrinter._print_Function_with_argss 4'' ',,T2ID)S) "+JD$IR!S$"3"3D!"#dii.1,,dLL*LL!1DKKN!BC A U# S! "99U# #!% #20104{{1~/3{{1~?0G0%t{{499R=3E3E'FFI99W% 1CHHc#g,>N=O4PP P 0s51Gcb|j}tj}tj}t t |j D]}||j||zz }|||z}!dj|j|jj|j|S)Nrq) rrZeror~reversedrrankrrEr|baser)r6rdimselemoffsetrs r9_print_IndexedzGLSLPrinter._print_Indexedszzvv% *+ A DLLOF* *D d1g F  KK  ( KK   r:ct|}t|jdrd|j|j|zSt|jdrd|j |jzS |j t |j}|jd|j |j|fS#t$r|j |j}YSwxYw)Nrz1.0/%sg?zsqrt(%s)r) r rrrrr|r$rr)r6rPRECrs r9 _print_PowzGLSLPrinter._print_Pows$ " %t00DAB B $((C ( DII 66 6 *KKdhh011% DII&:  *KK) *s6$C$C.-C.c*tt|SrM)rYr$r6rs r9 _print_intzGLSLPrinter._print_int"s5;r:cNdj|j|jS)Nz {}.0/{}.0)rEr>qrs r9_print_RationalzGLSLPrinter._print_Rational%s!!$&&$&&11r:c|j|j}|j|j}|j}dj |||S)Nz{} {} {})r|lhsrhsrel_oprE)r6rlhs_coderhs_codeops r9_print_RelationalzGLSLPrinter._print_Relational(sD;;txx(;;txx( [[  2x88r:Ncxjdrtj||S|j}d}fd|d|\}}|rt fdfd|Dx}}n j jdx}}|r,t fd fd |D}j d ||f}|S) Nr&)orderc(tfd|ggfS)NcL|r|d|gz|dfS|d|d|gzfS)Nrrpr=)xyr>s r9z;GLSLPrinter._print_Add..partition..5s91Q4!aS!A$'7adAaDRSQTHEUr:r )r>rs` r9 partitionz)GLSLPrinter._print_Add..partition4sUWX\^`b[cd dr:c,jd||fS)Nrrabr6s r9rz#GLSLPrinter._print_Add..add6s11%!Q@ @r:c"|jSrM)could_extract_minus_sign)args r9rz(GLSLPrinter._print_Add..9s)E)E)Gr:c||SrMr=rrrs r9rz(GLSLPrinter._print_Add..;s Qqr:c3@K|]}j|ywrMrrtr6s r9rz)GLSLPrinter._print_Add..;s3PqDKKN3Prr'c||SrMr=rs r9rz(GLSLPrinter._print_Add..As S1Xr:c3BK|]}j| ywrMr)rrnr6s r9rz)GLSLPrinter._print_Add..As/MA QB/Msr)rxr _print_Addas_ordered_termsr r|r) r6rrtermsrnegpossrs ` @r9rzGLSLPrinter._print_Add.s >>/ *))$EB B%%' e AGOS 13PC3PQ QAkk$.."89 9A -/M/MNC..us3i@Ar:c jdrtj|fi|S|j}fdt fdfd|D}|S)Nr&c,jd||fS)Nrrrs r9rz#GLSLPrinter._print_Mul..mulKs11%!A? ?r:c||SrMr=)rrrs r9rz(GLSLPrinter._print_Mul..Os s1Qxr:c3@K|]}j|ywrMrrs r9rz)GLSLPrinter._print_Mul..Os)HQ$++a.)Hr)rxr _print_Mulas_ordered_factorsr )r6rkwargsrrrs` @r9rzGLSLPrinter._print_MulGsU >>/ *))$?? ?'') @ ')H%)H Ir:rM)$__name__ __module__ __qualname____doc__setr!__annotations__ printmethodlanguager2r_default_settingsr1r?rBrGrKrPrNrrrrr _print_tuple _print_Tuplerrrrrrrrrrr=r:r9r r s "%NJ&KH[::  ? !#/ "$4'6,\.B4" 9LL '3* QD    29 2 r:r Nc 8t|j||S)aConverts 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_tor7s r9 glsl_coderRsV x ( (i 88r:c .tt|fi|y)zpPrints the GLSL representation of the given expression. See GLSLPrinter init function for settings. N)printr)rr7s r9 print_glslrs  )D %H %&r:rM) __future__r sympy.corerrsympy.core.functionrsympy.core.numbersrsympy.printing.codeprinterrsympy.printing.precedencer functoolsr r3r rrr=r:r9rs"&+20 5 5 5 5   F   F  F Vv W F 5 5 5 5  5!" 5#(r+rh K9Z'r: