def from_data(date=None, qobj=None, backend=None, job_id=None, noise_model=None, external_id=None, theta=None): # type: (str, dict, str, str, dict, str, list) -> FinishedExperiment """ We expect a dict with a qobj, job_id, backend name and optionally a noise model. When we have a Aer backend the simulation is redone to have the results. If the backend is a IBMQ then it is retrieved from the API. Thus it can take some time until this call ends. :param date: a string :param qobj: a dictionary :param job_id: a string :param noise_model: a dictionary :return: the Finished Experiment """ if theta is None: theta = [] if 'ibmq' in backend and job_id is not None: backend_obj = provider().get_backend(backend) # type: IBMQBackend job = backend_obj.retrieve_job(job_id) # type: IBMQJob qobj = job.qobj().to_dict() qobj = Qobj.from_dict(qobj) date = job.creation_date() elif date is not None and qobj is not None and backend is not None: if isinstance(qobj, dict): qobj = Qobj.from_dict(qobj) backend_obj = qiskit.Aer.get_backend(backend) # type: AerBackend job = backend_obj.run(qobj=qobj, noise_model=noise_model) # type: AerJob job_id = job.job_id() else: raise ValueError("Either use a IBMQ backend with a job_id or provide a date, qobj, backend.") if noise_model is not None: noise_model = NoiseModel.from_dict(noise_model) if isinstance(date, str): date = dateutil.parser.parse(date) # type: datetime.datetime external_id = 'job_{}'.format(date.strftime("%Y%m%dT%H%M%SZ")) if external_id is None else external_id running_experiment = RunningExperiment(date=date, qobj=qobj, noise_model=noise_model, job=job, external_id=external_id) while not running_experiment.is_done(): time.sleep(10) LOG.info("Simulation job {} is not done yet.".format(job_id)) fin_ex = FinishedExperiment.from_running_experiment(running_experiment) fin_ex.set_theta(theta) return fin_ex
def setUp(self): self.seed = 88 self.qasm_filename = self._get_resource_path('qasm/example.qasm') self.qp = QuantumProgram() self.qp.load_qasm_file(self.qasm_filename, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm('example')).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() circuit_config = {'coupling_map': None, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': self.seed} resources = {'max_credits': 3} self.qobj = {'id': 'test_sim_single_shot', 'config': { 'max_credits': resources['max_credits'], 'shots': 1024, }, 'experiments': [circuit], 'header': {'backend_name': 'local_qasm_simulator_py'}} self.qobj = Qobj.from_dict(self.qobj) self.qobj.experiments[0].config = QobjItem.from_dict(circuit_config) self.qobj.experiments[0].header.name = 'test'
def test_qobj_reset(self): filename = self._get_resource_path('qobj/cpp_reset.json') with open(filename, 'r') as file: qobj = Qobj.from_dict(json.load(file)) result = self.backend.run(qobj).result() expected_data = { 'reset': { 'statevector': np.array([1, 0]) }, 'x reset': { 'statevector': np.array([1, 0]) }, 'y reset': { 'statevector': np.array([1, 0]) }, 'h reset': { 'statevector': np.array([1, 0]) } } for name in expected_data: # Check snapshot is |0> state snapshots = result.data(name)['snapshots'] self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][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_measure_opt_flag(self): filename = self._get_resource_path('qobj/cpp_measure_opt_flag.json') with open(filename, 'r') as file: qobj = Qobj.from_dict(json.load(file)) result = self.backend.run(qobj).result() shots = qobj.config.shots sampled_measurements = { 'measure (sampled)': True, 'trivial (sampled)': True, 'reset1 (shots)': False, 'reset2 (shots)': False, 'reset3 (shots)': False, 'gate1 (shots)': False, 'gate2 (shots)': False, 'gate3 (shots)': False, 'gate4 (shots)': False } for name in sampled_measurements: snapshots = result.get_snapshots(name) # Check snapshot keys self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') # Check number of snapshots # there should be 1 for measurement sampling optimization # and there should be >1 for each shot beign simulated. num_snapshots = len(snapshots['0'].get('statevector', [])) if sampled_measurements[name] is True: self.assertEqual(num_snapshots, 1, msg=name + ' snapshot length') else: self.assertEqual(num_snapshots, shots, msg=name + ' snapshot length')
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.get_snapshots('save_command') self.assertEqual(set(snapshots), {'0', '1', '10', '11'}, msg='snapshot keys') state0 = snapshots['0']['statevector'][0] state10 = snapshots['10']['statevector'][0] state1 = snapshots['1']['statevector'][0] state11 = snapshots['11']['statevector'][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 run_with_api(self, api): """Creates a new `IBMQJob` instance running with the provided API object.""" self._current_api = api self._current_qjob = IBMQJob(Qobj.from_dict(new_fake_qobj()), api, False) return self._current_qjob
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.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][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 try_loading_cache_from_file(self): if len(self.qobjs) == 0 and self.cache_file is not None and len(self.cache_file) > 0: cache_handler = open(self.cache_file, "rb") cache = pickle.load(cache_handler, encoding="ASCII") cache_handler.close() self.qobjs = [Qobj.from_dict(qob) for qob in cache['qobjs']] self.mappings = cache['mappings'] logger.debug("Circuit cache loaded from file: {}".format(self.cache_file))
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.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][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 try_loading_cache_from_file(self): if len(self.qobjs) == 0 and self.cache_file is not None and len(self.cache_file) > 0: with open(self.cache_file, "rb") as cache_handler: try: cache = pickle.load(cache_handler, encoding="ASCII") except (EOFError) as e: logger.debug("No cache found in file: {}".format(self.cache_file)) return self.qobjs = [Qobj.from_dict(qob) for qob in cache['qobjs']] self.mappings = cache['mappings'] self.cache_transpiled_circuits = cache['transpile'] logger.debug("Circuit cache loaded from file: {}".format(self.cache_file))
def _result_from_job_response(self, job_response): # type: (AcQuantumResultResponse) -> Result backend = self.backend() # type: BaseBackend config = backend.configuration() # type: BackendConfiguration experiment = self._api.get_experiment(int(self.job_id())) # type: AcQuantumExperiment result_details = {} job_results = job_response.get_results() if len(job_results) == 1: experiment_result = job_results[0] # type: AcQuantumResult counts = dict((hex(int(k, 2)), int(v * experiment_result.shots)) for k, v in experiment_result.data.items()) self._qobj = Qobj.from_dict(json.loads(experiment.code)) self._job_name = self._qobj.experiments[0].header.name success = experiment_result.exception is None result_details = { "status": self._status.name, "success": success, "name": self._job_name, "seed": experiment_result.seed, "shots": experiment_result.shots, "data": { "counts": counts }, "start_time": experiment_result.start_time, "finish_time": experiment_result.finish_time, "header": self._qobj.experiments[0].header.as_dict() } from dateutil.parser import parser date = parser().parse(result_details['finish_time']) result_dict = { 'results': [result_details], 'backend_name': config.backend_name, 'backend_version': config.backend_version, 'qobj_id': self._qobj.qobj_id, 'job_id': str(self.job_id()), 'success': len(job_results) == 1, 'header': { "backend_name": config.backend_name }, "date": date.isoformat() } result = Result.from_dict(result_dict) return result
def from_dict(dict): return FinishedExperiment( backend_name=dict.get('backend_name', ''), backend_version=dict.get('backend_version', None), date=dateutil.parser.parse(dict['date']) if 'date' in dict else None, qobj=Qobj.from_dict(dict.get('qobj', {})), job_id=dict.get('job_id', ''), status=JobStatus[dict['job_status']] if 'job_status' in dict else JobStatus.INITIALIZING, results=[ExperimentResult.from_dict(d) for d in dict.get('results', [])], noise_model=NoiseModel.from_dict(dict['noise_model']) if 'noise_model' in dict and dict['noise_model'] is not None else None, external_id=dict.get('external_id', None), theta=dict.get('theta', np.arange(0, 2*np.pi, 0.1)), # fixing a bug here.... argh! parameters=dict.get('parameters', []) )
def try_loading_cache_from_file(self): """ load cache from file """ if not self.qobjs and self.cache_file: with open(self.cache_file, "rb") as cache_handler: try: cache = pickle.load(cache_handler, encoding="ASCII") except EOFError: logger.debug("No cache found in file: %s", self.cache_file) return self.qobjs = [Qobj.from_dict(qob) for qob in cache['qobjs']] self.mappings = cache['mappings'] self.cache_transpiled_circuits = cache['transpile'] logger.debug("Circuit cache loaded from file: %s", self.cache_file)
def qobj(self): """Return the Qobj submitted for this job. Note that this method might involve querying the API for results if the Job has been created in a previous Qiskit session. Returns: Qobj: the Qobj submitted for this job. """ if not self._qobj_payload: # Populate self._qobj_payload by retrieving the results. self._wait_for_job() return Qobj.from_dict(self._qobj_payload)
def setUp(self): self.seed = 88 self.qasm_filename = self._get_resource_path('qasm/example.qasm') with open(self.qasm_filename, 'r') as qasm_file: self.qasm_text = qasm_file.read() self.qasm_ast = qiskit.qasm.Qasm(data=self.qasm_text).parse() self.qasm_be = qiskit.unroll.CircuitBackend( ['u1', 'u2', 'u3', 'id', 'cx']) self.qasm_circ = qiskit.unroll.Unroller(self.qasm_ast, self.qasm_be).execute() qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qc = qc # create qobj compiled_circuit1 = transpile(DAGCircuit.fromQuantumCircuit(self.qc), format='json') compiled_circuit2 = transpile(DAGCircuit.fromQuantumCircuit( self.qasm_circ), format='json') self.qobj = { 'id': 'test_qobj', 'config': { 'max_credits': 3, 'shots': 2000, 'backend_name': 'local_qasm_simulator_cpp', 'seed': 1111 }, 'circuits': [{ 'name': 'test_circuit1', 'compiled_circuit': compiled_circuit1, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, }, { 'name': 'test_circuit2', 'compiled_circuit': compiled_circuit2, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, }] } self.qobj = Qobj.from_dict(self.qobj) # Simulator backend try: self.backend = QasmSimulatorCpp() except FileNotFoundError as fnferr: raise unittest.SkipTest('cannot find {} in path'.format(fnferr))
def test_saving_and_loading_one_circ(self): """ Saving and Loading one Circ test """ with tempfile.NamedTemporaryFile(suffix='.inp', delete=True) as cache_tmp_file: cache_tmp_file_name = cache_tmp_file.name var_form = RYRZ(num_qubits=4, depth=5) backend = BasicAer.get_backend('statevector_simulator') params0 = aqua_globals.random.random_sample( var_form.num_parameters) circ0 = var_form.construct_circuit(params0) qi0 = QuantumInstance(backend, circuit_caching=True, cache_file=cache_tmp_file_name, skip_qobj_deepcopy=True, skip_qobj_validation=True, seed_simulator=self.seed, seed_transpiler=self.seed) _ = qi0.execute([circ0]) with open(cache_tmp_file_name, "rb") as cache_handler: saved_cache = pickle.load(cache_handler, encoding="ASCII") self.assertIn('qobjs', saved_cache) self.assertIn('mappings', saved_cache) qobjs = [Qobj.from_dict(qob) for qob in saved_cache['qobjs']] self.assertTrue(isinstance(qobjs[0], Qobj)) self.assertGreaterEqual(len(saved_cache['mappings'][0][0]), 50) qi1 = QuantumInstance(backend, circuit_caching=True, cache_file=cache_tmp_file_name, skip_qobj_deepcopy=True, skip_qobj_validation=True, seed_simulator=self.seed, seed_transpiler=self.seed) params1 = aqua_globals.random.random_sample( var_form.num_parameters) circ1 = var_form.construct_circuit(params1) qobj1 = qi1.circuit_cache.load_qobj_from_cache( [circ1], 0, run_config=qi1.run_config) self.assertTrue(isinstance(qobj1, Qobj)) _ = qi1.execute([circ1]) self.assertEqual(qi0.circuit_cache.mappings, qi1.circuit_cache.mappings) self.assertLessEqual(qi1.circuit_cache.misses, 0)
def test_unitary_simulator(self): """test generation of circuit unitary""" self.qp.load_qasm_file(self.qasm_filename, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm('example')).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() # strip measurements from circuit to avoid warnings circuit['operations'] = [ op for op in circuit['operations'] if op['name'] != 'measure' ] # the simulator is expecting a JSON format, so we need to convert it # back to JSON qobj = { 'id': 'unitary', 'config': { 'max_credits': None, 'shots': 1, 'backend_name': 'local_unitary_simulator_py' }, 'circuits': [{ 'name': 'test', 'compiled_circuit': circuit, 'compiled_circuit_qasm': self.qp.get_qasm('example'), 'config': { 'coupling_map': None, 'basis_gates': None, 'layout': None, 'seed': None } }] } qobj = Qobj.from_dict(qobj) # numpy.savetxt currently prints complex numbers in a way # loadtxt can't read. To save file do, # fmtstr=['% .4g%+.4gj' for i in range(numCols)] # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, # delimiter=',') expected = np.loadtxt( self._get_resource_path('example_unitary_matrix.dat'), dtype='complex', delimiter=',') result = UnitarySimulatorPy().run(qobj).result() self.assertTrue( np.allclose(result.get_unitary('test'), expected, rtol=1e-3))
def _run_job(self, job_id, qobj): if isinstance(qobj, Qobj): qobj_dict = qobj.as_dict() else: qobj_dict = qobj self._validate() # set backend to Clifford simulator if 'config' in qobj_dict: qobj_dict['config']['simulator'] = 'clifford' else: qobj_dict['config'] = {'simulator': 'clifford'} qobj = Qobj.from_dict(qobj_dict) result = run(qobj, self._configuration.exe) result['job_id'] = job_id return result_from_old_style_dict(result)
def fake_qobj(): backend = FakeBackend() qobj = { 'id': 'test-id', 'config': { 'backend_name': backend.name, 'shots': 1024, 'max_credits': 100 }, 'circuits': [{ 'compiled_circuit_qasm': 'fake-code', 'config': { 'seed': 123456 } }] } return Qobj.from_dict(qobj)
def qobj(self) -> Qobj: """Return the Qobj for this job. Note that this method might involve querying the API for results if the Job has been created in a previous Qiskit session. Returns: the Qobj for this job. Raises: JobError: if there was some unexpected failure in the server. """ # pylint: disable=access-member-before-definition,attribute-defined-outside-init if not self._qobj: # type: ignore[has-type] self._wait_for_completion() with api_to_job_error(): qobj = self._api.job_download_qobj(self.job_id(), self._use_object_storage) self._qobj = Qobj.from_dict(qobj) return self._qobj
def qobj(self) -> Optional[Qobj]: """Return the Qobj for this job. Returns: The Qobj for this job, or ``None`` if the job does not have a Qobj. Raises: IBMQJobApiError: If an unexpected error occurred when retrieving job information from the server. """ if not self.kind: return None # pylint: disable=access-member-before-definition,attribute-defined-outside-init if not self._qobj: # type: ignore[has-type] with api_to_job_error(): qobj = self._api.job_download_qobj( self.job_id(), self._use_object_storage) self._qobj = Qobj.from_dict(qobj) return self._qobj
def __init__(self, _backend: BaseBackend, api: AccountClient, _job_id: str, _creation_date: datetime, _api_status: ApiJobStatus, **kwargs: Any) -> None: """IBMQJob constructor. Args: _backend: The backend instance used to run this job. api: Object for connecting to the server. _job_id: Job ID. _creation_date: Job creation date. _api_status: Job status returned by the server. kwargs: Additional job attributes. """ # pylint: disable=redefined-builtin # Convert qobj from dictionary to Qobj. if isinstance(kwargs.get('_qobj', None), dict): self._qobj = Qobj.from_dict(kwargs.pop('_qobj')) BaseModel.__init__(self, _backend=_backend, _job_id=_job_id, _creation_date=_creation_date, _api_status=_api_status, **kwargs) BaseJob.__init__(self, self.backend(), self.job_id()) # Model attributes. self._api = api self._use_object_storage = (self.kind == ApiJobKind.QOBJECT_STORAGE) self._queue_info = None # type: Optional[QueueInfo] self._status, self._queue_info = self._get_status_position( _api_status, kwargs.pop('info_queue', None)) # Properties used for caching. self._cancelled = False self._job_error_msg = None # type: Optional[str]
def fake_qobj(): backend = FakeBackend() qobj = { 'id': 'test-id', 'config': { 'shots': 1024, 'max_credits': 100 }, 'experiments': [{ 'header': { 'compiled_circuit_qasm': 'fake-code' }, 'config': { 'seed': 123456 }, 'instructions': [] }], 'header': { 'backend_name': backend.name } } return Qobj.from_dict(qobj)
def test_run_ReturnsCorrectResult(self): api = Mock() api.create_project.return_value = {'id': 42} api.get_jobs_from_project.return_value = [] api.execute_qasm_async.return_value = 42 simulator = QuantumInspireBackend(api, Mock()) instructions = [{ 'name': 'cx', 'params': [], 'texparams': [], 'qubits': [0, 1], 'memory': [0, 1] }, { 'name': 'measure', 'qubits': [0], 'memory': [1] }] qobj_dict = self._basic_qobj_dictionary qobj_dict['experiments'][0]['instructions'] = instructions qobj = Qobj.from_dict(qobj_dict) job = simulator.run(qobj) self.assertEqual('42', job.job_id())
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.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][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')
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.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 3, msg=name + ' snapshot length') state = snapshots['0']['statevector'][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') rho = snapshots['0']['density_matrix'] self.assertAlmostEqual(np.trace(rho), 1) prob = snapshots['0']['probabilities'] self.assertAlmostEqual(np.sum(prob), 1)
def test_if_statement(self): self.log.info('test_if_statement_x') shots = 100 max_qubits = 3 qp = QuantumProgram() qr = qp.create_quantum_register('qr', max_qubits) cr = qp.create_classical_register('cr', max_qubits) circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr]) circuit_if_true.x(qr[0]) circuit_if_true.x(qr[1]) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.x(qr[2]).c_if(cr, 0x3) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.measure(qr[2], cr[2]) circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr]) circuit_if_false.x(qr[0]) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.x(qr[2]).c_if(cr, 0x3) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.measure(qr[2], cr[2]) basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(), unroll.JsonBackend(basis_gates)) ucircuit_true = unroller.execute() unroller = unroll.Unroller( qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(), unroll.JsonBackend(basis_gates)) ucircuit_false = unroller.execute() qobj = { 'id': 'test_if_qobj', 'config': { 'max_credits': 3, 'shots': shots, }, 'experiments': [ucircuit_true, ucircuit_false], 'header': {'backend_name': 'local_qasm_simulator_py'} } qobj['experiments'][0]['header']['name'] = 'test_if_true' qobj['experiments'][0]['config'] = { 'coupling_map': None, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': None } qobj['experiments'][1]['header']['name'] = 'test_if_false' qobj['experiments'][1]['config'] = { 'coupling_map': None, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': None } qobj = Qobj.from_dict(qobj) result = QasmSimulatorPy().run(qobj).result() result_if_true = result.get_data('test_if_true') self.log.info('result_if_true circuit:') self.log.info(circuit_if_true.qasm()) self.log.info('result_if_true=%s', result_if_true) result_if_false = result.get_data('test_if_false') self.log.info('result_if_false circuit:') self.log.info(circuit_if_false.qasm()) self.log.info('result_if_false=%s', result_if_false) self.assertTrue(result_if_true['counts']['111'] == 100) self.assertTrue(result_if_false['counts']['001'] == 100)