Ejemplo n.º 1
0
def circuitXXBraidingCorrectionSimulation(psi0, c_ops=[]):
    N = 8
    schedule = []
    for i in range(2):
        # XX braiding, stage 1
        schedule += [ry(np.pi / 2., N=N, target=i) for i in [5, 6]]
        # XX braiding, stage 2
        schedule += [rz(-np.pi / 2., N=N, target=i) for i in [5, 6]]
        # XX braiding, stage 3
        schedule += [controlled_gate(sigmaz(), N=N, control=5, target=6)]
        # XX braiding, stage 4
        schedule += [ry(-np.pi / 2., N=N, target=i) for i in [5, 6]]
    # perform time evolution and return the final state
    return scheduledUnitaryEvolution(psi0, schedule)
Ejemplo n.º 2
0
def random_unitary_gate(delta,alpha,theta,beta,value):
    gate = qt.Qobj(qt.phasegate(delta)*qt.rz(alpha)*qt.ry(theta)*qt.rz(beta))
    if value == True:
        gate = gate *qt.Qobj([[0,1],[1,0]])
    else:
        gate = gate
    return gate
Ejemplo n.º 3
0
def rando(orig):
    (n, n) = orig.shape
    theta = uniform(0.0, math.pi * 2.0)
    #pick a rotation any rotation
    phaser = randint(0, 3)
    if phaser == 0:
        gate = qt.phasegate(theta)
    elif phaser == 1:
        gate = qt.rz(theta)
    elif phaser == 2:
        gate = qt.ry(theta)
    else:
        gate = qt.globalphase(theta)
    (m, m) = gate.shape
    cc = 0
    while n != m and cc < 10:
        pick = randint(0, 1)
        if not pick:
            gate = qt.tensor(gate, id2)
            gate = tensor_fix(gate)
        else:
            gate = tensor_fix(qt.tensor(id2, gate))
        (m, m) = gate.shape
        cc += 1
    gate = gate * orig
    return gate
Ejemplo n.º 4
0
def alter_hadamard(hada,seed):
    (n,n)=hada.shape
    theta = uniform(0.0,math.pi*2.0)
    
    #pick a rotation any rotation
    phaser=randint(0,3)
    if phaser ==0:
        gate=qt.phasegate(theta)
    elif phaser == 1:
        gate=qt.rz(theta)
    elif phaser==2:
        gate = qt.ry(theta)
    else:
        gate=qt.globalphase(theta)
        
    #alter gate
    if seed == 0:
        u1=gate
    else:
        u1=id2
    i=1
    while u1.shape != (n,n):
        if i ==seed: #set a alteration on specified qubit
            u1=qt.tensor(u1,gate)
            u1=tensor_fix(u1)
        else:
            u1=qt.tensor(u1,id2)
            u1=tensor_fix(u1)
        i+=1
    final_gate=u1*hada
    return final_gate
Ejemplo n.º 5
0
def get2(x):
    """ parametrized (6 parameters) circuitry which can create a c. GHZ 
    state i.e. |000> - |111>"""
    g1 = qt.tensor(qt.rx(x[0]), qt.rx(x[1]), qt.rx(x[2]))
    g2 = qt.cnot(3, 1, 2)
    g3 = qt.cnot(3, 0, 2)
    g4 = qt.tensor(qt.rx(x[3]), qt.rx(x[4]), qt.ry(x[5]))
    return g4 * g3 * g2 * g1 * qt.tensor(zero, zero, zero)
def env_error_single(rho, a0, a1, t, N=1, pos=0):
    """Apply environmental error on a single qubit from the state rho."""
    a = (a0 + a1)*t
    X = qt.rx(np.pi, N, pos)
    Y = qt.ry(np.pi, N, pos)
    Z = qt.rz(np.pi, N, pos)
    # ss = sigma_z * rho * sigma_z.dag()
    lamb = np.exp(-a * t)
    c1 = (3*lamb + 1)/4
    c2 = (1 - lamb)/4
    # print("T: ", t, "lamb: ", lamb)
    rho = (c1 * rho + c2 * (Z * rho * Z.dag() + X * rho * X.dag()
           + Y * rho * Y.dag()))
    return rho
Ejemplo n.º 7
0
def circuitTeleportationSimulation(psi, c_ops=[]):
    N = 8
    psi0 = tensor([basis(2, 0), psi] + [basis(2, 0) for i in range(N - 2)])
    schedule = []
    # encoding, Hadamards stage 1, 2
    schedule += [snot(N=N, target=i) for i in range(N)]
    # encoding, CZs, stage 3
    schedule += [
        controlled_gate(sigmaz(), N=N, control=0, target=1),
        controlled_gate(sigmaz(), N=N, control=2, target=3),
        controlled_gate(sigmaz(), N=N, control=4, target=5)
    ]
    # encoding, Hadamards, stage 4, 5
    schedule += [snot(N=N, target=i) for i in [1, 3, 5]]
    # teleportation, stage 6
    schedule += [ry(np.pi / 2., N=N, target=i) for i in [1, 2, 3, 4]]
    # teleportation, stage 7
    schedule += [rz(-np.pi / 2., N=N, target=i) for i in [1, 2, 3, 4]]
    # teleportation, stage 8
    schedule += [
        controlled_gate(sigmaz(), N=N, control=1, target=2),
        controlled_gate(sigmaz(), N=N, control=3, target=4)
    ]
    # teleportation, stage 9
    schedule += [ry(-np.pi / 2., N=N, target=i) for i in [1, 2, 3, 4]]
    # decoding, stage 10, 11
    schedule += [snot(N=N, target=i) for i in [1, 3]]
    # decoding, stage 12
    schedule += [
        controlled_gate(sigmaz(), N=N, control=0, target=1),
        controlled_gate(sigmaz(), N=N, control=2, target=3)
    ]
    # decoding, stage 13, 14
    schedule += [snot(N=N, target=i) for i in [0, 1, 2, 3]]
    # perform time evolution and return the final state
    return scheduledUnitaryEvolution(psi0, schedule)
Ejemplo n.º 8
0
def random_altered_unitary_gate(delta,alpha,theta,beta,value):
    if delta == 0.0 and alpha == 0.0 and theta == math.pi and value == True:
        angles = ['delta','alpha','beta']
    else:
        angles = ['delta','alpha','theta','beta']
    altered_variable = choice(angles)
    if altered_variable == 'delta':
        delta = uniform(0.0,2.0*math.pi)
    if altered_variable == 'alpha':
        alpha = uniform(0.0,2.0*math.pi)
    if altered_variable == 'theta':
        theta = uniform(0.0,2.0*math.pi)
    if altered_variable == 'beta':
        beta = uniform(0.0,2.0*math.pi)
    gate = qt.Qobj(qt.phasegate(delta)*qt.rz(alpha)*qt.ry(theta)*qt.rz(beta))
    if value == True:
        gate = gate *qt.Qobj([[0,1],[1,0]])
    else:
        gate = gate
    return gate
Ejemplo n.º 9
0
    def plot_trajectories(self, times, trajs, plot_title=''):
        '''
		Plot output of a simulation result on the Bloch sphere
		'''
        f = plt.figure(figsize=(5, 5), facecolor='white')
        f.suptitle(plot_title, x=0.2)
        # plt.title(plot_title)
        xp2 = qu.rx(np.pi * 0.5)
        yp2 = qu.ry(np.pi * 0.5)
        zp2 = qu.rz(np.pi * 0.5)
        xpi = qu.sigmax()
        ypi = qu.sigmay()
        zpi = qu.sigmaz()
        up = qu.basis(2, 0)
        dn = qu.basis(2, 1)
        # ax = f.add_subplot(1, 1, 1, axisbg='red')

        # p1 = f.add_subplot(2,2,1)
        # plt.plot(times,trajs[0])
        # legend(['OneX','OneY','OneZ'],loc='best')

        # p2 = f.add_subplot(2,2,3)
        # pure = norm(trajs[0],axis=1)
        # plt.plot(times,pure)
        # legend(['Purity'],loc='best')
        # ylim(-0.1,1.1)
        # p3 = f.add_subplot(1,2,2, projection='3d')
        b = qu.Bloch(fig=f)  #,axes=p3)
        b.zlabel = [r"$\left|1\right\rangle $", r"$\left|0\right\rangle$"]
        b.xlabel = [r"$ X $", r""]
        b.ylabel = [r"$ Y $", r""]
        b.vector_color = sb.color_palette()
        b.add_states([yp2 * up, xp2 * xpi * up, up])
        b.point_color = sb.color_palette('dark')[3:4]
        b.add_points(trajs, 'l')
        # b.add_points(trajs[0][0].transpose(),'s')
        b.font_size = 30
        b.sphere_color = '000000'
        b.render(f)
        b.show()
 def ry(self, angle: float) -> None:
     self.parent._apply(qt.ry(angle), [self.qubit_id])  # <3>
Ejemplo n.º 11
0
def main():

    pop = input("How many of each gate do you want to populate? ")
    pop = int(pop)
    split = input(
        "Give training set split, in the form of a number between 0 and 1: ")
    k = input("Give a k value: ")
    k = int(k)
    d = input("Gimme a range of reference states: ")
    d = int(d)
    qubits = 3
    n = 2**qubits
    csvpath = [
        "WTrainingData2000new.csv", "WTrainingData2000QFT.csv",
        "WTrainingData2000Had.csv", "WTrainingData2000QFT2.csv"
    ]
    r1 = tensor_fix(qt.tensor(qt.ry(-1.23096), id2))
    r1 = tensor_fix(qt.tensor(r1, id2))
    r2 = tensor_fix(qt.tensor(qt.ry(np.pi / 4), id2))
    r2 = tensor_fix(qt.tensor(r2, id2))
    r3 = tensor_fix(qt.tensor(qt.ry(-1 * np.pi / 4), id2))
    r3 = tensor_fix(qt.tensor(r3, id2))
    state_creator = [
        r1,
        paulix(3, 1),
        paulix(3, 2),
        qt.cnot(3, 0, 1), r2,
        qt.cnot(3, 1, 0), r3,
        paulix(3, 0),
        paulix(3, 1),
        qt.cnot(3, 0, 2),
        qt.cnot(3, 1, 2)
    ]
    state_creator_tags = [
        "Rotation", "X", "X2", "CNOT", "Rotation2", "CNOT2", "Rotation3", "X3",
        "X4", "CNOT3", "CNOT4"
    ]
    circuit = []
    angles = []
    for i in range(len(state_creator)):
        circuit.append(state_creator[i])
        circuit.append(state_creator_tags[i])
    cat = categorize(circuit)
    alt = []
    angles = []
    for i in range(len(circuit)):
        if type(circuit[i]) == str:
            continue
        else:
            alt.append(gate_troubleshooter(circuit[i], n))
    choice = [2, 4, 5, 6]
    vector_name = ['new', 'QFT', 'Hadamard 2', 'Fourier State']
    index = 0
    for x in choice:
        choice = x
        path = csvpath[index]
        vectors = gen_basis_vectors(n, n, choice)
        print(vector_name[index])
        index = index + 1
        probs = alter_wcirc(alt, angles, vectors, pop, cat, qubits, d, path)
        KNN(probs, split, k)
    return 0
Ejemplo n.º 12
0
def create_data(time_per_count, num_samples, num_counts, gate_list, time_unit, noise_type=None, walking_amp=None, telegraph_amp=None, \
                res=None, freq_list=None, amp_list=None, phase_list=None, start_f=None, stop_f=None, fluctuators=None, plot_noise=False, \
                add_noise=False, noise_object=None, dc_angle_offset=0, constant_linear_drift=0):
    #time_per_shot: time in seconds for a single (prep-gate-measure+delay)
    #num_samples: how many timestamps and strings of counts you want to have
    #num_counts: how many data points to create (how many ones and zeros) per sample (i.e. per timestamp) --> affects both time of a sample and precision
    #num_shots: how many times (shots) you apply (prep-gate_list-meas) to get one count (a single 0 or 1) --> determines the time of one count, but won't affect precision
    #gate_list: gates you want to do for your operation, entered as a list of strings
    #xerr,yerr,zerr: 2D tuples with overrotation amplitude in radians and frequency in Hz
    #constant linear drift: enter in rads/second
    rho0 = _qt.operator_to_vector(_qt.ket2dm(_qt.basis(2, 0)))
    rho1 = _qt.operator_to_vector(_qt.ket2dm(_qt.basis(2, 1)))
    zero_counts = []
    one_counts = []
    timestep = num_counts * time_per_count  #the time to get a full bitstring of zeros and ones for one sample, i.e. one timestamp
    timestamps = np.arange(
        timestep, num_samples * timestep,
        timestep)  #array of 1*timestep, 2*timestep,....(num_samples)*timestep
    probs = []
    total_time = (time_per_count * num_counts * num_samples) / time_unit

    sig = 0
    if noise_type == "Sine":
        #this function returns the noise object so you can enter it back in as a parameter
        # in the event that you call the function repeatedly for an identical set of parameters
        if noise_object != None:
            sig = noise_object
            #print("REUSING NOISE OBJECT")
            while total_time > sig.times[-1] + timestep:
                sig.next_interval()
                #print("Doing a NEXT INTERVAL")
        else:
            #print("INITIALIZING NEW NOISE")
            sig = _ns.NoiseSignalSine(time_unit=time_unit)
            sig.configure_noise(resolution_factor=res,
                                freq_list=freq_list,
                                amp_list=amp_list,
                                phase_list=phase_list,
                                total_time=total_time)
            sig.init()
            if add_noise != None:
                sig.add_random_noise(
                    add_noise
                )  #add normal noise with specified std deviation if requested
    elif noise_type == "Random Walk":
        sig = _ns.NoiseSignalRandomWalk(initial_seed=1234, time_unit=time_unit)
        sig.configure_noise(walking_amp, res, total_time)
        sig.init()
    elif noise_type == "Telegraph":
        sig = _ns.NoiseSignalTelegraph(initial_seed=1234, time_unit=time_unit)
        sig.configure_noise(exponent=1,
                            amplitude=telegraph_amp,
                            total_fluctuators=fluctuators,
                            start_freq=start_f,
                            stop_freq=stop_f,
                            total_time=total_time)
        sig.init()
        sig.interpolation_settings(do_interpolation=True,
                                   resolution_factor=res)

    if plot_noise == True:
        sig.plot_noise_signal()

    angle_list = []
    expected_angle_list = []

    compressed_gate_list = compress_gate_list(gate_list)
    for time in timestamps:
        noise_at_time = 0
        if noise_type != None:
            #print(time/time_unit)
            noise_at_time = sig[time / time_unit]
        rho = rho0
        total_angle = 0
        total_ideal_angle = 0

        for gate in compressed_gate_list:
            gate_name = gate[0]
            gate_repetitions = gate[1]
            '''
            Next step: calculate change in rotation error within each shot. Currently takes the time at the start of the experiment shot
            and applies that to all gates in one shot. Depending on the timescale of the error and time per shot, this simplification may need
            to be addressed so that each gate, say each Gx in (Gx)^11, has an error associated with its specific time, not the same error for
            all 11 Gx gates.
            '''

            if gate_name == 'Gx':
                angle = (
                    np.pi / 2 + noise_at_time
                ) * gate_repetitions + dc_angle_offset + constant_linear_drift * time
                ideal_angle = (
                    np.pi / 2
                ) * gate_repetitions + dc_angle_offset + constant_linear_drift * time
                rho = (_qt.to_super(_qt.rx(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2 * np.pi)
                ideal_angle = ideal_angle % (2 * np.pi)
                if angle > np.pi:
                    angle = 2 * np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2 * np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == 'Gy':
                angle = (
                    np.pi / 2 + noise_at_time
                ) * gate_repetitions + dc_angle_offset + constant_linear_drift * time
                ideal_angle = (
                    np.pi / 2
                ) * gate_repetitions + dc_angle_offset + constant_linear_drift * time
                rho = (_qt.to_super(_qt.ry(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2 * np.pi)
                ideal_angle = ideal_angle % (2 * np.pi)
                if angle > np.pi:
                    angle = 2 * np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2 * np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == 'Gz':
                angle = (
                    np.pi / 2 + noise_at_time
                ) * gate_repetitions + dc_angle_offset + constant_linear_drift * time
                ideal_angle = (
                    np.pi / 2
                ) * gate_repetitions + dc_angle_offset + constant_linear_drift * time
                rho = (_qt.to_super(_qt.rz(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2 * np.pi)
                ideal_angle = ideal_angle % (2 * np.pi)
                if angle > np.pi:
                    angle = 2 * np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2 * np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == "Gi":
                #apply only the oscillating drift angle, don't add it to pi/2
                angle = (
                    noise_at_time
                ) * gate_repetitions + dc_angle_offset + constant_linear_drift * time
                ideal_angle = 0 + dc_angle_offset + constant_linear_drift * time
                print("applying Gi with angle ", angle)
                rho = (_qt.to_super(_qt.rz(angle))) * rho
                angle = angle % (2 * np.pi)
                ideal_angle = 0
                if angle > np.pi:
                    angle = 2 * np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2 * np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            total_angle += angle
            total_ideal_angle += ideal_angle

        #append the total rotation angle after timestamp 'time'
        angle_list.append(total_angle)
        expected_angle_list.append(total_ideal_angle)
        #calculate probabilities of being in 1 after the experiment has been applied
        p1 = (rho.dag() * rho1).norm()
        #fix the p1 if it exceeds 1 due to rounding error
        if p1 > 1:
            #print("p1 exceeds 1 for time {}".format(time))
            #print("prob is {}".format(p1))
            #print("Resetting to {}".format(2-p1))
            p1 = 2 - p1
        probs.append(p1)
        one_count = np.random.binomial(
            num_counts, p1
        )  #simulates a summation of the number of 1-counts you get in one bitstring sample
        zero_count = num_counts - one_count  #simulates summation of the number of 0-counts in one bitstring sample
        one_counts.append(one_count)
        zero_counts.append(zero_count)

    if plot_noise == True:
        plt.plot(timestamps,
                 np.asarray(expected_angle_list),
                 label="Ideal Angle",
                 ls='dashed',
                 color='orange')
        plt.plot(timestamps, np.asarray(angle_list), label="Drifting Angle")
        plt.legend()
        plt.xlabel("Time, seconds")
        plt.yticks(np.linspace(0, np.pi, 5),
                   ['0', '$\pi/4$', '$\pi/2$', '$3\pi/4$', '$\pi$'])
        plt.ylabel("Angle, radians\n(Displayed between 0 and $\pi$)")
        plt.title("Time-Dependent Rotation Angle after each {}".format(
            gate_list_to_string(gate_list)))
        plt.grid()
        plt.show()

        plt.figure(figsize=(15, 3))
        plt.plot(timestamps, probs)
        plt.ylim(0, 1)
        plt.xlim(timestamps[0], timestamps[-1])
        plt.xlabel("Time, seconds")
        plt.ylabel("Probability of Measuring State {1}")
        plt.title("Simulated {} with {} Noise".format(
            gate_list_to_string(gate_list), noise_type))
        plt.grid()
        plt.show()

    return (np.asarray(one_counts), np.asarray(zero_counts),
            np.asarray(timestamps), probs, np.asarray(expected_angle_list),
            np.asarray(angle_list), sig)
Ejemplo n.º 13
0
def main():
    d = 4
    qubits = 2
    n = 2**qubits
    th = uniform(0, 2 * np.pi)
    rotate = tensor_fix(qt.tensor(id2, qt.ry(th)))
    rotate = tensor_fix(qt.tensor(rotate, id2))
    """
    state_creator=[rotate*hadamaker(qubits,[1]),qt.cnot(qubits,1,2),qt.cnot(qubits,0,1),hadamaker(qubits,[0]),qt.cnot(qubits,1,2),conv_cz()]
    state_creator_tags=["Hadamard","CNOT","CNOT2","Hadamard2","CNOT3","Control Z"]
    circuit=[]

    for i in range(len(state_creator)):
        circuit.append(state_creator[i])
        circuit.append(state_creator_tags[i])
    alt=[]
    for i in range(len(circuit)):
        if type(circuit[i]) == str:
            continue
        else:
            alt.append(gate_troubleshooter(circuit[i],n))
    """
    ghzcirc = [hadamaker(qubits, [0]), qt.cnot(qubits, 0, 1)]
    ghz_tags = ["Hadamard", "CNOT"]
    circuit = []
    for i in range(len(ghzcirc)):
        circuit.append(ghzcirc[i])
        circuit.append(ghz_tags[i])
    #cat=categorize(circuit)
    alt = []
    #angles=[]
    for i in range(len(circuit)):
        if type(circuit[i]) == str:
            continue
        else:
            alt.append(gate_troubleshooter(circuit[i], n))
    choice = [2, 4, 5, 6]
    vector_name = ['new', 'QFT', 'Hadamard 2', 'Fourier State']
    #ideals=[]
    tolerance = input("Give a tolerance: ")
    tolerance = float(tolerance)
    vectors = gen_basis_vectors(n, n, 5)
    ideal = get_ideal(alt, vectors, qubits, d)
    print(vector_name[i])
    print(ideal[0])
    ideal = [
        0.7803300858899107, 0.7803300858899107, 0.7803300858899107,
        0.7803300858899107
    ]
    #ideals.append(ideal[0])

    path = input(
        "Give csv file location, remembering to use forward slashes: ")
    KNN(path, 0.8, 5, tolerance, ideal)
    """
    tolerance=0.9
    for i in range(10):
        multi=uniform(0,1)
        ideal2=ideal[0]
        probvector=[]
        for x in range(len(ideal2)):
            probvector.append(multi*ideal2[x])
        truth=within_tolerance(tolerance,probvector,ideal[0])
        print(multi)
        print(truth)
    """
    return 0
Ejemplo n.º 14
0
def ramsey_experiment(left_gate_list, right_gate_list, L, field_f, transition_f, nCounts, time_per_gate, gate_switching_time, \
                      experiment_sample_time, time_units=1e-6, noise_type=None, freq_list=0,amp_list=0, phase_list=0,\
                      start_f=0, stop_f=0, fluctuators=0, plot_noise = False):
    #left and right gate_lists: lists of the gates sandwiching the Gi gates
    #L: the number of Gi gates. If you want to vary this, make it a list
    #field_f: frequency of external field in Hz. To vary this, make it a list. Either L or field_f must vary.
    #transition_f: frequency of the qubit transition in Hz.
    #time_per_gate: total time to complete one Gx, Gy, Gi, or Gz
    #switching_time: additional time before you start any new gate or change gates
    #experiment_sample_time: time at which you trigger a single expeimrent (single count), usually 60 Hz triggered
    #nCounts: number of times to repeat one experiment (a single set of parameters)
    #time_units: baseline units (in seconds) for any additional drift noise signal you may want to add. Defaults to ms.

    #check that the input has something to be varied
    if type(L) == type(field_f):
        print("Error: Either L or field_f must vary over a range!")
        return None
    #this list will contain the varied parameter, either detuning in Hz or delay time in s
    varied_param = []

    if type(L) == list:
        total_experiments = len(L)
        experiment_list = []
        for l in L:
            experiment_list.append(left_gate_list + ['Gi'] * l +
                                   right_gate_list)
        field_f_list = [field_f] * total_experiments
        varied_param = [(time_per_gate * l + gate_switching_time) for l in L]

    else:
        total_experiments = len(field_f)
        experiment_list = [left_gate_list + ['Gi'] * L + right_gate_list
                           ] * total_experiments
        field_f_list = field_f
        varied_param = delta_list

    #create a noise object:
    if noise_type != None and noise_type == "Sine":
        total_time = total_experiments * nCounts * experiment_sample_time + 1  #assumes that every count is taken every 0.016 seconds; no experiment takes longer
        sig = _ns.NoiseSignalSine(time_unit=time_units)
        sig.configure_noise(resolution_factor=1,
                            freq_list=freq_list,
                            amp_list=amp_list,
                            phase_list=phase_list,
                            total_time=total_time / time_units)
        sig.init()

        if plot_noise == True:
            sig.plot_noise_signal()

    probs = [
    ]  #a list of total_expeirment* elements. Has the probability for each experiment set (assumes constant p for all nCounts)
    time_per_experiment_set = [
    ]  #has the time at the start of each experiment set
    ones_counts = []  #number of 1s counted for each experiment set
    angles = []  #total theta rotation for each experiment set
    ideal_angles = []  #has the ideal theta rotation for each experiment set
    transition_f_list = [
    ]  #list of the transition frequency at the start of each experiment set
    detuning_list = [
    ]  #list of the detuning at the start of each experiment set
    absolute_time = 0  #seconds
    rho0 = _qt.operator_to_vector(_qt.ket2dm(_qt.basis(2, 0)))
    rho1 = _qt.operator_to_vector(_qt.ket2dm(_qt.basis(2, 1)))

    for experiment_index in range(total_experiments):
        experiment = experiment_list[experiment_index]
        compressed_experiment = compress_gate_list(experiment)
        #the following line assumes that each count for each experiment set is triggered at 0.0167 seconds (no single gate sequence can be longer than 1/60)
        absolute_time += experiment_sample_time * nCounts
        #print("Starting experiment set {} at {} s".format(experiment_index, absolute_time))
        rho = rho0
        total_angle = 0
        total_ideal_angle = 0
        modified_transition_f = transition_f
        detuning = field_f_list[experiment_index] - modified_transition_f
        for gate_name, repetitions in compressed_experiment:
            if noise_type != None:
                if absolute_time >= total_time:
                    print("Abs time: {}, total_time: {}".format(
                        absolute_time, total_time))
                detuning_noise = sig[absolute_time / time_units]
            else:
                detuning_noise = 0
            if gate_name == 'Gx':
                angle = (np.pi / 2) * repetitions
                ideal_angle = (np.pi / 2) * repetitions
                rho = (_qt.to_super(_qt.rx(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2 * np.pi)
                ideal_angle = ideal_angle % (2 * np.pi)
                if angle > np.pi:
                    angle = 2 * np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2 * np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == 'Gy':
                angle = (np.pi / 2) * repetitions
                ideal_angle = (np.pi / 2) * repetitions
                rho = (_qt.to_super(_qt.ry(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2 * np.pi)
                ideal_angle = ideal_angle % (2 * np.pi)
                if angle > np.pi:
                    angle = 2 * np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2 * np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == "Gi":
                #print("starting {} with z-rotation 2pi*{:.2f}".format(gate_list_to_string(experiment), detuning*(time_per_gate*repetitions + gate_switching_time)))
                #make the transition frequency oscillate between a fraction of its nominal value
                modified_transition_f = transition_f * (1 + detuning_noise)
                detuning = field_f_list[
                    experiment_index] - modified_transition_f
                angle = 2 * np.pi * detuning * (time_per_gate * repetitions +
                                                gate_switching_time)
                rho = (_qt.to_super(_qt.rz(angle))) * rho
            total_angle += angle
            total_ideal_angle += ideal_angle

        #calculate probabilities of being in 1 after the all the gates in the experiment have been applied
        p1 = (rho.dag() * rho1).norm()
        #fix the p1 if it exceeds 1 due to rounding error
        if p1 > 1:
            p1 = 2 - p1
        #get nCounts of data (bits) for the experiment
        one_counts = np.random.binomial(nCounts, p1)
        angles.append(total_angle)
        ideal_angles.append(total_ideal_angle)
        probs.append(p1)
        ones_counts.append(one_counts)
        time_per_experiment_set.append(absolute_time)
        transition_f_list.append(modified_transition_f)
        detuning_list.append(detuning)

    return np.asarray(ones_counts), np.asarray(
        time_per_experiment_set), np.asarray(probs), np.asarray(varied_param)
Ejemplo n.º 15
0
 def RY(self, target, theta):
     self.state = ry(theta, self.qubits, self.qubits - 1 - target) * self.state
 def ry(self, theta : float) -> None:
     self.parent._apply(qt.ry(theta), self.qubit_id)
Ejemplo n.º 17
0
 def as_qobj_operator(self, instance: "GateInstance") -> qutip.Qobj:
     return qutip.ry(instance.params[0])
 def ry(self, theta: float) -> None:
     self.state = qt.ry(theta) * self.state
Ejemplo n.º 19
0
    #testing witnesses and cost functions for GHZ states
    f1 = gen_F1_graph(N_test, edges_test)
    f2 = gen_F2_graph(N_test, edges_test)
    f = gen_proj_graph_state(N_test, edges_test)
    ev1 = assert_and_recast_to_real(np.linalg.eigvals((f1-f).full()))
    ev2 = assert_and_recast_to_real(np.linalg.eigvals((f2-f).full()))
    assert np.all(ev1 <= 1e-6), "fom1 should be <= f"
    assert np.all(ev2 <= 1e-6), "fom2 should be <= f"
    assert np.allclose(np.max(ev1),0), "there should be at least one 0 e.v. (corresponding to the target state)"
    assert np.allclose(np.max(ev2),0), "there should be at least one 0 e.v. (corresponding to the target state)"
    
    # 
    nb_q = 6
    x_rdm = np.array([1.70386471,1.38266762,3.4257722,5.78064,3.84102323,2.37653078])
    init = qt.tensor(*[zero]*nb_q)
    rot_init = qt.tensor(*[qt.ry(N=1, phi=x) for n,x in enumerate(x_rdm)])
    cz = [cphase(np.pi, nb_q, c, t) for c, t in edges_test]
    entangl = prod_listop(cz)
    fin = entangl * rot_init * init
    qt.expect(f, fin)
    qt.expect(f1, fin)
    qt.expect(f2, fin)
    
    exp_stab = [qt.expect(s, fin) for s in list_stab]
    
    N_test = 6
    edges_test = [[i, i+1]for i in range(N_test-1)] + [[N_test-1, 0]] 
    graph_test = gen_graph_state(N=N_test, edges=edges_test)
    #gen_decomposition_paulibasis(graph_test, N = N_test, threshold=1e-6, symbolic=True)
    
Ejemplo n.º 20
0
def CO_ry(Chromosome, phase=np.pi / 8):
    return np.dot(Chromosome, np.array(qc.ry(phase).full()))
def get_sigmas(N=1, pos=0):
    """Return set of single qubit X Y Z gates."""
    sigmas = [qt.qeye([2]*N), qt.rx(np.pi, N, pos), qt.ry(np.pi, N, pos),
              qt.rz(np.pi, N, pos)]
    return sigmas
Ejemplo n.º 22
0
def Ry(angle):
    return qt.ry(angle)