K i)I$dZddlmZddlmZddlmZddlmZddl m Z ddl m Z ddl mZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZmZmZddlm Z m!Z!ddl"m#Z#ddl$m%Z%m&Z&gdZ'dZ(dZ)dZ*dZ+dZ,ddddZ-dZ.dZ/y)zLogic for representing operators in state in various bases. TODO: * Get represent working with continuous hilbert spaces. * Document default basis functionality. )Add)Expr)Mul)I)Pow) integrate)Dagger) Commutator)AntiCommutator) InnerProduct)QExpr) TensorProduct)flatten_scalar)KetBaseBraBase StateBase)Operator OuterProduct)qapply)operators_to_statestate_to_operators) representrep_innerproductrep_expectationintegrate_result get_basisenumerate_statesc t|trq|jr t|S|jr t |S|j r t |S|js|js |tk(r t|Std|z)z/Convert from a SymPy scalar to a Python scalar.zExpected number, got: %r) isinstancer is_Integerintis_Floatfloat is_Rational is_Numberis_NumberSymbolrcomplex TypeError)es e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/physics/quantum/represent.py_sympy_to_scalarr+*sl!T <<q6M ZZ8O ]]8O [[A--a1:  .2 33c |jdd}|dk(rddl}t|tr;t|ts+d|d<t |fi|}|||d< |j di|St|tr>t|jdfi|}|jd dD]}|t|fi|z}|St|t r|j#\}} |d vr t%| } t|fi|}|d k(r2| dkr-dd lm} | } | |j+j-}|dk(rj.j1|| S|| zSt|t2r+|jD cgc]} t| fi|} } t3| St|t4r"t5t|jdfi|St|t6rA|jd} |jd }tt9| |t9|| z fi|St|t:rA|jd} |jd }tt9| |t9|| zfi|St|t8tt<fs|d vr t%|S|St|t8tt<fst?d|zd|vr|dxxd z cc<nd |d<d|vrg|d<t|jdfi|}|jd}tA|jddD]} t|tr%|dxxd z cc<|djC|dnt|trt| tr|dxxd z cc<not|tr(t| tr|djC|dn7t|tr't| tr|djC|dt| fi|}|dk(r)t|jDr|jG||}n||z}| }tI|}tK||fi|}|S#t$r}d |d<t|ttfr* t|fi|cYd}~S#t$r t|wxYwt|tr* t|fi|cYd}~S#t$r t|wxYwt|d}~wwxYwcc} w)aF Represent the quantum expression in the given basis. In quantum mechanics abstract states and operators can be represented in various basis sets. Under this operation the follow transforms happen: * Ket -> column vector or function * Bra -> row vector of function * Operator -> matrix or differential operator This function is the top-level interface for this action. This function walks the SymPy expression tree looking for ``QExpr`` instances that have a ``_represent`` method. This method is then called and the object is replaced by the representation returned by this method. By default, the ``_represent`` method will dispatch to other methods that handle the representation logic for a particular basis set. The naming convention for these methods is the following:: def _represent_FooBasis(self, e, basis, **options) This function will have the logic for representing instances of its class in the basis set having a class named ``FooBasis``. Parameters ========== expr : Expr The expression to represent. basis : Operator, basis set An object that contains the information about the basis set. If an operator is used, the basis is assumed to be the orthonormal eigenvectors of that operator. In general though, the basis argument can be any object that contains the basis set information. options : dict Key/value pairs of options that are passed to the underlying method that finds the representation. These options can be used to control how the representation is done. For example, this is where the size of the basis set would be set. Returns ======= e : Expr The SymPy expression of the represented quantum expression. Examples ======== Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp`` method, the ket can be represented in the z-spin basis. >>> from sympy.physics.quantum import Operator, represent, Ket >>> from sympy import Matrix >>> class SzUpKet(Ket): ... def _represent_SzOp(self, basis, **options): ... return Matrix([1,0]) ... >>> class SzOp(Operator): ... pass ... >>> sz = SzOp('Sz') >>> up = SzUpKet('up') >>> represent(up, basis=sz) Matrix([ [1], [0]]) Here we see an example of representations in a continuous basis. We see that the result of representing various combinations of cartesian position operators and kets give us continuous expressions involving DiracDelta functions. >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra >>> X = XOp() >>> x = XKet() >>> y = XBra('y') >>> represent(X*x) x*DiracDelta(x - x_2) formatsympynumpyrNF replace_nonebasisT)r0 scipy.sparser4)invzMul expected, got: %rindexunities)&getr0rr rr _representNotImplementedErrorrrrrrrrargsr as_base_expr+scipy.sparse.linalgr5tocsctocsrlinalg matrix_powerrr r rr r r(reversedappendndarraymatmulrr)exproptionsr.np temp_basisstrerrresultr=baseexpr5argnew_argsABlast_argnext_args r*rr8sf[[7 +F $z$ 'E"'t/w/  !)GG  2"4??-W- -& D# 499Q<373IIabM 9Di888F 9 D# $$& c . ."3'C)) ^ #a /%Ctzz|$**,D W 99))$4 4s{ D- (9=C#Ic-W-CCh'' D& !i ! 8899 D* % IIaL IIaLQSAY.:':: D. ) IIaL IIaLQSAY.:':: sL,? @ . .#D) ) dS, = >/$677'A  tyy} 0 0Fyy}H #2' h ) G  !  I  % %gg&6 7 ' *z#w/G G  !  ' *z#x/H I  % %gg&6 7 ' *z#w/G I  % %gg&6 7S,G, W Hbjj!AYYx0Ff_F#*F #F dF 6g 6F ME# 2'+GN #$' 236+D8S >RS' R82S 8S  SS c t|ttfs tdt |fi|}t|t s t dd|vrd|d<t||dd}t|tr|}|dj|k(r|dn|d}n(|d|k(r|djn|dj}|}t||}|j}|jdd}|j||}|S) a Returns an innerproduct like representation (e.g. ````) for the given state. Attempts to calculate inner product with a bra from the specified basis. Should only be passed an instance of KetBase or BraBase Parameters ========== expr : KetBase or BraBase The expression to be represented Examples ======== >>> from sympy.physics.quantum.represent import rep_innerproduct >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> rep_innerproduct(XKet()) DiracDelta(x - x_1) >>> rep_innerproduct(XKet(), basis=PxOp()) sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi)) >>> rep_innerproduct(PxKet(), basis=XOp()) sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi)) zexpr passed is not a Bra or KetzCan't form this representation!r6r3rr.r/) rrrr(rrr<rdualr doitr:_format_represent) rHrIr2 basis_ketsbraketprodrMr.s r*rrs8 dWg. /9:: d &g &E eY '!"CDDg!%)91=J$  *1 2 2d :z!} 1 %/]&z!}!!&qM..  S !D YY[F [[7 +F  # #FF 3F Mr,c d|vrd|d<t|ts tdt|fi|}|t|ts t dt ||dd}|dj}|d}t||z|z}|S)a! Returns an ```` type representation for the given operator. Parameters ========== expr : Operator Operator to be represented in the specified basis Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet >>> from sympy.physics.quantum.represent import rep_expectation >>> rep_expectation(XOp()) x_1*DiracDelta(x_1 - x_2) >>> rep_expectation(XOp(), basis=PxOp()) >>> rep_expectation(XOp(), basis=PxKet()) r6r3z(The passed expression is not an operatorz*Could not get basis kets for this operatorrWr) rrr(rrr<rrXr)rHrI basis_stater[r\r]rMs r*rr3s0g dH %BCCD,G,K*[)"D!"NOO!+ww/?CJ Q-  C Q-C CHSL !F Mr,c ht|ts|Sd|d<d|vr|jd}t|fi||d<n"t|dtst|fi||d<|j dd}||S|j dg}t |dk(r|St||}|Dcgc]}|jd}}|D]k} | |jvst|} | jjj} | jjj} t|| | | f}m|Scc}w)ak Returns the result of integrating over any unities ``(|x>>> from sympy import symbols, DiracDelta >>> from sympy.physics.quantum.represent import integrate_result >>> from sympy.physics.quantum.cartesian import XOp, XKet >>> x_ket = XKet() >>> X_op = XOp() >>> x, x_1, x_2 = symbols('x, x_1, x_2') >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2)) x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2) >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2), ... unities=[1]) x*DiracDelta(x - x_2) Tr1r2r8Nr7r)rrr=rrpoplenrlabel free_symbolsr hilbert_spaceintervalstartendr) orig_exprrMrIrPr2r7ketskcoordscoordbasis_oprhris r*rr_sAR fd # "GNgnnR $S4G4 () 4$Y:': KK &E } kk)R(G 7|q E7 +D"& 'Qaggaj 'F '< F'' ')%0H**3399E((1155Cvuc':;F < M(s%D/NT)r2r1c ||sy|pt|trt|jSt|trt|j St|t rt|}||SdSyt|t s t|ts;t|t r+t|}|yt|tr|St|St|tr|St|tr t|Sy)a Returns a basis state instance corresponding to the basis specified in options=s. If no basis is specified, the function tries to form a default basis state of the given expression. There are three behaviors: 1. The basis specified in options is already an instance of StateBase. If this is the case, it is simply returned. If the class is specified but not an instance, a default instance is returned. 2. The basis specified is an operator or set of operators. If this is the case, the operator_to_state mapping method is used. 3. No basis is specified. If expr is a state, then a default instance of its class is returned. If expr is an operator, then it is mapped to the corresponding state. If it is neither, then we cannot obtain the basis state. If the basis cannot be mapped, then it is not changed. This will be called from within represent, and represent will only pass QExpr's. TODO (?): Support for Muls and other types of expressions? Parameters ========== expr : Operator or StateBase Expression whose basis is sought Examples ======== >>> from sympy.physics.quantum.represent import get_basis >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> x = XKet() >>> X = XOp() >>> get_basis(x) |x> >>> get_basis(X) |x> >>> get_basis(x, basis=PxOp()) |px> >>> get_basis(x, basis=PxKet) |px> N) rr _make_default __class__r dual_classrrr issubclass)rHr2r1rI state_inststates r*rrsf }\ } dG $ 0 0 g & !23 3 h '+D1J","8J Cd C UH %%+ 5(0K"5) = y )L ' ' E9 % E9 %U##r,c8 |}|S#t$r|cYSwxYw)N)r()rHs r*rqrqs+v K  s  c&|d}t|dvr tdt|ts t dt|dk(r|d}|d|d<nt|d}|d|d < |j |fi|}|S#t$rg}Y|SwxYw) a Returns instances of the given state with dummy indices appended Operates in two different modes: 1. Two arguments are passed to it. The first is the base state which is to be indexed, and the second argument is a list of indices to append. 2. Three arguments are passed. The first is again the base state to be indexed. The second is the start index for counting. The final argument is the number of kets you wish to receive. Tries to call state._enumerate_state. If this fails, returns an empty list Parameters ========== args : list See list of operation modes above for explanation Examples ======== >>> from sympy.physics.quantum.cartesian import XBra, XKet >>> from sympy.physics.quantum.represent import enumerate_states >>> test = XKet('foo') >>> enumerate_states(test, 1, 3) [|foo_1>, |foo_2>, |foo_3>] >>> test2 = XBra('bar') >>> enumerate_states(test2, [4, 5, 10]) [?? eY '899 4yA~!W !%a a\ $Q $e$$Z;7; J  Js,B BB)0__doc__sympy.core.addrsympy.core.exprrsympy.core.mulrsympy.core.numbersrsympy.core.powerrsympy.integrals.integralsrsympy.physics.quantum.daggerr sympy.physics.quantum.commutatorr $sympy.physics.quantum.anticommutatorr "sympy.physics.quantum.innerproductr sympy.physics.quantum.qexprr #sympy.physics.quantum.tensorproductr!sympy.physics.quantum.matrixutilsrsympy.physics.quantum.staterrrsympy.physics.quantum.operatorrrsympy.physics.quantum.qapplyr!sympy.physics.quantum.operatorsetrr__all__r+rrrrrrqrr9r,r*rs  //7?;-=<CCA/T  4D6r)XHV"Nb 7r,