def test_run_path_multiple_circuits_mismatch_length(self):
     """Test parameterized circuit path via backed.run()"""
     shots = 1000
     backend = AerSimulator()
     circuit = QuantumCircuit(2)
     theta = Parameter('theta')
     circuit.rx(theta, 0)
     circuit.cx(0, 1)
     circuit.measure_all()
     parameter_binds = [{theta: [0, pi, 2 * pi]}]
     with self.assertRaises(AerError):
         backend.run([circuit] * 3,
                     shots=shots,
                     parameter_binds=[parameter_binds]).result()
class MockFineFreq(MockIQBackend):
    """A mock backend for fine frequency calibration."""

    def __init__(self, freq_shift: float, sx_duration: int = 160):
        super().__init__()
        self.freq_shift = freq_shift
        self.dt = self.configuration().dt
        self.sx_duration = sx_duration
        self.simulator = AerSimulator(method="automatic")

    def _compute_probability(self, circuit: QuantumCircuit) -> float:
        """The freq shift acts as the value that will accumulate phase."""

        delay = None
        for instruction in circuit.data:
            if instruction[0].name == "delay":
                delay = instruction[0].duration

        if delay is None:
            return 1.0
        else:
            reps = delay // self.sx_duration

            qc = QuantumCircuit(1)
            qc.sx(0)
            qc.rz(np.pi * reps / 2 + 2 * np.pi * self.freq_shift * delay * self.dt, 0)
            qc.sx(0)
            qc.measure_all()

            counts = self.simulator.run(qc, seed_simulator=1).result().get_counts(0)

            return counts.get("1", 0) / sum(counts.values())
    def test_parameterized_qobj_qasm_save_expval(self):
        """Test parameterized qobj with Expectation Value snapshot and qasm simulator."""
        shots = 1000
        labels = save_expval_labels() * 3
        counts_targets = save_expval_counts(shots) * 3
        value_targets = save_expval_pre_meas_values() * 3

        backend = AerSimulator()
        qobj = self.parameterized_qobj(backend=backend,
                                       shots=1000,
                                       measure=True,
                                       snapshot=True)
        self.assertIn('parameterizations', qobj.to_dict()['config'])
        with self.assertWarns(DeprecationWarning):
            job = backend.run(qobj, **self.BACKEND_OPTS)
            result = job.result()
            success = getattr(result, 'success', False)
            num_circs = len(result.to_dict()['results'])
            self.assertTrue(success)
            self.compare_counts(result,
                                range(num_circs),
                                counts_targets,
                                delta=0.1 * shots)
            # Check snapshots
            for j, target in enumerate(value_targets):
                data = result.data(j)
                for label in labels:
                    self.assertAlmostEqual(data[label],
                                           target[label],
                                           delta=1e-7)
 def test_run_path_with_more_params_than_expressions_multiple_circuits(
         self):
     """Test parameterized circuit path via backed.run()"""
     shots = 2000
     backend = AerSimulator()
     circuit = QuantumCircuit(2)
     theta = Parameter('theta')
     theta_squared = theta * theta
     phi = Parameter('phi')
     circuit.rx(theta, 0)
     circuit.cx(0, 1)
     circuit.rz(theta_squared, 1)
     circuit.ry(phi, 1)
     circuit.measure_all()
     parameter_binds = [{theta: [0, pi, 2 * pi], phi: [0, 1, pi]}] * 3
     res = backend.run([circuit] * 3,
                       shots=shots,
                       parameter_binds=parameter_binds).result()
     counts = res.get_counts()
     for index, expected in enumerate([{
             '00': shots
     }, {
             '01': 0.25 * shots,
             '11': 0.75 * shots
     }, {
             '10': shots
     }] * 3):
         self.assertDictAlmostEqual(counts[index],
                                    expected,
                                    delta=0.05 * shots)
示例#5
0
    def compute_probabilities(self, circuits: List[QuantumCircuit]) -> List[Dict[str, float]]:
        """Return the probability of being in the excited state."""
        sx_duration = self.sx_duration
        freq_shift = self.freq_shift
        dt = self.dt
        simulator = AerSimulator(method="automatic")
        output_dict_list = []
        for circuit in circuits:
            probability_output_dict = {}
            delay = None
            for instruction in circuit.data:
                if instruction[0].name == "delay":
                    delay = instruction[0].duration

            if delay is None:
                probability_output_dict = {"1": 1, "0": 0}
            else:
                reps = delay // sx_duration

                qc = QuantumCircuit(1)
                qc.sx(0)
                qc.rz(np.pi * reps / 2 + 2 * np.pi * freq_shift * delay * dt, 0)
                qc.sx(0)
                qc.measure_all()

                counts = simulator.run(qc, seed_simulator=1).result().get_counts(0)
                probability_output_dict["1"] = counts.get("1", 0) / sum(counts.values())
                probability_output_dict["0"] = 1 - probability_output_dict["1"]
            output_dict_list.append(probability_output_dict)

        return output_dict_list
def do_trotter_decomposition_observable(initialstate, decomp_function,
                                        observable, simulator,
                                        quantum_computer_dict, timestep,
                                        numberofsteps, num_shots):
    rotation = timestep * 2
    if simulator == "noisy_qasm":
        backend, coupling_map, noise_model = quantum_computer_dict[simulator]
    elif simulator == "real" or simulator == "noiseless_qasm":
        backend = quantum_computer_dict[simulator]
    N = initialstate.N
    qc = QuantumCircuit(N)
    qc.append(deepcopy(initialstate.get_qiskit_circuit()), range(N))
    for i in range(numberofsteps):
        qc.append(decomp_function(N, rotation, J=1, g=1), range(N))
    #print(qc)
    ps = observable.return_paulistrings()[0].return_string()
    #print(ps)
    for i in range(len(ps)):
        if ps[i] == 1:
            qc.h(i)
        if ps[i] == 2:
            qc.sdg(i)
            qc.h(i)
    qc.measure_all()
    if simulator == "noisy_qasm":
        '''Changes Here'''
        sim_noise = AerSimulator(noise_model=noise_model)
        circ_noise = transpile(qc, sim_noise, coupling_map=coupling_map)
        results = sim_noise.run(circ_noise, shots=num_shots).result()
        counts = results.get_counts()
    elif simulator == "noiseless_qasm":
        counts = execute(qc, backend=backend,
                         shots=num_shots).result().get_counts()
    elif simulator == "real":
        job = execute(qc, backend=backend, shots=num_shots)
        job_monitor(job, interval=2)
        results = job.result()
        counts = results.get_counts()
    newcountdict = {}
    for key in counts.keys():
        newkey = key[::-1]
        newcountdict[newkey] = counts[key]
    result = 0
    for key in newcountdict.keys():
        subresult = 1
        for i in range(len(ps)):
            if ps[i] == 0:
                subresult = subresult
            else:
                if key[i] == '0':
                    subresult = subresult
                elif key[i] == '1':
                    subresult = subresult * (-1)
        result = result + subresult * newcountdict[key]
    return result / sum(newcountdict.values())
示例#7
0
    def test_run_path_with_truncation(self):
        """Test parameterized circuits with truncation"""
        backend = AerSimulator(method='statevector')
        theta = Parameter('theta')
        circuit = QuantumCircuit(5, 2)
        for q in range(5):
            circuit.ry(theta, q)
        circuit.cx(0, 1)
        circuit.cx(1, 2)
        for q in range(5):
            circuit.ry(theta, q)
        circuit.cx(0, 1)
        circuit.cx(1, 2)
        circuit.append(
            SaveStatevector(3, label='sv', pershot=False, conditional=False),
            range(3))

        param_map = {theta: [0.1 * i for i in range(3)]}
        param_sets = [{theta: 0.1 * i} for i in range(3)]

        resolved_circuits = [
            circuit.bind_parameters(param_set) for param_set in param_sets
        ]

        result = backend.run(circuit, parameter_binds=[param_map]).result()
        self.assertSuccess(result)

        result_without_parameters = backend.run(resolved_circuits).result()
        self.assertSuccess(result_without_parameters)

        for actual_result in result.results:
            metadata = actual_result.metadata
            self.assertEqual(metadata["active_input_qubits"],
                             [q for q in range(3)])
        for i in range(3):
            self.assertEqual(
                result.data(i)['sv'],
                result_without_parameters.data(i)['sv'])
 def test_run_path_already_transpiled_parameter_expression(self):
     """Test parameterizations with a transpiled parameter expression."""
     shots = 1000
     backend = AerSimulator()
     circuit = QuantumCircuit(1)
     theta = Parameter('theta')
     circuit.rx(theta, 0)
     circuit.measure_all()
     parameter_binds = [{theta: [0, pi, 2 * pi]}]
     tqc = transpile(circuit, basis_gates=['u3'])
     res = backend.run(tqc, shots=shots,
                       parameter_binds=parameter_binds).result()
     counts = res.get_counts()
     self.assertEqual(counts, [{'0': shots}, {'1': shots}, {'0': shots}])
 def test_run_path(self):
     """Test parameterized circuit path via backed.run()"""
     shots = 1000
     backend = AerSimulator()
     circuit = QuantumCircuit(2)
     theta = Parameter('theta')
     circuit.rx(theta, 0)
     circuit.cx(0, 1)
     circuit.measure_all()
     parameter_binds = [{theta: [0, pi, 2 * pi]}]
     res = backend.run(circuit,
                       shots=shots,
                       parameter_binds=parameter_binds).result()
     counts = res.get_counts()
     self.assertEqual(counts, [{'00': shots}, {'11': shots}, {'00': shots}])
 def test_run_path_with_expressions_multiple_params_per_instruction(self):
     """Test parameterized circuit path via backed.run()"""
     shots = 1000
     backend = AerSimulator()
     circuit = QuantumCircuit(2)
     theta = Parameter('theta')
     theta_squared = theta * theta
     circuit.rx(theta, 0)
     circuit.cx(0, 1)
     circuit.rz(theta_squared, 1)
     circuit.u(theta, theta_squared, theta, 1)
     circuit.measure_all()
     parameter_binds = [{theta: [0, pi, 2 * pi]}]
     res = backend.run(circuit,
                       shots=shots,
                       parameter_binds=parameter_binds).result()
     counts = res.get_counts()
     self.assertEqual(counts, [{'00': shots}, {'01': shots}, {'00': shots}])
 def test_run_path_already_bound_parameter_expression(self):
     """Test parameterizations with a parameter expression that's already bound."""
     shots = 1000
     backend = AerSimulator()
     circuit = QuantumCircuit(2)
     tmp = Parameter('x')
     theta = Parameter('theta')
     expr = tmp - tmp
     bound_expr = expr.bind({tmp: 1})
     circuit.rx(theta, 0)
     circuit.rx(bound_expr, 0)
     circuit.cx(0, 1)
     circuit.measure_all()
     parameter_binds = [{theta: [0, pi, 2 * pi]}]
     res = backend.run(circuit,
                       shots=shots,
                       parameter_binds=parameter_binds).result()
     counts = res.get_counts()
     self.assertEqual(counts, [{'00': shots}, {'11': shots}, {'00': shots}])
    def test_parameterized_qobj_statevector(self):
        """Test parameterized qobj with Expectation Value snapshot and qasm simulator."""
        statevec_targets = save_expval_final_statevecs() * 3

        backend = AerSimulator(method="statevector")
        qobj = self.parameterized_qobj(
            backend=backend,
            measure=False,
            snapshot=False,
            save_state=True,
        )
        self.assertIn('parameterizations', qobj.to_dict()['config'])
        with self.assertWarns(DeprecationWarning):
            job = backend.run(qobj, **self.BACKEND_OPTS)
            result = job.result()
            success = getattr(result, 'success', False)
            num_circs = len(result.to_dict()['results'])
            self.assertTrue(success)

            for j in range(num_circs):
                statevector = result.get_statevector(j)
                np.testing.assert_array_almost_equal(statevector,
                                                     statevec_targets[j].data,
                                                     decimal=7)
示例#13
0
    def calculate_expectation(self, pauli_string_object):
        # previous_expectation_vals = self.previous_expectation_vals
        # initial_state_object = self.initial_state_object
        # sim = self.sim
        # backend = self.backend
        # coupling_map = self.coupling_map
        # meas_error_mitigate = self.meas_error_mitigate
        # meas_filter = self.meas_filter
        # noise_model = self.noise_model
        # num_shots = self.num_shots

        pauli_string_strform = pauli_string_object.get_string_for_hash()
        pauli_string_coeff = pauli_string_object.return_coefficient()
        # print(pauli_string_coeff)
        pauli_string = pauli_string_strform
        if pauli_string in self.previous_expectation_vals.keys():
            return pauli_string_coeff * self.previous_expectation_vals[
                pauli_string]
        qc = self.make_qc_to_measure_pstring(self.initial_state_object,
                                             pauli_string)

        if self.sim == "noisy_qasm":
            '''NEED TO MAKE SOME CHANGES HERE FOR ARTIFICIAL NOISE MODEL: JON'''
            #results = execute(qc, backend=self.backend, shots = self.num_shots, coupling_map = self.coupling_map, noise_model = self.noise_model).result()
            '''Changes Here'''
            sim_noise = AerSimulator(noise_model=self.noise_model)
            circ_noise = transpile(qc,
                                   sim_noise,
                                   coupling_map=self.coupling_map)
            results = sim_noise.run(circ_noise, shots=self.num_shots).result()

            if self.meas_error_mitigate == True:
                results = self.meas_filter.apply(results)
            counts = results.get_counts()
        elif self.sim == "noiseless_qasm":
            counts = execute(qc, backend=self.backend,
                             shots=self.num_shots).result().get_counts()
        elif self.sim == "real":
            job = execute(qc, backend=self.backend, shots=self.num_shots)
            job_monitor(job, interval=2)
            results = job.result()
            if self.meas_error_mitigate == True:
                results = self.meas_filter.apply(results)
            counts = results.get_counts()
        #print("Finished shots")

        frequency_dict = dict()
        total_num_of_counts = sum(counts.values())
        for key, value in counts.items():
            frequency_dict[key] = value / total_num_of_counts
        ans = 0 + 0j
        #since we did measurement in Z basis, we must change our pauli_string.
        #Note that when we did "make qc to measure p_string", we have already
        #reversed the p_string there.  for the "counts" object, note that the
        #bitstrings are in qiskit order, i.e the rightmost bit is the 1st
        #qubit.
        new_pauli_string = []
        for char in pauli_string:
            new_pauli_string.append(
                "1") if char != "0" else new_pauli_string.append(char)
        new_pauli_string = "".join(new_pauli_string)
        for key, value in frequency_dict.items():
            # print(key)
            coeff = np.base_repr(int(key, 2) & int(new_pauli_string, 2),
                                 base=2).count("1")  #bitwise and
            ans += (-1)**coeff * value
        # print(pauli_string, ans)
        self.previous_expectation_vals[pauli_string] = ans
        return ans * pauli_string_coeff


# def make_expectation_calculator(initial_state_object, sim, quantum_com_choice_results, num_shots = 8192, meas_error_mitigate = False, meas_filter = None):
#     """
#     This upper function has a dictionary that stores the previously calculated expectation values, so we don't do any re-calculation.

#     sim can be either noisy_qasm, noiseless_qasm, or real.
#     """
#     if sim == "noisy_qasm" or sim == "real":
#         if meas_error_mitigate == True and meas_filter == None:
#             raise(RuntimeError("no meas_filter specified, so no measurement error mitigation can be done!"))
#     if sim == "noisy_qasm":
#         backend, coupling_map, noise_model = quantum_com_choice_results[sim]
#     elif sim == "real" or sim == "noiseless_qasm":
#         backend = quantum_com_choice_results[sim]
#     previous_expectation_vals = dict()

#     def expectation_calculator(pauli_string_object):
#         pauli_string_strform = pauli_string_object.get_string_for_hash()
#         pauli_string_coeff = pauli_string_object.return_coefficient()
#         # print(pauli_string_coeff)
#         pauli_string = pauli_string_strform
#         if pauli_string in previous_expectation_vals.keys():
#             return pauli_string_coeff * previous_expectation_vals[pauli_string]
#         qc = make_qc_to_measure_pstring(initial_state_object, pauli_string)

#         if sim == "noisy_qasm":
#             results = execute(qc, backend=backend, shots = num_shots, coupling_map = coupling_map, noise_model = noise_model).result()
#             if meas_error_mitigate == True:
#                 results = meas_filter.apply(results)
#             counts = results.get_counts()
#         elif sim == "noiseless_qasm":
#             counts = execute(qc, backend=backend, shots = num_shots).result().get_counts()
#         elif sim == "real":
#             job = execute(qc, backend = backend, shots = num_shots)
#             job_monitor(job, interval = 2)
#             results = job.result()
#             if meas_error_mitigate == True:
#                 results = meas_filter.apply(results)
#             counts = results.get_counts()
#         #print("Finished shots")

#         frequency_dict = dict()
#         total_num_of_counts = sum(counts.values())
#         for key,value in counts.items():
#             frequency_dict[key] = value/total_num_of_counts
#         ans = 0 + 0j
#         #since we did measurement in Z basis, we must change our pauli_string.
#         #Note that when we did "make qc to measure p_string", we have already
#         #reversed the p_string there.  for the "counts" object, note that the
#         #bitstrings are in qiskit order, i.e the rightmost bit is the 1st
#         #qubit.
#         new_pauli_string = []
#         for char in pauli_string:
#             new_pauli_string.append("1") if char != "0" else new_pauli_string.append(char)
#         new_pauli_string = "".join(new_pauli_string)
#         for key, value in frequency_dict.items():
#             # print(key)
#             coeff = np.base_repr(int(key,2) & int(new_pauli_string, 2), base = 2).count("1") #bitwise and
#             ans += (-1)**coeff * value
#         # print(pauli_string, ans)
#         previous_expectation_vals[pauli_string] = ans
#         return ans * pauli_string_coeff
#     return expectation_calculator

#%% Testing
# if __name__ == "__main__":
#     num_qubits = 2
#     quantum_computer = "ibmq_rome"

#     sim = "noisy_qasm"
#     num_shots = 8192

#     # sim = "noiseless_qasm"
#     # num_shots = 100000

#     test_pstring = "23"
#     pauli_string_object = pcp.paulistring(num_qubits, test_pstring, -1j)
#     initial_state_object = acp.Initialstate(num_qubits, "efficient_SU2", 123, 3)

#     initial_statevector = initial_state_object.get_statevector()
#     print("the matrix multiplication result is",initial_statevector.conj().T @ pauli_string_object.get_matrixform() @ initial_statevector)

#     quantum_computer_choice_results = choose_quantum_computer("ibm-q-nus", group = "default", project = "reservations", quantum_com = quantum_computer)

#     #Noisy QASM
#     meas_filter = measurement_error_mitigator(num_qubits, sim, quantum_computer_choice_results, shots = num_shots)
#     expectation_calculator = make_expectation_calculator(initial_state_object, sim, quantum_computer_choice_results, meas_error_mitigate = True, meas_filter = meas_filter)

#     #Noiseless QASM
#     # expectation_calculator = make_expectation_calculator(initial_state_object, sim, quantum_computer_choice_results, meas_error_mitigate = False)

#     print("the quantum result is",expectation_calculator(pauli_string_object))

# import Qiskit_helperfunctions_kh as qhf #IBMQ account is loaded here in this import
# hub, group, project = "ibm-q-nus", "default", "reservations"
# quantum_com = "ibmq_rome"

# #Other parameters for running on the quantum computer
# sim = "noisy_qasm"
# num_shots = 8192

# quantum_computer_choice_results = qhf.choose_quantum_computer(hub, group, project, quantum_com)
# mitigate_meas_error = True
# meas_filter = qhf.measurement_error_mitigator(num_qubits, sim, quantum_computer_choice_results, shots = num_shots)

# expectation_calculator = qhf.make_expectation_calculator(initial_state, sim, quantum_computer_choice_results, meas_error_mitigate = mitigate_meas_error, meas_filter = meas_filter)
    return model, schedule


if __name__ == '__main__':
    # Run Aer simulator
    shots = 4000
    circuits = grovers_circuit(final_measure=True, allow_sampling=True)
    targets = [{
        '0x0': 5 * shots / 8,
        '0x1': shots / 8,
        '0x2': shots / 8,
        '0x3': shots / 8
    }]
    simulator = AerSimulator()
    result = simulator.run(transpile(circuits, simulator),
                           shots=shots).result()
    assert result.status == 'COMPLETED'
    assert result.success is True
    compare_counts(result, circuits, targets, delta=0.05 * shots)

    # Run qasm simulator
    simulator = QasmSimulator()
    result = simulator.run(transpile(circuits, simulator),
                           shots=shots).result()
    assert result.status == 'COMPLETED'
    assert result.success is True
    compare_counts(result, circuits, targets, delta=0.05 * shots)

    # Run statevector simulator
    circuits = cx_gate_circuits_deterministic(final_measure=False)
    targets = cx_gate_statevector_deterministic()
示例#15
0
def ibmsim(circ):
    sim = AerSimulator()

    compiled = transpile(circ, sim)
    return sim.run(compiled, shots=100000).result()