コード例 #1
0
def make_target(nf, nq, ptype, n_bit, n_bits):
    id_list = lambda: [qutip.qeye(2) for _ in range(n_bits + 1)]
    x_ops = [id_list() for _ in range(n_bits)]
    z_ops = [id_list() for _ in range(n_bits)]
    h_ops = [id_list() for _ in range(n_bits)]
    ih_ops = [id_list() for _ in range(n_bits)]
    cx_ops = []
    m_cz_ops = []
    m_cx_ops = []
    m_cy_ops = []

    for i in range(n_bits):
        z_ops[i][i + 1] = qutip.sigmaz()
        x_ops[i][i + 1] = qutip.sigmax()
        h_ops[i][i + 1] = qutip.hadamard_transform()
        ih_ops[i][i + 1] = qutip.Qobj([[-1, 1], [-1j, -1j]]) / sqrt(2)
        z_ops[i] = qutip.tensor(*z_ops[i])
        x_ops[i] = qutip.tensor(*x_ops[i])
        h_ops[i] = qutip.tensor(*h_ops[i])
        ih_ops[i] = qutip.tensor(*ih_ops[i])
        cx_ops.append(
            qutip.controlled_gate(qutip.hadamard_transform(), n_bits + 1,
                                  i + 1, 0))
        m_cz_ops.append(
            qutip.controlled_gate(qutip.sigmax(), n_bits + 1, i + 1, 0))
        m_cx_ops.append(h_ops[i] * m_cz_ops[i] * h_ops[i])
        m_cy_ops.append(ih_ops[i] * m_cz_ops[i] * ih_ops[i])

    for ops in (x_ops, z_ops, h_ops, m_cz_ops, m_cx_ops, m_cy_ops):
        ops.reverse()

    bits_n = 2**n_bits
    flip_target = id_list()
    flip_target[0] = qutip.sigmax()
    flip_target = qutip.tensor(*flip_target)
    if ptype == 'i':
        targ = qutip.tensor(*id_list())
    elif ptype == 'mz':
        targ = m_cz_ops[n_bit - 1] * flip_target
    elif ptype == 'mx':
        targ = m_cx_ops[n_bit - 1]
    elif ptype == 'my':
        targ = m_cy_ops[n_bit - 1]
    elif ptype == 'x':
        targ = x_ops[n_bit - 1]
    elif ptype == 'z':
        targ = z_ops[n_bit - 1]
    U = np.zeros((nq * nf, nq * nf), dtype=np.complex)
    U[:bits_n, :bits_n] = targ[:bits_n, :bits_n]
    U[nf:nf + bits_n, :bits_n] = targ[bits_n:, :bits_n]
    U[:bits_n, nf:nf + bits_n] = targ[:bits_n, bits_n:]
    U[nf:nf + bits_n, nf:nf + bits_n] = targ[bits_n:, bits_n:]
    mask_c = np.zeros(nf)
    mask_c[:bits_n] = 1
    mask_q = np.zeros(nq)
    mask_q[:2] = 1
    mask = np.kron(mask_q, mask_c)
    mask = np.arange(len(mask))[mask == 1]
    return U, mask
コード例 #2
0
def gen_basis_vectors(n, dims, choice):
    vectors = []
    basic_states = []
    bits = int(math.log(n, 2))
    #for i in range(n):
    #state=qt.basis(n,i)
    #fock_states.append(state)
    q = rabbit(bits, [], 0)
    basic_states.append(q)
    q = rabbit(bits, [1], 0)
    basic_states.append(q)
    q = rabbit(bits, [n - 1], 0)
    basic_states.append(q)
    indexvec = []
    for i in range(bits):
        indexvec.append(i)
    q = rabbit(bits, indexvec, 1)
    basic_states.append(q)
    test_opt1 = [
        basic_states[0], basic_states[1], basic_states[2], basic_states[3]
    ]
    test_opt2 = [
        basic_states[0], basic_states[1], basic_states[2], basic_states[3],
        basic_states[-1] + basic_states[1]
    ]
    if choice == 1:  #Basis states
        vectors = basic_states
        q = qt.Qobj(np.ones(n))
        q = q.unit()
        vectors.append(q)
        vectors.append(state)  #there is no two for now
    elif choice == 2:
        vectors = basic_states
    elif choice == 3:  #Hadamard option 1
        h = tensor_fix(qt.hadamard_transform(bits))
        for state in basic_states:
            state_n = h * state
            state_n = state_n.unit()
            vectors.append(state_n)
    elif choice == 4:  #QFT option 1
        quft = tensor_fix(qft.qft(bits))
        for state in basic_states:
            state_n = quft * state
            state_n = state_n.unit()
            vectors.append(state_n)
    elif choice == 5:  #Hadamard option 2
        h = tensor_fix(qt.hadamard_transform(bits))
        for state in basic_states:
            state_n = h * state
            state_n = state_n.unit()
            vectors.append(state_n)
    elif choice == 6:  #QFT option 2
        quft = tensor_fix(qft.qft(bits))
        for state in basic_states:
            state_n = quft * state
            state_n = state_n.unit()
            vectors.append(state_n)
        vectors.append(state_n)
    return vectors
コード例 #3
0
ファイル: CommentedCode.py プロジェクト: SPL-LSU/Codes
def gen_basis_vectors(n,dims,choice):
    vectors=[]
    fock_states=[]
    bits=int(math.log(n,2))
    q=rabbit(bits,[],0)
    basic_states.append(q)
    q=rabbit(bits,[1],0)
    basic_states.append(q)
    q=rabbit(bits,[n-1],0)
    basic_states.append(q)
    indexvec=[]
    for i in range(bits):
        indexvec.append(i)
    q=rabbit(bits,indexvec,1)
    basic_states.append(q)
    if choice == 1: #Unused psuedo-Basis states
        vectors = basis_states
        q=qt.Qobj(np.ones(n))
        q=q.unit()
        vectors.append(q)
        vectors.append(state) 
    elif choice ==2: #true basis states
        vectors=basic_states
    elif choice == 3: #Hadamard option 1
        h=tensor_fix(qt.hadamard_transform(bits))
        for state in basic_states:
            state_n=h*state
            state_n=state_n.unit()
            vectors.append(state_n)
    elif choice == 4: #QFT option 1
        quft=tensor_fix(qft.qft(bits))
        for state in basis_states:
            state_n=quft*state
            state_n=state_n.unit()
            vectors.append(state_n)
    elif choice == 5: #Hadamard option 2
        h=tensor_fix(qt.hadamard_transform(bits))
        for state in basis_states:
            state_n=h*state
            state_n=state_n.unit()
            vectors.append(state_n)
    elif choice == 6: #QFT option 2
        quft=tensor_fix(qft.qft(bits))
        for state in basis_states:
            state_n=quft*state
            state_n=state_n.unit()
            vectors.append(state_n)
        vectors.append(state_n)
    return vectors
コード例 #4
0
ファイル: singlegatetest.py プロジェクト: SPL-LSU/Codes
def get_single_gate_data():
    inputs = []
    h = tensor_fix(qt.hadamard_transform())
    zero = tensor_fix(qt.fock(2, 0))
    one = tensor_fix(qt.fock(2, 1))
    inputs.append(h * zero)
    inputs.append(h * one)
    inputs.append(h * zero)
    inputs.append(h * one)
    gate = paulix(1, 0)
    ideal = get_ideal([gate], inputs, inputs, 1, 4)
    tag = "X"
    pop = input("how may data points? ")
    pop = int(pop)
    path = "SingleDoubleHada2000.csv"
    probabilities = []
    for i in range(pop):
        alt_gate = alter(gate)
        temparray = []
        for state in inputs:
            final = basic_b(state, [alt_gate])
            prob = dis(final, state)
            temparray.append(prob)
        if within_tolerance(0.78, temparray, ideal[0]):
            temparray.append("tolerance")
        else:
            temparray.append(tag)
        probabilities.append(temparray)
        with open(path, 'a', newline='') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerow(temparray)
        csvFile.close
    return probabilities
コード例 #5
0
def genstate(s):
    """helper function to obtain the correct initialization"""
    newstr = s.replace("+", "0")
    newstr = newstr.replace("-", "1")
    print(newstr)
    state = qt.ket(newstr)
    if s[0] == "+" or s[0] == "-":
        operator = qt.hadamard_transform()
    else:
        operator = qt.identity(2)
    for i in range(1, len(s), 1):
        if s[i] == "+" or s[i] == "-":
            #apply hadamard
            operator = qt.tensor([operator, qt.hadamard_transform()])
        else:
            operator = qt.tensor([operator, qt.identity(2)])
    return operator * state
コード例 #6
0
 def test_normalize_Fock_superpositons(self):
     matrix = qutip.hadamard_transform(N=1).full()
     state = (mb.ManyBosonFockState(2, mal=(0, 0)) -
              mb.ManyBosonFockState(2, mal=(1, 1)))
     state.evolve(matrix)
     state.normalize_coefficients()
     np.testing.assert_allclose(state.get_coefficients(),
                                [0.7071067811865475, -0.7071067811865475])
コード例 #7
0
def genstate(s):
    """helper function to obtain the correct initialization"""
    newstr = s.replace("+","0")
    newstr = newstr.replace("-","1")
    print(newstr)
    state = qt.ket(newstr)
    if s[0] == "+" or s[0]=="-":
        operator=qt.hadamard_transform()
    else:
        operator=qt.identity(2)
    for i in range(1,len(s),1):
        if s[i] == "+" or s[i]=="-":
            #apply hadamard
            operator = qt.tensor([operator,qt.hadamard_transform()])
        else:
            operator = qt.tensor([operator,qt.identity(2)])
    return operator * state
コード例 #8
0
 def test_create_and_evolve_from_cf(self):
     mbfs = mb.ManyBosonFockState(2, mal=(0, 1))
     mbps = mbfs.evolve(qutip.hadamard_transform().full())
     amps = mbps.get_many_boson_amplitudes()
     self.assertEqual(list(amps.keys()), [(1, 1), (2, )])
     expected_output_11 = np.array([0])
     expected_output_2 = np.array([0.70710678 + 0.j, -0.70710678 + 0.j])
     np.testing.assert_allclose(amps[(1, 1)], expected_output_11)
     np.testing.assert_allclose(amps[(2, )], expected_output_2)
コード例 #9
0
ファイル: WPermanentTraining.py プロジェクト: SPL-LSU/Codes
def hadamard_preprocessing(hada):
    storage = hada.full()
    (n, n) = hada.shape
    q = np.log(n) / np.log(2)  #number of qubits
    seed = randint(0, q - 1)
    forbidden = []  #a vector to hold forbidden seeds
    mag = storage[0][0]  #magnitude of the elements in the hadamard
    ongoing = True
    while ongoing:
        i = 1
        count = 0
        while seed in forbidden:  #make sure the seed isn't forbidden
            seed = randint(0, q - 1)
            count += 1
            if count == 200:  #no infinite loops
                break
        #initialize test unitary
        if seed == 0:
            u1 = qt.hadamard_transform(1)
        else:
            u1 = id2
        #create test unitary
        while u1.shape != (n, n):
            if i == seed:  #set a hadamard on specified qubit
                u1 = qt.tensor(u1, qt.hadamard_transform(1))
                u1 = tensor_fix(u1)
            else:
                u1 = qt.tensor(u1, id2)
                u1 = tensor_fix(u1)
            i += 1
        check = u1 * hada
        if check.full(
        )[0][0] > mag:  #if there's a hadamard on that qubit, true
            ongoing = False
        elif count == 200:
            print("oops")
            break
        else:  #no hadamard on that seed qubit
            forbidden.append(seed)
    return hada, seed
コード例 #10
0
ファイル: WPermanentTraining.py プロジェクト: SPL-LSU/Codes
def hadamaker(qubits, affected):
    array = []
    i = 0
    while len(array) < qubits:
        if i in affected:
            gate = qt.hadamard_transform()
            gate = tensor_fix(gate)
        else:
            gate = id2
        array.append(gate)
        i += 1
    hadamade = qt.Qobj([[1]])
    for gate in array:
        hadamade = qt.tensor(hadamade, gate)
        hadamade = tensor_fix(hadamade)
    return hadamade
コード例 #11
0
    def set_gate_group(self, gate_group, custom_gates=None):
        """
        Defines the gate group to be used within the enviroment

        Args:
            gate_group (str): name of the gate group used
            custom_gates (dict): A set of custom gates may be defined using a dictionary,
                                 the form looks like{"gate_name":gate_function}

        Returns:
            None

        """
        gate_group = gate_group.lower()
        if gate_group == 'clifford':
            # Clifford group uses cnot, phase gate and hadamard
            self.gate_group_list = [
                self.qcircuit.iden, self.qcircuit.cx, self.qcircuit.h,
                self.qcircuit.s, self.qcircuit.t
            ]

        elif gate_group == 'pauli':
            self.gate_group_list = [
                self.qcircuit.iden, self.qcircuit.h, self.qcircuit.x,
                self.qcircuit.z, self.qcircuit.cx
            ]

        elif gate_group == 'IQP':
            self.gate_group_list = [
                self.qcircuit.iden, self.qcircuit.t, (2, self.c_s_gate)
            ]
            # Sets up the circuit with initial hadamard gates,
            # as is necessary for circuits with the IQP format
            temp_state = (hadamard_transform(self.num_qubits) *
                          qubit_states(self.num_qubits)).full()
            self.qcircuit.initialize(
                temp_state.flatten(),
                [self.q_reg[i] for i in range(self.num_qubits)])

        elif gate_group == 'custom':
            assert custom_gates is not None, 'custom_gates is not defined.'
            self.gate_group_list = custom_gates

        else:
            raise "%s gate_group not defined!" % gate_group
コード例 #12
0
 def init_unitaries(self, target_name, U_targ=None):
     if not U_targ:
         if target_name == 'x' or target_name == 'sigmax' or target_name == 'XGate':
             if self.two_level:
                 U_targ = sigmax()
             else:
                 U_targ = get_sigmax()
         elif target_name == 'h' or target_name == 'hadamard':
             if self.two_level:
                 U_targ = hadamard_transform(1)
             else:
                 U_targ = get_hadamard()
         elif target_name == 'cnot':
             if self.two_level:
                 U_targ = cnot()
             else:
                 U_targ = get_cnot()
     self.U_targ = U_targ
     self.target_name = target_name
コード例 #13
0
def get_hadamard():
    h = hadamard_transform(1).full()
    hadamard_3 = Qobj([[h[0][0], h[0][1], 0], [h[1][0], h[1][1], 0], [0, 0,
                                                                      1]])
    return hadamard_3
コード例 #14
0
ファイル: CommentedCode.py プロジェクト: SPL-LSU/Codes
def arb_circuit_generator(length,qubits):
    circuit=[]
    angles=[]
    controls=[]
    id2=np.identity(2)
    id2=qt.Qobj(id2)
    n=2**qubits
    Had = 0
    CNOT = 0
    Ran = 0
    while len(circuit)<2*length:
        seed=randint(1,3)
        if seed ==1:
            temp=qt.hadamard_transform()
            temp=tensor_fix(temp)
            circuit.append(temp)
            circuit.append("Hadamard")
            Had = Had +1
        if seed == 2:
            temp=rot(qubits,False)
            circuit.append(temp)
            circuit.append("CNOT")
            CNOT = CNOT +1
        if seed == 3:
            (temp,ang)=unitary_gate(False) 
            circuit.append(temp)
            circuit.append("Random Unitary")
            angles.append(ang)
            Ran = Ran +1
    for i in circuit:
        if type(i) == str:
            continue
        else:
            i=tensor_fix(i)
    for i in range(len(circuit)):
        if type(circuit[i]) == str:
            continue
        elif circuit[i].full().shape == (n,n):
            continue
        else:
            place=randint(1,qubits)
            before=qubits-place
            after=qubits-before-1
            temp=circuit[i]
            temp=qt.Qobj(temp)
            if place == 1:
                circuit[i]=qt.tensor(temp,id2)
            else:
                while before > 0:
                    if circuit[i].full().shape == (n,n):
                        break
                    temp=qt.tensor(id2,temp)
                    temp=tensor_fix(temp)
                    circuit[i]=temp
                    before=before-1
                while after > 0:
                    if circuit[i].full().shape == (n,n):
                        break
                    temp=qt.tensor(temp,id2)
                    temp=tensor_fix(temp)
                    circuit[i]=temp
                    after=after-1
    composition = ["Hadamards:",Had,"CNOT:",CNOT,"Random Unitary:",Ran]
    return (circuit,angles,controls,composition)
コード例 #15
0
def hadamard(bits):
    return qutip.Qobj(qutip.hadamard_transform(bits).data)
コード例 #16
0
# simulator.py: Defines a class that implements a multi-qubit simulator.
##
# Copyright (c) Sarah Kaiser and Chris Granade.
# Code sample from the book "Learn Quantum Computing with Python and Q#" by
# Sarah Kaiser and Chris Granade, published by Manning Publications Co.
# Book ISBN 9781617296130.
# Code licensed under the MIT License.
##

from interface import QuantumDevice, Qubit
import qutip as qt
import numpy as np
from typing import List

KET_0 = qt.basis(2, 0)
H = qt.hadamard_transform()

# tag::qubit_and_sq_operations[]


class SimulatedQubit(Qubit):
    qubit_id: int
    parent: "Simulator"

    def __init__(self, parent_simulator: "Simulator", id: int):  # <1>
        self.qubit_id = id
        self.parent = parent_simulator

    def h(self) -> None:
        self.parent._apply(H, [self.qubit_id])  # <2>
コード例 #17
0
ファイル: codes.py プロジェクト: arnelg/arXiv-1901.08071
 def logical_H(self):
     S = self.encoder(kraus=True)
     return S * qt.hadamard_transform() * S.dag()
コード例 #18
0
 def h(self):
     self.parent._apply(qt.hadamard_transform(), [self.id])
コード例 #19
0
import qutip
import itertools as it

## Shortcuts of some main qutip objects
zero = qt.qubits.qubit_states(1, [0])
one = qt.qubits.qubit_states(1, [1])
I, X, Y, Z = qt.identity([2]), qt.sigmax(), qt.sigmay(), qt.sigmaz()
Rx, Ry, Rz = qt.rx, qt.ry, qt.rz
op_pauli_1 = [X, Y, Z, I]
s_zero_1, s_one_1 = basis(2, 0), basis(2, 1)
s_plus_1, s_minus_1 = 1 / np.sqrt(2) * (s_zero_1 + s_one_1), 1 / np.sqrt(2) * (
    s_zero_1 - s_one_1)

#two qubits
CN = cnot()
HDM = hadamard_transform()


# =========================================================================== #
# Define the functions needed
# =========================================================================== #
# GHZ related functions
def get_ghz(nb_qubits, angle=0):
    """ Generate a GHZ state of the form |00..00> + exp(i * angle) |11..11> """
    a = tensor([zero for _ in range(nb_qubits)])
    b = tensor([one for _ in range(nb_qubits)])
    return 1 / np.sqrt(2) * (a + np.exp(1.0j * angle) * b)


def get_ghz_offdiag(nb_qubits):
    """ generate the Hermitian operator |0...0><1...1| + |1...1><0...0|"""