1 Star 9 Fork 3

xpeter80 / Quantum-SVM-MINIST

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
gates.py 34.60 KB
一键复制 编辑 原始数据 按行查看 历史
xpeter80 提交于 2020-06-27 07:31 . init
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
from __future__ import division
import numpy as np
import scipy.sparse as sp
from qutip.qobj import Qobj
from qutip.operators import identity, qeye, sigmax
from qutip.tensor import tensor
from qutip.states import fock_dm
from itertools import product
from functools import partial, reduce
from operator import mul
__all__ = ['sigma_x', 'rx', 'ry', 'rz', 'sqrtnot', 'snot', 'phasegate', 'cphase', 'cnot',
'csign', 'berkeley', 'swapalpha', 'swap', 'iswap', 'sqrtswap',
'sqrtiswap', 'fredkin', 'toffoli', 'rotation', 'controlled_gate',
'globalphase', 'hadamard_transform', 'gate_sequence_product',
'gate_expand_1toN', 'gate_expand_2toN', 'gate_expand_3toN',
'qubit_clifford_group','controlled_s','controlled_s_inv','controlled_ry','controlled_f','controlled_h']
#
# Single Qubit Gates
#
def sigma_x(N=None, target=0):
"""Operator sigma X.
Returns
-------
result : qobj
Quantum object for operator describing the sigma X.
"""
if N is not None:
return gate_expand_1toN(sigma_x(), N, target)
else:
return Qobj([[0, 1],
[1, 0]])
def rx(phi, N=None, target=0):
"""Single-qubit rotation for operator sigmax with angle phi.
Returns
-------
result : qobj
Quantum object for operator describing the rotation.
"""
if N is not None:
return gate_expand_1toN(rx(phi), N, target)
else:
return Qobj([[np.cos(phi / 2), -1j * np.sin(phi / 2)],
[-1j * np.sin(phi / 2), np.cos(phi / 2)]])
def ry(phi, N=None, target=0):
"""Single-qubit rotation for operator sigmay with angle phi.
Returns
-------
result : qobj
Quantum object for operator describing the rotation.
"""
if N is not None:
return gate_expand_1toN(ry(phi), N, target)
else:
return Qobj([[np.cos(phi / 2), -np.sin(phi / 2)],
[np.sin(phi / 2), np.cos(phi / 2)]])
def rz(phi, N=None, target=0):
"""Single-qubit rotation for operator sigmaz with angle phi.
Returns
-------
result : qobj
Quantum object for operator describing the rotation.
"""
if N is not None:
return gate_expand_1toN(rz(phi), N, target)
else:
return Qobj([[np.exp(-1j * phi / 2), 0],
[0, np.exp(1j * phi / 2)]])
def sqrtnot(N=None, target=0):
"""Single-qubit square root NOT gate.
Returns
-------
result : qobj
Quantum object for operator describing the square root NOT gate.
"""
if N is not None:
return gate_expand_1toN(sqrtnot(), N, target)
else:
return Qobj([[0.5 + 0.5j, 0.5 - 0.5j],
[0.5 - 0.5j, 0.5 + 0.5j]])
def snot(N=None, target=0):
"""Quantum object representing the SNOT (Hadamard) gate.
Returns
-------
snot_gate : qobj
Quantum object representation of SNOT gate.
Examples
--------
>>> snot()
Quantum object: dims = [[2], [2]], \
shape = [2, 2], type = oper, isHerm = True
Qobj data =
[[ 0.70710678+0.j 0.70710678+0.j]
[ 0.70710678+0.j -0.70710678+0.j]]
"""
if N is not None:
return gate_expand_1toN(snot(), N, target)
else:
return 1 / np.sqrt(2.0) * Qobj([[1, 1],
[1, -1]])
def phasegate(theta, N=None, target=0):
"""
Returns quantum object representing the phase shift gate.
Parameters
----------
theta : float
Phase rotation angle.
Returns
-------
phase_gate : qobj
Quantum object representation of phase shift gate.
Examples
--------
>>> phasegate(pi/4)
Quantum object: dims = [[2], [2]], \
shape = [2, 2], type = oper, isHerm = False
Qobj data =
[[ 1.00000000+0.j 0.00000000+0.j ]
[ 0.00000000+0.j 0.70710678+0.70710678j]]
"""
if N is not None:
return gate_expand_1toN(phasegate(theta), N, target)
else:
return Qobj([[1, 0],
[0, np.exp(1.0j * theta)]],
dims=[[2], [2]])
#
# 2 Qubit Gates
#
def cphase(theta, N=2, control=0, target=1):
"""
Returns quantum object representing the controlled phase shift gate.
Parameters
----------
theta : float
Phase rotation angle.
N : integer
The number of qubits in the target space.
control : integer
The index of the control qubit.
target : integer
The index of the target qubit.
Returns
-------
U : qobj
Quantum object representation of controlled phase gate.
"""
if N < 1 or target < 0 or control < 0:
raise ValueError("Minimum value: N=1, control=0 and target=0")
if control >= N or target >= N:
raise ValueError("control and target need to be smaller than N")
U_list1 = [identity(2)] * N
U_list2 = [identity(2)] * N
U_list1[control] = fock_dm(2, 1)
U_list1[target] = phasegate(theta)
U_list2[control] = fock_dm(2, 0)
U = tensor(U_list1) + tensor(U_list2)
return U
def cnot(N=None, control=0, target=1):
"""
Quantum object representing the CNOT gate.
Returns
-------
cnot_gate : qobj
Quantum object representation of CNOT gate
Examples
--------
>>> cnot()
Quantum object: dims = [[2, 2], [2, 2]], \
shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 1.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 1.+0.j]
[ 0.+0.j 0.+0.j 1.+0.j 0.+0.j]]
"""
if (control == 1 and target == 0) and N is None:
N = 2
if N is not None:
return gate_expand_2toN(cnot(), N, control, target)
else:
return Qobj([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]],
dims=[[2, 2], [2, 2]])
def csign(N=None, control=0, target=1):
"""
Quantum object representing the CSIGN gate.
Returns
-------
csign_gate : qobj
Quantum object representation of CSIGN gate
Examples
--------
>>> csign()
Quantum object: dims = [[2, 2], [2, 2]], \
shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 1.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 1.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j -1.+0.j]]
"""
if (control == 1 and target == 0) and N is None:
N = 2
if N is not None:
return gate_expand_2toN(csign(), N, control, target)
else:
return Qobj([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, -1]],
dims=[[2, 2], [2, 2]])
def berkeley(N=None, targets=[0, 1]):
"""
Quantum object representing the Berkeley gate.
Returns
-------
berkeley_gate : qobj
Quantum object representation of Berkeley gate
Examples
--------
>>> berkeley()
Quantum object: dims = [[2, 2], [2, 2]], \
shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ cos(pi/8).+0.j 0.+0.j 0.+0.j 0.+sin(pi/8).j]
[ 0.+0.j cos(3pi/8).+0.j 0.+sin(3pi/8).j 0.+0.j]
[ 0.+0.j 0.+sin(3pi/8).j cos(3pi/8).+0.j 0.+0.j]
[ 0.+sin(pi/8).j 0.+0.j 0.+0.j cos(pi/8).+0.j]]
"""
if (targets[0] == 1 and targets[1] == 0) and N is None:
N = 2
if N is not None:
return gate_expand_2toN(cnot(), N, targets=targets)
else:
return Qobj([[np.cos(np.pi / 8), 0, 0, 1.0j * np.sin(np.pi / 8)],
[0, np.cos(3 * np.pi / 8), 1.0j *
np.sin(3 * np.pi / 8), 0],
[0, 1.0j * np.sin(3 * np.pi / 8),
np.cos(3 * np.pi / 8), 0],
[1.0j * np.sin(np.pi / 8), 0, 0, np.cos(np.pi / 8)]],
dims=[[2, 2], [2, 2]])
def swapalpha(alpha, N=None, targets=[0, 1]):
"""
Quantum object representing the SWAPalpha gate.
Returns
-------
swapalpha_gate : qobj
Quantum object representation of SWAPalpha gate
Examples
--------
>>> swapalpha(alpha)
Quantum object: dims = [[2, 2], [2, 2]], \
shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.5*(1 + exp(j*pi*alpha) 0.5*(1 - exp(j*pi*alpha) 0.+0.j]
[ 0.+0.j 0.5*(1 - exp(j*pi*alpha) 0.5*(1 + exp(j*pi*alpha) 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]
"""
if (targets[0] == 1 and targets[1] == 0) and N is None:
N = 2
if N is not None:
return gate_expand_2toN(cnot(), N, targets=targets)
else:
return Qobj([[1, 0, 0, 0],
[0, 0.5 * (1 + np.exp(1.0j * np.pi * alpha)),
0.5 * (1 - np.exp(1.0j * np.pi * alpha)), 0],
[0, 0.5 * (1 - np.exp(1.0j * np.pi * alpha)),
0.5 * (1 + np.exp(1.0j * np.pi * alpha)), 0],
[0, 0, 0, 1]],
dims=[[2, 2], [2, 2]])
def swap(N=None, targets=[0, 1]):
"""Quantum object representing the SWAP gate.
Returns
-------
swap_gate : qobj
Quantum object representation of SWAP gate
Examples
--------
>>> swap()
Quantum object: dims = [[2, 2], [2, 2]], \
shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 1.+0.j 0.+0.j]
[ 0.+0.j 1.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]
"""
if targets != [0, 1] and N is None:
N = 2
if N is not None:
return gate_expand_2toN(swap(), N, targets=targets)
else:
return Qobj([[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]],
dims=[[2, 2], [2, 2]])
def iswap(N=None, targets=[0, 1]):
"""Quantum object representing the iSWAP gate.
Returns
-------
iswap_gate : qobj
Quantum object representation of iSWAP gate
Examples
--------
>>> iswap()
Quantum object: dims = [[2, 2], [2, 2]], \
shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+1.j 0.+0.j]
[ 0.+0.j 0.+1.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]
"""
if targets != [0, 1] and N is None:
N = 2
if N is not None:
return gate_expand_2toN(iswap(), N, targets=targets)
else:
return Qobj([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]],
dims=[[2, 2], [2, 2]])
def sqrtswap(N=None, targets=[0, 1]):
"""Quantum object representing the square root SWAP gate.
Returns
-------
sqrtswap_gate : qobj
Quantum object representation of square root SWAP gate
"""
if targets != [0, 1] and N is None:
N = 2
if N is not None:
return gate_expand_2toN(sqrtswap(), N, targets=targets)
else:
return Qobj(np.array([[1, 0, 0, 0],
[0, 0.5 + 0.5j, 0.5 - 0.5j, 0],
[0, 0.5 - 0.5j, 0.5 + 0.5j, 0],
[0, 0, 0, 1]]),
dims=[[2, 2], [2, 2]])
def sqrtiswap(N=None, targets=[0, 1]):
"""Quantum object representing the square root iSWAP gate.
Returns
-------
sqrtiswap_gate : qobj
Quantum object representation of square root iSWAP gate
Examples
--------
>>> sqrtiswap()
Quantum object: dims = [[2, 2], [2, 2]], \
shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 1.00000000+0.j 0.00000000+0.j \
0.00000000+0.j 0.00000000+0.j]
[ 0.00000000+0.j 0.70710678+0.j \
0.00000000-0.70710678j 0.00000000+0.j]
[ 0.00000000+0.j 0.00000000-0.70710678j\
0.70710678+0.j 0.00000000+0.j]
[ 0.00000000+0.j 0.00000000+0.j \
0.00000000+0.j 1.00000000+0.j]]
"""
if targets != [0, 1] and N is None:
N = 2
if N is not None:
return gate_expand_2toN(sqrtiswap(), N, targets=targets)
else:
return Qobj(np.array([[1, 0, 0, 0],
[0, 1 / np.sqrt(2), 1j / np.sqrt(2), 0],
[0, 1j / np.sqrt(2), 1 / np.sqrt(2), 0],
[0, 0, 0, 1]]), dims=[[2, 2], [2, 2]])
#
# 3 Qubit Gates
#
def fredkin(N=None, control=0, targets=[1, 2]):
"""Quantum object representing the Fredkin gate.
Returns
-------
fredkin_gate : qobj
Quantum object representation of Fredkin gate.
Examples
--------
>>> fredkin()
Quantum object: dims = [[2, 2, 2], [2, 2, 2]], \
shape = [8, 8], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]
"""
if [control, targets[0], targets[1]] != [0, 1, 2] and N is None:
N = 3
if N is not None:
return gate_expand_3toN(fredkin(), N,
[control, targets[0]], targets[1])
else:
return Qobj([[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1]],
dims=[[2, 2, 2], [2, 2, 2]])
def toffoli(N=None, controls=[0, 1], target=2):
"""Quantum object representing the Toffoli gate.
Returns
-------
toff_gate : qobj
Quantum object representation of Toffoli gate.
Examples
--------
>>> toffoli()
Quantum object: dims = [[2, 2, 2], [2, 2, 2]], \
shape = [8, 8], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j]]
"""
if [controls[0], controls[1], target] != [0, 1, 2] and N is None:
N = 3
if N is not None:
return gate_expand_3toN(toffoli(), N, controls, target)
else:
return Qobj([[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0]],
dims=[[2, 2, 2], [2, 2, 2]])
#
# Miscellaneous Gates
#
def rotation(op, phi, N=None, target=0):
"""Single-qubit rotation for operator op with angle phi.
Returns
-------
result : qobj
Quantum object for operator describing the rotation.
"""
if N is not None:
return gate_expand_1toN(rotation(op, phi), N, target)
else:
return (-1j * op * phi / 2).expm()
def controlled_gate(U, N=2, control=0, target=1, control_value=1):
"""
Create an N-qubit controlled gate from a single-qubit gate U with the given
control and target qubits.
Parameters
----------
U : Qobj
Arbitrary single-qubit gate.
N : integer
The number of qubits in the target space.
control : integer
The index of the first control qubit.
target : integer
The index of the target qubit.
control_value : integer (1)
The state of the control qubit that activates the gate U.
Returns
-------
result : qobj
Quantum object representing the controlled-U gate.
"""
if [N, control, target] == [2, 0, 1]:
return (tensor(fock_dm(2, control_value), U) +
tensor(fock_dm(2, 1 - control_value), identity(2)))
else:
U2 = controlled_gate(U, control_value=control_value)
return gate_expand_2toN(U2, N=N, control=control, target=target)
def controlled_s(N=2, control=0, target=1, control_value=1):
"""
Create an N-qubit controlled gate from phase gate with the given
control and target qubits.
Parameters
----------
N : integer
The number of qubits in the target space.
control : integer
The index of the first control qubit.
target : integer
The index of the target qubit.
control_value : integer (1)
The state of the control qubit that activates the gate U.
Returns
-------
result : qobj
Quantum object representing the controlled-s gate.
"""
U = Qobj([[1, 0],
[0, 1j]])
if [N, control, target] == [2, 0, 1]:
return (tensor(fock_dm(2, control_value), U) +
tensor(fock_dm(2, 1 - control_value), identity(2)))
else:
U2 = controlled_gate(U, control_value=control_value)
return gate_expand_2toN(U2, N=N, control=control, target=target)
def controlled_s_inv(N=2, control=0, target=1, control_value=1):
"""
Create an N-qubit controlled gate from inversed phase gate with the given
control and target qubits.
Parameters
----------
N : integer
The number of qubits in the target space.
control : integer
The index of the first control qubit.
target : integer
The index of the target qubit.
control_value : integer (1)
The state of the control qubit that activates the gate U.
Returns
-------
result : qobj
Quantum object representing the controlled-s gate.
"""
U = Qobj([[1, 0],
[0, -1j]])
if [N, control, target] == [2, 0, 1]:
return (tensor(fock_dm(2, control_value), U) +
tensor(fock_dm(2, 1 - control_value), identity(2)))
else:
U2 = controlled_gate(U, control_value=control_value)
return gate_expand_2toN(U2, N=N, control=control, target=target)
def controlled_ry(phi, N=2, control=0, target=1, control_value=1):
"""
Create an N-qubit controlled gate from y-rotation gate with the given
control and target qubits.
Parameters
----------
N : integer
The number of qubits in the target space.
control : integer
The index of the first control qubit.
target : integer
The index of the target qubit.
control_value : integer (1)
The state of the control qubit that activates the gate U.
Returns
-------
result : qobj
Quantum object representing the controlled-s gate.
"""
U = ry(phi)
if [N, control, target] == [2, 0, 1]:
return (tensor(fock_dm(2, control_value), U) +
tensor(fock_dm(2, 1 - control_value), identity(2)))
else:
U2 = controlled_gate(U, control_value=control_value)
return gate_expand_2toN(U2, N=N, control=control, target=target)
def controlled_f(co, N=2, control=0, target=1, control_value=1):
"""
Create an N-qubit controlled gate from f gate with the given
control and target qubits.
Parameters
----------
N : integer
The number of qubits in the target space.
control : integer
The index of the first control qubit.
target : integer
The index of the target qubit.
control_value : integer (1)
The state of the control qubit that activates the gate U.
Returns
-------
result : qobj
Quantum object representing the controlled-s gate.
"""
U0 = Qobj([[1.0065, 0.2425],
[0.2425, 0.9935]])
U = (co * 1j * np.pi * U0).expm()
if [N, control, target] == [2, 0, 1]:
return (tensor(fock_dm(2, control_value), U) +
tensor(fock_dm(2, 1 - control_value), identity(2)))
else:
U2 = controlled_gate(U, control_value=control_value)
return gate_expand_2toN(U2, N=N, control=control, target=target)
def controlled_h(N=2, control=0, target=1, control_value=1):
"""
Create an N-qubit controlled gate from hadamard gate with the given
control and target qubits.
Parameters
----------
N : integer
The number of qubits in the target space.
control : integer
The index of the first control qubit.
target : integer
The index of the target qubit.
control_value : integer (1)
The state of the control qubit that activates the gate U.
Returns
-------
result : qobj
Quantum object representing the controlled-s gate.
"""
U = 1 / np.sqrt(2.0) * Qobj([[1, 1],
[1, -1]])
if [N, control, target] == [2, 0, 1]:
return (tensor(fock_dm(2, control_value), U) +
tensor(fock_dm(2, 1 - control_value), identity(2)))
else:
U2 = controlled_gate(U, control_value=control_value)
return gate_expand_2toN(U2, N=N, control=control, target=target)
def globalphase(theta, N=1):
"""
Returns quantum object representing the global phase shift gate.
Parameters
----------
theta : float
Phase rotation angle.
Returns
-------
phase_gate : qobj
Quantum object representation of global phase shift gate.
Examples
--------
>>> phasegate(pi/4)
Quantum object: dims = [[2], [2]], \
shape = [2, 2], type = oper, isHerm = False
Qobj data =
[[ 0.70710678+0.70710678j 0.00000000+0.j]
[ 0.00000000+0.j 0.70710678+0.70710678j]]
"""
data = (np.exp(1.0j * theta) * sp.eye(2 ** N, 2 ** N,
dtype=complex, format="csr"))
return Qobj(data, dims=[[2] * N, [2] * N])
#
# Operation on Gates
#
def _hamming_distance(x, bits=32):
"""
Calculate the bit-wise Hamming distance of x from 0: That is, the number
1s in the integer x.
"""
tot = 0
while x:
tot += 1
x &= x - 1
return tot
def hadamard_transform(N=1):
"""Quantum object representing the N-qubit Hadamard gate.
Returns
-------
q : qobj
Quantum object representation of the N-qubit Hadamard gate.
"""
data = 2 ** (-N / 2) * np.array([[(-1) ** _hamming_distance(i & j)
for i in range(2 ** N)]
for j in range(2 ** N)])
return Qobj(data, dims=[[2] * N, [2] * N])
def gate_sequence_product(U_list, left_to_right=True):
"""
Calculate the overall unitary matrix for a given list of unitary operations
Parameters
----------
U_list : list
List of gates implementing the quantum circuit.
left_to_right : Boolean
Check if multiplication is to be done from left to right.
Returns
-------
U_overall : qobj
Overall unitary matrix of a given quantum circuit.
"""
U_overall = 1
for U in U_list:
if left_to_right:
U_overall = U * U_overall
else:
U_overall = U_overall * U
return U_overall
def _powers(op, N):
"""
Generator that yields powers of an operator `op`,
through to `N`.
"""
acc = qeye(op.dims[0])
yield acc
for _ in range(N - 1):
acc *= op
yield acc
def qubit_clifford_group(N=None, target=0):
"""
Generates the Clifford group on a single qubit,
using the presentation of the group given by Ross and Selinger
(http://www.mathstat.dal.ca/~selinger/newsynth/).
Parameters
-----------
N : int or None
Number of qubits on which each operator is to be defined
(default: 1).
target : int
Index of the target qubit on which the single-qubit
Clifford operators are to act.
Yields
------
op : Qobj
Clifford operators, represented as Qobj instances.
"""
# The Ross-Selinger presentation of the single-qubit Clifford
# group expresses each element in the form C_{ijk} = E^i X^j S^k
# for gates E, X and S, and for i in range(3), j in range(2) and
# k in range(4).
#
# We start by defining these gates. E is defined in terms of H,
# \omega and S, so we define \omega and H first.
w = np.exp(1j * 2 * np.pi / 8)
H = snot()
X = sigmax()
S = phasegate(np.pi / 2)
E = H * (S ** 3) * w ** 3
for op in map(partial(reduce, mul), product(_powers(E, 3),
_powers(X, 2), _powers(S, 4))):
# partial(reduce, mul) returns a function that takes products
# of its argument, by analogy to sum. Note that by analogy,
# sum can be written as partial(reduce, add).
# product(...) yields the Cartesian product of its arguments.
# Here, each element is a tuple (E**i, X**j, S**k) such that
# partial(reduce, mul) acting on the tuple yields E**i * X**j * S**k.
# Finally, we optionally expand the gate.
if N is not None:
yield gate_expand_1toN(op, N, target)
else:
yield op
#
# Gate Expand
#
def gate_expand_1toN(U, N, target):
"""
Create a Qobj representing a one-qubit gate that act on a system with N
qubits.
Parameters
----------
U : Qobj
The one-qubit gate
N : integer
The number of qubits in the target space.
target : integer
The index of the target qubit.
Returns
-------
gate : qobj
Quantum object representation of N-qubit gate.
"""
if N < 1:
raise ValueError("integer N must be larger or equal to 1")
if target >= N:
raise ValueError("target must be integer < integer N")
return tensor([identity(2)] * (target) + [U] +
[identity(2)] * (N - target - 1))
def gate_expand_2toN(U, N, control=None, target=None, targets=None):
"""
Create a Qobj representing a two-qubit gate that act on a system with N
qubits.
Parameters
----------
U : Qobj
The two-qubit gate
N : integer
The number of qubits in the target space.
control : integer
The index of the control qubit.
target : integer
The index of the target qubit.
targets : list
List of target qubits.
Returns
-------
gate : qobj
Quantum object representation of N-qubit gate.
"""
if targets is not None:
control, target = targets
if control is None or target is None:
raise ValueError("Specify value of control and target")
if N < 2:
raise ValueError("integer N must be larger or equal to 2")
if control >= N or target >= N:
raise ValueError("control and not target must be integer < integer N")
if control == target:
raise ValueError("target and not control cannot be equal")
p = list(range(N))
if target == 0 and control == 1:
p[control], p[target] = p[target], p[control]
elif target == 0:
p[1], p[target] = p[target], p[1]
p[1], p[control] = p[control], p[1]
else:
p[1], p[target] = p[target], p[1]
p[0], p[control] = p[control], p[0]
return tensor([U] + [identity(2)] * (N - 2)).permute(p)
def gate_expand_3toN(U, N, controls=[0, 1], target=2):
"""
Create a Qobj representing a three-qubit gate that act on a system with N
qubits.
Parameters
----------
U : Qobj
The three-qubit gate
N : integer
The number of qubits in the target space.
controls : list
The list of the control qubits.
target : integer
The index of the target qubit.
Returns
-------
gate : qobj
Quantum object representation of N-qubit gate.
"""
if N < 3:
raise ValueError("integer N must be larger or equal to 3")
if controls[0] >= N or controls[1] >= N or target >= N:
raise ValueError("control and not target is None."
" Must be integer < integer N")
if (controls[0] == target or
controls[1] == target or
controls[0] == controls[1]):
raise ValueError("controls[0], controls[1], and target"
" cannot be equal")
p = list(range(N))
p1 = list(range(N))
p2 = list(range(N))
if controls[0] <= 2 and controls[1] <= 2 and target <= 2:
p[controls[0]] = 0
p[controls[1]] = 1
p[target] = 2
#
# N > 3 cases
#
elif controls[0] == 0 and controls[1] == 1:
p[2], p[target] = p[target], p[2]
elif controls[0] == 0 and target == 2:
p[1], p[controls[1]] = p[controls[1]], p[1]
elif controls[1] == 1 and target == 2:
p[0], p[controls[0]] = p[controls[0]], p[0]
elif controls[0] == 1 and controls[1] == 0:
p[controls[1]], p[controls[0]] = p[controls[0]], p[controls[1]]
p2[2], p2[target] = p2[target], p2[2]
p = [p2[p[k]] for k in range(N)]
elif controls[0] == 2 and target == 0:
p[target], p[controls[0]] = p[controls[0]], p[target]
p1[1], p1[controls[1]] = p1[controls[1]], p1[1]
p = [p1[p[k]] for k in range(N)]
elif controls[1] == 2 and target == 1:
p[target], p[controls[1]] = p[controls[1]], p[target]
p1[0], p1[controls[0]] = p1[controls[0]], p1[0]
p = [p1[p[k]] for k in range(N)]
elif controls[0] == 1 and controls[1] == 2:
# controls[0] -> controls[1] -> target -> outside
p[0], p[1] = p[1], p[0]
p[0], p[2] = p[2], p[0]
p[0], p[target] = p[target], p[0]
elif controls[0] == 2 and target == 1:
# controls[0] -> target -> controls[1] -> outside
p[0], p[2] = p[2], p[0]
p[0], p[1] = p[1], p[0]
p[0], p[controls[1]] = p[controls[1]], p[0]
elif controls[1] == 0 and controls[0] == 2:
# controls[1] -> controls[0] -> target -> outside
p[1], p[0] = p[0], p[1]
p[1], p[2] = p[2], p[1]
p[1], p[target] = p[target], p[1]
elif controls[1] == 2 and target == 0:
# controls[1] -> target -> controls[0] -> outside
p[1], p[2] = p[2], p[1]
p[1], p[0] = p[0], p[1]
p[1], p[controls[0]] = p[controls[0]], p[1]
elif target == 1 and controls[1] == 0:
# target -> controls[1] -> controls[0] -> outside
p[2], p[1] = p[1], p[2]
p[2], p[0] = p[0], p[2]
p[2], p[controls[0]] = p[controls[0]], p[2]
elif target == 0 and controls[0] == 1:
# target -> controls[0] -> controls[1] -> outside
p[2], p[0] = p[0], p[2]
p[2], p[1] = p[1], p[2]
p[2], p[controls[1]] = p[controls[1]], p[2]
elif controls[0] == 0 and controls[1] == 2:
# controls[0] -> self, controls[1] -> target -> outside
p[1], p[2] = p[2], p[1]
p[1], p[target] = p[target], p[1]
elif controls[1] == 1 and controls[0] == 2:
# controls[1] -> self, controls[0] -> target -> outside
p[0], p[2] = p[2], p[0]
p[0], p[target] = p[target], p[0]
elif target == 2 and controls[0] == 1:
# target -> self, controls[0] -> controls[1] -> outside
p[0], p[1] = p[1], p[0]
p[0], p[controls[1]] = p[controls[1]], p[0]
#
# N > 4 cases
#
elif controls[0] == 1 and controls[1] > 2 and target > 2:
# controls[0] -> controls[1] -> outside, target -> outside
p[0], p[1] = p[1], p[0]
p[0], p[controls[1]] = p[controls[1]], p[0]
p[2], p[target] = p[target], p[2]
elif controls[0] == 2 and controls[1] > 2 and target > 2:
# controls[0] -> target -> outside, controls[1] -> outside
p[0], p[2] = p[2], p[0]
p[0], p[target] = p[target], p[0]
p[1], p[controls[1]] = p[controls[1]], p[1]
elif controls[1] == 2 and controls[0] > 2 and target > 2:
# controls[1] -> target -> outside, controls[0] -> outside
p[1], p[2] = p[2], p[1]
p[1], p[target] = p[target], p[1]
p[0], p[controls[0]] = p[controls[0]], p[0]
else:
p[0], p[controls[0]] = p[controls[0]], p[0]
p1[1], p1[controls[1]] = p1[controls[1]], p1[1]
p2[2], p2[target] = p2[target], p2[2]
p = [p[p1[p2[k]]] for k in range(N)]
return tensor([U] + [identity(2)] * (N - 3)).permute(p)
Python
1
https://gitee.com/xpeter/Quantum-SVM-MINIST.git
git@gitee.com:xpeter/Quantum-SVM-MINIST.git
xpeter
Quantum-SVM-MINIST
Quantum-SVM-MINIST
master

搜索帮助