def forward(self, input_state, H, N, N_SYS_B, D): """ Args: input_state: The initial state with default |0..> H: The target Hamiltonian Returns: The loss. """ out_state = U_theta(self.theta, input_state, N, D) # rho_AB = utils.matmul(utils.matrix_conjugate_transpose(out_state), out_state) rho_AB = matmul( transpose( fluid.framework.ComplexVariable(out_state.real, -out_state.imag), perm=[1, 0]), out_state) # compute the partial trace and three losses rho_B = partial_trace(rho_AB, 2**(N - N_SYS_B), 2**(N_SYS_B), 1) rho_B_squre = matmul(rho_B, rho_B) loss1 = (trace(matmul(rho_B, H))).real loss2 = (trace(rho_B_squre)).real * 2 loss3 = -(trace(matmul(rho_B_squre, rho_B))).real / 2 loss = loss1 + loss2 + loss3 # 损失函数 # option: if you want to check whether the imaginary part is 0, uncomment the following # print('loss_iminary_part: ', loss.numpy()[1]) return loss - 3 / 2, rho_B
def forward(self): # 生成初始的编码器 E 和解码器 D\n", E = Encoder(self.theta) E_dagger = dagger(E) D = E_dagger D_dagger = E # 编码量子态 rho_in rho_BA = matmul(matmul(E, self.rho_in), E_dagger) # 取 partial_trace() 获得 rho_encode 与 rho_trash rho_encode = partial_trace(rho_BA, 2**N_B, 2**N_A, 1) rho_trash = partial_trace(rho_BA, 2**N_B, 2**N_A, 2) # 解码得到量子态 rho_out rho_CA = kron(self.rho_C, rho_encode) rho_out = matmul(matmul(D, rho_CA), D_dagger) # 通过 rho_trash 计算损失函数 zero_Hamiltonian = fluid.dygraph.to_variable( np.diag([1, 0]).astype('complex128')) loss = 1 - (trace(matmul(zero_Hamiltonian, rho_trash))).real return loss, self.rho_in, rho_out
def __measure_parameterless(self, state, which_qubits, result_desired): r"""进行 01 测量。 Args: state (ComplexVariable): 输入的量子态 which_qubits (list): 测量作用的量子比特编号 result_desired (list): 期望得到的测量结果,如 ``"0"``、``"1"`` 或者 ``["0", "1"]`` Returns: ComplexVariable: 测量坍塌后的量子态 ComplexVariable:测量坍塌得到的概率 list: 测量得到的结果(0 或 1) """ n = self.get_qubit_number() assert len(which_qubits) == len(result_desired), \ "the length of qubits wanted to be measured and the result desired should be same" op_list = [np.eye(2, dtype=np.complex128)] * n for i, ele in zip(which_qubits, result_desired): k = int(ele) rho = np.zeros((2, 2), dtype=np.complex128) rho[int(k), int(k)] = 1 op_list[i] = rho if n > 1: measure_operator = fluid.dygraph.to_variable(NKron(*op_list)) else: measure_operator = fluid.dygraph.to_variable(op_list[0]) state_measured = matmul(matmul(measure_operator, state), dagger(measure_operator)) prob = trace( matmul(matmul(dagger(measure_operator), measure_operator), state)).real state_measured = elementwise_div(state_measured, prob) return state_measured, prob, result_desired
def forward(self, state_in, label): """ Args: state_in: The input quantum state, shape [-1, 1, 2^n] label: label for the input state, shape [-1, 1] Returns: The loss: L = ((<Z> + 1)/2 + bias - label)^2 """ # Numpy array -> variable Ob = fluid.dygraph.to_variable(Observable(self.n)) label_pp = fluid.dygraph.to_variable(label) Utheta = U_theta(self.theta, n=self.n, depth=self.depth) U_dagger = dagger(Utheta) state_out = matmul(matmul(state_in, Utheta), U_dagger) E_Z = trace(matmul(state_out, Ob)) # map <Z> to the predict label state_predict = E_Z.real * 0.5 + 0.5 + self.bias loss = fluid.layers.reduce_mean((state_predict - label_pp)**2) is_correct = fluid.layers.where( fluid.layers.abs(state_predict - label_pp) < 0.5).shape[0] acc = is_correct / label.shape[0] return loss, acc, state_predict.numpy()
def forward(self, H, N, N_SYS_B, beta, D): # Apply quantum neural network onto the initial state rho_AB = U_theta(self.initial_state, self.theta, N, D) # Calculate the partial tarce to get the state rho_B of subsystem B rho_B = partial_trace(rho_AB, 2**(N - N_SYS_B), 2**(N_SYS_B), 1) # Calculate the three components of the loss function rho_B_squre = matmul(rho_B, rho_B) loss1 = (trace(matmul(rho_B, H))).real loss2 = (trace(rho_B_squre)).real * 2 / beta loss3 = -((trace(matmul(rho_B_squre, rho_B))).real + 3) / (2 * beta) # Get the final loss function loss = loss1 + loss2 + loss3 return loss, rho_B
def forward(self, H, N, N_SYS_B, beta, D): # 施加量子神经网络 rho_AB = U_theta(self.initial_state, self.theta, N, D) # 计算偏迹 partial trace 来获得子系统B所处的量子态 rho_B rho_B = partial_trace(rho_AB, 2**(N - N_SYS_B), 2**(N_SYS_B), 1) # 计算三个子损失函数 rho_B_squre = matmul(rho_B, rho_B) loss1 = (trace(matmul(rho_B, H))).real loss2 = (trace(rho_B_squre)).real * 2 / beta loss3 = -((trace(matmul(rho_B_squre, rho_B))).real + 3) / (2 * beta) # 最终的损失函数 loss = loss1 + loss2 + loss3 return loss, rho_B
def test_complex_x(self): input = rand([2, 20, 2, 3]).astype( self._dtype) + 1j * rand([2, 20, 2, 3]).astype(self._dtype) for place in self._places: with dg.guard(place): var_x = dg.to_variable(input) result = cpx.trace(var_x, offset=1, axis1=0, axis2=2).numpy() target = np.trace(input, offset=1, axis1=0, axis2=2) self.assertTrue(np.allclose(result, target))
def __measure_parameterized(self, state, which_qubits, result_desired, theta): r"""进行参数化的测量。 Args: state (ComplexVariable): 输入的量子态 which_qubits (list): 测量作用的量子比特编号 result_desired (list): 期望得到的测量结果,如 ``"0"``、``"1"`` 或者 ``["0", "1"]`` theta (Variable): 测量运算的参数 Returns: ComplexVariable: 测量坍塌后的量子态 Variable:测量坍塌得到的概率 list: 测量得到的结果(0 或 1) """ n = self.get_qubit_number() assert len(which_qubits) == len(result_desired), \ "the length of qubits wanted to be measured and the result desired should be same" op_list = [fluid.dygraph.to_variable(np.eye(2, dtype=np.complex128)) ] * n for idx in range(0, len(which_qubits)): i = which_qubits[idx] ele = result_desired[idx] if int(ele) == 0: basis0 = fluid.dygraph.to_variable( np.array([[1, 0], [0, 0]], dtype=np.complex128)) basis1 = fluid.dygraph.to_variable( np.array([[0, 0], [0, 1]], dtype=np.complex128)) rho0 = elementwise_mul(basis0, cos(theta[idx])) rho1 = elementwise_mul(basis1, sin(theta[idx])) rho = elementwise_add(rho0, rho1) op_list[i] = rho elif int(ele) == 1: # rho = diag(concat([cos(theta[idx]), sin(theta[idx])])) # rho = ComplexVariable(rho, zeros((2, 2), dtype="float64")) basis0 = fluid.dygraph.to_variable( np.array([[1, 0], [0, 0]], dtype=np.complex128)) basis1 = fluid.dygraph.to_variable( np.array([[0, 0], [0, 1]], dtype=np.complex128)) rho0 = elementwise_mul(basis0, sin(theta[idx])) rho1 = elementwise_mul(basis1, cos(theta[idx])) rho = elementwise_add(rho0, rho1) op_list[i] = rho else: print("cannot recognize the results_desired.") # rho = ComplexVariable(ones((2, 2), dtype="float64"), zeros((2, 2), dtype="float64")) measure_operator = fluid.dygraph.to_variable(op_list[0]) if n > 1: for idx in range(1, len(op_list)): measure_operator = kron(measure_operator, op_list[idx]) state_measured = matmul(matmul(measure_operator, state), dagger(measure_operator)) prob = trace( matmul(matmul(dagger(measure_operator), measure_operator), state)).real state_measured = elementwise_div(state_measured, prob) return state_measured, prob, result_desired
def forward(self, N): # 施加量子神经网络 U = U_theta(self.theta, N) # rho_tilde 是将 U 作用在 rho 后得到的量子态 U*rho*U^dagger rho_tilde = matmul(matmul(U, self.rho), hermitian(U)) # 计算损失函数 loss = trace(matmul(self.sigma, rho_tilde)) return loss.real, rho_tilde
def forward(self, N): # Apply quantum neural network onto the initial state U = U_theta(self.theta, N) # rho_tilda is the quantum state obtained by acting U on rho, which is U*rho*U^dagger rho_tilde = matmul(matmul(U, self.rho), dagger(U)) # Calculate loss function loss = trace(matmul(self.sigma, rho_tilde)) return loss.real, rho_tilde
def forward(self, x): rho_in = fluid.dygraph.to_variable(x) E = Encoder(self.theta) E_dagger = dagger(E) D = E_dagger D_dagger = E rho_BA = matmul(matmul(E, rho_in), E_dagger) rho_encode = partial_trace(rho_BA, 2**N_B, 2**N_A, 1) rho_trash = partial_trace(rho_BA, 2**N_B, 2**N_A, 2) rho_CA = kron(self.rho_C, rho_encode) rho_out = matmul(matmul(D, rho_CA), D_dagger) zero_Hamiltonian = fluid.dygraph.to_variable( np.diag([1, 0]).astype('complex128')) loss = 1 - (trace(matmul(zero_Hamiltonian, rho_trash))).real return loss, rho_out, rho_encode
def expecval(self, H): r"""量子线路输出的量子态关于可观测量H的期望值。 Hint: 如果想输入的可观测量的矩阵为 :math:`0.7Z\otimes X\otimes I+0.2I\otimes Z\otimes I` 。则 ``H`` 应为 ``[[0.7, 'z0,x1'], [0.2, 'z1']]`` 。 Args: H (list): 可观测量的相关信息 Returns: Variable: 量子线路输出的量子态关于H的期望值 代码示例: .. code-block:: python import numpy as np from paddle import fluid from paddle_quantum.circuit import UAnsatz n = 5 H_info = [[0.1, 'x1'], [0.2, 'y0,z4']] theta = np.ones(3) input_state = np.ones(2**n)+0j input_state = input_state / np.linalg.norm(input_state) with fluid.dygraph.guard(): input_state_var = fluid.dygraph.to_variable(input_state) theta = fluid.dygraph.to_variable(theta) cir = UAnsatz(n) cir.rx(theta[0], 0) cir.rz(theta[1], 1) cir.rx(theta[2], 2) cir.run_state_vector(input_state_var) expect_value = cir.expecval(H_info).numpy() print(f'计算得到的{H_info}期望值是{expect_value}') :: 计算得到的[[0.1, 'x1'], [0.2, 'y0,z4']]期望值是[0.05403023] .. code-block:: python import numpy as np from paddle import fluid from paddle_quantum.circuit import UAnsatz n = 5 H_info = [[0.1, 'x1'], [0.2, 'y0,z4']] theta = np.ones(3) input_state = np.diag(np.arange(2**n))+0j input_state = input_state / np.trace(input_state) with fluid.dygraph.guard(): input_state_var = fluid.dygraph.to_variable(input_state) theta = fluid.dygraph.to_variable(theta) cir = UAnsatz(n) cir.rx(theta[0], 0) cir.ry(theta[1], 1) cir.rz(theta[2], 2) cir.run_density_matrix(input_state_var) expect_value = cir.expecval(H_info).numpy() print(f'计算得到的{H_info}期望值是{expect_value}') :: 计算得到的[[0.1, 'x1'], [0.2, 'y0,z4']]期望值是[-0.02171538] """ if self.__run_state == 'state_vector': return vec_expecval(H, self.__state).real elif self.__run_state == 'density_matrix': state = self.__state H_mat = fluid.dygraph.to_variable(pauli_str_to_matrix(H, self.n)) return trace(matmul(state, H_mat)).real else: # Raise error raise ValueError( "no state for measurement; please run the circuit first")