def E_s(x_, y_dim):
    # (2 a_j)^2
    xx_derivative = Matrix(9, 1, [0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0])
    xx_outer = TensorProduct(xx_derivative, xx_derivative.T)
    # (\frac{1}{2} (2 a_{j+1} x_i + b_{j+1} - 2 a_{j-1} x_i - b_{j-1}))^2
    xy_derivative = Matrix(
        9, 1, [-2.0 * x, -1.0, 0.0, 0.0, 0.0, 0.0, 2.0 * x, 1.0, 0.0])
    xy_derivative = 0.5 * xy_derivative
    xy_outer = TensorProduct(xy_derivative, xy_derivative.T)
    # (a_{j+1} x_i^2 + b_{j+1} x_i + c_{j+1} - 2a_{j} x_i^2 - 2 b_{j} x_i - 2 c_{j} + a_{j-1} x_i^2 + b_{j-1} x_i + c_{j-1})^2
    yy_derivative = Matrix(
        9, 1, [x * x, x, 1.0, -2.0 * x * x, -2.0 * x, -2.0, x * x, x, 1.0])
    yy_outer = TensorProduct(yy_derivative, yy_derivative.T)

    combined = xx_outer + 2.0 * xy_outer + yy_outer
    A_pattern = np.zeros((9, 9))
    for i in x_:
        A_pattern += np.array(combined.subs(x, i)).astype(np.float64)

    # Fill along diagonal
    A_dim = y_dim * 3 * 2
    A = np.zeros((A_dim, A_dim))
    for i in range(0, y_dim - 2):
        idx_n = i * 3
        A[idx_n:idx_n + 9, idx_n:idx_n + 9] += A_pattern
        idx_s = i * 3 + y_dim * 3
        A[idx_s:idx_s + 9, idx_s:idx_s + 9] += A_pattern
    return A
Example #2
0
def Potential(K1, K2, J, epsilon):
    ############ LIST OF CONSTANTS USED#################
    #	K1		#Spring constant of Top 1
    #	K2		#Spring constant of Top2
    #	J		#Eignevalue of J^2 operator
    #	epsilon		#Coupling strength of the two tops
    N = int(
        2 * J + 1
    )  #Dimension of the Hamiltonian of one top; Number of spin degenerate states permissible
    N2 = N * N  #Dimension of the Tensor Product space
    ####################################################

    Jz = [[0 for x in range(N)]
          for y in range(N)]  #To calculate the representation of Jz
    Identity = [[0 for x in range(N)]
                for y in range(N)]  #To calculate the Identity

    #To calculate the Jz (Angular Momentum along z axis)
    for x in range(N):
        m = -x + J
        Jz[x][x] = m
        Identity[x][x] = 1

    Identity = np.matrix(Identity)
    Jz = np.matrix(Jz)
    Jz_sq = Jz * Jz
    J1 = (Jz + 0.5 * Identity)
    J_sq = J1 * J1
    Identity = np.matrix(Identity)
    V = (K1 / (2 * J)) * TensorProduct(
        Jz_sq, Identity) + (K2 / (2 * J)) * TensorProduct(
            Identity, J_sq) + (epsilon / J) * TensorProduct(
                Jz, J1)  #To calculate the Fourier Coefficient of the Potential
    return V
Example #3
0
def tensorized_basis_3D(order):
    total_integration_points = (order + 1) * (order + 1)
    r,s,t = sym.symbols('r,s,t')
    r_gll = sym.symbols('r_0:%d' % (order + 1))
    s_gll = sym.symbols('s_0:%d' % (order + 1))
    t_gll = sym.symbols('t_0:%d' % (order + 1))

    # Get N + 1 lagrange polynomials in each direction.
    generator_r = generating_polynomial_lagrange(order, 'r', r_gll)
    generator_s = generating_polynomial_lagrange(order, 's', s_gll)
    generator_t = generating_polynomial_lagrange(order, 't', t_gll)

    # Get tensorized basis.
    basis = TensorProduct(generator_t, generator_s, generator_r)
    gll_coordinates, gll_weights = gauss_lobatto_legendre_quadruature_points_weights(order + 1)

    basis = basis.subs([(v, c) for v, c in zip(r_gll, gll_coordinates)])
    basis = basis.subs([(v, c) for v, c in zip(s_gll, gll_coordinates)])
    basis = basis.subs([(v, c) for v, c in zip(t_gll, gll_coordinates)])

    # Get gradient of basis functions.
    basis_gradient_r = sym.Matrix([sym.diff(i, r) for i in basis])
    basis_gradient_s = sym.Matrix([sym.diff(i, s) for i in basis])
    basis_gradient_t = sym.Matrix([sym.diff(i, t) for i in basis])

    routines = [('interpolate_order{}_hex'.format(order),basis),
                ('interpolate_r_derivative_order{}_hex'.format(order), basis_gradient_r),
                ('interpolate_s_derivative_order{}_hex'.format(order), basis_gradient_s),
                ('interpolate_t_derivative_order{}_hex'.format(order), basis_gradient_t)]
    codegen(routines, "C", "order{}_hex".format(order), to_files=True, project="SALVUS")

    # fix headers (#include "order4_hex.h" -> #include <Element/HyperCube/Autogen/order3_hex.h>)
    fixHeader(order,"hex",".")
def setUpTripartiteSystem(d):
    """
    Builds desired tripartite system of 3 qudits
    """
    rho = setUpNQudits(3, d)
    POVM = setUpPOVMElements(d)
    tau = TensorProduct(rho[0], rho[1], rho[2])
    M = TensorProduct(POVM[0], POVM[1], sympy.eye(d, d))
    return (M * tau).trace()
Example #5
0
def U(t):
    U00_t = U00(t)
    U11_t = U11(t)
    Up_t = Up(t)
    Um_t = Um(t)

    return TensorProduct(o0000, U00_t) + \
           TensorProduct(o1111, U11_t) + \
           TensorProduct(opp, Up_t) + \
           TensorProduct(omm, Um_t)
Example #6
0
def tensorized_basis_2D(order):

    total_integration_points = (order + 1) * (order + 1)
    eps, eta, rho = sym.symbols('epsilon eta rho')
    eps_gll = sym.symbols('epsilon_0:%d' % (order + 1))
    eta_gll = sym.symbols('eta_0:%d' % (order + 1))

    # Get N + 1 lagrange polynomials in each direction.
    generator_eps = generating_polynomial_lagrange(order, 'epsilon', eps_gll)
    generator_eta = generating_polynomial_lagrange(order, 'eta', eta_gll)

    # Get tensorized basis.
    basis = TensorProduct(generator_eta, generator_eps)
    gll_coordinates, gll_weights = gauss_lobatto_legendre_quadruature_points_weights(order + 1)
    basis = basis.subs([(v, c) for v, c in zip(eps_gll, gll_coordinates)])
    basis = basis.subs([(v, c) for v, c in zip(eta_gll, gll_coordinates)])

    # Get gradient of basis functions.
    basis_gradient_eps = sym.Matrix([sym.diff(i, eps) for i in basis])
    basis_gradient_eta = sym.Matrix([sym.diff(i, eta) for i in basis])

    # Get closure mapping.
    closure = sym.Matrix(generate_closure_mapping(order), dtype=int)

    # Write code
    routines = []
    autocode = CCodeGen()
    routines.append(autocode.routine(
        'interpolate_order{}_square'.format(order), basis,
        argument_sequence=None))
    routines.append(autocode.routine(
        'interpolate_eps_derivative_order{}_square'.format(order), basis_gradient_eps,
        argument_sequence=None))
    routines.append(autocode.routine(
        'interpolate_eta_derivative_order{}_square'.format(order), basis_gradient_eta,
        argument_sequence=None))
    routines.append(autocode.routine(
        'closure_mapping_order{}_square'.format(order), closure,
        argument_sequence=None))
    routines.append(autocode.routine(
        'gll_weights_order{}_square'.format(order), sym.Matrix(gll_weights),
        argument_sequence=None))
    routines.append(autocode.routine(
        'gll_coordinates_order{}_square'.format(order), sym.Matrix(gll_coordinates),
        argument_sequence=None))
    autocode.write(routines, 'order{}_square'.format(order), to_files=True)

    # reformat some code.
    for code, lend in zip(['order{}_square.c', 'order{}_square.h'], [' {', ';']):
        with io.open(code.format(order), 'rt') as fh:
            text = fh.readlines()
            text = [line.replace('double', 'int') if 'closure' in line else line for line in text]

        with io.open(code.format(order), 'wt') as fh:
            fh.writelines(text)
Example #7
0
def tensorNqubits(portao, alvo, qubits): #muda o portao de 1 bit para um de N qubits no alvo a escolha
    i=0
    alvo=alvo-1
    while i < alvo: #faz produtos tensoriais para os qubits anteriores ao alvo
        portao=TensorProduct(eye(2), portao) 
        i = i + 1
    i=0
    while i < qubits - alvo - 1: #faz produtos tensoriais para os qubits posteriores ao alvo
        portao=TensorProduct(portao, eye(2)) 
        i = i + 1
    return portao 
def setUpN2QubitSystems(n):
    r1 = sym.Symbol('r_1')
    r2 = sym.Symbol('r_2')
    t = sym.Symbol('theta')
    rho = sym.Matrix([[1 + r1, 0], [0, 1 - r1]])
    sigma = sym.Matrix([[1 + r2 * cos(t), r2 * sin(t)],[r2 * sin(t), 1 - r2 * cos(t)]])
    rho_not = rho
    sigma_not = sigma
    for i in range(1, n):
        rho = TensorProduct(rho_not, rho)
        sigma = TensorProduct(sigma_not, sigma)
    return (rho, sigma, r1, r2, t)
def Toom_Cook_Kronecker_Matrices(points, kernel_size, output_size, precision):
    input_size = kernel_size + output_size - 1
    points_number = input_size - 1
    G, GT = G_Matrix(points, points_number, kernel_size)
    AT, A = AT_Matrix(points, points_number, output_size)
    BT, B = BT_Matrix(points, points_number)
    G_Kronecker = TensorProduct(G, G)
    AT_Kronecker = TensorProduct(AT, AT)
    BT_Kronecker = TensorProduct(BT, BT)
    G_Kronecker = np.array(G_Kronecker).astype(precision)
    AT_Kronecker = np.array(AT_Kronecker).astype(precision)
    BT_Kronecker = np.array(BT_Kronecker).astype(precision)
    print(G_Kronecker)
    return G_Kronecker, AT_Kronecker, BT_Kronecker
Example #10
0
def tensorized_basis_2D(order):

    total_integration_points = (order + 1) * (order + 1)
    eps, eta, rho = sym.symbols('epsilon eta rho')
    eps_gll = sym.symbols('epsilon_0:%d' % (order + 1))
    eta_gll = sym.symbols('eta_0:%d' % (order + 1))

    # Get N + 1 lagrange polynomials in each direction.
    generator_eps = generating_polynomial_lagrange(order, 'epsilon', eps_gll)
    generator_eta = generating_polynomial_lagrange(order, 'eta', eta_gll)

    # Get tensorized basis.
    basis = TensorProduct(generator_eta, generator_eps)
    basis = basis.subs([(v, c)
                        for v, c in zip(eps_gll, gll_coordinates(order))])
    basis = basis.subs([(v, c)
                        for v, c in zip(eta_gll, gll_coordinates(order))])
    sym.pprint(basis)

    # Get gradient of basis functions.
    basis_gradient_eps = sym.Matrix([sym.diff(i, eps) for i in basis])
    basis_gradient_eta = sym.Matrix([sym.diff(i, eta) for i in basis])

    # Get diagonal mass matrix
    mass_matrix = rho * basis * basis.T
    mass_matrix_diagonal = sym.Matrix(
        [mass_matrix[i, i] for i in range(total_integration_points)])

    # Write code
    routines = []
    autocode = CCodeGen()
    routines.append(
        autocode.routine('interpolate_order{}_square'.format(order),
                         basis,
                         argument_sequence=None))
    routines.append(
        autocode.routine(
            'interpolate_eps_derivative_order{}_square'.format(order),
            basis_gradient_eps,
            argument_sequence=None))
    routines.append(
        autocode.routine(
            'interpolate_eta_derivative_order{}_square'.format(order),
            basis_gradient_eta,
            argument_sequence=None))
    routines.append(
        autocode.routine('diagonal_mass_matrix_order{}_square'.format(order),
                         mass_matrix_diagonal,
                         argument_sequence=None))
    autocode.write(routines, 'order{}_square'.format(order), to_files=True)
def E_d(x_shadow, x_nonshadow, pen_inter, y_dim, patch):
    ############################
    # Compute A
    ############################
    # Compute quadratic outer product via sympy
    quadratic = Matrix(3, 1, [x * x, x, 1.0])
    quadratic_outer = TensorProduct(quadratic, quadratic.T)

    A_nonshadow = np.zeros((3, 3))
    # Non-shadow pattern
    for x_ in x_nonshadow:
        A_nonshadow += np.array(quadratic_outer.subs(x, x_)).astype(np.float64)

    # Shadow pattern
    A_shadow = np.zeros((3, 3))
    for x_ in x_shadow:
        A_shadow += np.array(quadratic_outer.subs(x, x_)).astype(np.float64)

    # Fill A along diagonal with the two patterns
    # First half non_shadow, second  half shadow pattern
    A_dim = y_dim * 3 * 2
    A = np.zeros((A_dim, A_dim))
    for i in np.arange(0, A_dim / 2, 3, dtype=np.int16):
        A[i:i + 3, i:i + 3] = A_nonshadow
    for i in np.arange(A_dim / 2, A_dim, 3, dtype=np.int16):
        A[i:i + 3, i:i + 3] = A_shadow
    ###########################
    # Compute b
    ###########################
    b = np.zeros(y_dim * 3 * 2)
    for i in range(0, y_dim):
        # Cut out nonshadow patch
        patch_nonshadow = patch[i, int(np.ceil(pen_inter[1])):]
        # Cut out shadow patch
        patch_shadow = patch[i, 0:int(np.floor(pen_inter[0])) + 1]

        # sum_j I_{i,j} * x_i^2
        b[3 * i] = np.sum(np.multiply(patch_nonshadow, np.square(x_nonshadow)))
        # sum_j I_{i,j} * x_i
        b[3 * i + 1] = np.sum(np.multiply(patch_nonshadow, x_nonshadow))
        # sum_j I_{i,j}
        b[3 * i + 2] = np.sum(patch_nonshadow)

        b[3 * i + y_dim * 3] = np.sum(
            np.multiply(patch_shadow, np.square(x_shadow)))
        b[3 * i + y_dim * 3 + 1] = np.sum(np.multiply(patch_shadow, x_shadow))
        b[3 * i + y_dim * 3 + 2] = np.sum(patch_shadow)

    return A, b
 def enlarge_single_opt_sympy(self, opt, qubit, number_of_qubits):
     """Enlarge single operator to n qubits.
     It is exponential in the number of qubits.
     Args:
         opt (object): the single-qubit opt.
         qubit (int): the qubit to apply it on counts from 0 and order
             is q_{n-1} ... otimes q_1 otimes q_0.
         number_of_qubits (int): the number of qubits in the system.
     Returns:
         Matrix: the enlarged matrix that operates on all qubits in the system.
     """
     temp_1 = eye(2**(number_of_qubits - qubit - 1))
     temp_2 = eye(2**(qubit))
     enlarge_opt = TensorProduct(temp_1, TensorProduct(opt, temp_2))
     return enlarge_opt
Example #13
0
def test_evaluate_pauli_product():
    from sympy.physics.paulialgebra import evaluate_pauli_product

    assert evaluate_pauli_product(I * sigma2 * sigma3) == -sigma1

    # Check issue 6471
    assert evaluate_pauli_product(-I * 4 * sigma1 * sigma2) == 4 * sigma3

    assert evaluate_pauli_product(
        1 + I*sigma1*sigma2*sigma1*sigma2 + \
        I*sigma1*sigma2*tau1*sigma1*sigma3 + \
        ((tau1**2).subs(tau1, I*sigma1)) + \
        sigma3*((tau1**2).subs(tau1, I*sigma1)) + \
        TensorProduct(I*sigma1*sigma2*sigma1*sigma2, 1)
    ) == 1 -I + I*sigma3*tau1*sigma2 - 1 - sigma3 - I*TensorProduct(1,1)
Example #14
0
    def __init__(self, N, s, kind):
        self.__N = N
        self.__s = s
        self.__kind = kind

        # First, initialize single-qubit density matrix depending on 'kind'
        if s * 2 % 1 != 0:
            raise ValueError('s must be either an integer or a half-integer.')
        if s < 0:
            raise ValueError('s cannot be negative.')

        single_dim = int(2 * s + 1)
        if kind == 'up':
            vec = sym.Matrix(basis(single_dim, 0))
            dens = sym.Matrix(
                sym.Matrix(basis(single_dim, 0)) *
                sym.conjugate(sym.Matrix(basis(single_dim, 0)).T))
            #self.__vector = TensorProduct(sym.Matrix(basis(single_dim, 0)), sym.Matrix(basis(single_dim, 0)))
            #dens = self.__vector * sym.conjugate(self.__vector.T)#np.outer(basis(single_dim, 0), basis(single_dim, 0))
            self.__pure = True
        elif kind == 'down':
            vec = sym.Matrix(basis(single_dim, single_dim - 1))
            dens = sym.Matrix(
                sym.Matrix(basis(single_dim, single_dim - 1)) *
                sym.conjugate(sym.Matrix(basis(single_dim, single_dim - 1)).T))
            #self.__vector = TensorProduct(sym.Matrix(basis(single_dim, single_dim-1)), sym.Matrix(basis(single_dim, single_dim-1)))
            #dens = self.__vector * sym.conjugate(self.__vector.T)#np.outer(basis(single_dim, 0), basis(single_dim, 0))
            self.__pure = True
        elif kind == 'mixed':
            self.__vector = None
            dens = sym.Matrix(np.identity(single_dim) /
                              single_dim)  #qu.maximally_mixed_dm(single_dim)
            self.__pure = False
        else:
            raise ValueError('State kind not recognized.')

        for ii in range(N):
            if ii == 0:
                if self.__pure:
                    vector = vec
                rho = dens
            else:
                if self.__pure:
                    vector = TensorProduct(vector, vec)
                rho = TensorProduct(rho, dens)  #qu.tensor(rho, dens)

        self.__vector = vector
        self.__rho = rho
    def _setup(self):
        self._F0_N_ssro, self._F1_N_ssro, self._F0_e_ssro, self._F1_e_ssro, self._F0_RO_pulse, self._F1_RO_pulse, self._P_min1, self._P_0 = \
            sympy.symbols('F0_N_ssro F1_N_ssro F0_e_ssro F1_e_ssro F0_RO_pulse F1_RO_pulse P_min1 P_0')
        self._p_correlations = sympy.DeferredVector('p_correlations')

        # The total error matrix is the tensor product of the nitrogen and electron error matrices.
        # The nitrogen error matrix is built up of three matrices RO_err, CNOT_err and Init_err.
        # RO_err reflects fidelities of the electron RO,
        # CNOT_err reflects the fidelities in the pi (F0) and 2pi (F1) parts of the pi-2pi pulse (as CNOT gate).
        # Init_err includes populations in the three nitrogen lines after initialization in -1.
        #The inverse matrices are calculated before the tensorproduct, since this is much faster.

        self.error_matrix_N = (sympy.Matrix([[self._F0_N_ssro, 1.-self._F1_N_ssro],[1.-self._F0_N_ssro, self._F1_N_ssro]]) * \
            sympy.Matrix([[self._F0_RO_pulse, 1.-self._F1_RO_pulse, 0.],[1.-self._F0_RO_pulse, self._F1_RO_pulse, 1.]]) * \
                sympy.Matrix([[self._P_min1,self._P_0],[self._P_0,self._P_min1],[1.-self._P_0-self._P_min1,1.-self._P_0-self._P_min1]]))

        self.error_matrix_e = (sympy.Matrix(
            [[self._F0_e_ssro, 1. - self._F1_e_ssro],
             [1. - self._F0_e_ssro, self._F1_e_ssro]]))

        self.correction_matrix_N = self.error_matrix_N.inv()
        self.correction_matrix_e = self.error_matrix_e.inv()
        self.correction_matrix = TensorProduct(self.correction_matrix_N,
                                               self.correction_matrix_e)

        corr_vec =  self.correction_matrix * \
            sympy.Matrix([self._p_correlations[0], self._p_correlations[1], self._p_correlations[2], self._p_correlations[3]])
        corr_p_correlations = corr_vec

        self.p0_formula = error.Formula()
        self.p0_formula.formula = corr_p_correlations
Example #16
0
    def __init__(self,
                 C0=sp.Symbol('C0', real=True),
                 C2=sp.Symbol('C2', real=True),
                 A=sp.Symbol('A', real=True),
                 R=sp.Symbol('R', real=True),
                 kcut=0,
                 mz=0,
                 n_sheets=sp.Symbol('n_sheets', int=True)):

        so = sp.Matrix([[1, 0], [0, 1]])
        sx = sp.Matrix([[0, 1], [1, 0]])
        sy = sp.Matrix([[0, -sp.I], [sp.I, 0]])
        sz = sp.Matrix([[1, 0], [0, -1]])

        ho = C0 + C2 * (self.kx**2 + self.ky**2)
        hx = A * self.ky
        hy = -A * self.kx
        hz = 2 * R * (self.kx**3 - 3 * self.kx * self.ky**2) + mz

        if (not np.isclose(kcut, 0)):
            ratio = (self.kx**2 + self.ky**2) / kcut**2
            cutfactor = 1 / (1 + (ratio))
            hz *= cutfactor
        hdiag = ho * so + hx * sx + hy * sy + hz * sz

        #build hamiltonian with nz sheets
        diag = sp.eye(n_sheets)
        h = TensorProduct(diag, hdiag)

        super().__init__(h, n_sheets)
Example #17
0
def solution_space_basis(oper,
                         matrix_M,
                         expr_list,
                         base_expr,
                         pool="",
                         debug=False):
    '''solve (matrix_F otimes matrix_M)*alpha=alpha for a certain symmetry 

    ####return (list of Matrix): a list of vectors (single column Matrix object)
    return (list of list of number): a list of lists (each sublist represent a vector)

    oper (dict): a dictionary with four keys "op3x3", "rep", "is_au" and "name"
    matrix_M (Matrix): matrix_M matrix
    expr_list (list of Symbol): a list of expression basis (f_i(k))
    base_expr (list of Symbol): three symbols used in expr_list
    pool (pool): if pool object passed in, then use it
    debug (boolean): if True, print the progress infomation
    '''
    debug_print(oper["name"], "start", do_print=debug)
    matrix_F = get_matrix_F(oper["op3x3"], expr_list, base_expr, pool=pool)
    debug_print(oper["name"],
                "got matrix_F, calculating (FxM)*alpha=alpha",
                do_print=debug)
    matrix_FM = TensorProduct(matrix_F, matrix_M)
    temp = matrix_FM - sp.eye(matrix_FM.shape[0])
    # curr_basis = np.array(mat.nullspace(simplify=sp.nsimplify)).tolist()
    # solution_basis = [m.T.tolist()[0] for m in nullspace(mat, simplify=sp.nsimplify, pool=pool)]
    solution_basis = nullspace(temp, pool=pool, debug=debug)
    debug_print(oper["name"], "end", do_print=debug)
    return solution_basis
def E_c_hardcoder(y_dim):
    A_pattern_dim = y_dim * 3 + 9
    # (2 a_{j, n} x_i + b_{j, n} - 2 a_{j, s} x_i - b_{j, s})^2
    x_derivative = Matrix.zeros(A_pattern_dim, 1)
    x_derivative[3] = 2.0 * x  # 2 a_{j, n}
    x_derivative[4] = 1.0  # b_{j, n}
    x_derivative[-6] = -2.0 * x  # - 2 a_{j, s} x_i
    x_derivative[-5] = -1.0  # - b_{j, s}
    x_outer = TensorProduct(x_derivative, x_derivative.T)

    # \frac{1}{4} (a_{j+1,n} x_i^2 + b_{j+1,n} x_i + c_{j+1,n}
    # - a_{j+1,s} x_i^2 - b_{j+1,s} x_i - c_{j+1,s} - a_{j-1,n} x_i^2
    # - b_{j-1,n} x_i - c_{j-1,n} + a_{j-1,s} x_i^2 + b_{j-1,s} x_i + c_{j-1,s})^2
    y_derivative = Matrix.zeros(A_pattern_dim, 1)
    y_derivative[6] = x * x  # a_{j+1,n} x_i^2
    y_derivative[7] = x  # b_{j+1,n} x_i
    y_derivative[8] = 1.0  # c_{j+1,n}
    y_derivative[-3] = -x * x  # - a_{j+1,s} x_i^2
    y_derivative[-2] = -x  # - b_{j+1,s} x_i
    y_derivative[-1] = -1.0  # - c_{j+1,s}
    y_derivative[0] = -x * x  #- a_{j-1,n} x_i^2
    y_derivative[1] = -x  #- b_{j-1,n} x_i
    y_derivative[2] = -1.0  #- c_{j-1,n}
    y_derivative[-9] = x * x  # a_{j-1,s} x_i^2
    y_derivative[-8] = x  # b_{j-1,s} x_i
    y_derivative[-7] = 1.0  # c_{j-1,s}
    y_derivative = y_derivative * 0.5
    y_outer = TensorProduct(y_derivative, y_derivative.T)

    # Combine x and y derivatives
    combined = x_outer + y_outer

    # Convert to numpy array
    combined_np = np.array(combined.tolist())
    # Find indices of nonzero matrix entries
    idx = np.nonzero(combined_np)
    # Build sympy array of nonzero entries
    combined_reduced = Array(combined_np[idx[0], idx[1]])
    # Now we have an index list and an sympy expression Array, where
    # combined_reduced[i] corresponds to matrix position (idx[0,i], idx[1, i])

    # Save these two data structures as files
    file_Ec_sympy = open('Ec_sympy.obj', 'wb')
    pickle.dump(combined_reduced, file_Ec_sympy)
    file_Ec_idx = open('Ec_idx.obj', 'wb')
    pickle.dump(idx, file_Ec_idx)
Example #19
0
def tensorized_basis_2D(order):

    total_integration_points = (order + 1) * (order + 1)
    eps, eta, rho = sym.symbols("epsilon eta rho")
    eps_gll = sym.symbols("epsilon_0:%d" % (order + 1))
    eta_gll = sym.symbols("eta_0:%d" % (order + 1))

    # Get N + 1 lagrange polynomials in each direction.
    generator_eps = generating_polynomial_lagrange(order, "epsilon", eps_gll)
    generator_eta = generating_polynomial_lagrange(order, "eta", eta_gll)

    # Get tensorized basis.
    basis = TensorProduct(generator_eta, generator_eps)
    basis = basis.subs([(v, c) for v, c in zip(eps_gll, gll_coordinates(order))])
    basis = basis.subs([(v, c) for v, c in zip(eta_gll, gll_coordinates(order))])
    sym.pprint(basis)

    # Get gradient of basis functions.
    basis_gradient_eps = sym.Matrix([sym.diff(i, eps) for i in basis])
    basis_gradient_eta = sym.Matrix([sym.diff(i, eta) for i in basis])

    # Get diagonal mass matrix
    mass_matrix = rho * basis * basis.T
    mass_matrix_diagonal = sym.Matrix([mass_matrix[i, i] for i in range(total_integration_points)])

    # Write code
    routines = []
    autocode = CCodeGen()
    routines.append(autocode.routine("interpolate_order{}_square".format(order), basis, argument_sequence=None))
    routines.append(
        autocode.routine(
            "interpolate_eps_derivative_order{}_square".format(order), basis_gradient_eps, argument_sequence=None
        )
    )
    routines.append(
        autocode.routine(
            "interpolate_eta_derivative_order{}_square".format(order), basis_gradient_eta, argument_sequence=None
        )
    )
    routines.append(
        autocode.routine(
            "diagonal_mass_matrix_order{}_square".format(order), mass_matrix_diagonal, argument_sequence=None
        )
    )
    autocode.write(routines, "order{}_square".format(order), to_files=True)
Example #20
0
 def kron(self, other):  # Kronecker product
     if self.__cuda:
         if cupy_is_available:
             result = cp.kron(self.__matrix, other.get())
         else:
             result = np.kron(self.__matrix, other.get())
     else:
         result = TensorProduct(self.__matrix, other.get())
     return Matrix(result, self.__cuda)
    def apply_measurement(self, op, input_register, moutputs):
        # Find the operator of the measurement instance we're running
        measurement = self.find_measurement(op['operator_id'])

        # Using the same principle as in apply_gate, obtain a matrix we can
        # run on all lines
        before = op['lines'][0]
        after = self.register_size - op['lines'][-1] - 1
        matrix = TensorProduct(eye(2**before), measurement.matrix,
                               eye(2**after))

        # To contain the possible states the system could fall into after the
        # measurement
        states = []
        # For each triple in the eigensystem
        # Eigenvalue, duplicity (not needed here), eigenvectors
        for val, dup, vecs in matrix.eigenvects():
            # For each vector in the eigenvector basis
            for vec in vecs:
                # Obtain a projection operator P = x*x^T
                p = vec * vec.H

                # Probability of this outcome Pr = |phi>^T * P * |phi>
                # [0] because we want the value of a 1x1 matrix
                probability = (input_register.H * p * input_register)[0]
                # Don't need to consider this outcome anymore if it
                # won't happen
                if probability == 0: continue

                # Calculate the new register |phi'> = P*|phi> / sqrt(Pr)
                register = p * input_register / sqrt(probability)

                # Copy the measurement outputs as we're branching so don't
                # want to affect other branches
                moutputs = dict(moutputs)
                # Store the outcome that's just happened in the measurement
                # outputs
                moutputs[op['oid']] = val

                # Add the state tuple into states
                state = (register, probability, moutputs)
                states.append(state)

        return states
    def apply_measurement(self, op, input_register, moutputs):
        # Find the operator of the measurement instance we're running
        measurement = self.find_measurement(op['operator_id'])

        # Using the same principle as in apply_gate, obtain a matrix we can
        # run on all lines
        before = op['lines'][0]
        after = self.register_size - op['lines'][-1] - 1
        matrix = TensorProduct(eye(2**before), measurement.matrix, eye(2**after))

        # To contain the possible states the system could fall into after the
        # measurement
        states = []
        # For each triple in the eigensystem
        # Eigenvalue, duplicity (not needed here), eigenvectors
        for val, dup, vecs in matrix.eigenvects():
            # For each vector in the eigenvector basis
            for vec in vecs:
                # Obtain a projection operator P = x*x^T
                p = vec * vec.H

                # Probability of this outcome Pr = |phi>^T * P * |phi>
                # [0] because we want the value of a 1x1 matrix
                probability = (input_register.H * p * input_register)[0]
                # Don't need to consider this outcome anymore if it
                # won't happen
                if probability == 0: continue

                # Calculate the new register |phi'> = P*|phi> / sqrt(Pr)
                register = p * input_register / sqrt(probability)

                # Copy the measurement outputs as we're branching so don't
                # want to affect other branches
                moutputs = dict(moutputs)
                # Store the outcome that's just happened in the measurement
                # outputs
                moutputs[op['oid']] = val

                # Add the state tuple into states
                state = (register, probability, moutputs)
                states.append(state)

        return states
Example #23
0
def build_hurwitz_radon_general(n):
    """ The function gets as input a number 'n' and returns a set of matrices of size n x n
    that meets the Hurwitz-Radon constraints. Here no assumption is made on 'b', where b is a Hurwitz-Radon parameter"""
    a, b, c, d = find_hurwitz_radon_parameters(n)
    mat_set = build_hurwitz_radon(n)
    if not mat_set:  #  if the list is empty
        return mat_set
    if b > 1:
        for ind, mat in enumerate(mat_set):
            mat_set[ind] = TensorProduct(mat, eye(b))
    return mat_set
Example #24
0
def tensorized_basis_3D(order):
    total_integration_points = (order + 1) * (order + 1)
    r, s, t = sym.symbols('r,s,t')
    r_gll = sym.symbols('r_0:%d' % (order + 1))
    s_gll = sym.symbols('s_0:%d' % (order + 1))
    t_gll = sym.symbols('t_0:%d' % (order + 1))

    # Get N + 1 lagrange polynomials in each direction.
    generator_r = generating_polynomial_lagrange(order, 'r', r_gll)
    generator_s = generating_polynomial_lagrange(order, 's', s_gll)
    generator_t = generating_polynomial_lagrange(order, 't', t_gll)

    # Get tensorized basis.
    basis = TensorProduct(generator_t, generator_s, generator_r)
    gll_coordinates, gll_weights = gauss_lobatto_legendre_quadruature_points_weights(
        order + 1)

    basis = basis.subs([(v, c) for v, c in zip(r_gll, gll_coordinates)])
    basis = basis.subs([(v, c) for v, c in zip(s_gll, gll_coordinates)])
    basis = basis.subs([(v, c) for v, c in zip(t_gll, gll_coordinates)])

    # Get gradient of basis functions.
    basis_gradient_r = sym.Matrix([sym.diff(i, r) for i in basis])
    basis_gradient_s = sym.Matrix([sym.diff(i, s) for i in basis])
    basis_gradient_t = sym.Matrix([sym.diff(i, t) for i in basis])

    routines = [('interpolate_order{}_hex'.format(order), basis),
                ('interpolate_r_derivative_order{}_hex'.format(order),
                 basis_gradient_r),
                ('interpolate_s_derivative_order{}_hex'.format(order),
                 basis_gradient_s),
                ('interpolate_t_derivative_order{}_hex'.format(order),
                 basis_gradient_t)]
    codegen(routines,
            "C",
            "order{}_hex".format(order),
            to_files=True,
            project="SALVUS")

    # fix headers (#include "order4_hex.h" -> #include <Element/HyperCube/Autogen/order3_hex.h>)
    fixHeader(order, "hex", ".")
Example #25
0
def cnot3(psi, qubit_negado):
    #matriz e produto tensorial se o bit negado for o 1
    if qubit_negado == 1:
        cnotm2= Matrix([[1, 0, 0, 0], #matriz de 2 qubits onde primeiro controla o posterior
    [0, 0, 0, 1],
    [0, 0, 1, 0],
    [0, 1, 0, 0]])
        cnot=TensorProduct(cnotm2, eye(2))#produto tensorial para operar 3 qubits
        
    #matriz e produto tensorial se o bit negado for o 3
    else:
        cnotm2= Matrix([[1, 0, 0, 0], #matriz de 2 qubits onde um qubit controla o anterior
    [0, 1, 0, 0],
    [0, 0, 0, 1],
    [0, 0, 1, 0]])
        cnot=TensorProduct(eye(2), cnotm2)#produto tensorial para operar 3 qubits
    
    psi=np.matrix(psi)  #para poder multiplicar o vetor de estado pelo operador
    
    psi=psi*cnot       #opera a multiplicacao de matrizes
    
    return psi.tolist()[0] #transforma a matriz de volta em lista
def unitary_partial_swap(angles, step, n_qubits):
    inter = int(n_qubits / 2 - 1)
    if step > inter :
        raise NameError("Le qubit selectionne est incorrect.")
    elif step == 0 :
        return TensorProduct(TensorProduct(eye(2 ** (inter + step)), partial_swap(angles[inter - step])), eye(2 ** (inter - step)))
    else :
        U = TensorProduct(TensorProduct(eye(2 ** (inter + step)), partial_swap(angles[inter - step])), eye(2 ** (inter - step)))
        return TensorProduct(TensorProduct(eye(2 ** (inter - step)), partial_swap(angles[inter + step])), eye(2 ** (inter + step))) * U
Example #27
0
    def __init__(self,
                 A=sp.Symbol('A', real=True),
                 t=sp.Symbol('t', real=True),
                 tt=sp.Symbol('tt', real=True),
                 m5=sp.Symbol('m5', real=True),
                 n_sheets=sp.Symbol('n_sheets', int=True)):

        #set of hermitian matrices
        Gamma1 = sp.Matrix([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0],
                            [1, 0, 0, 0]])
        Gamma2 = sp.Matrix([[0, 0, 0, -sp.I], [0, 0, sp.I, 0],
                            [0, -sp.I, 0, 0], [sp.I, 0, 0, 0]])
        Gamma3 = sp.Matrix([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0],
                            [0, -1, 0, 0]])
        Gamma5 = sp.Matrix([[0, 0, -sp.I, 0], [0, 0, 0, -sp.I],
                            [sp.I, 0, 0, 0], [0, sp.I, 0, 0]])

        #diagonal part of hamiltonian
        hdiag = A * ( m5 + t * ( sp.cos(self.kx) + sp.cos(self.ky) ) ) * Gamma5 \
               + A * tt * ( sp.sin(self.kx) * Gamma1 + sp.sin(self.ky) * Gamma2 )

        #hopping between sheets
        hoffdiag = A * (1 / 2 * t * Gamma5 + 1 /
                        (2 * sp.I) * tt * Gamma3)  #lower offdiag blocks
        hoffdiag_c = A * (1 / 2 * t * Gamma5 - 1 /
                          (2 * sp.I) * tt * Gamma3)  #upper offdiag blocks

        #build hamiltonian with nz sheets
        diag = sp.eye(n_sheets)
        lower = sp.Matrix.jordan_block(n_sheets, 0, band='lower')
        upper = sp.Matrix.jordan_block(n_sheets, 0, band='upper')

        h = TensorProduct(diag, hdiag) + TensorProduct(
            lower, hoffdiag) + TensorProduct(upper, hoffdiag_c)

        super().__init__(h, n_sheets, degenerate_eigenvalues=True)
    def apply_gate(self, op, input_register, moutputs):
        # Find the operator of the gate instance we're running
        gate = self.find_gate(op['operator_id'])

        # Number of lines before the lines we're running on
        before = op['lines'][0]
        # Number of lines after the lines we're running on
        after = self.register_size - op['lines'][-1] - 1
        # Obtain an overall matrix by Kronecking together (matrix tensor
        # product) an identity on (before) lines, the matrix we want to run
        # and an identity on (after) lines
        matrix = TensorProduct(eye(2**before), gate.matrix, eye(2**after))

        # The only thing running the gate affects is the state, which is just
        # |phi'> = M|phi>
        return [(matrix * input_register, 1, moutputs)]
Example #29
0
def test_tensor_product():
    a11, a12, a21, a22, b11, b12, b21, b22 = sp.symbols(
        'a11 a12 a21 a22 b11 b12 b21 b22')
    A = Matrix([
        [a11, a12],
        [a21, a22],
    ])
    B = Matrix([
        [b11, b12],
        [b21, b22],
    ])
    actual = TensorProduct(A, B)
    expected = Matrix([
        [a11 * b11, a11 * b12, a12 * b11, a12 * b12],
        [a11 * b21, a11 * b22, a12 * b21, a12 * b22],
        [a21 * b11, a21 * b12, a22 * b11, a22 * b12],
        [a21 * b21, a21 * b22, a22 * b21, a22 * b22],
    ])
    assert actual == expected
    def apply_controlled(self, op, input_register, moutputs):
        # Find the operator of the controlled gate instance we're running
        gate = self.find_controlled_gate(op['operator_id'])

        # Find the value that was measured by the measurement we're
        # conditional upon
        # We need the second line because the sympified value may be different
        # from the moutputs value. This will affect array indexing, but ==
        # will still find them equal
        value = moutputs[op['measurement_id']]
        value = filter(lambda val: val == value, gate.values)[0]
        # Find the matrix corresponding to that value
        # TODO Do we need both the parse_expr.str and the filter expression?
        small_matrix = gate.matrices[custom_parse_expr(str(value))]

        # Use the same logic as in apply_gate and apply_measurement to tensor
        # together a large matrix we can apply to all lines
        before = op['lines'][0]
        after = self.register_size - op['lines'][-1] - 1
        matrix = TensorProduct(eye(2**before), small_matrix, eye(2**after))

        # Now just apply the gate like in apply_gate
        return ([(matrix * input_register, 1, moutputs)])
Example #31
0
R = (1 / sqrt(2)) * Matrix([[I, -I], [1, 1]])

# %%
R.adjoint() * T * R

# %%
Omega_T_d = (pi / ((pi / (2 * omega))**2)) * F * T_d * F.adjoint()

# %%
Omega_T_d

# %%
Hs = I * hbar * omega * Matrix([[0, 1], [-1, 0]])

# %%
J = TensorProduct(hbar * Omega_T_d, eye(2)) + TensorProduct(eye(2), Hs)

# %%
J

# %%
J.eigenvects()

# %% [markdown]
# ## Ordinary quantum theory

# %%
t = Symbol('t')
t0 = Symbol('t_0')

# %%
Example #32
0
def qsimplify_pauli(e):
    """
    Simplify an expression that includes products of pauli operators.

    Parameters
    ==========

    e : expression
        An expression that contains products of Pauli operators that is
        to be simplified.

    Examples
    ========

    >>> from sympy.physics.quantum.pauli import SigmaX, SigmaY
    >>> from sympy.physics.quantum.pauli import qsimplify_pauli
    >>> sx, sy = SigmaX(), SigmaY()
    >>> sx * sy
    SigmaX()*SigmaY()
    >>> qsimplify_pauli(sx * sy)
    I*SigmaZ()
    """
    if isinstance(e, Operator):
        return e

    if isinstance(e, (Add, Pow, exp, TensorProduct)):
        t = type(e)
        return t(*[qsimplify_pauli(arg) for arg in e.args])

    if isinstance(e, Mul):

        c, nc = e.args_cnc()

        nc_s = []
        while nc:
            if not isinstance(nc[0], SigmaOpBase):
                curr = nc.pop(0)

                if isinstance(curr, TensorProduct):
                  curr = TensorProduct(*(qsimplify_pauli(arg)
                                         for arg in curr.args))
                nc_s.append(curr)
                continue

            curr = [nc.pop(0)]
            names = [curr[0].name]

            while (len(nc) and isinstance(nc[0], SigmaOpBase)):
                x = nc.pop(0)
                if x.name in names:
                    idx = names.index(x.name)
                    y = _qsimplify_pauli_product(curr[idx], x)
                    c1, nc1 = y.args_cnc()
                    curr[idx] = Mul(*nc1)
                    c = c + c1
                else:
                    curr.append(x)
                    names.append(x.name)

            # TODO: Don't make assumptions about what the names are.
            # TODO: This sorted order is properly part of a canonical form which
            #       should be enforced and preserved elsewhere in the module.
            curr = sorted(curr,
                          key=lambda e: e.name if hasattr(e, 'name') else 0)

            nc_s.extend(curr)

        return Mul(*c) * Mul(*nc_s)

    return e
Example #33
0
def mueller_matrix(J):
    u"""The Mueller matrix corresponding to Jones matrix `J`.

    Parameters
    ----------
    ``J`` : sympy Matrix
        A Jones matrix.

    Returns
    -------
    sympy Matrix
        The corresponding Mueller matrix.

    Examples
    --------
    Generic optical components.

    >>> from sympy import pprint, symbols, pi, simplify
    >>> from sympy.physics.optics.polarization import (mueller_matrix,
    ...     linear_polarizer, half_wave_retarder, quarter_wave_retarder)
    >>> theta = symbols("theta", real=True)

    A linear_polarizer
    >>> pprint(mueller_matrix(linear_polarizer(theta)), use_unicode=True)
    ⎡            cos(2⋅θ)      sin(2⋅θ)     ⎤
    ⎢  1/2       ────────      ────────    0⎥
    ⎢               2             2         ⎥
    ⎢                                       ⎥
    ⎢cos(2⋅θ)  cos(4⋅θ)   1    sin(4⋅θ)     ⎥
    ⎢────────  ──────── + ─    ────────    0⎥
    ⎢   2         4       4       4         ⎥
    ⎢                                       ⎥
    ⎢sin(2⋅θ)    sin(4⋅θ)    1   cos(4⋅θ)   ⎥
    ⎢────────    ────────    ─ - ────────  0⎥
    ⎢   2           4        4      4       ⎥
    ⎢                                       ⎥
    ⎣   0           0             0        0⎦

    A half-wave plate
    >>> pprint(mueller_matrix(half_wave_retarder(theta)), use_unicode=True)
    ⎡1              0                           0               0 ⎤
    ⎢                                                             ⎥
    ⎢        4           2                                        ⎥
    ⎢0  8⋅sin (θ) - 8⋅sin (θ) + 1           sin(4⋅θ)            0 ⎥
    ⎢                                                             ⎥
    ⎢                                     4           2           ⎥
    ⎢0          sin(4⋅θ)           - 8⋅sin (θ) + 8⋅sin (θ) - 1  0 ⎥
    ⎢                                                             ⎥
    ⎣0              0                           0               -1⎦

    A quarter-wave plate
    >>> pprint(mueller_matrix(quarter_wave_retarder(theta)), use_unicode=True)
    ⎡1       0             0            0    ⎤
    ⎢                                        ⎥
    ⎢   cos(4⋅θ)   1    sin(4⋅θ)             ⎥
    ⎢0  ──────── + ─    ────────    -sin(2⋅θ)⎥
    ⎢      2       2       2                 ⎥
    ⎢                                        ⎥
    ⎢     sin(4⋅θ)    1   cos(4⋅θ)           ⎥
    ⎢0    ────────    ─ - ────────  cos(2⋅θ) ⎥
    ⎢        2        2      2               ⎥
    ⎢                                        ⎥
    ⎣0    sin(2⋅θ)     -cos(2⋅θ)        0    ⎦

    """
    A = Matrix([[1, 0, 0, 1], [1, 0, 0, -1], [0, 1, 1, 0], [0, -I, I, 0]])

    return simplify(A * TensorProduct(J, J.conjugate()) * A.inv())
Example #34
0
l = np.count_nonzero(v)
m = np.reshape(v,(3,3))
print (l)
print (m)
print(m.T)
print(inv(m))
print(np.dot(m,inv(m)))
print("=============")
print(m)
swap_col(m,0,2)
print(m)
print(swap_col_r(m,0,2))
print("===Tensor Product == ")
id = Matrix([[1,0],[0,1]])
i = Matrix([[1,0],[-1,0]])
id_i = TensorProduct(id,i)
print(id_i)
print(np.reshape(id_i,(2,8)))
print("===Fun - operation on matrix elemnets")
f_id_i = [ fun(x) for x in id_i]
print(f_id_i)
print("==Reed_Muller Transform==")
w= Matrix([[1,0],[1,1]])
w_1 = w.inv()
R3 = TensorProduct(w,TensorProduct(w,w))
print(R3)
pprint(R3)
f = Matrix([1,0,0,1,1,0,1,1])
pprint(f)
print("===")
s_f = [x%2 for x in R3*f]
Example #35
0
    
The cnot performs the following transformation:
    
|00> -> |00>
|01> -> |01>
|10> -> |11>
|11> -> |10>
"""

theta = Symbol('theta')

X = np.array([[0, 1j], [-1j, 0]])

CNOT = Matrix(
    np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]))

I = Matrix(np.eye(2))
sigmax = Matrix(1j * X * theta)
sigmax_inv = Matrix(-1j * X * theta)

R = simplify(exp(sigmax))
R_ = simplify(exp(sigmax_inv))
IX = simplify(TensorProduct(I, R))
IX_ = simplify(TensorProduct(I, R_))

U = IX_ * CNOT * IX

M_ij = Matrix([[U[0, 0], U[0, 2]], [U[2, 0], U[2, 2]]])

pprint(simplify(M_ij))