Skip to content

Commit 00b1396

Browse files
author
QuLeaf
authored
Merge pull request #25 from yangguohao/task77
[PaddlePaddle Hackathon]77 为哈密顿量矩阵实现指定量子比特数
2 parents 77279bd + 3b7f210 commit 00b1396

File tree

3 files changed

+17
-7
lines changed

3 files changed

+17
-7
lines changed

paddle_quantum/circuit.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def __init__(self, n):
5959
paddle.to_tensor(np.array([math.pi / 4])), paddle.to_tensor(np.array([-math.pi / 4]))]
6060
# Record history of adding gates to the circuit
6161
self.__history = []
62-
62+
6363
def expand(self,new_n):
6464
"""
6565
为原来的量子电路进行比特数扩展
@@ -82,7 +82,7 @@ def expand(self,new_n):
8282
_state = kron(self.__state,_state)
8383
self.__state = _state
8484
self.n = new_n
85-
85+
8686
def __add__(self, cir):
8787
r"""重载加法 ‘+’ 运算符,用于拼接两个维度相同的电路
8888

paddle_quantum/utils.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -914,17 +914,21 @@ def decompose_pauli_words(self):
914914
pass
915915
return self.coefficients, self.__pauli_words
916916

917-
def construct_h_matrix(self):
917+
def construct_h_matrix(self, n_qubit=None):
918918
r"""构建 Hamiltonian 在 Z 基底下的矩阵。
919919
920920
Returns:
921921
np.ndarray: Z 基底下的哈密顿量矩阵形式
922922
"""
923923
coefs, pauli_words, sites = self.decompose_with_sites()
924-
n_qubit = 1
925-
for site in sites:
926-
if type(site[0]) is int:
927-
n_qubit = max(n_qubit, max(site) + 1)
924+
if n_qubit is None:
925+
n_qubit = 1
926+
for site in sites:
927+
if type(site[0]) is int:
928+
print(n_qubit,(site))
929+
n_qubit = max(n_qubit, max(site) + 1)
930+
else:
931+
assert n_qubit>=self.n_qubits,"输入的量子数不小于哈密顿量表达式中所对应的量子比特数"
928932
h_matrix = np.zeros([2 ** n_qubit, 2 ** n_qubit], dtype='complex64')
929933
spin_ops = SpinOps(n_qubit, use_sparse=True)
930934
for idx in range(len(coefs)):
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from paddle_quantum.utils import Hamiltonian
2+
3+
h = Hamiltonian([(1, 'Z0, Z1')])
4+
5+
print(h.construct_h_matrix())
6+
print(h.construct_h_matrix(4))

0 commit comments

Comments
 (0)