def test_qobj_save_load(self): filename = self._get_resource_path('qobj/cpp_save_load.json') with open(filename, 'r') as file: qobj = Qobj.from_dict(json.load(file)) result = self.backend.run(qobj).result() snapshots = result.data('save_command')['snapshots']['statevector'] self.assertEqual(set(snapshots), {'0', '1', '10', '11'}, msg='snapshot keys') state0 = format_statevector(snapshots['0'][0]) state10 = format_statevector(snapshots['10'][0]) state1 = format_statevector(snapshots['1'][0]) state11 = format_statevector(snapshots['11'][0]) expected_state0 = np.array([1, 0]) expected_state10 = np.array([1 / np.sqrt(2), 1 / np.sqrt(2)]) fidelity0 = np.abs(expected_state0.dot(state0.conj())) ** 2 fidelity1 = np.abs(expected_state0.dot(state1.conj())) ** 2 fidelity10 = np.abs(expected_state10.dot(state10.conj())) ** 2 fidelity11 = np.abs(expected_state10.dot(state11.conj())) ** 2 self.assertAlmostEqual(fidelity0, 1.0, places=10, msg='snapshot 0') self.assertAlmostEqual(fidelity10, 1.0, places=10, msg='snapshot 0') self.assertAlmostEqual(fidelity1, 1.0, places=10, msg='snapshot 0') self.assertAlmostEqual(fidelity11, 1.0, places=10, msg='snapshot 0')
def test_combine_circuit_extension_instructions(self): """Test combining circuits containing barrier, initializer, snapshot """ qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr) desired_vector = [0.5 + 0.j, 0.5 + 0.j, 0.5 + 0.j, 0.5 + 0.j] qc1.initialize(desired_vector, qr) qc1.barrier() qc2 = QuantumCircuit(qr, cr) qc2.snapshot(slot='1') qc2.measure(qr, cr) new_circuit = qc1 + qc2 backend = Aer.get_backend('qasm_simulator') shots = 1024 result = execute(new_circuit, backend=backend, shots=shots, seed=78).result() snapshot_vectors = result.data(0)['snapshots']['statevector']['1'] snapshot = format_statevector(snapshot_vectors[0]) fidelity = state_fidelity(snapshot, desired_vector) self.assertGreater(fidelity, 0.99) counts = result.get_counts() target = { '00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4 } threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold)
def get_counts(self, experiment=None): """Get the histogram data of an experiment. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``get_data()``. Returns: dict[str:int]: a dictionary with the counts for each qubit, with the keys containing a string in binary format and separated according to the registers in circuit (e.g. ``0100 1110``). The string is little-endian (cr[0] on the right hand side). Raises: QiskitError: if there are no counts for the experiment. """ exp = self._get_experiment(experiment) try: header = exp.header.to_dict() except (AttributeError, QiskitError): # header is not available header = None if 'counts' in self.data(experiment).keys(): return postprocess.format_counts( self.data(experiment)['counts'], header) elif 'statevector' in self.data(experiment).keys(): vec = postprocess.format_statevector( self.data(experiment)['statevector']) return state_to_counts(vec) else: raise QiskitError( 'No counts for experiment "{0}"'.format(experiment))
def test_conditionals(self): filename = self._get_resource_path('qobj/cpp_conditionals.json') with open(filename, 'r') as file: qobj = Qobj.from_dict(json.load(file)) result = self.backend.run(qobj).result() expected_data = { 'single creg (c0=0)': { 'statevector': np.array([1, 0, 0, 0])}, 'single creg (c0=1)': { 'statevector': np.array([0, 0, 0, 1])}, 'two creg (c1=0)': { 'statevector': np.array([1, 0, 0, 0])}, 'two creg (c1=1)': { 'statevector': np.array([0, 0, 0, 1])} } for name in expected_data: # Check snapshot snapshots = result.data(name)['snapshots']['statevector'] self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = format_statevector(snapshots['0'][0]) expected_state = expected_data[name]['statevector'] fidelity = np.abs(expected_state.dot(state.conj())) ** 2 self.assertAlmostEqual(fidelity, 1.0, places=10, msg=name + ' snapshot fidelity')
def get_counts(self, experiment=None): """Get the histogram data of an experiment. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``data([experiment])``. Returns: dict[str:int] or list[dict[str:int]]: a dictionary or a list of dictionaries. A dictionary has the counts for each qubit with the keys containing a string in binary format and separated according to the registers in circuit (e.g. ``0100 1110``). The string is little-endian (cr[0] on the right hand side). Raises: QiskitError: if there are no counts for the experiment. """ if experiment is None: exp_keys = range(len(self.results)) else: exp_keys = [experiment] dict_list = [] for key in exp_keys: exp = self._get_experiment(key) try: header = exp.header.to_dict() except (AttributeError, QiskitError): # header is not available header = None if "counts" in self.data(key).keys(): if header: counts_header = { k: v for k, v in header.items() if k in {"time_taken", "creg_sizes", "memory_slots"} } else: counts_header = {} dict_list.append( Counts(self.data(key)["counts"], **counts_header)) elif "statevector" in self.data(key).keys(): vec = postprocess.format_statevector( self.data(key)["statevector"]) dict_list.append( statevector.Statevector(vec).probabilities_dict( decimals=15)) else: raise QiskitError('No counts for experiment "{}"'.format( repr(key))) # Return first item of dict_list if size is 1 if len(dict_list) == 1: return dict_list[0] else: return dict_list
def test_qobj_two_qubit_gates(self): filename = self._get_resource_path('qobj/cpp_two_qubit_gates.json') with open(filename, 'r') as file: qobj = Qobj.from_dict(json.load(file)) result = self.backend.run(qobj).result() expected_data = { 'h0 CX01': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 CX10': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 CX01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h1 CX10': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 cx01': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 cx10': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 cx01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h1 cx10': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 cz01': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h0 cz10': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 cz01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h1 cz10': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h0 h1 cz01': {'statevector': np.array([0.5, 0.5, 0.5, -0.5])}, 'h0 h1 cz10': {'statevector': np.array([0.5, 0.5, 0.5, -0.5])}, 'h0 rzz01': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])}, 'h0 rzz10': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])}, 'h1 rzz01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])}, 'h1 rzz10': { 'statevector': np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])}, 'h0 h1 rzz01': {'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])}, 'h0 h1 rzz10': {'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])} } for name in expected_data: # Check snapshot snapshots = result.data(name)['snapshots']['statevector'] self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = format_statevector(snapshots['0'][0]) expected_state = expected_data[name]['statevector'] fidelity = state_fidelity(expected_state, state) self.assertAlmostEqual(fidelity, 1.0, places=10, msg=name + ' snapshot fidelity')
def get_counts(self, experiment=None): """Get the histogram data of an experiment. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``get_data()``. Returns: dict[str:int] or list[dict[str:int]]: a dictionary or a list of dictionaries. A dictionary has the counts for each qubit with the keys containing a string in binary format and separated according to the registers in circuit (e.g. ``0100 1110``). The string is little-endian (cr[0] on the right hand side). Raises: QiskitError: if there are no counts for the experiment. """ if experiment is None: exp_keys = range(len(self.results)) else: exp_keys = [experiment] dict_list = [] for key in exp_keys: exp = self._get_experiment(key) try: header = exp.header.to_dict() except (AttributeError, QiskitError): # header is not available header = None if 'counts' in self.data(key).keys(): dict_list.append(postprocess.format_counts(self.data(key)['counts'], header)) elif 'statevector' in self.data(key).keys(): vec = postprocess.format_statevector(self.data(key)['statevector']) dict_list.append(state_to_counts(vec)) else: raise QiskitError('No counts for experiment "{0}"'.format(key)) # Return first item of dict_list if size is 1 if len(dict_list) == 1: return dict_list[0] else: return dict_list
def get_statevector(self, experiment=None, decimals=None): """Get the final statevector of an experiment. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``data()``. decimals (int): the number of decimals in the statevector. If None, does not round. Returns: list[complex]: list of 2^num_qubits complex amplitudes. Raises: QiskitError: if there is no statevector for the experiment. """ try: return postprocess.format_statevector(self.data(experiment)['statevector'], decimals=decimals) except KeyError: raise QiskitError('No statevector for experiment "{}"'.format(experiment))
def test_snapshot(self): """snapshot a bell state in the middle of circuit""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) circuit = qiskit.QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.snapshot('3') circuit.cx(qr[0], qr[1]) circuit.h(qr[1]) sim = Aer.get_backend('statevector_simulator') result = execute(circuit, sim).result() # TODO: rely on Result.get_statevector() postprocessing rather than manual snapshots = result.data(0)['snapshots']['statevector']['3'] snapshot = format_statevector(snapshots[0]) target = [0.70710678 + 0.j, 0. + 0.j, 0. + 0.j, 0.70710678 + 0.j] fidelity = state_fidelity(snapshot, target) self.assertGreater( fidelity, self._desired_fidelity, "snapshot has low fidelity{0:.2g}.".format(fidelity))
def _format_tree(self, current_node, decimals): current_node['value'] = postprocess.format_statevector( current_node['value'], decimals=decimals) if 'path_0' in current_node: self._format_tree(current_node['path_0'], decimals) self._format_tree(current_node['path_1'], decimals)
def test_qobj_measure_opt(self): filename = self._get_resource_path('qobj/cpp_measure_opt.json') with open(filename, 'r') as file: qobj = Qobj.from_dict(json.load(file)) result = self.backend.run(qobj).result() shots = qobj.config.shots expected_data = { 'measure (opt)': { 'deterministic': True, 'counts': {'00': shots}, 'statevector': np.array([1, 0, 0, 0])}, 'x0 measure (opt)': { 'deterministic': True, 'counts': {'01': shots}, 'statevector': np.array([0, 1, 0, 0])}, 'x1 measure (opt)': { 'deterministic': True, 'counts': {'10': shots}, 'statevector': np.array([0, 0, 1, 0])}, 'x0 x1 measure (opt)': { 'deterministic': True, 'counts': {'11': shots}, 'statevector': np.array([0, 0, 0, 1])}, 'y0 measure (opt)': { 'deterministic': True, 'counts': {'01': shots}, 'statevector': np.array([0, 1j, 0, 0])}, 'y1 measure (opt)': { 'deterministic': True, 'counts': {'10': shots}, 'statevector': np.array([0, 0, 1j, 0])}, 'y0 y1 measure (opt)': { 'deterministic': True, 'counts': {'11': shots}, 'statevector': np.array([0, 0, 0, -1j])}, 'h0 measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 2, '01': shots / 2}, 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 2, '10': shots / 2}, 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h0 h1 measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4}, 'statevector': np.array([0.5, 0.5, 0.5, 0.5])}, 'bell measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 2, '11': shots / 2}, 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])} } for name in expected_data: # Check counts: counts = result.get_counts(name) expected_counts = expected_data[name]['counts'] if expected_data[name].get('deterministic', False): self.assertEqual(counts, expected_counts, msg=name + ' counts') else: threshold = 0.04 * shots self.assertDictAlmostEqual(counts, expected_counts, threshold, msg=name + 'counts') # Check snapshot snapshots = result.data(name)['snapshots']['statevector'] self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = format_statevector(snapshots['0'][0]) expected_state = expected_data[name]['statevector'] fidelity = np.abs(expected_state.dot(state.conj())) ** 2 self.assertAlmostEqual(fidelity, 1.0, places=10, msg=name + ' snapshot fidelity')
def test_qobj_single_qubit_gates(self): filename = self._get_resource_path('qobj/cpp_single_qubit_gates.json') with open(filename, 'r') as file: qobj = Qobj.from_dict(json.load(file)) result = self.backend.run(qobj).result() expected_data = { 'snapshot': { 'statevector': np.array([1, 0])}, 'id(U)': { 'statevector': np.array([1, 0])}, 'id(u3)': { 'statevector': np.array([1, 0])}, 'id(u1)': { 'statevector': np.array([1, 0])}, 'id(direct)': { 'statevector': np.array([1, 0])}, 'x(U)': { 'statevector': np.array([0, 1])}, 'x(u3)': { 'statevector': np.array([0, 1])}, 'x(direct)': { 'statevector': np.array([0, 1])}, 'y(U)': { 'statevector': np.array([0, 1j])}, 'y(u3)': { 'statevector': np.array([0, 1j])}, 'y(direct)': { 'statevector': np.array([0, 1j])}, 'h(U)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(u3)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(u2)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(direct)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(direct) z(U)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) z(u3)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) z(u1)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) z(direct)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) s(U)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) s(u3)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) s(u1)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) s(direct)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) sdg(U)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) sdg(u3)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) sdg(u1)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) sdg(direct)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) t(U)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) t(u3)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) t(u1)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) t(direct)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) tdg(U)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])}, 'h(direct) tdg(u3)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])}, 'h(direct) tdg(u1)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])}, 'h(direct) tdg(direct)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])} } for name in expected_data: # Check snapshot snapshots = result.data(name)['snapshots']['statevector'] self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = format_statevector(snapshots['0'][0]) expected_state = expected_data[name]['statevector'] inner_product = expected_state.dot(state.conj()) self.assertAlmostEqual(inner_product, 1.0, places=10, msg=name + ' snapshot fidelity')