Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【PaddlePaddle Hackathon】76 量子电路的量子比特数扩展 #27

Merged
merged 5 commits into from
Nov 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions paddle_quantum/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from paddle_quantum.utils import partial_trace, dagger, pauli_str_to_matrix
from paddle_quantum import shadow
from paddle_quantum.intrinsic import *
from paddle_quantum.state import density_op
from paddle_quantum.state import density_op,vec

__all__ = [
"UAnsatz",
Expand Down Expand Up @@ -59,7 +59,30 @@ 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):
"""
为原来的量子电路进行比特数扩展

Args:
new_n(int):扩展后的量子比特数
"""
assert new_n>=self.n,'扩展后量子比特数要大于原量子比特数'
diff = new_n-self.n
dim = 2**diff
if self.__state is not None:
if self.__run_mode=='density_matrix':
shape = (dim,dim)
_state = paddle.to_tensor(density_op(diff))
elif self.__run_mode=='state_vector':
shape = (dim,)
_state = paddle.to_tensor(vec(0,diff))

_state= paddle.reshape(_state,shape)
_state = kron(self.__state,_state)
self.__state = _state
self.n = new_n

def __add__(self, cir):
r"""重载加法 ‘+’ 运算符,用于拼接两个维度相同的电路

Expand Down
1 change: 1 addition & 0 deletions test_and_documents/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
通过在UAnsatz类中添加新的成员函数expand来实现扩展
34 changes: 34 additions & 0 deletions test_and_documents/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from paddle_quantum.circuit import UAnsatz
from paddle import kron
from paddle_quantum.state import vec,density_op
import paddle


#density_matrix
def test_density_matrix():
cir = UAnsatz(1)
cir.ry(paddle.to_tensor(1,dtype='float64'),0)
state = cir.run_density_matrix()
cir.expand(3)
print(cir.get_state())

cir2 = UAnsatz(3)
cir2.ry(paddle.to_tensor(1,dtype='float64'),0)
cir2.run_density_matrix()
print(cir2.get_state())

#state_vector
def test_state_vector():
cir = UAnsatz(1)
cir.ry(paddle.to_tensor(1,dtype='float64'),0)
state = cir.run_state_vector()
cir.expand(3)
print(cir.get_state())

cir2 = UAnsatz(3)
cir2.ry(paddle.to_tensor(1,dtype='float64'),0)
cir2.run_state_vector()
print(cir2.get_state())

test_density_matrix()
test_state_vector()