Example #1
0
def ang_mom_lowering(ang_mom=None, mag=None):
    """
    Args:    
        ang_mom: The total angular momentum quantum number
        mag: The magnetic quantum number
    
    Returns:    
        If ang_mom == None and mag== None, the general formula for the lowering operator for spherical harmonics is returned.    
        Else, the formula for the lowering operator is computed using Dirac notation
    
    Note:
        Bra(str(j), str(","), str(m))*h_b*sqrt(j*(j+1)-m*(m-1))*Ket(str(j), str(','), str(m-1))
    
    """

    L_x, L_y = symbols("L_x L_y")
    if ang_mom == None and mag == None:
        return Operator(L_x) - I * Operator(L_y)
    if ang_mom == j and mag == m:
        return Bra(str(j), str(","),
                   str(m)) * h_b * sqrt(j * (j + 1) - m * (m - 1)) * Ket(
                       str(j), str(','), str(m - 1))
    if (str(ang_mom), str(","), str(mag)) == (str(ang_mom), str(','),
                                              str(mag - 1)):
        return h_b * sqrt(ang_mom * (ang_mom + 1) - mag * (mag - 1))
    else:
        return 0
Example #2
0
def kinetic_energy(var=None):
    """

    Args:
        var: The variable in which the derivative is with respect to.

    Returns:
        The kinetic energy operator, with respect to the chosen parameter. 
        
    Note:
        The "1" in the derivative is a placeholder, which will be replaced.
        If var == None, the general linear operator is printed, with all three positional arguments "x", "y", and "z"

    """

    m = Symbol("m")
    if var == None:
        return (Operator(
            (-I * h_b * (Derivative("1", x)))**2) * (1 / (2 * m))) + (Operator(
                (-I * h_b *
                 (Derivative("1", y)))**2) * (1 / (2 * m))) + (Operator(
                     (-I * h_b * (Derivative("1", z)))**2) * (1 / (2 * m)))
    else:
        return (Operator(
            (-I * h_b * (Derivative("1", var)))**2) * (1 / (2 * m)))
Example #3
0
def ang_mom_raising(ang_mom=None, mag=None):
    """
    Args:    
        ang_mom: The total angular momentum quantum number
        mag: The magnetic quantum number
    
    Returns:    
        If ang_mom == None and mag == None, the general formula for the raising operator for spherical harmonics is returned.    
        Else, the formula for the raising operator is computed using Dirac notation
    
    Note:
        Bra(str(j), str(","), str(m))*h_b*sqrt(j*(j+1)-m*(m+1))*Ket(str(j), str(','), str(m+1))

        .. math::
          \\langle j, m | \\hbar \\sqrt{ j (j+1) - m (m+1) }  | j, m+1 \\rangle
        
    """

    L_x, L_y, j, m = symbols("L_x L_y j m")
    if ang_mom == None and mag == None:
        return Operator(L_x) + I * Operator(L_y)
    if ang_mom == j and mag == m:
        return Bra(str(j), str(","),
                   str(m)) * h_b * sqrt(j * (j + 1) - m * (m + 1)) * Ket(
                       str(j), str(','), str(m + 1))
    if (str(ang_mom), str(","), str(mag)) == (str(ang_mom), str(','),
                                              str(mag + 1)):
        return h_b * sqrt(ang_mom * (ang_mom + 1) - mag * (mag + 1))
    else:
        return 0
Example #4
0
def logOp(O, n):
    lg = sp.S(1)
    sig = -1
    for i in range(1, n):
        sig *= -1
        f = sp.Rational(sig, i)
        op = O - sp.S(1)
        op = delterms(op, Operator("A"), Operator("B"), n - i + 1)
        lg += f * op**i
    return lg
Example #5
0
def comm_1(commutator_1, commutator_2, aux):
    """
    This function is not used directly, it is only used in the comm() function below. 

    Args:
        commutator_1: The first operator in the commutator
        commutator_2: The second operator in the commutator
        aux: The auxiliary function. This is defined below, as F(x).

    Returns:
        The commutator of commutator_1 and commutator_2 with respect to the auxiliary function.

    """

    return expand((Commutator(Operator(commutator_1), Operator(commutator_2)) *
                   aux).doit())
Example #6
0
def factorization(expr, var):
    """
    Args:    
        expr: the expression of interest
        var: the variable of interest. This is most likely going to be the same variable used in the auxiliary function.
        
    Returns:    
        The simplified commutator. This is only used when both of the operators in the commutator are angular momentum operators.
    
    """

    L_z, L_y, L_x = symbols("L_z, L_y, L_x")
    if var == z:
        return comm(Operator(z), lin_mom(z), f(z)) * L_z
    if var == y:
        return comm(Operator(y), lin_mom(y), f(y)) * L_y
    if var == x:
        return comm(Operator(x), lin_mom(x), f(x)) * L_x
Example #7
0
def comm_steps(commutator_1, commutator_2, aux):
    """
    Args:    
        commutator_1: the first operator
        commutator_2: the second operator
        aux: the auxiliary function
    
    Returns:    
        Three main steps used to solve a commutator. The first is the printed commutator in brackets, the second is the expansion, and the 
        third output will be the answer. Please note that as of now, the code does not understand the 
        addition/subtraction/multiplication/division of commutators, and so if there are multiple commutators in a line (ex: 
        comm_steps(comm(A, B) - comm(C, D))) the code will not process this and therefore each individual commutator needs to have its own 
        line.
        
    """

    return display(Commutator(Operator(commutator_1), Operator(commutator_2))*aux),\
                    display(comm_1(Operator(commutator_1), Operator(commutator_2), aux)),\
                            display(expression_replace(comm_1(Operator(commutator_1), Operator(commutator_2), aux), find_variable(aux)))
Example #8
0
    def __new__(cls, *args, **hints):
        if not len(args) in [1, 2]:
            raise ValueError("1 or 2 parameters expected, got %s" % args)

        if len(args) == 1:
            args = (args[0], Integer(1))

        if len(args) == 2:
            args = (args[0], Integer(args[1]))

        return Operator.__new__(cls, *args)
Example #9
0
    def __new__(cls, *args, **hints):
        if not len(args) in [1, 2]:
            raise ValueError('1 or 2 parameters expected, got %s' % args)

        if len(args) == 1:
            args = (args[0], Integer(1))

        if len(args) == 2:
            args = (args[0], Integer(args[1]))

        return Operator.__new__(cls, *args)
Example #10
0
def expand_xp_to_aA(expr_string, dim, evaluate=True, hbar=1):
    x = Operator('x')
    p = Operator('p')
    expr = parse_expr(expr_string, local_dict={'x': x, 'p': p})
    a_ = Operator('a')
    A_ = Operator('A')
    expr_ = expr.subs([(x, (a_ + A_) * sym.sqrt(hbar / 2)),
                       (p, (a_ - A_) * sym.sqrt(hbar / 2) / 1j)])
    expr_ = expr_.expand()
    aA = str(expr_)
    if evaluate == False:
        return aA

    a = sym.MatrixSymbol('a', dim, dim)
    A = sym.MatrixSymbol('A', dim, dim)
    down = Matrix(downMatLeft(dim, 1))
    up = Matrix(upMatLeft(dim, 1))
    expr__ = parse_expr(aA, local_dict={'a': a, 'A': A, 'I': sym.I})
    expr__ = expr__.subs([(a, down), (A, up)])
    res = matrix2numpy(expr__, dtype=np.complex)
    return res
Example #11
0
def potential_energy(var):
    """
    
    Args:
        var: The variable for the given function. This is usually "x", "y" or "z".
    
    Returns:
        The general potential energy operator, v(x)
    
    """

    return Operator(Function("v")(var))
Example #12
0
def f(var):
    """

    Args:
        var: This is what the auxiliary function is with respect to. It should also match the parameters of the other arguments in the 
        comm() function. (example: if one operator is lin_mom(y), the auxiliary function should be f(y).

    Returns:
        This is the auxiliary function, commonly used in the comm() function.
        This simply returns "f(x)", x being with chosen parameter.

    """

    return Operator(Function('f')(var))
Example #13
0
def generate_variables(name, n_vars=1, hermitian=None, commutative=True):
    """Generates a number of commutative or noncommutative variables

    :param name: The prefix in the symbolic representation of the noncommuting
                 variables. This will be suffixed by a number from 0 to
                 n_vars-1 if n_vars > 1.
    :type name: str.
    :param n_vars: The number of variables.
    :type n_vars: int.
    :param hermitian: Optional parameter to request Hermitian variables .
    :type hermitian: bool.
    :param commutative: Optional parameter to request commutative variables.
                        Commutative variables are Hermitian by default.
    :type commutative: bool.

    :returns: list of :class:`sympy.physics.quantum.operator.Operator` or
              :class:`sympy.physics.quantum.operator.HermitianOperator`
              variables or `sympy.Symbol`

    :Example:

    >>> generate_variables('y', 2, commutative=True)
    [y0, y1]
    """

    variables = []
    for i in range(n_vars):
        if n_vars > 1:
            var_name = '%s%s' % (name, i)
        else:
            var_name = '%s' % name
        if commutative:
            if hermitian is None or hermitian:
                variables.append(Symbol(var_name, real=True))
            else:
                variables.append(Symbol(var_name, complex=True))
        elif hermitian is not None and hermitian:
            variables.append(HermitianOperator(var_name))
        else:
            variables.append(Operator(var_name))
    return variables
import sympy as sym
from sympy.physics.quantum import Operator
from sympy.physics.quantum.operator import DifferentialOperator

D0, D1, D2 = sym.symbols('D0 D1 D2', real=True)
x, x0, x1, x2, x3 = sym.symbols('x x0 x1 x2 x3', real=True)
eps, omega0, mu = sym.symbols('eps omega0 mu', real=True)
A, B = sym.symbols('A B', real=True)
T0, T1, T2 = sym.symbols('T0 T1 T2', real=True)
D0 = Operator('D0')
D1 = Operator('D1')
f = sym.Function('f')
d = DifferentialOperator(sym.diff(f(x), x), f(x))
print(sym.pretty(d(1 / x)))
# ddt2 = D0**2 + 2 * eps * D0 * D1 + eps**2 * (D1**2 + 2 * D0 * D2)
# ddt = D0 + eps * D1

ddt2 = D0**2 + 2 * eps * D0 * D1
ddt = D0 + eps * D1

# x = x0 + eps * x1 + eps**2 * x2 + eps**3 * x3
x = x0 + eps * x1

f = ddt * x - (ddt * x)**3
equ = ddt2 * x + omega0**2 * x - eps * f
# equ = ddt2 * x + 2 * eps * mu * ddt * x + x + eps * x**3
equ = equ.expand()

print(sym.pretty(equ.subs({eps: 0})))
print(sym.pretty(equ.coeff(eps)))
# print(sym.pretty(equ.coeff(eps**2)))
Example #15
0
#!/usr/bin/env python
# -*- coding: utf-8 -*- 
# 07-12-2020
# alex
# test_relE.py

import sympy as sp
from sympy.physics.quantum import Operator, Commutator
import sys
sys.path.insert(0, '../')
import relations as rl
from qolib import *

if __name__ == "__main__":
    A = Operator("A")
    B = Operator("B")

    E = llegir_base("niats_base.txt", A, B)
    ord_bch = len(rl.tamE) + 1
    for i in range(1, ord_bch):
        for j in range(1, rl.tamE[i - 1] + 1):
            for k in range(1, ord_bch):
                for l in range(1, rl.tamE[k - 1] + 1):
                    if rl.relE[i][j][k][l][0][0] != 0:
                        res = rl.relE[i][j][k][l]
                        cad = "[E" + str(i) + str(j) + ", E" + str(k) + str(l) + "] - ("
                        primer = True
                        resq = sp.S(0)
                        for m in res:
                            resq += sp.Rational(m[0], m[1])*E[m[2]][m[3]]
                            if m[0] > 0 and primer == False:
Example #16
0
 def __new__(cls, *args, **hints):
     return Operator.__new__(cls, *args, **hints)
Example #17
0
complete_a = expr_a.subs(a_0, expr_a_0).subs(b_0, expr_b_0)
complete_a = complete_a.subs(omega_p, expr_omega_p)
complete_a = complete_a.subs(omega_0, expr_omega_0)
complete_a = complete_a.subs(Omega, expr_Omega)

complete_b = expr_b.subs(a_0, expr_a_0).subs(b_0, expr_b_0)
complete_b = complete_b.subs(omega_p, expr_omega_p)
complete_b = complete_b.subs(omega_0, expr_omega_0)
complete_b = complete_b.subs(Omega, expr_Omega)

# =============================================================================
# Spin Related Definitions
# =============================================================================

hbar = symbols(r"\hbar", real=True, positive=True)
sigma_x = Operator(r"\mathbf{\sigma}_x")
sigma_y = Operator(r"\mathbf{\sigma}_y")
sigma_z = Operator(r"\mathbf{\sigma}_z")

expr_sigma_x = Matrix([[0, 1], [1, 0]])
expr_sigma_y = Matrix([[0, -I], [I, 0]])
expr_sigma_z = Matrix([[1, 0], [0, -1]])

S_x = Operator("S_x")
S_y = Operator("S_y")
S_z = Operator("S_z")

expr_S_x = (hbar / 2) * expr_sigma_x
expr_S_y = (hbar / 2) * expr_sigma_y
expr_S_z = (hbar / 2) * expr_sigma_z
Example #18
0
from sympy.physics.quantum import Commutator, Dagger, Operator
from sympy.abc import x, y

A = Operator('A')
B = Operator('B')
C = Operator('C')
comm = Commutator(A, B)

#[A,B]
comm.doit()
#A*B - B*A
comm = Commutator(B, A)
comm
#-[A,B]
Commutator(3 * x * A, x * y * B)
#3*x**2*y*[A,B]
Commutator(A + B, C).expand(commutator=True)
#[A,C] + [B,C]
Commutator(A, B + C).expand(commutator=True)
#[A,B] + [A,C]
Commutator(A * B, C).expand(commutator=True)
#[A,C]*B + A*[B,C]
Commutator(A, B * C).expand(commutator=True)
#[A,B]*C + B*[A,C]
Dagger(Commutator(A, B))
#-[Dagger(A),Dagger(B)]
Example #19
0
def time_deriv1(var, order=1):
    pq_s = Symbol("pq_s")
    aux = Operator(Function("f")(q))
    pq_s = (Operator(p) * Operator(q) + Operator(q) * Operator(p)) / 2

    h1 = (expand(((Commutator(Operator(var**(order)), ham(
        p, q)).expand(commutator=True)) * aux).doit()))

    if var == V:
        der = f'((p)*(Derivative(V, q, {order}+1))+(Derivative(V, q, {order}+1))*(p))/2/m'

    if var == p:
        p1 = lin_mom(q, order)
        h1 = (str(simplify(h1)).replace("p", str(Operator(p1))))

    else:
        h1 = str(
            expand(((Commutator(ham(p, q), Operator(
                var**(order))).expand(commutator=True)) * aux).doit()))
        h1 = h1.replace("pq_s", "((p*q+q*p))/2")

    start_points = []
    end_points = []

    start = 0

    s = h1.find("Derivative(1, q)", start)
    while s != -1:
        s = h1.find("Derivative(1, q)", start)

        if var == pq_s:
            start = s + len(f"Derivative(1, q) ")
        else:
            start = s + len(f"Derivative(1, q)")

        start_points.append(s)
        if s == -1:
            break

        if var == pq_s:
            e = h1.find(" ", start + 1)
        else:
            e = h1.find("f(q)", start) + 4

        end_points.append(e)

    if start_points[-1] == -1:
        start_points.remove(start_points[-1])

    new_derivative_function = []
    replace_spot = []

    for i in range(len(start_points)):
        func = h1[start_points[i]:end_points[i]]
        func = start_points[i] + len(f"Derivative(1, q)")
        func1 = h1.find("*", func, end_points[i])

        repl = h1[start_points[i]:end_points[i]].find("1") + start_points[i]
        replace_spot.append(repl)

        if var == p:
            new_func = h1[func1:end_points[i]]
            new_derivative_function.append(new_func)

        else:
            new_func = h1[func1 - 3:end_points[i]]
            new_derivative_function.append(new_func)

    temp = h1.split(" ")

    position_list = []
    temp_list = []

    for i in range(len(temp)):
        if var == p:
            st = 1
        else:
            st = 0

        for r in range(st, len(new_derivative_function)):

            if temp[i].find(new_derivative_function[r]) != -1:
                temp[i] = temp[i].replace(new_derivative_function[r], "")

        if temp[i].find("Derivative") == -1:
            continue

        else:
            position = temp[i].find("1,")
            if position != -1:
                position_list.append(position)
                temp_list.append(i)

    TL = len(temp_list) - 1
    nested_list = []
    while TL > -1:
        r = [temp_list[TL], position_list[TL]]
        nested_list.append(r)
        TL -= 1
        if TL == -1:
            break

    nested_list.reverse()

    if var == p:
        for i in range(len(nested_list)):
            temp[nested_list[i][0]] = \
                temp[nested_list[i][0]].replace(temp[nested_list[i][0]][nested_list[i][1]], new_derivative_function[i][1:])

    else:
        for i in range(len(nested_list)):
            temp[nested_list[i][0]] = \
                temp[nested_list[i][0]].replace(temp[nested_list[i][0]][nested_list[i][1]], "1/" + new_derivative_function[i][1:])

    string = " ".join(temp)
    if "(*" in string:
        string = string.replace("(*", "(")
    s = sympify(string)
    s1 = expand(s.doit())
    if var == p:
        repl = 1
        if order == 2:
            s1 = s1 / 2
    else:
        repl = 0
    s2 = str(s1).replace("hbar*i", "1").replace("I", "1").replace(
        "f(q)",
        f"{repl}").replace(f"hbar**2*i**2*Derivative({repl}, q)",
                           "p").replace(f"Derivative({repl}, q)", "p").replace(
                               "hbar**2*i**2",
                               "1").replace("Derivative(v(q), (q, 2))", "0")

    if var == V:
        return sympify(der)  #/(i*hbar)
    else:
        return sympify(s2)  #/(i*hbar)
Example #20
0
def expression_replace(expr, var):
    """
    
    This is only used within the "comm()" function. 
    
    expression_replace(expr, var)

    Args:
        expr: The expanded commutator to be replaced
        var: The variable/parameter with respect to the chosen commutator.

    Returns:
        This replaces the Derivative(1, x) present in the expanded commutator with either Derivative(F(x), x) or Derivative(x*F(x), x).
        
    Note: 
        The above states "x", but can be done for x, y, or z variables.
        The "expr" parameter is a str()


    """

    L_x, L_z, L_y, p_x, p_y, p_z, x, y, z = symbols(
        "L_x, L_z, L_y, p_x, p_y, p_z, x, y, z")

    if str('[p_x,x]') in str(expr):
        return sympify(
            str(
                sympify(
                    str(expr).replace(
                        str('[p_x,x]'),
                        str(
                            expression_replace(
                                comm(lin_mom(var), Operator(var), f(var)),
                                K))))).replace(str(p_y * z - p_z * y),
                                               str(-L_x)))

    if str('[p_y, y]') in str(expr):
        return sympify(
            str(
                sympify(
                    str(R).replace(
                        str('[p_y,y]'),
                        str(
                            expression_replace(
                                comm(lin_mom(var), Operator(var), f(var)),
                                K))))).replace(str(p_x * z - p_z * x),
                                               str(-L_y)))

    if str('[p_z,z]') in str(expr):
        return sympify(
            str(
                sympify(
                    str(expr).replace(
                        str('[p_z,z]'),
                        str(
                            expression_replace(
                                comm(lin_mom(var), Operator(var), f(var)),
                                K))))).replace(str(p_x * y - p_y * x),
                                               str(-L_z)))

    else:

        expr = str(expr)

        starting_pos = expr.find(f"Derivative(1, {var})")
        second = expr[starting_pos + 17:].find(f"Derivative(1, {var})")

        w = expr[starting_pos + 17:].find(f"f({var})")
        wn = starting_pos + 17 + w + len(f"f({var})")
        f = expr[starting_pos + second +
                 len(f"Derivative(1, {var})") * 2:].find(f"f({var})")
        fn = starting_pos + second + len(
            f"Derivative(1, {var})") * 2 + f + len(f"f({var})")

        k = f"Derivative(1, {var}), {var})"

        if k in expr:
            term1 = expr[starting_pos + 21:wn]
            term2 = expr[starting_pos + second + 17 + 21:fn]
            one = f"Derivative({term1}, {var}), {var})"
            two = f"Derivative({term2}, {var}), {var})"

        else:
            term1 = expr[starting_pos + len(f"Derivative(1, {var})") + 1:wn]
            if len(f"{var}") == 1:
                term2 = expr[starting_pos + second +
                             len(f"Derivative(1, {var})") * 2 + 2:fn]
            if len(f"{var}") == 2:
                term2 = expr[starting_pos + second +
                             len(f"Derivative(1, {var})") * 2 + 1:fn]
            if len(f"{var}") == 3:
                term2 = expr[starting_pos + second +
                             len(f"Derivative(1, {var})") * 2:fn]

            one = f"Derivative({term1}, {var})"
            two = f"Derivative({term2}, {var})"

        x1 = expr.replace(expr[starting_pos + second + 17:fn],
                          two).replace(expr[starting_pos:wn], one)
        x2 = sympify(x1).doit()
        x3 = simplify(x2.replace(i**2, -1))

        return x3
Example #21
0
 def default_args(self):
     return (Operator("a"), Symbol("t"))
Example #22
0
# alex
# test_relZ.py

import sympy as sp
from sympy.physics.quantum import Operator, Commutator
import sys
sys.path.insert(0, '../')
import relations as rl
from qolib import *

if __name__ == "__main__":
    n_max = 9
    Y = []
    Y.append([0])
    for i in range(n_max + 1):
        Y.append(Operator("Y_{%d}" % (i + 1)))

    Z = llegir_baseCAdj("compAdj_base.txt", Y)

    ord_bch = len(rl.tamZ) + 1
    for i in range(1, ord_bch):
        for j in range(1, rl.tamZ[i - 1] + 1):
            for k in range(1, ord_bch):
                for l in range(1, rl.tamZ[k - 1] + 1):
                    if rl.relZ[i][j][k][l][0][0] != 0:
                        res = rl.relZ[i][j][k][l]
                        cad = "[Z" + str(i) + str(j) + ", Z" + str(k) + str(
                            l) + "] - ("
                        primer = True
                        resq = sp.S(0)
                        for m in res:
Example #23
0
def comm(commutator_1, commutator_2, aux):
    L_z, L_y, L_x = symbols("L_z, L_y, L_x")
    """
    This function has a few different outputs, depending on the parameters.

    Args:
        commutator_1: the first operator
        commutator_2: the second operator
        aux: the auxiliary function

    Returns:
        This function automatically returns a solved commutator. For more complicated commutators involving the angular momentum operators (L_z, L_y, L_x), please make sure that the correct notation is being used (ex: if you want the angular momentum operator in the "x" direction, please use "L_x"
    
    
    Note:    
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols("x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        L_z = x*p_y - y*p_x
        L_y = z*p_x - x*p_z
        L_x = y*p_z - z*p_y

    """

    if commutator_1 == L_z and commutator_2 == L_y:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(x * p_y), Operator(z * p_x)) * aux +
                Commutator(Operator(y * p_x), Operator(x * p_z)) * aux -
                Commutator(Operator(x * p_y), Operator(x * p_z)) * aux -
                Commutator(Operator(y * p_x), Operator(z * p_x)) * aux)
    if commutator_1 == L_z and commutator_2 == L_x:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(x * p_y), Operator(y * p_z)) * aux +
                Commutator(Operator(y * p_x), Operator(z * p_y)) * aux -
                Commutator(Operator(x * p_y), Operator(z * p_y)) * aux -
                Commutator(Operator(y * p_x), Operator(y * p_z)) * aux)
    if commutator_1 == L_y and commutator_2 == L_z:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(z * p_x), Operator(x * p_y)) * aux +
                Commutator(Operator(x * p_z), Operator(y * p_x)) * aux -
                Commutator(Operator(z * p_x), Operator(y * p_x)) * aux -
                Commutator(Operator(x * p_z), Operator(x * p_y)) * aux)
    if commutator_1 == L_y and commutator_2 == L_x:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(z * p_x), Operator(y * p_z)) * aux +
                Commutator(Operator(x * p_z), Operator(z * p_y)) * aux -
                Commutator(Operator(z * p_x), Operator(z * p_y)) * aux -
                Commutator(Operator(x * p_z), Operator(y * p_z)) * aux)
    if commutator_1 == L_x and commutator_2 == L_z:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(y * p_z), Operator(x * p_y)) * aux +
                Commutator(Operator(z * p_y), Operator(y * p_x)) * aux -
                Commutator(Operator(y * p_z), Operator(y * p_x)) * aux -
                Commutator(Operator(z * p_y), Operator(x * p_y)) * aux)
    if commutator_1 == L_x and commutator_2 == L_y:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(y * p_z), Operator(z * p_x)) * aux +
                Commutator(Operator(z * p_y), Operator(x * p_z)) * aux -
                Commutator(Operator(y * p_z), Operator(x * p_z)) * aux -
                Commutator(Operator(z * p_y), Operator(z * p_x)) * aux)

    if commutator_1 == L_z:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(x * p_y), Operator(commutator_2)) * aux -
                Commutator(Operator(y * p_x), Operator(commutator_2)) * aux)
    if commutator_1 == L_y:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(z * p_x), Operator(commutator_2)) * aux -
                Commutator(Operator(x * p_z), Operator(commutator_2)) * aux)
    if commutator_1 == L_x:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(y * p_z), Operator(commutator_2)) * aux -
                Commutator(Operator(z * p_y), Operator(commutator_2)) * aux)
    if commutator_2 == L_z:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(commutator_1), Operator(x * p_y)) * aux -
                Commutator(Operator(commutator_1), Operator(y * p_x)) * aux)
    if commutator_2 == L_y:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(commutator_1), Operator(z * p_x)) * aux -
                Commutator(Operator(commutator_1), Operator(x * p_z)) * aux)
    if commutator_2 == L_x:
        x, p_y, y, p_x, z, p_z, L_z, L_y, L_x = symbols(
            "x, p_y, y, p_x, z, p_z, L_z, L_y, L_x")
        return (Commutator(Operator(commutator_1), Operator(y * p_z)) * aux -
                Commutator(Operator(commutator_1), Operator(z * p_y)) * aux)
    else:
        return (expression_replace(
            comm_1(Operator(commutator_1), Operator(commutator_2), aux),
            find_variable(aux)))
Example #24
0
from sympy import symbols
from sympy.physics.quantum import AntiCommutator
from sympy.physics.quantum import Operator, Dagger
x, y = symbols('x,y')
A = Operator('A')
B = Operator('B')

ac = AntiCommutator(A, B)
ac
print(ac)

#doit multiple the anti A*B + B*A
ac.doit()
#define un autre anti
ab = AntiCommutator(3 * x * A, x * y * B)
#Adjoint operations applied to the anticommutator are properly applied to the arguments:
aa = Dagger(AntiCommutator(A, B))
Example #25
0
 def __new__(cls, *args, **hints):
     return Operator.__new__(cls, *args, **hints)
Example #26
0
    def __new__(cls, *args, **hints):
        if not len(args) in [2]:
            raise ValueError('2 parameters expected, got %s' % str(args))

        return Operator.__new__(cls, *args)
Example #27
0
def ham(p, q):
    p, q, v, mass = symbols("p q v mass")
    v = Function("v")
    return Operator(lin_mom(q, 2) / (2 * mass)) + Operator(v(q))
Example #28
0
    SigmaZ,
    SigmaMinus,
    SigmaPlus,
    qsimplify_pauli,
)
from sympy.physics.quantum.pauli import SigmaZKet, SigmaZBra
from sympy.testing.pytest import raises


sx, sy, sz = SigmaX(), SigmaY(), SigmaZ()
sx1, sy1, sz1 = SigmaX(1), SigmaY(1), SigmaZ(1)
sx2, sy2, sz2 = SigmaX(2), SigmaY(2), SigmaZ(2)

sm, sp = SigmaMinus(), SigmaPlus()
sm1, sp1 = SigmaMinus(1), SigmaPlus(1)
A, B = Operator("A"), Operator("B")


def test_pauli_operators_types():

    assert isinstance(sx, SigmaOpBase) and isinstance(sx, SigmaX)
    assert isinstance(sy, SigmaOpBase) and isinstance(sy, SigmaY)
    assert isinstance(sz, SigmaOpBase) and isinstance(sz, SigmaZ)
    assert isinstance(sm, SigmaOpBase) and isinstance(sm, SigmaMinus)
    assert isinstance(sp, SigmaOpBase) and isinstance(sp, SigmaPlus)


def test_pauli_operators_commutator():

    assert Commutator(sx, sy).doit() == 2 * I * sz
    assert Commutator(sy, sz).doit() == 2 * I * sx
def nested_commutator_cc(nested_level,
                         cluster_levels,
                         max_cu=3,
                         max_n_open=6,
                         min_n_open=0,
                         for_commutator=True,
                         expand_hole=True,
                         single_reference=False,
                         unitary=False,
                         n_process=1,
                         hermitian_tensor=True):
    """
    Compute the BCH nested commutator in coupled cluster theory.
    :param nested_level: the level of nested commutator
    :param cluster_levels: a list of integers for cluster operator, e.g., [1,2,3] for T1 + T2 + T3
    :param max_cu: max value of cumulant allowed for contraction
    :param max_n_open: the max number of open indices for contractions kept for return
    :param min_n_open: the min number of open indices for contractions kept for return
    :param for_commutator: compute only non-zero terms for commutators if True
    :param expand_hole: expand HoleDensity to Kronecker minus Cumulant if True
    :param single_reference: use single-reference amplitudes if True
    :param unitary: use unitary formalism if True
    :param n_process: number of processes launched for tensor canonicalization
    :param hermitian_tensor: assume tensors being Hermitian if True
    :return: a list of contracted canonicalized Term objects
    """
    if not isinstance(nested_level, int):
        raise ValueError("Invalid nested_level (must be an integer)")
    if not isinstance(cluster_levels, Iterable):
        raise ValueError("Invalid type for cluster_operator")
    if not all(isinstance(t, int) for t in cluster_levels):
        raise ValueError(
            "Invalid content in cluster_operator (must be all integers)")

    scale_factor = 1.0 / factorial(nested_level)
    out = []

    hole_label = 'c' if single_reference else 'h'
    particle_label = 'v' if single_reference else 'p'

    # symbolic evaluate nested commutator
    t = sum(Operator(f'T{i}') for i in cluster_levels)
    h = HermitianOperator('H1') + HermitianOperator('H2')
    a = t - Dagger(t) if unitary else t

    for term in sympy_nested_commutator_recursive(nested_level, h,
                                                  a).doit().expand().args:
        coeff, tensors = term.as_coeff_mul()
        factor = scale_factor * int(coeff)

        tensor_names = []
        for tensor in tensors:
            if isinstance(tensor, Pow):
                if isinstance(tensor.base, Dagger):
                    tensor_names += ['X' + str(tensor.base.args[0])[1:]] * int(
                        tensor.exp)
                else:
                    tensor_names += [str(tensor.base)] * int(tensor.exp)
            else:
                if isinstance(tensor, Dagger):
                    tensor_names.append('X' + str(tensor.args[0])[1:])
                else:
                    tensor_names.append(str(tensor))

        list_of_terms = []
        start = 0
        for name in tensor_names:
            real_name, n_body = name[0], int(name[1:])
            if real_name == 'T' or real_name == 'X':
                list_of_terms.append(
                    cluster_operator(n_body,
                                     start=start,
                                     excitation=(real_name == 'T'),
                                     hole_label=hole_label,
                                     particle_label=particle_label))
                start += n_body
            else:
                list_of_terms.append(hamiltonian_operator(n_body))

        out += contract_terms(list_of_terms, max_cu, max_n_open, min_n_open,
                              factor, for_commutator, expand_hole, n_process,
                              hermitian_tensor)

    return combine_terms(out)