def generate_cases_2_qubits_exp_vals_with_angles(matrix, matrix_name, angles): for initial_matrix, initial_matrix_names in two_qubit_initial_states: for angle in angles: outputs = [] operator_names = [] for operator, operator_name in two_qubit_operators: operator_names.append('"{}"'.format(operator_name)) circuit_ket = mul(matrix, initial_matrix) * sympy.Matrix( [[1], [0], [0], [0]]) circuit_ket = circuit_ket.subs("theta", angle) circuit_bra = sympy.conjugate(sympy.Transpose(circuit_ket)) expectation_value = mul(circuit_bra, mul(operator, circuit_ket))[0] outputs.append(sympy.simplify(expectation_value)) operator_names_string = "[" + ", ".join(operator_names) + "], " gate_names_string = '[["{}", "{}"], "{}", '.format( initial_matrix_names[0], initial_matrix_names[1], matrix_name) angle_string = "[{}], ".format(angle).replace("pi", "np.pi") exp_vals_string = "[" for output in outputs: exp_vals_string += ("{},".format(output).replace( "sqrt", "np.sqrt").replace("pi", "np.pi").replace( "1.0*I", "1.0j").replace("*I", "*1.0j")) exp_vals_string += "]" print(gate_names_string + angle_string + operator_names_string + exp_vals_string + "],")
def _get_transpose(x): if isinstance(x, (list, tuple)): xT = x[1] x = x[0] else: xT = sp.Transpose(x) return x, xT
def getEquation(self): """Prints learned equation of a trained model.""" # prepares lists for weights and biases weights = [] bias = [] # pulls/separates weights and biases from a model for i in range(1, self.numLayers+1): weights.append(self.model.layers[i].get_weights()[0]) bias.append(self.model.layers[i].get_weights()[1]) # creates generic input vector X = make_symbolic(1, self.inputSize) for i, _ in enumerate(weights): # computes the result of the next linear layer W = sympy.Matrix(weights[i]) b = sympy.Transpose(sympy.Matrix(bias[i])) Y = sympy.zeros(1, b.cols) X = X*W + b # computes the result of the next nonlinear layer, if applicable if i != (len(weights) - 1): u, v = self.nonlinearInfo[i] # computes the result of the unary component of the nonlinear # layer # iterating over unary input for j in range(u): Y[0, j] = self.hypothesisSet[1][self.unaryFunctions[i][j]]( X[0, j]) # computes the result of the binary component of the nonlinear # layer # iterating over binary input for j in range(v): Y[0, j+u] = X[0, j * 2 + u] * X[0, j * 2 + u + 1] # removes final v rows which are now outdated for j in range(u + v, Y.cols): Y.col_del(u + v) X = Y if i == (len(weights) - 1): # computes the result of the binary component of the nonlinear # layer # iterating over binary input for j in range(int(X.cols/2)): if sympy.Abs(X[0, j*2+1]) == 0: Y[0, j] = 0 else: Y[0, j] = X[0, j*2] / X[0, j*2+1] for j in range(int(X.cols/2)): Y.col_del(int(X.cols/2)) X = Y return X
def intersect(self, ray, world_state): # unpack the plane p0 = self.p n = self.n # unpack the ray l0 = np.squeeze(ray[0]) l = np.squeeze(ray[1]) l = l / np.linalg.norm(l) #code.interact(local=locals()) # #d = (p0 - l0).dot(n)/(l.dot(n)) num = sp.Transpose(sp.Matrix(p0[0:3] - l0)) * (sp.Matrix(n[0:3])) den = sp.Transpose(sp.Matrix(l)) * (sp.Matrix(n[0:3])) num = num.as_explicit() den = den.as_explicit() d = num[0] / den[0] return d
def procNoiseCovar(self, delD, delTheta): M = sympy.Matrix([[self.stdTheta ** 2, 0, 0], [0, self.stdD ** 2, 0], [0, 0, self.stdD ** 2]]) print("M 2") print(M) Fu = self.stateTransUJacob(delD, delTheta) Q = Fu * M * sympy.Transpose(Fu) print("Q") print(Q) return Q
def intersect(self, ray, world_state): # unpack the ray l0 = np.squeeze(ray[0]) l = np.squeeze(ray[1]) l = l / np.linalg.norm(l) # project ray to plane t = self.plane.intersect(ray, world_state) #code.interact(local=locals()) #p = t * l + l0 p = t * sp.Transpose(sp.Matrix(l)) + sp.Transpose(sp.Matrix(l0)) #if np.linalg.norm(p - self.p) < self.radius: # return t #else: # return float('inf') #code.interact(local=locals()) d = (p - sp.Transpose(sp.Matrix(self.p[0:3]))) dt = sp.Transpose(d) d = sp.sqrt((d.as_mutable() * dt).as_explicit()[0]) return Piecewise((t, d < self.radius), (float('inf'), True))
def generate_cases_1_qubit_exp_vals(matrix, matrix_name): for initial_matrix, initial_matrix_name in single_qubit_initial_states: outputs = [] for operator in single_qubit_operators: circuit_ket = mul(matrix, initial_matrix) * sympy.Matrix([[1], [0] ]) circuit_bra = sympy.conjugate(sympy.Transpose(circuit_ket)) expectation_value = mul(circuit_bra, mul(operator, circuit_ket))[0] outputs.append(sympy.simplify(expectation_value)) gate_names_string = '["{}", "{}", '.format(initial_matrix_name, matrix_name) exp_vals_string = ("[{}, {}, {}, {}]".format(*outputs).replace( "sqrt", "np.sqrt").replace("pi", "np.pi").replace("1.0*I", "1.0j").replace("*I", "*1.0j")) print(gate_names_string + exp_vals_string + "],")
def f1(x, xT, P, A): """ :param x: matrix :param xT: transpose of x :param P: matrix :param A: matrix :return: x^T (A^T P + P A) x """ AT = sp.Transpose(A) e0 = sp.Mul(AT, P, evaluate=False) e1 = sp.Mul(P, A, evaluate=False) e2 = sp.Add(e0, e1, evaluate=False) e = sp.Mul(xT, e2, evaluate=False) e = sp.Mul(e, x, evaluate=False) m = { str(P[r, c]): P[r, c] for r in range(P.shape[0]) for c in range(P.shape[0]) } m.update({str(x): x for x in x}) e = parse_expr(str(e), local_dict=m) # res = sp.expand((xT * (AT * P + P * A) * x)[0]) return sp.expand(e[0])
def padeDiretoPrecisaoFinita(objeto, grauDoNumerador, grauDoDenominador, prec): # Fixar precisão de 'prec' algarismos significativos mp.dps = prec # Matriz dos coeficientes do sistema Ab = a A = matrizDosCoeficientes(objeto, grauDoNumerador, grauDoDenominador, prec) # erro if (A is None): return ("A = None") if (type(A) is str): return (A) # Se a matriz é nula if (A == 0): return ("A matriz dos coeficientes não é invertível. ") # Se a matriz A é invertível if (A.det() != 0): ##-- Construção do denominador --## # Cálculo dos coeficientes do denominador do aproximante de Padé B = sp.transpose( matrizDosTermosIndependentes(objeto, grauDoNumerador, grauDoDenominador, prec)) Bn = A.LUsolve(B) # Potências de x do denominador Dx = sp.Matrix(np.zeros((grauDoDenominador + 1, 1))) for linha in range(0, grauDoDenominador + 1): Dx[linha] = x**(linha) # Vetor para os coeficientes do denominador bn = sp.Matrix(np.zeros((1, grauDoDenominador + 1))) # Definir b_0 = 1 para a função racional em x = 0 tomar o valor N(0) = c_0 bn[0] = 1 # Matriz transposta dos coeficientes do denominador for coluna in range(1, grauDoDenominador + 1): bn[coluna] = Bn[-coluna] # Denominador do aproximante de Padé Denominador = sp.Function('Denominador') Denominador = bn * Dx ##-- Construção do numerador --## # Vetor para os coeficientes do numerador cn = sp.Matrix(np.zeros((1, grauDoNumerador + 1))) # Potências do numerador Nx = sp.Matrix(np.zeros((grauDoNumerador + 1, 1))) for linha in range(0, grauDoNumerador + 1): Nx[linha] = x**(linha) # Se o grau do numerador é menor do que o grau do denominador if (grauDoNumerador < grauDoDenominador): coluna = 1 while (coluna <= grauDoNumerador + 1): An = sp.Matrix( coeficientesParaCalcularCoeficentesDoNumerador( objeto, grauDoNumerador, grauDoDenominador, prec)[-coluna:]) Bn = sp.Matrix(bn[0:coluna]) cn[coluna - 1] = sp.Transpose(An) * Bn coluna += 1 # Numerador do aproximante de Padé Numerador = sp.Function('Numerador') Numerador = cn * Nx # Função racional R = sp.Function('R') R = Numerador[0] / Denominador[0] # Aproximante de Padé Pade = sp.Function('Pade') Pade = R return (Pade) # Se o grau do mumerador é maior do que o grau do denominador else: # Cálculo dos coeficientes c_n até n = grau do denominador coluna = 1 while (coluna <= grauDoDenominador + 1): An = sp.Matrix( coeficientesParaCalcularCoeficentesDoNumerador( objeto, grauDoNumerador, grauDoDenominador, prec)[-coluna:]) Bn = sp.Matrix(bn[0:coluna]) cn[coluna - 1] = sp.Transpose(An) * Bn coluna += 1 # Cálculo dos coeficiente c_n para n > grau do denominador j = -1 while (coluna <= grauDoNumerador + 1): An = sp.Matrix( coeficientesParaCalcularCoeficentesDoNumerador( objeto, grauDoNumerador, grauDoDenominador, prec)[-coluna:j]) Bn = sp.Matrix(bn[0:]) cn[coluna - 1] = sp.Transpose(An) * Bn coluna += 1 j -= 1 # Numerador do aproximante de Padé Numerador = sp.Function('Numerador') Numerador = cn * Nx # Função racional R = sp.Function('R') R = Numerador[0] / Denominador[0] # Aproximante de Padé Pade = sp.Function('Pade') Pade = R return (Pade) # Se a matriz não é invertível else: return ("A matriz dos coeficientes não é invertível. ") return
theta_pitch, phi_yaw = symbols('theta_pitch phi_yaw') RO_L = RotationSym(theta_pitch, 'Y') * RotationSym(phi_yaw, 'Z') * RotationSym( -pi / 2, 'Z') * RotationSym(pi / 2 - l3, 'X') * RotationSym(alpha, 'Z') VL = (RO_L[:3, :3])[:, 1] UL = ((RotationSym(theta_L, 'Y') * RotationSym(l1, 'X'))[:3, :3])[:, 1] #-- RO_R = RotationSym(theta_pitch, 'Y') * RotationSym(phi_yaw, 'Z') * RotationSym( -pi / 2, 'Z') * RotationSym(pi / 2 - l3, 'X') * RotationSym(-alpha, 'Z') VR = (RO_R[:3, :3])[:, 1] UR = ((RotationSym(pi, 'Z') * RotationSym(theta_R, 'Y') * RotationSym(l1, 'X'))[:3, :3])[:, 1] fL = (sy.Transpose(VL) * UL)[0] - cos(l2) fR = (sy.Transpose(VR) * UR)[0] - cos(l2) fL = sy.collect(sy.trigsimp(fL, deep='True'), sin(theta_L - theta_pitch)) fR = sy.collect(sy.trigsimp(fR, deep='True'), cos(theta_R + theta_pitch)) f3 = (sy.Transpose(VL) * VR)[0] - cos(2 * alpha) dataL = (theta_pitch, phi_yaw, theta_L, theta_R, l1, l2, l3, alpha) UL_, VL_ = sy.lambdify(dataL, UL), sy.lambdify(dataL, VL) UR_, VR_ = sy.lambdify(dataL, UR), sy.lambdify(dataL, VR) FL_ = sy.lambdify(dataL, fL) FR_ = sy.lambdify(dataL, fR) F3_ = sy.lambdify(dataL, f3)
], [0, 0]]) JO_L1 = sp.Matrix([[0, 0], [0, 0], [1, 0]]) JO_L2 = sp.Matrix([[0, 0], [0, 0], [1, 1]]) JP_M1 = sp.Matrix([[0, 0], [0, 0], [0, 0]]) JP_M2 = sp.Matrix([[-a1 * sp.sin(theta1), 0], [a1 * sp.cos(theta1), 0], [0, 0]]) JO_M1 = sp.Matrix([[0, 0], [0, 0], [kr1, 0]]) JO_M2 = sp.Matrix([[0, 0], [0, 0], [1, kr2]]) R0_1 = sp.Matrix([[sp.cos(theta1), -1 * sp.sin(theta1), 0], [sp.sin(theta1), sp.cos(theta1), 0], [0, 0, 1]]) R1_2 = sp.Matrix([[sp.cos(theta2), -1 * sp.sin(theta2), 0], [sp.sin(theta2), sp.cos(theta2), 0], [0, 0, 1]]) R0_2 = R0_1 * R1_2 term1 = ml1 * sp.Transpose(JP_L1) * JP_L1 + sp.Transpose( JO_L1) * R0_1 * Il1 * sp.Transpose(R0_1) * JO_L1 term2 = mm1 * sp.Transpose(JP_M1) * JP_M1 + sp.Transpose( JO_M1) * R0_1 * Im1 * sp.Transpose(R0_1) * JO_M1 term3 = ml2 * sp.Transpose(JP_L2) * JP_L2 + sp.Transpose( JO_L2) * R0_2 * Il2 * sp.Transpose(R0_2) * JO_L2 term4 = mm2 * sp.Transpose(JP_M2) * JP_M2 + sp.Transpose( JO_M2) * R0_2 * Im2 * sp.Transpose(R0_2) * JO_M2 B = term1 + term2 + term3 + term4 print(B) #print(len(B)) #B11 = [Il1 + Il2 + Im1*kr1**2 + Im2 + ml1*(l1**2*sin(theta1)**2 + l1**2*cos(theta1)**2) + ml2*((-a1*sin(theta1) - l2*sin(theta1 + theta2))**2 + (a1*cos(theta1) + l2*cos(theta1 + theta2))**2) + mm2*(a1**2*sin(theta1)**2 + a1**2*cos(theta1)**2),
def proc_error_covar(Fx, Q, P_old): P = Fx * P_old * sympy.Transpose(Fx) + Q return P
def proc_noise_covar(std_theta, std_V, std_D, Fu): M = sympy.Matrix([[std_theta**2, 0, 0], [0, std_V**2, 0], [0, 0, std_D**2]]) Q = Fu * M * sympy.Transpose(Fu) return Q
interacoes = interacoes + 1 n = 0 matrix_X = Matrix(n_exp, 1, lambda i, j: i + j) for x in range(0, n_exp): matrix_X[n] = Symbol("x" + str(n + 1)) n = n + 1 Jac = Matrix([matrix_X]) if (flag == 0): matriz_um = jcb_direct_diff(M, Jac, x_zero) matriz_dois = matrix_z(M, Jac, x_zero, matriz_um) res = np.array( [list(matriz_dois.values()) for item in matriz_dois.values()]) res = sympy.Matrix(res) maz2_true = res.row(0) maz2_true = sympy.Transpose(maz2_true) maz = (maz2_true - maz2_true) + maz2_true matriz_dois = maz var = check_diff(matriz_dois) if var > 0: break else: x_zero = (x_zero + matriz_dois) flag = flag + 1 print(x_zero) print(interacoes)