Skip to content

Commit

Permalink
Merge pull request #25 from yangguohao/task77
Browse files Browse the repository at this point in the history
[PaddlePaddle Hackathon]77 为哈密顿量矩阵实现指定量子比特数
  • Loading branch information
QuLeaf authored Nov 3, 2021
2 parents 77279bd + 3b7f210 commit 00b1396
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
4 changes: 2 additions & 2 deletions paddle_quantum/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def __init__(self, n):
paddle.to_tensor(np.array([math.pi / 4])), paddle.to_tensor(np.array([-math.pi / 4]))]
# Record history of adding gates to the circuit
self.__history = []

def expand(self,new_n):
"""
为原来的量子电路进行比特数扩展
Expand All @@ -82,7 +82,7 @@ def expand(self,new_n):
_state = kron(self.__state,_state)
self.__state = _state
self.n = new_n

def __add__(self, cir):
r"""重载加法 ‘+’ 运算符,用于拼接两个维度相同的电路
Expand Down
14 changes: 9 additions & 5 deletions paddle_quantum/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -914,17 +914,21 @@ def decompose_pauli_words(self):
pass
return self.coefficients, self.__pauli_words

def construct_h_matrix(self):
def construct_h_matrix(self, n_qubit=None):
r"""构建 Hamiltonian 在 Z 基底下的矩阵。
Returns:
np.ndarray: Z 基底下的哈密顿量矩阵形式
"""
coefs, pauli_words, sites = self.decompose_with_sites()
n_qubit = 1
for site in sites:
if type(site[0]) is int:
n_qubit = max(n_qubit, max(site) + 1)
if n_qubit is None:
n_qubit = 1
for site in sites:
if type(site[0]) is int:
print(n_qubit,(site))
n_qubit = max(n_qubit, max(site) + 1)
else:
assert n_qubit>=self.n_qubits,"输入的量子数不小于哈密顿量表达式中所对应的量子比特数"
h_matrix = np.zeros([2 ** n_qubit, 2 ** n_qubit], dtype='complex64')
spin_ops = SpinOps(n_qubit, use_sparse=True)
for idx in range(len(coefs)):
Expand Down
6 changes: 6 additions & 0 deletions test_documents/test_construct_h_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from paddle_quantum.utils import Hamiltonian

h = Hamiltonian([(1, 'Z0, Z1')])

print(h.construct_h_matrix())
print(h.construct_h_matrix(4))

0 comments on commit 00b1396

Please sign in to comment.