K i_XdZddlmZddlmZddlmZddlmZm Z m Z m Z ddl m Z mZddlmZmZddlmZdd lmZdd lmZdd lmZmZdd lmZGd deZGddeZGddeeZ GddeZ!ee!e!dZ"ee!edZ"eee!dZ"y)a Module that defines indexed objects. The classes ``IndexedBase``, ``Indexed``, and ``Idx`` represent a matrix element ``M[i, j]`` as in the following diagram:: 1) The Indexed class represents the entire indexed object. | ___|___ ' ' M[i, j] / \__\______ | | | | | 2) The Idx class represents indices; each Idx can | optionally contain information about its range. | 3) IndexedBase represents the 'stem' of an indexed object, here `M`. The stem used by itself is usually taken to represent the entire array. There can be any number of indices on an Indexed object. No transformation properties are implemented in these Base objects, but implicit contraction of repeated indices is supported. Note that the support for complicated (i.e. non-atomic) integer expressions as indices is limited. (This should be improved in future releases.) Examples ======== To express the above matrix element example you would write: >>> from sympy import symbols, IndexedBase, Idx >>> M = IndexedBase('M') >>> i, j = symbols('i j', cls=Idx) >>> M[i, j] M[i, j] Repeated indices in a product implies a summation, so to express a matrix-vector product in terms of Indexed objects: >>> x = IndexedBase('x') >>> M[i, j]*x[j] M[i, j]*x[j] If the indexed objects will be converted to component based arrays, e.g. with the code printers or the autowrap framework, you also need to provide (symbolic or numerical) dimensions. This can be done by passing an optional shape parameter to IndexedBase upon construction: >>> dim1, dim2 = symbols('dim1 dim2', integer=True) >>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2)) >>> A.shape (dim1, 2*dim1, dim2) >>> A[i, j, 3].shape (dim1, 2*dim1, dim2) If an IndexedBase object has no shape information, it is assumed that the array is as large as the ranges of its indices: >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> M[i, j].shape (m, n) >>> M[i, j].ranges [(0, m - 1), (0, n - 1)] The above can be compared with the following: >>> A[i, 2, j].shape (dim1, 2*dim1, dim2) >>> A[i, 2, j].ranges [(0, m - 1), None, (0, n - 1)] To analyze the structure of indexed expressions, you can use the methods get_indices() and get_contraction_structure(): >>> from sympy.tensor import get_indices, get_contraction_structure >>> get_indices(A[i, j, j]) ({i}, {}) >>> get_contraction_structure(A[i, j, j]) {(j,): {A[i, j, j]}} See the appropriate docstrings for a detailed explanation of the output. )Iterable)Number) StdFactKB)ExprTuplesympifyS)_filter_assumptionsSymbol) fuzzy_bool fuzzy_not)_sympify)KroneckerDelta)dispatch) is_sequence NotIterable) filldedentc eZdZy)IndexExceptionN)__name__ __module__ __qualname__Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/tensor/indexed.pyrrxsrrceZdZdZdZdZdZdZfdZe dZ e dZ dZ e dZ e d Ze d Ze d Ze d Ze d ZdZe dZe dZxZS)IndexedaRepresents a mathematical object with indices. >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j) A[i, j] It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``: ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``. >>> A = IndexedBase('A') >>> a_ij = A[i, j] # Prefer this, >>> b_ij = Indexed(A, i, j) # over this. >>> a_ij == b_ij True Tc"ddlm}ddlm}|s t dt |t tfr t|}n0t|ds$t |tsttdttt|}t ||tt |fr-t#d|Drt%|dk(r||dS||St'|}t)j*||g|i|}tj-||j.|S) Nr NDimArray MatrixBasez!Indexed needs at least one index. __getitem__z The base can only be replaced with a string, Symbol, IndexedBase or an object with a method for getting items (i.e. an object with a `__getitem__` method). c34K|]}|jywN) is_number).0is r z"Indexed.__new__..sMh^_akkMhs)sympy.tensor.array.ndim_arrayr sympy.matrices.matrixbaser"r isinstancestrr IndexedBasehasattr TypeErrorrlistmaprrralllenrr__new___set_assumptions assumptions0)clsbaseargskw_argsr r"objs rr6zIndexed.__new__s;8 !DE E dS&M *t$D}-j{6SJ(  C&' dY%D E#MhcgMhJh4yA~DG}$Dz!~ll37t7w7$$S$*;*;< rczt|tt|jj zSr%super_hashable_contenttuplesortedr8itemsself __class__s rrAzIndexed._hashable_content/w(*U6$:K:K:Q:Q:S3T-UUUrct|Sr%)r.rFs rnamez Indexed.names 4yrcy)z8Allow derivatives with respect to an ``Indexed`` object.TrrJs r _diff_wrtzIndexed._diff_wrtsrcddlm}t|tr|j|jk(rt |j t |j k7rdj||}t|tj}t|j |j D]\}}|t||z}|St|j|r0ddl m}t||j|g|jddSt!|j j#|rtj$Stj&S)Nrrz'Different # of indices: d({!s})/d({!s}))derive_by_arrayr*)r+r r-rr:r5indicesformatrr Oneziprsympy.tensor.arrayrOr;rhasNaNZero)rFwrtr msgresultindex1index2rOs r_eval_derivativezIndexed._eval_derivatives; c7 #DII(=4<< C $44?FFtGJL$S))UUF"%dllCKK"@ 9.88 9M  9 - :?499c:KTYYqr]K KT\\"&&s+uu 66Mrcp|jjDcic] \}}| || c}}Scc}}wr% _assumptionsrDrFkvs rr8zIndexed.assumptions01!%!2!2!8!8!:LAam1LLL 22c |jdS)aJReturns the ``IndexedBase`` of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).base A >>> B = IndexedBase('B') >>> B == B[i, j].base True rr;rJs rr:z Indexed.bases yy|rc |jddS)z Returns the indices of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).indices (i, j) r*NrgrJs rrPzIndexed.indicessyy}rc2t|jdz S)as Returns the rank of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j, k, l, m = symbols('i:m', cls=Idx) >>> Indexed('A', i, j).rank 2 >>> q = Indexed('A', i, j, k, l, m) >>> q.rank 5 >>> q.rank == len(q.indices) True r*)r5r;rJs rrankz Indexed.ranks&499~!!rcz|jjr|jjSg}|jD]S}t|dd}t|dd}d||fvrt t d|z ||z dz}|j|Ut|S#t $rt t d|zwxYw)abReturns a list with dimensions of each index. Dimensions is a property of the array, not of the indices. Still, if the ``IndexedBase`` does not define a shape attribute, it is assumed that the ranges of the indices correspond to the shape of the array. >>> from sympy import IndexedBase, Idx, symbols >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', m) >>> A = IndexedBase('A', shape=(n, n)) >>> B = IndexedBase('B') >>> A[i, j].shape (n, n) >>> B[i, j].shape (m, m) upperNlowerz@ Range is not defined for all indices in: %sr*zc Shape cannot be inferred from Idx with undefined range: %s) r:shaperPgetattrrrr1appendr)rFsizesr(rlrmsizes rrnz Indexed.shape s( 99??99?? " AAw-EAw-Eu~%$Z1CEI1J&KLL 4u}q( LL  e}  4$Z1+-112&344 4s 6B!B:cg}t}|jD]G}t|d|}t|d|}|||fvr|j||f7|jdI|S)aReturns a list of tuples with lower and upper range of each index. If an index does not define the data members upper and lower, the corresponding slot in the list contains ``None`` instead of a tuple. Examples ======== >>> from sympy import Indexed,Idx, symbols >>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges [(0, 1), (0, 3), (0, 7)] >>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges [(0, 2), (0, 2), (0, 2)] >>> x, y, z = symbols('x y z', integer=True) >>> Indexed('A', x, y, z).ranges [None, None, None] rlrmN)objectrProrp)rFrangessentinelr(rlrms rruzIndexed.ranges0sn(8 $AAw1EAw1Eu~- uen- d#  $ rctt|j|j}|j|jddj |dS)N[z, ])r2r3doprintrPr:join)rFprPs r _sympystrzIndexed._sympystrOs<s199dll3499TYY/71CDDrc|jj}|jDchc]}|jD]}|}}}|r |h|z|zS|Scc}}wr%)r: free_symbolsrP)rFbase_free_symbolsr(fsindices_free_symbolss rrzIndexed.free_symbolsSsi II22  ?q~~ ?)+B ?  ? ? 6--0DD D' '  ?sAc*ddlm}|ddd|hS)Nr)sympy_deprecation_warningz The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. z1.9zdeprecated-expr-free-symbols)deprecated_since_versionactive_deprecations_target)sympy.utilities.exceptionsr)rFrs rexpr_free_symbolszIndexed.expr_free_symbols]s$H!# &+'E  Gv r)rrr__doc__ is_Indexed is_symbolis_Atomr6rApropertyrKrMr]r8r:rPrjrnrur}rr __classcell__rGs@rrr|s"JIG:V(MM"  ""(##J<E((  rrceZdZdZdZdZedZdejdddZ e dZ fdZ e d Zd Ze d Ze d Ze d Ze dZdZxZS)r/ah Represent the base or stem of an indexed object The IndexedBase class represent an array that contains elements. The main purpose of this class is to allow the convenient creation of objects of the Indexed class. The __getitem__ method of IndexedBase returns an instance of Indexed. Alone, without indices, the IndexedBase class can be used as a notation for e.g. matrix equations, resembling what you could do with the Symbol class. But, the IndexedBase class adds functionality that is not available for Symbol instances: - An IndexedBase object can optionally store shape information. This can be used in to check array conformance and conditions for numpy broadcasting. (TODO) - An IndexedBase object implements syntactic sugar that allows easy symbolic representation of array operations, using implicit summation of repeated indices. - The IndexedBase object symbolizes a mathematical structure equivalent to arrays, and is recognized as such for code generation and automatic compilation and wrapping. >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> A = IndexedBase('A'); A A >>> type(A) When an IndexedBase object receives indices, it returns an array with named axes, represented by an Indexed object: >>> i, j = symbols('i j', integer=True) >>> A[i, j, 2] A[i, j, 2] >>> type(A[i, j, 2]) The IndexedBase constructor takes an optional shape argument. If given, it overrides any shape information in the indices. (But not the index ranges!) >>> m, n, o, p = symbols('m n o p', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> A[i, j].shape (m, n) >>> B = IndexedBase('B', shape=(o, p)) >>> B[i, j].shape (o, p) Assumptions can be specified with keyword arguments the same way as for Symbol: >>> A_real = IndexedBase('A', real=True) >>> A_real.is_real True >>> A != A_real True Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase: >>> I = symbols('I', integer=True) >>> C_inherit = IndexedBase(I) >>> C_explicit = IndexedBase('I', integer=True) >>> C_inherit == C_explicit True Tc|j}t|jdd}||d<t||_||j_y)z?Set assumptions on obj, making sure to apply consistent values. commutativeTN)copyr getrr` _generator)r= assumptions tmp_asm_copyis_commutatives rr7zIndexedBase._set_assumptionssL#'') #KOOM4$HI%3 M"$[1&2#rN)offsetstridesc <ddlm}ddlm}t |\}}t |t r t|fi|}nXt |tr|j|}n6t |||fr|St |tr t|St|}t|r t|}n | t|}|tj|||} ntj||} || _|| _|| _t || _t&j)| || S)Nrr!r)r,r"r+r r r-r.r _mergerrrrrr6_shape_offset_strides_namer/r7) r9labelrnrrr<r"r rr=s rr6zIndexedBase.__new__s8;27; W eS !50K0E v &,,{3K  I6 7L x (E? "UOE u 5ME  %LE  ,,sE51C,,sE*C   J $$S+6 rc|jSr%)rrJs rrKzIndexedBase.names zzrczt|tt|jj zSr%r?rEs rrAzIndexedBase._hashable_contentrHrcp|jjDcic] \}}| || c}}Scc}}wr%r_ras rr8zIndexedBase.assumptions0rdrec t|rG|jr,t|jt|k7r tdt |g|i|S|jr#t|jdk7r tdt ||fi|S)NzRank mismatch.r*)rrnr5rr)rFrPr<s rr#zIndexedBase.__getitem__sy w zzc$**oW=$%56645'5W5 5zzc$**o2$%56644G4 4rc|jS)aUReturns the shape of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase, Idx >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).shape (x, y) Note: If the shape of the ``IndexedBase`` is specified, it will override any shape information given by the indices. >>> A = IndexedBase('A', shape=(x, y)) >>> B = IndexedBase('B') >>> i = Idx('i', 2) >>> j = Idx('j', 1) >>> A[i, j].shape (x, y) >>> B[i, j].shape (2, 1) )rrJs rrnzIndexedBase.shapes2{{rc|jS)aReturns the strided scheme for the ``IndexedBase`` object. Normally this is a tuple denoting the number of steps to take in the respective dimension when traversing an array. For code generation purposes strides='C' and strides='F' can also be used. strides='C' would mean that code printer would unroll in row-major order and 'F' means unroll in column major order. )rrJs rrzIndexedBase.strides s}}rc|jS)a]Returns the offset for the ``IndexedBase`` object. This is the value added to the resulting index when the 2D Indexed object is unrolled to a 1D form. Used in code generation. Examples ========== >>> from sympy.printing import ccode >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> l, m, n, o = symbols('l m n o', integer=True) >>> A = IndexedBase('A', strides=(l, m, n), offset=o) >>> i, j, k = map(Idx, 'ijk') >>> ccode(A[i, j, k]) 'A[l*i + m*j + n*k + o]' )rrJs rrzIndexedBase.offsets(||rc |jdS)zReturns the label of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).label A rrgrJs rrzIndexedBase.label1syy|rc8|j|jSr%rzrrFr|s rr}zIndexedBase._sympystr@yy$$rr%)rrrrrr staticmethodr7r rWr6rrKrAr8r#rnrrrr}rrs@rr/r/js@BIG33!&&$BVMM 54 *  %rr/ceZdZdZdZdZdZdZdZdZ d dZ e dZ e dZ e dZdZe d Ze d Zy) IdxaRepresents an integer index as an ``Integer`` or integer expression. There are a number of ways to create an ``Idx`` object. The constructor takes two arguments: ``label`` An integer or a symbol that labels the index. ``range`` Optionally you can specify a range as either * ``Symbol`` or integer: This is interpreted as a dimension. Lower and upper bounds are set to ``0`` and ``range - 1``, respectively. * ``tuple``: The two elements are interpreted as the lower and upper bounds of the range, respectively. Note: bounds of the range are assumed to be either integer or infinite (oo and -oo are allowed to specify an unbounded range). If ``n`` is given as a bound, then ``n.is_integer`` must not return false. For convenience, if the label is given as a string it is automatically converted to an integer symbol. (Note: this conversion is not done for range or dimension arguments.) Examples ======== >>> from sympy import Idx, symbols, oo >>> n, i, L, U = symbols('n i L U', integer=True) If a string is given for the label an integer ``Symbol`` is created and the bounds are both ``None``: >>> idx = Idx('qwerty'); idx qwerty >>> idx.lower, idx.upper (None, None) Both upper and lower bounds can be specified: >>> idx = Idx(i, (L, U)); idx i >>> idx.lower, idx.upper (L, U) When only a single bound is given it is interpreted as the dimension and the lower bound defaults to 0: >>> idx = Idx(i, n); idx.lower, idx.upper (0, n - 1) >>> idx = Idx(i, 4); idx.lower, idx.upper (0, 3) >>> idx = Idx(i, oo); idx.lower, idx.upper (0, oo) TNc Pt|tr t|d}tt t ||f\}}|j r|js td|S|js tdt|rt|dk7r ttdt|z|D]A}|jdus|tjus%|tjus8td|t!|f}nmt|t"rD|tjur t%|jr td |t!d |d z f}n|rttd |f}t#j&|g|i|}d|j(d <d|j(d<|S)NT)integerzIndex is not an integer number.z%Idx object requires an integer label.zC Idx range tuple must have length 2, but got %sFz#Idx object requires integer bounds.z)Idx object requires an integer dimension.rr*zc The range must be an ordered iterable or integer SymPy expression.finitereal)r-r.r r2r3r is_Number is_integerr1rr5 ValueErrorrr InfinityNegativeInfinityrrr r6r`)r9rranger<boundr;r=s rr6z Idx.__new__s eS !5$/EC%89 u ??## ABBLCD D  5zQ -FHKE -S"TUU K$$-%qzz2I!););;#$IJJ K%-'D t $AJJ&9U5E5E+F KLL%519--D J(-./ /6Dll3111%)"#'  rc |jdS)aaReturns the label (Integer or integer expression) of the Idx object. Examples ======== >>> from sympy import Idx, Symbol >>> x = Symbol('x', integer=True) >>> Idx(x).label x >>> j = Symbol('j', integer=True) >>> Idx(j).label j >>> Idx(j + 1).label j + 1 rrgrJs rrz Idx.labels$yy|rcF |jddS#t$rYywxYw)zReturns the lower bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).lower 0 >>> Idx('j', 5).lower 0 >>> Idx('j').lower is None True r*rNr; IndexErrorrJs rrmz Idx.lower+  99Q<? "      cF |jddS#t$rYywxYw)zReturns the upper bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).upper 1 >>> Idx('j', 5).upper 4 >>> Idx('j').upper is None True r*NrrJs rrlz Idx.upperrrc8|j|jSr%rrs rr}z Idx._sympystrrrc|jjr|jjSt|jSr%)r is_SymbolrKr.rJs rrKzIdx.names)"&**"6"6tzzKC OKrc|hSr%rrJs rrzIdx.free_symbolss v rr%)rrrrr is_finiteis_realrrrMr6rrrmrlr}rKrrrrrrDs6pJIGIGI%N&((%LLrrc|j|n |j}|j|n |j}|j|j|k\dk(ry|j|j|kdk(ryyNTFrlrmlhsrhs other_upper other_lowers r _eval_is_gersi*# K*# K yy#)){":t!C yy#))k"9d!B rc|}|}|j|j|k\dk(ry|j|j|kdk(ryyr)rmrlrs rrrKKK yy#)){":t!C yy#))k"9d!B rc|}|}|j|j|kdk(ry|j|j|kDdk(ryyrrrs rrrrrN)#rcollections.abcrsympy.core.numbersrsympy.core.assumptionsr sympy.corerrrr sympy.core.symbolr r sympy.core.logicr r sympy.core.sympifyr(sympy.functions.special.tensor_functionsrsympy.multipledispatchrsympy.utilities.iterablesrrsympy.utilities.miscr Exceptionrrr/rrrrrrsVR%%,..92'C+>+ Y kdk\W%$ W%tn$nb #s   #v   &#  r