Esempio n. 1
0
    def tomography(self, full):
        if self.state == 'GHZ_teleport':
            self.qc.barrier()

            self.qc.cx(0, 1)
            self.qc.h(0)
            self.qc.h(2)

            c0 = ClassicalRegister(1)
            c1 = ClassicalRegister(1)
            c2 = ClassicalRegister(1)

            self.qc.add_register(c0, c1, c2)

            self.qc.measure(0, c0)
            self.qc.measure(1, c1)
            self.qc.measure(2, c2)

            self.qc.z(3).c_if(c0, 1)
            self.qc.x(3).c_if(c1, 1)
            self.qc.z(3).c_if(c2, 1)

            tomography_circuits = state_tomography_circuits(
                self.qc, self.q[self.a])
        else:
            tomography_circuits = state_tomography_circuits(self.qc, self.q)

        job = execute(tomography_circuits,
                      backend=self.backend,
                      coupling_map=self.coupling_map,
                      noise_model=self.noise_model,
                      basis_gates=self.basis_gates,
                      shots=self.shots,
                      optimization_level=3)
        tomography_results = job.result()

        rho = StateTomographyFitter(tomography_results,
                                    tomography_circuits).fit()

        if self.state == 'GHZ_teleport':
            self.histogram_data.append(
                tomography_results.get_counts(tomography_circuits[2]))
        else:
            self.histogram_data.append(
                tomography_results.get_counts(tomography_circuits[3**self.n -
                                                                  1]))

            if not full:
                rho = partial_trace(
                    rho, np.delete(np.arange(self.n), [self.a, self.b]))

        if self.state == 'GHZ_teleport':
            for i in range(3):
                self.qc.data.pop(-1)
            self.qc.remove_final_measurements()
            for i in range(3):
                self.qc.data.pop(-1)

        return rho
Esempio n. 2
0
    def tomography(self, qc, backend, device_settings,
                   meas_qubits):  # State tomography function
        tomography_circuits = state_tomography_circuits(qc, meas_qubits)
        if backend == Aer.get_backend(
                'qasm_simulator'):  # Job execution on qasm_simulator
            if device_settings:
                job = execute(tomography_circuits,
                              backend=backend,
                              coupling_map=self.coupling_map,
                              noise_model=self.noise_model,
                              basis_gates=self.basis_gates,
                              shots=self.shots,
                              optimization_level=3)
            else:
                job = execute(tomography_circuits,
                              backend=backend,
                              shots=self.shots,
                              optimization_level=3)
            job_id = None
        else:  # Job execution on live quantum processor
            job = execute(tomography_circuits,
                          backend=backend,
                          shots=self.shots,
                          optimization_level=3)
            job_monitor(job)  # hold and monitor job until it is completed
            job_id = job.job_id()
        tomography_results = job.result()

        rho = StateTomographyFitter(
            tomography_results,
            tomography_circuits).fit()  # Fit results to circuits

        return rho, job_id
def run_circuit_and_tomography(circuit, qubits, method='lstsq'):
    psi = Statevector.from_instruction(circuit)
    qst = tomo.state_tomography_circuits(circuit, qubits)
    job = qiskit.execute(qst, Aer.get_backend('qasm_simulator'), shots=5000)
    tomo_fit = tomo.StateTomographyFitter(job.result(), qst)
    rho = tomo_fit.fit(method=method)
    return (rho, psi)
Esempio n. 4
0
    def test_identity2(self, vector):
        # Define the linear system
        vector = np.array(vector)
        matrix = np.identity(2)
        system = LinearSystemSolverQSVE(matrix, vector, nprecision_bits=5, cval=0.1)

        # Get the circuit and registers
        circuit, _, _, col_register, _ = system.create_circuit(return_registers=True)

        # Test and debug
        print("Current vector is:", vector)
        print("Doing state tomography on col_register, which has {} qubit(s).".format(len(col_register)))
        tomo_circuits = tomography.state_tomography_circuits(circuit, col_register)
        print("There are {} tomography circuits. Running them now...".format(len(tomo_circuits)))
        job = execute(tomo_circuits, BasicAer.get_backend("qasm_simulator"), shots=10000)
        print("Finished running tomography circuits. Now fitting density matrix.")
        fitter = tomography.StateTomographyFitter(job.result(), tomo_circuits)
        rho = fitter.fit()
        print("Density matrix:\n", rho)

        expected = np.outer(vector, vector)
        expected /= np.trace(expected)

        print("Expected density matrix:\n", expected)

        self.assertTrue(np.allclose(rho, expected, atol=1e-2))
def run_circuit_and_tomography(circuit, qubits):
    job = qiskit.execute(circuit, Aer.get_backend('statevector_simulator'))
    psi = job.result().get_statevector(circuit)
    qst = tomo.state_tomography_circuits(circuit, qubits)
    job = qiskit.execute(qst, Aer.get_backend('qasm_simulator'), shots=5000)
    tomo_fit = tomo.StateTomographyFitter(job.result(), qst)
    rho_cvx = tomo_fit.fit(method='cvx')
    rho_mle = tomo_fit.fit(method='lstsq')
    return (rho_cvx, rho_mle, psi)
def run_circuit_and_tomography(circuit, qubits):
    job = qiskit.execute(circuit, Aer.get_backend('statevector_simulator'))
    psi = job.result().get_statevector(circuit)
    qst = tomo.state_tomography_circuits(circuit, qubits)
    job = qiskit.execute(qst, Aer.get_backend('qasm_simulator'), shots=5000)
    tomo_counts = tomo.tomography_data(job.result(), qst)
    probs, basis_matrix, _ = tomo.fitter_data(tomo_counts)
    rho_cvx = tomo.state_cvx_fit(probs, basis_matrix)
    rho_mle = tomo.state_mle_fit(probs, basis_matrix)
    return (rho_cvx, rho_mle, psi)
Esempio n. 7
0
 def time_state_tomography_cat(self, n_qubits):
     qr = qiskit.QuantumRegister(n_qubits, 'qr')
     circ = qiskit.QuantumCircuit(qr, name='cat')
     circ.h(qr[0])
     for i in range(1, n_qubits):
         circ.cx(qr[0], qr[i])
     psi = qiskit.execute(circ, self.sv_backend).result().get_statevector()
     qst_circ = tomo.state_tomography_circuits(circ, qr)
     tomo_result = qiskit.execute(qst_circ, self.qasm_backend,
                                  shots=5000).result()
     rho = tomo.StateTomographyFitter(tomo_result, qst_circ).fit()
     state_fidelity(psi, rho)
Esempio n. 8
0
 def time_state_tomography_bell(self, n_qubits):
     qr = qiskit.QuantumRegister(2)
     bell = qiskit.QuantumCircuit(qr)
     bell.h(qr[0])
     bell.cx(qr[0], qr[1])
     psi_bell = qiskit.execute(
         bell, self.sv_backend).result().get_statevector(bell)
     qr_full = qiskit.QuantumRegister(n_qubits)
     bell = qiskit.QuantumCircuit(qr_full)
     bell.h(qr_full[n_qubits - 2])
     bell.cx(qr_full[n_qubits - 2], qr_full[n_qubits - 1])
     qst_bell = tomo.state_tomography_circuits(
         bell, [qr_full[n_qubits - 2], qr_full[n_qubits - 1]])
     job = qiskit.execute(qst_bell, self.qasm_backend, shots=5000)
     rho_bell = tomo.StateTomographyFitter(job.result(), qst_bell).fit()
     state_fidelity(psi_bell, rho_bell)
    def test_fitter_string_input(self):
        q3 = QuantumRegister(3)
        bell = QuantumCircuit(q3)
        bell.h(q3[0])
        bell.cx(q3[0], q3[1])
        bell.cx(q3[1], q3[2])

        qst = tomo.state_tomography_circuits(bell, q3)
        qst_names = [circ.name for circ in qst]
        job = qiskit.execute(qst, Aer.get_backend('qasm_simulator'),
                             shots=5000)
        tomo_fit = tomo.StateTomographyFitter(job.result(), qst_names)
        rho = tomo_fit.fit(method=self.method)
        psi = Statevector.from_instruction(bell)
        F_bell = state_fidelity(psi, rho, validate=False)
        self.assertAlmostEqual(F_bell, 1, places=1)
Esempio n. 10
0
def state_tomography(qc, qubit_list):
    """
    A function for the state tomography for the given circuit 
    which the qubit_list are the qubits for the main system
    
    Parameters
        qc[QuantumCircuit]: a quantum circuit
          qubit_list[list]: a list of qubits in the system
          
    """

    qc_tomo = state_tomography_circuits(qc, qubit_list)
    job = execute(qc_tomo, Aer.get_backend('qasm_simulator'), shots=10000)
    result = job.result()
    state_tomo = StateTomographyFitter(result, qc_tomo)
    state_tomo_fit = state_tomo.fit()
    return state_tomo_fit
    def test_split_job(self):
        q3 = QuantumRegister(3)
        bell = QuantumCircuit(q3)
        bell.h(q3[0])
        bell.cx(q3[0], q3[1])
        bell.cx(q3[1], q3[2])

        psi = Statevector.from_instruction(bell)
        qst = tomo.state_tomography_circuits(bell, q3)
        qst1 = qst[:len(qst) // 2]
        qst2 = qst[len(qst) // 2:]

        backend = Aer.get_backend('qasm_simulator')
        job1 = qiskit.execute(qst1, backend, shots=5000)
        job2 = qiskit.execute(qst2, backend, shots=5000)

        tomo_fit = tomo.StateTomographyFitter([job1.result(), job2.result()], qst)

        rho_mle = tomo_fit.fit(method='lstsq')
        F_bell_mle = state_fidelity(psi, rho_mle, validate=False)
        self.assertAlmostEqual(F_bell_mle, 1, places=1)
Esempio n. 12
0
    def _state_tomography(self):
        """The state tomography.

        The HHL result gets extracted via state tomography. Available for
        qasm simulator and real hardware backends.
        """

        # Preparing the state tomography circuits
        tomo_circuits = state_tomography_circuits(self._circuit,
                                                  self._io_register)
        tomo_circuits_noanc = deepcopy(tomo_circuits)
        ca = ClassicalRegister(1)
        for circ in tomo_circuits:
            circ.add_register(ca)
            circ.measure(self._reciprocal._anc, ca[0])

        # Extracting the probability of successful run
        results = self._quantum_instance.execute(tomo_circuits)
        probs = []
        for circ in tomo_circuits:
            counts = results.get_counts(circ)
            s, f = 0, 0
            for k, v in counts.items():
                if k[0] == "1":
                    s += v
                else:
                    f += v
            probs.append(s/(f+s))
        probs = self._resize_vector(probs)
        self._ret["probability_result"] = np.real(probs)

        # Filtering the tomo data for valid results with ancillary measured
        # to 1, i.e. c1==1
        results_noanc = self._tomo_postselect(results)
        tomo_data = StateTomographyFitter(results_noanc, tomo_circuits_noanc)
        rho_fit = tomo_data.fit()
        vec = np.sqrt(np.diag(rho_fit))
        self._hhl_results(vec)
Esempio n. 13
0
    def run(self,
            circuits,
            meas_qubits=None,
            measure=None,
            count_chunks=False):
        """
        :param circuits: list of QuantumCircuit or QuantumCircuit
        :param meas_qubits: list of qubits that will be measured.
        :param measure: optional. By default after channel transformation we do tomography.
        Not implemented now
        :return: depend on measure parameter. By default, it's list of density matrix
        """
        if measure is not None:
            raise NotImplementedError

        if isinstance(circuits, QuantumCircuit):
            circuits = [circuits]

        meas_qubits, s_matrix = sort_list_and_transformation_matrix(
            meas_qubits)
        number_measure_experiments = 3**len(meas_qubits)

        jobs = []
        for qc in circuits:
            qr = qc.qregs[0]
            tomo_circuits = state_tomography_circuits(
                qc, [qr[qubit_number] for qubit_number in meas_qubits])
            jobs.extend(tomo_circuits)

        res = None
        for i, chunk_jobs in enumerate(chunks(jobs, self.max_jobs_per_one)):
            if count_chunks:
                print(f'chunk number: {i + 1}')
            execute_kwargs = {
                'experiments': chunk_jobs,
                'backend': self.backend,
                'shots': self.shots,
                'max_credits': 15
            }

            new_res = execute(**execute_kwargs).result()

            if res is None:
                res = new_res
            else:
                res += new_res

        matrices = []
        for i in range(int(len(res.results) / number_measure_experiments)):
            res_matrix = copy(res)
            res_matrix.results = res.results[i *
                                             number_measure_experiments:(i +
                                                                         1) *
                                             number_measure_experiments]

            rho = StateTomographyFitter(
                res_matrix, jobs[i * number_measure_experiments:(i + 1) *
                                 number_measure_experiments]).fit()
            rho = np.linalg.inv(s_matrix) @ rho @ s_matrix
            matrices.append(rho)
        return matrices
Esempio n. 14
0
    #operators = ['XY']
    probs = []
    basis_matrix = []
    for s in operators:
        #print("Tomo counts: ",tomo_counts)
        prob, mat = compute_expectation(2, s, tomo_counts, shots)
        #print("operator: {}".format(s))
        #print("exp: {}".format(prob))
        #print("mat: {}".format(mat))
        probs.append(prob)
        basis_matrix.append(mat)
    return probs, basis_matrix


# get expectation values of operators ... and convert the to the right format
qst_bell1 = tomo.state_tomography_circuits(bell1, qr1)
job = qiskit.execute(qst_bell1, Aer.get_backend('qasm_simulator'), shots=5000)
tomo_counts_psi1 = tomo.tomography_data(job.result(), qst_bell1)
#probs_psi1, basis_matrix, _ = tomo.fitter_data(tomo_counts_psi1)
probs_psi1, basis_matrix = get_expectation_values(tomo_counts_psi1)

#Psi 2
# Setup circuit to generate |psi2>
qr2 = QuantumRegister(2)
bell2 = QuantumCircuit(qr2)
bell2.y(qr2[0])
bell2.h(qr2[0])
bell2.cx(qr2[0], qr2[1])

# get state |psi2> using statevector_simulator
job = qiskit.execute(bell2, Aer.get_backend('statevector_simulator'))
Esempio n. 15
0
gate1Q = 0.1
gate2Q = 0.5

noise_model2.add_all_qubit_quantum_error(
    thermal_relaxation_error(t1, t2, gate1Q), 'u2')
noise_model2.add_all_qubit_quantum_error(
    thermal_relaxation_error(t1, t2, 2 * gate1Q), 'u3')
noise_model2.add_all_qubit_quantum_error(
    thermal_relaxation_error(t1, t2, gate2Q).tensor(
        thermal_relaxation_error(t1, t2, gate2Q)), 'cx')

# End Noise configuration

# Start state tomography - without noise

qst_deutsch = tomo.state_tomography_circuits(circuit, q5)
job = qiskit.execute(qst_deutsch, backend_sim, shots=5000)
results = job.result()
print("results:")
print(results.get_counts(0))
statefit = tomo.StateTomographyFitter(results, qst_deutsch)
p, M, weights = statefit._fitter_data(True, 0.5)
M_dg = np.conj(M).T
linear_inversion_matrix = np.linalg.inv(M_dg @ M) @ M_dg
rho_deutsch = linear_inversion_matrix @ p
rho_deutsch = np.reshape(rho_deutsch, (2**num_qubits, 2**num_qubits))

job = qiskit.execute(circuit, Aer.get_backend('statevector_simulator'))
psi_deutsch_clear = job.result().get_statevector(circuit)
print("Deutsch state vector (without noise): ")
print(psi_deutsch_clear)
Esempio n. 16
0
#append gates to the quantum circuit
circuit.h(q_reg[0])

print(circuit.qasm())

#run the circuit
job = qiskit.execute(circuit, BasicAer.get_backend('statevector_simulator'))

#get wave function at the end of the circuit
psi = job.result().get_statevector(circuit)
print('final state of the circuit', psi)

# Generate circuits for tomography and run tomography on simulator
t = time.time()
qst = tomo.state_tomography_circuits(circuit, q_reg)
job = qiskit.execute(qst, BasicAer.get_backend('qasm_simulator'), shots=SHOTS)
print('Time taken:', time.time() - t)

tomo_fitter = tomo.fitters.base_fitter.TomographyFitter(job.result(), qst)
# Extract tomography data so that counts are indexed by measurement configuration
#tomo_counts = tomo.tomography_data(job.result(), qst)

# Generate fitter data and reconstruct density matrix
probs, basis_matrix, weights = tomo_fitter._fitter_data(True, 0.5)
#print('tomography results', tomo_counts)

#bayesian reconstruction of the density matrix and error on observable
rho_fit, error_rho = bme_fit(probs, basis_matrix, SHOTS)

print("BME", rho_fit)
Esempio n. 17
0
def createQC2(r):
    #parameter setting lis
    paraLis16 = [0.196, 0.379, 0.981, 0.589, 1.178, 16]
    paraLis8 = [1.963, 1.115, 1.963, 2.615, 1.178, 8]
    paraLis4 = [-0.785, 1.017, 3.927, 2.517, 2.356, 4]
    paraLis2 = [-9.014 * 10**(-9), -0.75, 1.571, 0.75, -1.571, 2]
    paraLis = [paraLis16, paraLis8, paraLis4, paraLis2]
    #Register and circuit
    s = QuantumRegister(1, name='s')
    j = QuantumRegister(4, name='j')
    q = QuantumRegister(2, name='q')
    #cr = ClassicalRegister(1,name='cr')
    #crtmp= ClassicalRegister(2,name='crtmp')
    qc = QuantumCircuit(s, j, q)
    #Gate preparation
    qft = QFT(4, inverse=False)
    iqft = QFT(4, inverse=True)
    gateLis = []
    gateinvLis = []
    for i in range(4):
        toPut = Agate(paraLis[i]).control()
        gateLis.append(toPut)
    qc.h(j)
    qc.h(q)
    for i in range(4):
        gate = gateLis[i]
        qc.append(gate, qargs=[j[i]] + q[:])
    qc.append(iqft, qargs=j[:])
    #qc.swap(j[1],j[3])
    for i in range(4):
        angle = 2**(3 - i) * np.pi
        angle *= 2**(-r + 1)
        qc.cry(angle, j[i], s[0])
    qc.append(qft, qargs=j[:])

    for i in range(4):
        gate = gateLis[3 - i].inverse()
        qc.append(gate, qargs=[j[3 - i]] + q[:])
    qc.barrier()
    qc.h(j)

    #qc.measure(s,cr)
    qc.barrier()
    print(qc)
    tomo_circuits = state_tomography_circuits(qc, q)
    tomo_circuits_noanc = deepcopy(tomo_circuits)
    to_put = ClassicalRegister(1)
    for i in tomo_circuits:
        i.add_register(to_put)
        i.measure(s, to_put[0])
        print(i)

    backend = Aer.get_backend('qasm_simulator')
    results = execute(tomo_circuits, backend, shots=10**5).result()
    print(results.get_counts())
    probs = []
    for circ in tomo_circuits:
        counts = results.get_counts(circ)
        s, f = 0, 0
        for k, v in counts.items():
            if k[0] == "1":
                s += v
            else:
                f += v
        probs.append(s / (f + s))
    #results_noanc = tomo_postselect(results)
    data = StateTomographyFitter(results, tomo_circuits)
    print(data)
    #omo_data = StateTomographyFitter(results_noanc,tomo_circuits_noanc)
    rho_fit = data.fit()
    print(rho_fit)
    '''
Esempio n. 18
0

# RY-Ansatz parameters(theta1,..,theta4) obtained by VQD-iteration 
params = np.array([1.70075589,  1.72352203, -0.32227027, -1.34956145]) 

# circuit for 2-qubit RY Ansatz
var_form = RY(2, depth=1, entanglement="linear") 
circ = var_form.construct_circuit(parameters = params)
#circ.draw(output = 'mpl')


# In[36]:


# generate circuits for state tomography 
tomo_circuits = state_tomography_circuits(circ, circ.qregs)


# In[44]:


# exec state tomography experiments
job = execute(tomo_circuits, backend = backend_qasm, shots = 8192)


# In[10]:


job.status()