def main(): S_simulator = Aer.backends(name="statevector_simulator")[0] M_simulator = Aer.backends(name="qasm_simulator")[0] q = QuantumRegister(1) hello_qubit = QuantumCircuit(q) # apply identity gate hello_qubit.iden(q[0]) job = execute(hello_qubit, S_simulator) result = job.result() print("Result is: ", result.get_statevector())
def test_qft_vs_manual_qiskit_qft_comparison(): circuit = qcs.circuit_init(3) circuit.i(0) circuit.i(1) circuit.x(2) circuit.qft(0, 2) result = circuit.execute() sv = result.get_state_vector() S_simulator = Aer.backends(name='statevector_simulator')[0] q = QuantumRegister(3) qubit = QuantumCircuit(q) qubit.iden(q[0]) qubit.iden(q[1]) qubit.x(q[2]) #QFT qubit.h(q[0]) qubit.cu1(np.pi / 2, q[1], q[0]) qubit.cu1(np.pi / 4, q[2], q[0]) qubit.h(q[1]) qubit.cu1(np.pi / 4, q[2], q[1]) qubit.h(q[2]) job = execute(qubit, S_simulator) result_qkit = job.result() sv_qkit = result_qkit.get_statevector() assert np.testing.assert_allclose(sv, sv_qkit, atol=1e-8, rtol=1e-8) == None
def test_get_backend(self): """Test get backends. If all correct should return a name the same as input. """ backend = Aer.backends(name='qasm_simulator_py')[0] self.assertEqual(backend.name(), 'qasm_simulator_py')
def test_rxyz_gate_qiskit_comparison(): circuit = qcs.circuit_init(3) circuit.h(0) circuit.h(1) circuit.h(2) circuit.rx(1, -np.pi / 4) circuit.rx(2, np.pi / 16) circuit.ry(0, -np.pi / 3) circuit.ry(1, np.pi / 4) circuit.rz(2, -np.pi / 12) circuit.rz(0, np.pi / 6) result = circuit.execute() sv = result.get_state_vector() S_simulator = Aer.backends(name='statevector_simulator')[0] q = QuantumRegister(3) qubit = QuantumCircuit(q) qubit.h(q[0]) qubit.h(q[1]) qubit.h(q[2]) qubit.rx(-np.pi / 4, q[1]) qubit.rx(np.pi / 16, q[2]) qubit.ry(-np.pi / 3, q[0]) qubit.ry(np.pi / 4, q[1]) qubit.rz(-np.pi / 12, q[2]) qubit.rz(np.pi / 6, q[0]) job = execute(qubit, S_simulator) result_qkit = job.result() sv_qkit = result_qkit.get_statevector() assert np.testing.assert_allclose(sv, sv_qkit, atol=1e-8, rtol=1e-8) == None
def setUp(self): super().setUp() self.backends = Aer.backends() qr = QuantumRegister(1) cr = ClassicalRegister(1) self.qc1 = QuantumCircuit(qr, cr, name='circuit0') self.qc1.h(qr[0])
def available_backends(filters=None, compact=True): """ Return names of backends that are available in the SDK, optionally filtering them based on their capabilities. Note: In order for this function to return online backends, a connection with an online backend provider needs to be established by calling the `register()` function. Note: If two or more providers have backends with the same name, those names will be shown only once. To disambiguate and choose a backend from a specific provider, get the backend from that specific provider. Example:: p1 = register(token1) p2 = register(token2) execute(circuit, p1.get_backend('ibmq_5_tenerife')) execute(circuit, p2.get_backend('ibmq_5_tenerife')) Args: filters (dict or callable): filtering conditions. compact (bool): group backend names based on compact group names. Returns: list[str]: the names of the available backends. .. deprecated:: 0.6+ After 0.6, this function is deprecated. Please use the methods in `qiskit.IBMQ` and `qiskit.backends.local.Aer` instead (`backends()`). """ warnings.warn( 'available_backends() will be deprecated after 0.6. Please ' 'use the qiskit.IBMQ.backends() and qiskit.Aer.backends() ' 'method instead.', DeprecationWarning) if isinstance(filters, dict): kwargs = filters else: kwargs = {'filters': filters} ibmq_names = [backend.name() for backend in IBMQ.backends(**kwargs)] aer_names = [backend.name() for backend in Aer.backends(**kwargs)] if compact: # Hack for backwards compatibility: reverse the groups for local. aer_groups = Aer.grouped_backend_names() reversed_aer_groups = {} for group, items in aer_groups.items(): for alias in items: reversed_aer_groups[alias] = group aer_names = list(set(reversed_aer_groups[name] for name in aer_names)) return ibmq_names + aer_names
def test_aer_backend_properties(self): """Test backend properties. If all correct should pass the validation. """ aer_backends = Aer.backends() for backend in aer_backends: properties = backend.properties() self.assertEqual(properties, None)
def listLocalBackends(self): if version.parse(__version__) >= version.parse("0.6"): backs = [backend.name() for backend in Aer.backends()] else: raise QiskitUnsupportedVersion( 'Qiskit-terra version must be > v0.6') return backs
def test_deprecated_cpp_simulator_return_no_backend(self): """Test backends("local_qasm_simulator_cpp") does not return C++ simulator if it is not installed""" name = "local_qasm_simulator_cpp" backends = Aer.backends(name) if is_cpp_simulator_available(): self.assertEqual(len(backends), 1) self.assertIsInstance(backends[0] if backends else None, QasmSimulator) else: self.assertEqual(len(backends), 0)
def test_aer_backend_properties(self): """Test backend properties. If all correct should pass the validation. """ aer_backends = Aer.backends() for backend in aer_backends: properties = backend.properties() # FIXME test against schema and decide what properties # is for a simulator self.assertEqual(len(properties), 0)
def quantumCoinFlip(flips): q = QuantumRegister(1) c = ClassicalRegister(1) perfect_coin = QuantumCircuit(q,c) perfect_coin.h(q[0]) perfect_coin.measure(q,c) M_simulator = Aer.backends(name='qasm_simulator')[0] M = execute(perfect_coin,M_simulator,shots=flips).result().get_counts(perfect_coin) heads = M['0'] tails = M['1'] return heads,tails
def test_aer_backend_status(self): """Test backend_status. If all correct should pass the validation. """ backend = Aer.backends(name='qasm_simulator')[0] status = backend.status() schema_path = self._get_resource_path('backend_status_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) jsonschema.validate(status, schema)
def test_aer_backend_status(self): """Test backend_status. If all correct should pass the validation. """ schema_path = self._get_resource_path( 'backend_status_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) for backend in Aer.backends(): status = backend.status() jsonschema.validate(status.to_dict(), schema)
def test_empty_circuit_qiskit_comparison(): circuit = qcs.circuit_init(10) result = circuit.execute() sv = result.get_state_vector() S_simulator = Aer.backends(name='statevector_simulator')[0] q = QuantumRegister(10) qubit = QuantumCircuit(q) job = execute(qubit, S_simulator) result_qkit = job.result() sv_qkit = result_qkit.get_statevector() assert np.testing.assert_allclose(sv, sv_qkit, atol=1e-8, rtol=1e-8) == None
def listLocalBackends(self): if (version.parse(__version__) > version.parse("0.5") and version.parse(__version__) < version.parse("0.6")): backs = available_backends({'local': True}) elif (version.parse(__version__) > version.parse("0.6")): backs = [backend.name() for backend in Aer.backends()] else: raise QiskitUnsupportedVersion( 'Qiskit-terra version must be v0.5 or v0.6') return backs
def test_local_backend_configuration(self): """Test backend configuration. If all correct should pass the vaildation. """ local_backends = Aer.backends() for backend in local_backends: configuration = backend.configuration() schema_path = self._get_resource_path( 'deprecated/backends/backend_configuration_schema_old_py.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) jsonschema.validate(configuration, schema)
def test_aer_backend_configuration(self): """Test backend configuration. If all correct should pass the validation. """ schema_path = self._get_resource_path( 'backend_configuration_schema.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) aer_backends = Aer.backends() for backend in aer_backends: configuration = backend.configuration() jsonschema.validate(configuration.to_dict(), schema)
def get_device(self, noisy=False, **kwargs): """Get the ibm device used for executing circuits Args: noisy (bool): a boolean indicating if the user wants to use noisy simulations Returns: The ibm device that can use the ibm execute api """ # If not doing noisy simulation... if len(Aer.backends(self.device_name)) > 0: self.device = Aer.get_backend(self.device_name) else: raise RuntimeError("Could not find simulator with name: {}".format( self.device_name))
def test_aer_backend_status(self): """Test backend_status. If all correct should pass the vaildation. """ # FIXME: reintroduce in 0.6 self.skipTest('Skipping due to available vs operational') backend = Aer.backends(name='qasm_simulator')[0] status = backend.status() schema_path = self._get_resource_path( 'deprecated/backends/backend_status_schema_py.json', path=Path.SCHEMAS) with open(schema_path, 'r') as schema_file: schema = json.load(schema_file) jsonschema.validate(status, schema)
def test_simple_qaoa_vs_manual_qiskit_qaoa_comparison(): n = 5 p = 2 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 4, 1.0), (4, 2, 1.0)] graph = nx.Graph() graph.add_nodes_from(V) graph.add_weighted_edges_from(E) betas = np.random.uniform(-np.pi, np.pi, size=p) gammas = np.random.uniform(-np.pi, np.pi, size=p) circuit = qcs.circuit_init(n) for i in range(n): circuit.h(i) for beta, gamma in zip(betas, gammas): for i, j in graph.edges: circuit.cx(i, j) circuit.rot(j, gamma) circuit.cx(i, j) for i in range(n): circuit.rx(i, 2 * beta) result = circuit.execute() sv = result.get_state_vector() S_simulator = Aer.backends(name='statevector_simulator')[0] q = QuantumRegister(n) qubit = QuantumCircuit(q) for i in range(n): qubit.h(q[i]) for beta, gamma in zip(betas, gammas): for i, j in graph.edges: qubit.cx(q[int(i)], q[int(j)]) qubit.u1(gamma, q[int(j)]) qubit.cx(q[int(i)], q[int(j)]) for i in range(n): qubit.rx(beta * 2, q[i]) job = execute(qubit, S_simulator) result_qkit = job.result() sv_qkit = result_qkit.get_statevector() assert np.testing.assert_allclose(sv, sv_qkit, atol=1e-8, rtol=1e-8) == None
def test_qobj_headers_in_result(self): """Test that the qobj headers are passed onto the results.""" custom_qobj_header = {'x': 1, 'y': [1, 2, 3], 'z': {'a': 4}} for backend in Aer.backends(): with self.subTest(backend=backend): qobj = compile(self.qc1, backend) # Update the Qobj header. qobj.header = QobjHeader.from_dict(custom_qobj_header) # Update the Qobj.experiment header. qobj.experiments[0].header.some_field = 'extra info' result = backend.run(qobj).result() self.assertEqual(result.header.to_dict(), custom_qobj_header) self.assertEqual(result.results[0].header.some_field, 'extra info')
def test_deprecated(self): """Test that deprecated names map the same backends as the new names. """ deprecated_names = Aer.deprecated_backend_names() for oldname, newname in deprecated_names.items(): if newname == 'local_qasm_simulator_cpp' and not is_cpp_simulator_available( ): continue with self.subTest(oldname=oldname, newname=newname): try: real_backend = Aer.get_backend(newname) except KeyError: # The real name of the backend might not exist pass else: self.assertEqual(Aer.backends(oldname)[0], real_backend)
def test_circuit3_qiskit_comparison(): circuit = qcs.circuit_init(3) circuit.y(0) circuit.h(1) circuit.x(2) circuit.cx(0, 1) circuit.h(0) circuit.cz(1, 2) circuit.cy(0, 2) circuit.cy(0, 2) circuit.cz(1, 2) circuit.h(0) circuit.cx(0, 1) circuit.x(2) circuit.h(1) circuit.y(0) result = circuit.execute() sv = result.get_state_vector() S_simulator = Aer.backends(name='statevector_simulator')[0] q = QuantumRegister(3) qubit = QuantumCircuit(q) qubit.y(q[0]) qubit.h(q[1]) qubit.x(q[2]) qubit.cx(q[0], q[1]) qubit.h(q[0]) qubit.cz(q[1], q[2]) qubit.cy(q[0], q[2]) qubit.cy(q[0], q[2]) qubit.cz(q[1], q[2]) qubit.h(q[0]) qubit.cx(q[0], q[1]) qubit.x(q[2]) qubit.h(q[1]) qubit.y(q[0]) job = execute(qubit, S_simulator) result_qkit = job.result() sv_qkit = result_qkit.get_statevector() assert np.testing.assert_allclose(sv, sv_qkit, atol=1e-8, rtol=1e-8) == None
def test_deprecated(self): """Test that deprecated names map the same backends as the new names. """ deprecated_names = Aer._deprecated_backend_names() for oldname, newname in deprecated_names.items(): if (newname == 'qasm_simulator' or newname == 'statevector_simulator' ) and not is_cpp_simulator_available(): continue with self.subTest(oldname=oldname, newname=newname): try: resolved_newname = _get_first_available_backend(newname) real_backend = Aer.get_backend(resolved_newname) except QiskitBackendNotFoundError: # The real name of the backend might not exist pass else: self.assertEqual(Aer.backends(oldname)[0], real_backend)
def register_and_get_operational_backends(): # update registration info using internal methods because: # at this point I don't want to save to or remove credentials from disk # I want to update url, proxies etc without removing token and # re-adding in 2 methods ibmq_backends = [] try: credentials = None preferences = Preferences() url = preferences.get_url() token = preferences.get_token() if url is not None and url != '' and token is not None and token != '': credentials = Credentials(token, url, proxies=preferences.get_proxies({})) if credentials is not None: IBMQ._accounts[credentials.unique_id()] = IBMQSingleProvider( credentials, IBMQ) logger.debug("Registered with Qiskit successfully.") ibmq_backends = [x.name() for x in IBMQ.backends(url=url, token=token)] except Exception as e: logger.debug( "Failed to register with Qiskit: {}".format(str(e))) backends = set() aer_backends = [x.name() for x in Aer.backends()] for aer_backend in aer_backends: backend = aer_backend supported = True for unsupported_backend in QuantumInstance.UNSUPPORTED_BACKENDS: if backend.startswith(unsupported_backend): supported = False break if supported: backends.add(backend) return list(backends) + ibmq_backends
lambda x: x.configuration()['n_qubits'] >= 14 and not x.configuration()['simulator'] ) backend = least_busy(large_enough_devices) shots = 1024 mx = 3 elif (sys.argv[2] == 's'): # shoud be a s for simulator large_enough_devices = IBMQ.backends( filters= lambda x: x.configuration()['n_qubits'] >= 14 and x.configuration()['simulator'] ) backend = least_busy(large_enough_devices) shots = 8192 mx = 10 else: exit("s/r") else: print("Local simulator started") print(Aer.backends()) backend = Aer.get_backend('qasm_simulator') shots = 4096 mx = 3 print("backend = {0}".format(backend)) print("shots = {0}".format(shots)) print("max credits = {0}".format(mx)) job = execute(qc, backend=backend, shots=shots, max_credits=mx) print("job id = {0}".format(job.job_id())) result = job.result() counts = result.get_counts() print(counts) #plot_histogram(counts)
import numpy as np import math as m from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import circuit_drawer S_simulator = Aer.backends(name='statevector_simulator')[0] M_simulator = Aer.backends(name='qasm_simulator')[0] def QFT(qc, q, qubits): ''' Assigns all the gate operations for a Ouantum Fourier Transformation ''' R_phis = [0] for i in np.arange(2, int(qubits + 1)): R_phis.append(2 / (2**(i)) * m.pi) for j in np.arange(int(qubits)): qc.h(q[int(j + qubits)]) for k in np.arange(j + 1, int(qubits)): qc.cu1(R_phis[k], q[int(k) + qubits], q[int(j) + qubits]) def QFT_dgr(qc, q, qubits): ''' Assigns all the gate operations for an inverse Quantum Fourier Transfornation ''' R_phis = [0] for i in np.arange(2, int(qubits + 1)): R_phis.append(-2 / (2**(i)) * m.pi) for j in np.arange(int(qubits)):
#!/usr/bin/env python # coding: utf-8 print("Ch 8: IBM Qx simulators and how they are used") print("---------------------------------------------") # Import Qiskit and load account from qiskit import Aer, IBMQ IBMQ.load_account() provider = IBMQ.get_provider() # Load backends backends = Aer.backends() print("\nAer backends:\n\n", backends) # Collect Aer simulators simulators = [] for sim in range(0, len(backends)): backend = Aer.get_backend(str(backends[sim])) simulators.append(backend.configuration()) # Add IBM Q simulator ibmq_simulator = provider.backends(simulator=True) simulators.append(provider.get_backend(str(ibmq_simulator[0])).configuration()) # Display the raw simulator configuration details print("\nSimulator configuration details:") for sim in range(0, len(simulators)): print("\n") print(simulators[sim].backend_name)
"Print IBMQ backends", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--aer", action="store_true", default=False, help="Print the AER backends") parser.add_argument("--project", type=str, default="", help="Indicate a specific hub,group,project") args = parser.parse_args() if args.aer: print("AER backends") for backend in Aer.backends(): print(f"\t{backend} ({backend_configuration(backend)})") else: open_provider = IBMQ.load_account() if args.project == "": print("IBMQ backends (open)") for backend in open_provider.backends(): print( f"\t{backend} ({backend_configuration(backend)}): {backend_status(backend)}" ) else: (hub, group, project) = splitProjectInfo(args.project) print( f"IBMQ backends (hub: {hub}, group: {group}, project: {project})")
return (optimizer_output, report) if __name__ == '__main__': start_params, sample_number, q_device_name, minimizer_method, minimizer_options, minimizer_function = cmdline_parse_and_report( num_params=custom_ansatz.num_params, q_device_name_default='qasm_simulator', q_device_name_help= "Real devices: 'ibmqx4' or 'ibmqx5'. Use 'ibmq_qasm_simulator' for remote simulator or 'qasm_simulator' for local", minimizer_options_default= '{"maxfev":200, "xatol": 0.001, "fatol": 0.001}', start_param_value_default=0.0) # q_device_name = os.environ.get('VQE_QUANTUM_BACKEND', 'qasm_simulator') # try 'qasm_simulator', 'ibmq_qasm_simulator', 'ibmqx4', 'ibmqx5' local_backends_names = [b.name() for b in Aer.backends(operational=True)] try: print('Trying to connect to the LOCAL backend "{}"...'.format( q_device_name)) q_device = Aer.get_backend(q_device_name) except KeyError: print( 'Could not find the LOCAL q_device "{}" - available LOCAL q_devices:\n\t{}' .format(q_device_name, local_backends_names)) try: api_token = os.environ.get('CK_IBM_API_TOKEN') if not api_token: print( 'CK_IBM_API_TOKEN is not defined, so cannot connect to REMOTE q_devices - bailing out.' .format(q_device_name)) exit(1)